From f9c5ae7ecebd23882b43c4cb6c6d348ea3909645 Mon Sep 17 00:00:00 2001 From: "g.beausire" Date: Mon, 23 Nov 2026 14:59:38 +0100 Subject: [PATCH] Add support for taints as disruption The node disruption controller allows now to configure a taintSelector. Taints matched by this selector will be considered like disruption and will count in the budget --- DOC.md | 331 +++++++++++++++++- api/v1alpha1/nodedisruptionbudget_types.go | 50 ++- .../nodedisruptionbudget_types_test.go | 64 ++++ api/v1alpha1/zz_generated.deepcopy.go | 78 +++++ chart/templates/nodedisruptionbudget-crd.yaml | 98 +++++- ...tion.criteo.com_nodedisruptionbudgets.yaml | 98 +++++- .../nodedisruptionbudget_controller.go | 53 ++- .../nodedisruptionbudget_controller_test.go | 81 +++++ .../nodedisruptionbudget_taint_test.go | 131 +++++++ pkg/resolver/resolver.go | 11 +- 10 files changed, 974 insertions(+), 21 deletions(-) create mode 100644 api/v1alpha1/nodedisruptionbudget_types_test.go create mode 100644 internal/controller/nodedisruptionbudget_taint_test.go diff --git a/DOC.md b/DOC.md index ad82415..b9eff4a 100644 --- a/DOC.md +++ b/DOC.md @@ -103,6 +103,15 @@ It perform a POST http request containing the NodeDisruption that is being valid Maintenance will proceed only if the endpoint responds 2XX.
false + + hookV2BasePath + object + + HookV2BasePath holds the base path for the prepare, ready, terminate hooks that will be +called at different stages of the NodeDisruption lifecycle. +A POST http request containing a Disruption that is being reconciled is sent ot each of the hooks.
+ + false noticePeriod string @@ -135,6 +144,15 @@ whole hours, minutes and seconds, such as 30m or 1h30m.
PVCSelector query over PVCs whose nodes are managed by the disruption budget.
false + + supportedNodeDisruptionTypes + []string + + SupportedNodeDisruptionTypes is the list of node disruption types that this budget supports. +When set, this budget will only be considered during reconciliation of NodeDisruptions whose type +is in this list. When empty, the controller's default node disruption types are used.
+ + false @@ -175,12 +193,14 @@ Maintenance will proceed only if the endpoint responds 2XX. -### ApplicationDisruptionBudget.spec.noticePeriodOverrides[index] +### ApplicationDisruptionBudget.spec.hookV2BasePath [↩ Parent](#applicationdisruptionbudgetspec) -NoticePeriodOverrides overrides NoticePeriod for specific disruption types. +HookV2BasePath holds the base path for the prepare, ready, terminate hooks that will be +called at different stages of the NodeDisruption lifecycle. +A POST http request containing a Disruption that is being reconciled is sent ot each of the hooks. @@ -192,19 +212,53 @@ NoticePeriodOverrides overrides NoticePeriod for specific disruption types. - + - + + + + + + +
typecaBundle string - Type is the node disruption type this notice period applies to.
+ a PEM encoded CA bundle which will be used to validate the webhook's server certificate. If unspecified, system trust roots on the apiserver are used.
truefalse
urlstring + URL that will be called by the hook, in standard URL form (`scheme://host:port/path`).
+
false
+ + +### ApplicationDisruptionBudget.spec.noticePeriodOverrides[index] +[↩ Parent](#applicationdisruptionbudgetspec) + + + +TypedNoticePeriod is a notice period for a single node disruption type. + + + + + + + + + + + + + + + +
NameTypeDescriptionRequired
noticePeriod string NoticePeriod for disruptions of this type.
true
typestring + Type is the node disruption type this notice period applies to.
+
true
@@ -507,7 +561,7 @@ NodeDisruptionBudget is the Schema for the nodedisruptionbudgets API status object - DisruptionBudgetStatus defines the observed state of ApplicationDisruptionBudget
+
false @@ -551,6 +605,22 @@ NodeDisruptionBudgetSpec defines the desired state of NodeDisruptionBudget NodeSelector query over pods whose nodes are managed by the disruption budget.
false + + supportedNodeDisruptionTypes + []string + + SupportedNodeDisruptionTypes is the list of node disruption types that this budget supports. +When set, this budget will only be considered during reconciliation of NodeDisruptions whose type +is in this list. When empty, the controller's default node disruption types are used.
+ + false + + taintSelector + object + + TaintSelector allow to select taints that will be considered disruptions
+ + false @@ -637,12 +707,180 @@ merge patch.
+### NodeDisruptionBudget.spec.taintSelector +[↩ Parent](#nodedisruptionbudgetspec) + + + +TaintSelector allow to select taints that will be considered disruptions + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescriptionRequired
exclude[]object +
+
false
include[]object +
+
false
+ + +### NodeDisruptionBudget.spec.taintSelector.exclude[index] +[↩ Parent](#nodedisruptionbudgetspectaintselector) + + + +The pod this Toleration is attached to tolerates any taint that matches +the triple using the matching operator . + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescriptionRequired
effectstring + Effect indicates the taint effect to match. Empty means match all taint effects. +When specified, allowed values are NoSchedule, PreferNoSchedule and NoExecute.
+
false
keystring + Key is the taint key that the toleration applies to. Empty means match all taint keys. +If the key is empty, operator must be Exists; this combination means to match all values and all keys.
+
false
operatorstring + Operator represents a key's relationship to the value. +Valid operators are Exists and Equal. Defaults to Equal. +Exists is equivalent to wildcard for value, so that a pod can +tolerate all taints of a particular category.
+
false
tolerationSecondsinteger + TolerationSeconds represents the period of time the toleration (which must be +of effect NoExecute, otherwise this field is ignored) tolerates the taint. By default, +it is not set, which means tolerate the taint forever (do not evict). Zero and +negative values will be treated as 0 (evict immediately) by the system.
+
+ Format: int64
+
false
valuestring + Value is the taint value the toleration matches to. +If the operator is Exists, the value should be empty, otherwise just a regular string.
+
false
+ + +### NodeDisruptionBudget.spec.taintSelector.include[index] +[↩ Parent](#nodedisruptionbudgetspectaintselector) + + + +The pod this Toleration is attached to tolerates any taint that matches +the triple using the matching operator . + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescriptionRequired
effectstring + Effect indicates the taint effect to match. Empty means match all taint effects. +When specified, allowed values are NoSchedule, PreferNoSchedule and NoExecute.
+
false
keystring + Key is the taint key that the toleration applies to. Empty means match all taint keys. +If the key is empty, operator must be Exists; this combination means to match all values and all keys.
+
false
operatorstring + Operator represents a key's relationship to the value. +Valid operators are Exists and Equal. Defaults to Equal. +Exists is equivalent to wildcard for value, so that a pod can +tolerate all taints of a particular category.
+
false
tolerationSecondsinteger + TolerationSeconds represents the period of time the toleration (which must be +of effect NoExecute, otherwise this field is ignored) tolerates the taint. By default, +it is not set, which means tolerate the taint forever (do not evict). Zero and +negative values will be treated as 0 (evict immediately) by the system.
+
+ Format: int64
+
false
valuestring + Value is the taint value the toleration matches to. +If the operator is Exists, the value should be empty, otherwise just a regular string.
+
false
+ + ### NodeDisruptionBudget.status [↩ Parent](#nodedisruptionbudget) -DisruptionBudgetStatus defines the observed state of ApplicationDisruptionBudget + @@ -678,6 +916,13 @@ DisruptionBudgetStatus defines the observed state of ApplicationDisruptionBudget Default: 0
+ + + + + @@ -724,6 +969,40 @@ Basic information about disruptions
true
taintedNodes[]object + TaintedNodes contains nodes selected that have an allowed taint
+
false
watchedNodes []string
+ +### NodeDisruptionBudget.status.taintedNodes[index] +[↩ Parent](#nodedisruptionbudgetstatus) + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescriptionRequired
namestring +
+
true
taints[]string +
+
true
+ ## NodeDisruption [↩ Parent](#nodedisruptioncriteocomv1alpha1 ) @@ -795,6 +1074,22 @@ NodeDisruptionSpec defines the desired state of NodeDisruption + doNotGrantBefore + string + + DoNotGrantBefore prevents the disruption from being granted before the specified time
+
+ Format: date-time
+ + false + + duration + string + + Duration of the disruption once granted
+ + false + nodeSelector object @@ -805,7 +1100,16 @@ NodeDisruptionSpec defines the desired state of NodeDisruption retry object - Configure the retrying behavior of a NodeDisruption
+ Retry configuration allows to retry a disruption after rejection until the given deadline
+ + false + + startDate + string + + StartDate when the disruption should start
+
+ Format: date-time
false @@ -906,7 +1210,7 @@ merge patch.
-Configure the retrying behavior of a NodeDisruption +Retry configuration allows to retry a disruption after rejection until the given deadline @@ -1010,7 +1314,14 @@ NodeDisruptionStatus defines the observed state of NodeDisruption (/!\ it is eve + + + + + diff --git a/api/v1alpha1/nodedisruptionbudget_types.go b/api/v1alpha1/nodedisruptionbudget_types.go index e436b8c..89687e0 100644 --- a/api/v1alpha1/nodedisruptionbudget_types.go +++ b/api/v1alpha1/nodedisruptionbudget_types.go @@ -42,6 +42,40 @@ type NodeDisruptionBudgetSpec struct { // is in this list. When empty, the controller's default node disruption types are used. // +kubebuilder:validation:Optional SupportedNodeDisruptionTypes []string `json:"supportedNodeDisruptionTypes,omitempty"` + // TaintSelector allow to select taints that will be considered disruptions + // +kubebuilder:validation:Optional + TaintSelector *TaintSelector `json:"taintSelector,omitempty"` +} + +type TaintSelector struct { + Include []corev1.Toleration `json:"include,omitempty"` + Exclude []corev1.Toleration `json:"exclude,omitempty"` +} + +func tolerationsMatchTaint(tolerations []corev1.Toleration, taint *corev1.Taint) bool { + for i := range tolerations { + if tolerations[i].ToleratesTaint(taint) { + return true + } + } + return false +} + +func (ts *TaintSelector) MatchesTaint(taint *corev1.Taint) bool { + if tolerationsMatchTaint(ts.Exclude, taint) { + return false + } + return len(ts.Include) == 0 || tolerationsMatchTaint(ts.Include, taint) +} + +func (ts *TaintSelector) MatchingTaints(node *corev1.Node) []string { + var taints []string + for i := range node.Spec.Taints { + if ts.MatchesTaint(&node.Spec.Taints[i]) { + taints = append(taints, node.Spec.Taints[i].ToString()) + } + } + return taints } //+kubebuilder:object:root=true @@ -57,8 +91,20 @@ type NodeDisruptionBudget struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` - Spec NodeDisruptionBudgetSpec `json:"spec,omitempty"` - Status DisruptionBudgetStatus `json:"status,omitempty"` + Spec NodeDisruptionBudgetSpec `json:"spec,omitempty"` + Status NodeDisruptionBudgetStatus `json:"status,omitempty"` +} + +type NodeDisruptionBudgetStatus struct { + DisruptionBudgetStatus `json:",inline"` + + // TaintedNodes contains nodes selected that have an allowed taint + TaintedNodes []TaintedNode `json:"taintedNodes,omitempty"` +} + +type TaintedNode struct { + Name string `json:"name"` + Taints []string `json:"taints"` } // SelectorMatchesObject return true if the object is matched by one of the selectors diff --git a/api/v1alpha1/nodedisruptionbudget_types_test.go b/api/v1alpha1/nodedisruptionbudget_types_test.go new file mode 100644 index 0000000..f823297 --- /dev/null +++ b/api/v1alpha1/nodedisruptionbudget_types_test.go @@ -0,0 +1,64 @@ +package v1alpha1 + +import ( + "reflect" + "testing" + + corev1 "k8s.io/api/core/v1" +) + +func TestTaintSelectorMatchingTaints(t *testing.T) { + dedicated := corev1.Taint{Key: "crto.in/dedicated", Value: "team", Effect: corev1.TaintEffectNoSchedule} + cilium := corev1.Taint{Key: "node.cilium.io/agent-not-ready", Effect: corev1.TaintEffectNoSchedule} + unreachable := corev1.Taint{Key: "node.kubernetes.io/unreachable", Effect: corev1.TaintEffectNoExecute} + prefer := corev1.Taint{Key: "example.com/prefer", Effect: corev1.TaintEffectPreferNoSchedule} + + allHardEffectsButDedicated := TaintSelector{ + Include: []corev1.Toleration{ + {Operator: corev1.TolerationOpExists, Effect: corev1.TaintEffectNoSchedule}, + {Operator: corev1.TolerationOpExists, Effect: corev1.TaintEffectNoExecute}, + }, + Exclude: []corev1.Toleration{ + {Key: "crto.in/dedicated", Operator: corev1.TolerationOpExists}, + }, + } + ciliumOnly := TaintSelector{ + Include: []corev1.Toleration{ + {Key: "node.cilium.io/agent-not-ready", Operator: corev1.TolerationOpExists}, + }, + } + allButDedicated := TaintSelector{ + Exclude: []corev1.Toleration{ + {Key: "crto.in/dedicated", Operator: corev1.TolerationOpExists}, + }, + } + + tests := []struct { + name string + selector TaintSelector + taints []corev1.Taint + want []string + }{ + {"no taints", allHardEffectsButDedicated, nil, nil}, + {"excluded taint only", allHardEffectsButDedicated, []corev1.Taint{dedicated}, nil}, + {"included NoSchedule taint", allHardEffectsButDedicated, []corev1.Taint{cilium}, []string{"node.cilium.io/agent-not-ready:NoSchedule"}}, + {"included NoExecute taint", allHardEffectsButDedicated, []corev1.Taint{unreachable}, []string{"node.kubernetes.io/unreachable:NoExecute"}}, + {"PreferNoSchedule not included", allHardEffectsButDedicated, []corev1.Taint{prefer}, nil}, + {"excluded taint does not hide an included one", allHardEffectsButDedicated, []corev1.Taint{dedicated, cilium}, []string{"node.cilium.io/agent-not-ready:NoSchedule"}}, + {"allowlist matches listed key", ciliumOnly, []corev1.Taint{cilium}, []string{"node.cilium.io/agent-not-ready:NoSchedule"}}, + {"allowlist ignores other keys", ciliumOnly, []corev1.Taint{dedicated, unreachable}, nil}, + {"empty include matches any taint", allButDedicated, []corev1.Taint{prefer, unreachable}, []string{"example.com/prefer:PreferNoSchedule", "node.kubernetes.io/unreachable:NoExecute"}}, + {"empty include still applies exclude", allButDedicated, []corev1.Taint{dedicated}, nil}, + {"empty selector matches any taint", TaintSelector{}, []corev1.Taint{dedicated}, []string{"crto.in/dedicated=team:NoSchedule"}}, + {"empty selector needs a taint", TaintSelector{}, nil, nil}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + node := &corev1.Node{Spec: corev1.NodeSpec{Taints: tt.taints}} + if got := tt.selector.MatchingTaints(node); !reflect.DeepEqual(got, tt.want) { + t.Errorf("MatchingTaints() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/api/v1alpha1/zz_generated.deepcopy.go b/api/v1alpha1/zz_generated.deepcopy.go index 2df01a7..441200b 100644 --- a/api/v1alpha1/zz_generated.deepcopy.go +++ b/api/v1alpha1/zz_generated.deepcopy.go @@ -21,6 +21,7 @@ limitations under the License. package v1alpha1 import ( + corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" ) @@ -299,6 +300,11 @@ func (in *NodeDisruptionBudgetSpec) DeepCopyInto(out *NodeDisruptionBudgetSpec) *out = make([]string, len(*in)) copy(*out, *in) } + if in.TaintSelector != nil { + in, out := &in.TaintSelector, &out.TaintSelector + *out = new(TaintSelector) + (*in).DeepCopyInto(*out) + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NodeDisruptionBudgetSpec. @@ -311,6 +317,29 @@ func (in *NodeDisruptionBudgetSpec) DeepCopy() *NodeDisruptionBudgetSpec { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *NodeDisruptionBudgetStatus) DeepCopyInto(out *NodeDisruptionBudgetStatus) { + *out = *in + in.DisruptionBudgetStatus.DeepCopyInto(&out.DisruptionBudgetStatus) + if in.TaintedNodes != nil { + in, out := &in.TaintedNodes, &out.TaintedNodes + *out = make([]TaintedNode, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NodeDisruptionBudgetStatus. +func (in *NodeDisruptionBudgetStatus) DeepCopy() *NodeDisruptionBudgetStatus { + if in == nil { + return nil + } + out := new(NodeDisruptionBudgetStatus) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *NodeDisruptionList) DeepCopyInto(out *NodeDisruptionList) { *out = *in @@ -405,6 +434,55 @@ func (in *RetrySpec) DeepCopy() *RetrySpec { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *TaintSelector) DeepCopyInto(out *TaintSelector) { + *out = *in + if in.Include != nil { + in, out := &in.Include, &out.Include + *out = make([]corev1.Toleration, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.Exclude != nil { + in, out := &in.Exclude, &out.Exclude + *out = make([]corev1.Toleration, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TaintSelector. +func (in *TaintSelector) DeepCopy() *TaintSelector { + if in == nil { + return nil + } + out := new(TaintSelector) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *TaintedNode) DeepCopyInto(out *TaintedNode) { + *out = *in + if in.Taints != nil { + in, out := &in.Taints, &out.Taints + *out = make([]string, len(*in)) + copy(*out, *in) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TaintedNode. +func (in *TaintedNode) DeepCopy() *TaintedNode { + if in == nil { + return nil + } + out := new(TaintedNode) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *TypedNoticePeriod) DeepCopyInto(out *TypedNoticePeriod) { *out = *in diff --git a/chart/templates/nodedisruptionbudget-crd.yaml b/chart/templates/nodedisruptionbudget-crd.yaml index dd5e1f2..8c57109 100644 --- a/chart/templates/nodedisruptionbudget-crd.yaml +++ b/chart/templates/nodedisruptionbudget-crd.yaml @@ -119,12 +119,92 @@ spec: items: type: string type: array + taintSelector: + description: TaintSelector allow to select taints that will be considered + disruptions + properties: + exclude: + items: + description: |- + The pod this Toleration is attached to tolerates any taint that matches + the triple using the matching operator . + properties: + effect: + description: |- + Effect indicates the taint effect to match. Empty means match all taint effects. + When specified, allowed values are NoSchedule, PreferNoSchedule and NoExecute. + type: string + key: + description: |- + Key is the taint key that the toleration applies to. Empty means match all taint keys. + If the key is empty, operator must be Exists; this combination means to match all values and all keys. + type: string + operator: + description: |- + Operator represents a key's relationship to the value. + Valid operators are Exists and Equal. Defaults to Equal. + Exists is equivalent to wildcard for value, so that a pod can + tolerate all taints of a particular category. + type: string + tolerationSeconds: + description: |- + TolerationSeconds represents the period of time the toleration (which must be + of effect NoExecute, otherwise this field is ignored) tolerates the taint. By default, + it is not set, which means tolerate the taint forever (do not evict). Zero and + negative values will be treated as 0 (evict immediately) by the system. + format: int64 + type: integer + value: + description: |- + Value is the taint value the toleration matches to. + If the operator is Exists, the value should be empty, otherwise just a regular string. + type: string + type: object + type: array + include: + items: + description: |- + The pod this Toleration is attached to tolerates any taint that matches + the triple using the matching operator . + properties: + effect: + description: |- + Effect indicates the taint effect to match. Empty means match all taint effects. + When specified, allowed values are NoSchedule, PreferNoSchedule and NoExecute. + type: string + key: + description: |- + Key is the taint key that the toleration applies to. Empty means match all taint keys. + If the key is empty, operator must be Exists; this combination means to match all values and all keys. + type: string + operator: + description: |- + Operator represents a key's relationship to the value. + Valid operators are Exists and Equal. Defaults to Equal. + Exists is equivalent to wildcard for value, so that a pod can + tolerate all taints of a particular category. + type: string + tolerationSeconds: + description: |- + TolerationSeconds represents the period of time the toleration (which must be + of effect NoExecute, otherwise this field is ignored) tolerates the taint. By default, + it is not set, which means tolerate the taint forever (do not evict). Zero and + negative values will be treated as 0 (evict immediately) by the system. + format: int64 + type: integer + value: + description: |- + Value is the taint value the toleration matches to. + If the operator is Exists, the value should be empty, otherwise just a regular string. + type: string + type: object + type: array + type: object required: - maxDisruptedNodes - minUndisruptedNodes type: object status: - description: DisruptionBudgetStatus defines the observed state of ApplicationDisruptionBudget properties: currentDisruptions: default: 0 @@ -151,6 +231,22 @@ spec: default: 0 description: Number of disruption allowed on the nodes of this type: integer + taintedNodes: + description: TaintedNodes contains nodes selected that have an allowed + taint + items: + properties: + name: + type: string + taints: + items: + type: string + type: array + required: + - name + - taints + type: object + type: array watchedNodes: description: |- List of nodes that are being watched by the controller diff --git a/config/crd/bases/nodedisruption.criteo.com_nodedisruptionbudgets.yaml b/config/crd/bases/nodedisruption.criteo.com_nodedisruptionbudgets.yaml index 62b74fd..66de391 100644 --- a/config/crd/bases/nodedisruption.criteo.com_nodedisruptionbudgets.yaml +++ b/config/crd/bases/nodedisruption.criteo.com_nodedisruptionbudgets.yaml @@ -118,12 +118,92 @@ spec: items: type: string type: array + taintSelector: + description: TaintSelector allow to select taints that will be considered + disruptions + properties: + exclude: + items: + description: |- + The pod this Toleration is attached to tolerates any taint that matches + the triple using the matching operator . + properties: + effect: + description: |- + Effect indicates the taint effect to match. Empty means match all taint effects. + When specified, allowed values are NoSchedule, PreferNoSchedule and NoExecute. + type: string + key: + description: |- + Key is the taint key that the toleration applies to. Empty means match all taint keys. + If the key is empty, operator must be Exists; this combination means to match all values and all keys. + type: string + operator: + description: |- + Operator represents a key's relationship to the value. + Valid operators are Exists and Equal. Defaults to Equal. + Exists is equivalent to wildcard for value, so that a pod can + tolerate all taints of a particular category. + type: string + tolerationSeconds: + description: |- + TolerationSeconds represents the period of time the toleration (which must be + of effect NoExecute, otherwise this field is ignored) tolerates the taint. By default, + it is not set, which means tolerate the taint forever (do not evict). Zero and + negative values will be treated as 0 (evict immediately) by the system. + format: int64 + type: integer + value: + description: |- + Value is the taint value the toleration matches to. + If the operator is Exists, the value should be empty, otherwise just a regular string. + type: string + type: object + type: array + include: + items: + description: |- + The pod this Toleration is attached to tolerates any taint that matches + the triple using the matching operator . + properties: + effect: + description: |- + Effect indicates the taint effect to match. Empty means match all taint effects. + When specified, allowed values are NoSchedule, PreferNoSchedule and NoExecute. + type: string + key: + description: |- + Key is the taint key that the toleration applies to. Empty means match all taint keys. + If the key is empty, operator must be Exists; this combination means to match all values and all keys. + type: string + operator: + description: |- + Operator represents a key's relationship to the value. + Valid operators are Exists and Equal. Defaults to Equal. + Exists is equivalent to wildcard for value, so that a pod can + tolerate all taints of a particular category. + type: string + tolerationSeconds: + description: |- + TolerationSeconds represents the period of time the toleration (which must be + of effect NoExecute, otherwise this field is ignored) tolerates the taint. By default, + it is not set, which means tolerate the taint forever (do not evict). Zero and + negative values will be treated as 0 (evict immediately) by the system. + format: int64 + type: integer + value: + description: |- + Value is the taint value the toleration matches to. + If the operator is Exists, the value should be empty, otherwise just a regular string. + type: string + type: object + type: array + type: object required: - maxDisruptedNodes - minUndisruptedNodes type: object status: - description: DisruptionBudgetStatus defines the observed state of ApplicationDisruptionBudget properties: currentDisruptions: default: 0 @@ -150,6 +230,22 @@ spec: default: 0 description: Number of disruption allowed on the nodes of this type: integer + taintedNodes: + description: TaintedNodes contains nodes selected that have an allowed + taint + items: + properties: + name: + type: string + taints: + items: + type: string + type: array + required: + - name + - taints + type: object + type: array watchedNodes: description: |- List of nodes that are being watched by the controller diff --git a/internal/controller/nodedisruptionbudget_controller.go b/internal/controller/nodedisruptionbudget_controller.go index ee8d4bb..5725c73 100644 --- a/internal/controller/nodedisruptionbudget_controller.go +++ b/internal/controller/nodedisruptionbudget_controller.go @@ -123,7 +123,7 @@ func PruneNDBMetrics(ref nodedisruptionv1alpha1.NamespacedName) { func UpdateNDBMetrics(ref nodedisruptionv1alpha1.NamespacedName, ndb *nodedisruptionv1alpha1.NodeDisruptionBudget) { DisruptionBudgetMaxDisruptedNodes.WithLabelValues(ref.Namespace, ref.Name, ref.Kind).Set(float64(ndb.Spec.MaxDisruptedNodes)) DisruptionBudgetMinUndisruptedNodes.WithLabelValues(ref.Namespace, ref.Name, ref.Kind).Set(float64(ndb.Spec.MinUndisruptedNodes)) - UpdateBudgetStatusMetrics(ref, ndb.Status) + UpdateBudgetStatusMetrics(ref, ndb.Status.DisruptionBudgetStatus) } // MapFuncBuilder returns a MapFunc that is used to dispatch reconcile requests to @@ -191,11 +191,17 @@ func (r *NodeDisruptionBudgetResolver) Sync(ctx context.Context) error { nodes := resolver.NodeSetToStringList(nodeNames) - disruptionCount, disruptions, err := r.ResolveDisruption(ctx) + taintedNodes, err := r.GetTaintedNodes(ctx) if err != nil { return err } + disruptionCount, disruptions, err := r.ResolveDisruption(ctx, taintedNodeSet(taintedNodes)) + if err != nil { + return err + } + + r.NodeDisruptionBudget.Status.TaintedNodes = taintedNodes r.NodeDisruptionBudget.Status.WatchedNodes = nodes r.NodeDisruptionBudget.Status.CurrentDisruptions = disruptionCount r.NodeDisruptionBudget.Status.DisruptionsAllowed = computeNodeDisruptionBudgetDisruptionsAllowed( @@ -217,7 +223,9 @@ func (r *NodeDisruptionBudgetResolver) IsImpacted(disruptedNodes resolver.NodeSe // Return the number of disruption allowed considering a list of current node disruptions func (r *NodeDisruptionBudgetResolver) TolerateDisruption(disruptedNodes resolver.NodeSet) bool { watchedNodes := resolver.NewNodeSetFromStringList(r.NodeDisruptionBudget.Status.WatchedNodes) - disruptedNodesCount := watchedNodes.Intersection(disruptedNodes).Len() + taintedNodes := taintedNodeSet(r.NodeDisruptionBudget.Status.TaintedNodes) + impactedNodes := watchedNodes.Intersection(disruptedNodes) + disruptedNodesCount := impactedNodes.Len() - impactedNodes.Intersection(taintedNodes).Len() return r.NodeDisruptionBudget.Status.DisruptionsAllowed-disruptedNodesCount >= 0 } @@ -271,7 +279,41 @@ func (r *NodeDisruptionBudgetResolver) GetSelectedNodes(ctx context.Context) (re return nodesFromPods, nil } -func (r *NodeDisruptionBudgetResolver) ResolveDisruption(ctx context.Context) (int, []nodedisruptionv1alpha1.Disruption, error) { +func taintedNodeSet(taintedNodes []nodedisruptionv1alpha1.TaintedNode) resolver.NodeSet { + names := make([]string, 0, len(taintedNodes)) + for _, taintedNode := range taintedNodes { + names = append(names, taintedNode.Name) + } + return resolver.NewNodeSetFromStringList(names) +} + +func (r *NodeDisruptionBudgetResolver) GetTaintedNodes(ctx context.Context) ([]nodedisruptionv1alpha1.TaintedNode, error) { + taintSelector := r.NodeDisruptionBudget.Spec.TaintSelector + if taintSelector == nil { + return nil, nil + } + + matchingTaints := map[string][]string{} + nodeSet, err := r.Resolver.GetMatchingNodeFromNodeSelector(ctx, r.NodeDisruptionBudget.Spec.NodeSelector, func(node *corev1.Node) bool { + taints := taintSelector.MatchingTaints(node) + if len(taints) == 0 { + return false + } + matchingTaints[node.Name] = taints + return true + }) + if err != nil { + return nil, err + } + + var taintedNodes []nodedisruptionv1alpha1.TaintedNode + for _, name := range resolver.NodeSetToStringList(nodeSet) { + taintedNodes = append(taintedNodes, nodedisruptionv1alpha1.TaintedNode{Name: name, Taints: matchingTaints[name]}) + } + return taintedNodes, nil +} + +func (r *NodeDisruptionBudgetResolver) ResolveDisruption(ctx context.Context, taintedNodes resolver.NodeSet) (int, []nodedisruptionv1alpha1.Disruption, error) { disruptions := []nodedisruptionv1alpha1.Disruption{} selectedNodes, err := r.GetSelectedNodes(ctx) if err != nil { @@ -279,6 +321,7 @@ func (r *NodeDisruptionBudgetResolver) ResolveDisruption(ctx context.Context) (i } disruptionCount := 0 + grantedNodes := resolver.NewNodeSetFromStringList(nil) opts := []client.ListOption{} nodeDisruptions := &nodedisruptionv1alpha1.NodeDisruptionList{} @@ -302,6 +345,7 @@ func (r *NodeDisruptionBudgetResolver) ResolveDisruption(ctx context.Context) (i if selectedNodes.Intersection(impactedNodes).Len() > 0 { if nd.Status.State == nodedisruptionv1alpha1.Granted { disruptionCount++ + grantedNodes = grantedNodes.Union(impactedNodes) } disruptions = append(disruptions, nodedisruptionv1alpha1.Disruption{ Name: nd.Name, @@ -309,5 +353,6 @@ func (r *NodeDisruptionBudgetResolver) ResolveDisruption(ctx context.Context) (i }) } } + disruptionCount += taintedNodes.Len() - taintedNodes.Intersection(grantedNodes).Len() return disruptionCount, disruptions, err } diff --git a/internal/controller/nodedisruptionbudget_controller_test.go b/internal/controller/nodedisruptionbudget_controller_test.go index 33804bc..470af9f 100644 --- a/internal/controller/nodedisruptionbudget_controller_test.go +++ b/internal/controller/nodedisruptionbudget_controller_test.go @@ -182,6 +182,87 @@ var _ = Describe("NodeDisruptionBudget controller", func() { }) }) + When("a selected node gets a matching taint", func() { + It("counts the node as disrupted until the taint is removed", func() { + By("creating a budget with a taint selector") + ndb := &nodedisruptionv1alpha1.NodeDisruptionBudget{ + TypeMeta: metav1.TypeMeta{ + APIVersion: "nodedisruption.criteo.com/v1alpha1", + Kind: "NodeDisruptionBudget", + }, + ObjectMeta: metav1.ObjectMeta{ + Name: NDBname, + Namespace: NDBNamespace, + }, + Spec: nodedisruptionv1alpha1.NodeDisruptionBudgetSpec{ + NodeSelector: metav1.LabelSelector{MatchLabels: nodeLabels1}, + MaxDisruptedNodes: 1, + TaintSelector: &nodedisruptionv1alpha1.TaintSelector{ + Include: []corev1.Toleration{ + {Operator: corev1.TolerationOpExists, Effect: corev1.TaintEffectNoSchedule}, + }, + Exclude: []corev1.Toleration{ + {Key: "crto.in/dedicated", Operator: corev1.TolerationOpExists}, + {Key: "node.kubernetes.io/not-ready", Operator: corev1.TolerationOpExists}, + }, + }, + }, + } + Expect(k8sClient.Create(ctx, ndb)).Should(Succeed()) + + NDBLookupKey := types.NamespacedName{Name: NDBname, Namespace: NDBNamespace} + createdNDB := &nodedisruptionv1alpha1.NodeDisruptionBudget{} + Eventually(func() []string { + Expect(k8sClient.Get(ctx, NDBLookupKey, createdNDB)).Should(Succeed()) + return createdNDB.Status.WatchedNodes + }, timeout, interval).Should(Equal([]string{"node1", "node2"})) + Expect(createdNDB.Status.TaintedNodes).Should(BeEmpty()) + Expect(createdNDB.Status.DisruptionsAllowed).Should(Equal(1)) + + originalNode2 := &corev1.Node{} + Expect(k8sClient.Get(ctx, types.NamespacedName{Name: "node2"}, originalNode2)).Should(Succeed()) + originalTaints := originalNode2.Spec.Taints + setNode2Taints := func(taints []corev1.Taint) { + node := &corev1.Node{} + Expect(k8sClient.Get(ctx, types.NamespacedName{Name: "node2"}, node)).Should(Succeed()) + node.Spec.Taints = taints + Expect(k8sClient.Update(ctx, node)).Should(Succeed()) + } + DeferCleanup(setNode2Taints, originalTaints) + + By("adding an excluded taint to node2") + setNode2Taints(append([]corev1.Taint{{Key: "crto.in/dedicated", Value: "team", Effect: corev1.TaintEffectNoSchedule}}, originalTaints...)) + Consistently(func() int { + Expect(k8sClient.Get(ctx, NDBLookupKey, createdNDB)).Should(Succeed()) + return createdNDB.Status.CurrentDisruptions + }, time.Second*2, interval).Should(Equal(0)) + + By("adding an included taint to node2") + setNode2Taints(append([]corev1.Taint{ + {Key: "crto.in/dedicated", Value: "team", Effect: corev1.TaintEffectNoSchedule}, + {Key: "node.cilium.io/agent-not-ready", Effect: corev1.TaintEffectNoSchedule}, + }, originalTaints...)) + Eventually(func() []nodedisruptionv1alpha1.TaintedNode { + Expect(k8sClient.Get(ctx, NDBLookupKey, createdNDB)).Should(Succeed()) + return createdNDB.Status.TaintedNodes + }, timeout, interval).Should(Equal([]nodedisruptionv1alpha1.TaintedNode{{ + Name: "node2", + Taints: []string{"node.cilium.io/agent-not-ready:NoSchedule"}, + }})) + Expect(createdNDB.Status.CurrentDisruptions).Should(Equal(1)) + Expect(createdNDB.Status.DisruptionsAllowed).Should(Equal(0)) + + By("removing the added taints from node2") + setNode2Taints(originalTaints) + Eventually(func() []nodedisruptionv1alpha1.TaintedNode { + Expect(k8sClient.Get(ctx, NDBLookupKey, createdNDB)).Should(Succeed()) + return createdNDB.Status.TaintedNodes + }, timeout, interval).Should(BeEmpty()) + Expect(createdNDB.Status.CurrentDisruptions).Should(Equal(0)) + Expect(createdNDB.Status.DisruptionsAllowed).Should(Equal(1)) + }) + }) + When("NodeSelector is empty", func() { It("watches no nodes", func() { By("creating a budget with empty NodeSelector") diff --git a/internal/controller/nodedisruptionbudget_taint_test.go b/internal/controller/nodedisruptionbudget_taint_test.go new file mode 100644 index 0000000..a2e833e --- /dev/null +++ b/internal/controller/nodedisruptionbudget_taint_test.go @@ -0,0 +1,131 @@ +package controller + +import ( + "context" + "testing" + + nodedisruptionv1alpha1 "github.com/criteo/node-disruption-controller/api/v1alpha1" + "github.com/criteo/node-disruption-controller/pkg/resolver" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/kubernetes/scheme" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" +) + +var ( + taintTestPoolLabels = map[string]string{"pool": "a"} + ciliumTaint = corev1.Taint{Key: "node.cilium.io/agent-not-ready", Effect: corev1.TaintEffectNoSchedule} + dedicatedTaint = corev1.Taint{Key: "crto.in/dedicated", Value: "team", Effect: corev1.TaintEffectNoSchedule} + hardTaintsSelector = &nodedisruptionv1alpha1.TaintSelector{ + Include: []corev1.Toleration{ + {Operator: corev1.TolerationOpExists, Effect: corev1.TaintEffectNoSchedule}, + {Operator: corev1.TolerationOpExists, Effect: corev1.TaintEffectNoExecute}, + }, + Exclude: []corev1.Toleration{ + {Key: "crto.in/dedicated", Operator: corev1.TolerationOpExists}, + }, + } +) + +func taintTestNode(name string, taints ...corev1.Taint) *corev1.Node { + return &corev1.Node{ + ObjectMeta: metav1.ObjectMeta{Name: name, Labels: map[string]string{"pool": "a", "kubernetes.io/hostname": name}}, + Spec: corev1.NodeSpec{Taints: taints}, + } +} + +func taintTestND(name string, state nodedisruptionv1alpha1.NodeDisruptionState, node string) *nodedisruptionv1alpha1.NodeDisruption { + return &nodedisruptionv1alpha1.NodeDisruption{ + ObjectMeta: metav1.ObjectMeta{Name: name}, + Spec: nodedisruptionv1alpha1.NodeDisruptionSpec{ + NodeSelector: metav1.LabelSelector{MatchLabels: map[string]string{"kubernetes.io/hostname": node}}, + }, + Status: nodedisruptionv1alpha1.NodeDisruptionStatus{State: state}, + } +} + +func syncedTaintTestNDB(t *testing.T, maxDisrupted int, taintSelector *nodedisruptionv1alpha1.TaintSelector, objects ...client.Object) *NodeDisruptionBudgetResolver { + s := runtime.NewScheme() + require.NoError(t, scheme.AddToScheme(s)) + require.NoError(t, nodedisruptionv1alpha1.AddToScheme(s)) + + c := fake.NewClientBuilder().WithScheme(s).WithObjects(objects...).Build() + ndb := &nodedisruptionv1alpha1.NodeDisruptionBudget{ + ObjectMeta: metav1.ObjectMeta{Name: "ndb"}, + Spec: nodedisruptionv1alpha1.NodeDisruptionBudgetSpec{ + NodeSelector: metav1.LabelSelector{MatchLabels: taintTestPoolLabels}, + MaxDisruptedNodes: maxDisrupted, + TaintSelector: taintSelector, + }, + } + r := &NodeDisruptionBudgetResolver{ + NodeDisruptionBudget: ndb, + Client: c, + Resolver: resolver.Resolver{Client: c}, + } + require.NoError(t, r.Sync(context.Background())) + return r +} + +func TestNDBTaintSelectorAbsentIgnoresTaints(t *testing.T) { + r := syncedTaintTestNDB(t, 1, nil, + taintTestNode("node1", ciliumTaint), + taintTestNode("node2"), + ) + + assert.Nil(t, r.NodeDisruptionBudget.Status.TaintedNodes) + assert.Equal(t, 0, r.NodeDisruptionBudget.Status.CurrentDisruptions) + assert.Equal(t, 1, r.NodeDisruptionBudget.Status.DisruptionsAllowed) +} + +func TestNDBTaintedNodesCountAsDisrupted(t *testing.T) { + r := syncedTaintTestNDB(t, 2, hardTaintsSelector, + taintTestNode("node1", ciliumTaint), + taintTestNode("node2", dedicatedTaint), + taintTestNode("node3"), + ) + + assert.Equal(t, []nodedisruptionv1alpha1.TaintedNode{{Name: "node1", Taints: []string{"node.cilium.io/agent-not-ready:NoSchedule"}}}, r.NodeDisruptionBudget.Status.TaintedNodes) + assert.Equal(t, 1, r.NodeDisruptionBudget.Status.CurrentDisruptions) + assert.Equal(t, 1, r.NodeDisruptionBudget.Status.DisruptionsAllowed) +} + +func TestNDBTaintedNodeUnderGrantedDisruptionCountedOnce(t *testing.T) { + r := syncedTaintTestNDB(t, 2, hardTaintsSelector, + taintTestNode("node1", ciliumTaint), + taintTestNode("node2", ciliumTaint), + taintTestNode("node3"), + taintTestND("nd-node1", nodedisruptionv1alpha1.Granted, "node1"), + ) + + assert.Equal(t, []nodedisruptionv1alpha1.TaintedNode{{Name: "node1", Taints: []string{"node.cilium.io/agent-not-ready:NoSchedule"}}, {Name: "node2", Taints: []string{"node.cilium.io/agent-not-ready:NoSchedule"}}}, r.NodeDisruptionBudget.Status.TaintedNodes) + assert.Equal(t, 2, r.NodeDisruptionBudget.Status.CurrentDisruptions) + assert.Equal(t, 0, r.NodeDisruptionBudget.Status.DisruptionsAllowed) +} + +func TestNDBPendingDisruptionDoesNotCoverTaintedNode(t *testing.T) { + r := syncedTaintTestNDB(t, 2, hardTaintsSelector, + taintTestNode("node1", ciliumTaint), + taintTestNode("node2"), + taintTestND("nd-node1", nodedisruptionv1alpha1.Pending, "node1"), + ) + + assert.Equal(t, 1, r.NodeDisruptionBudget.Status.CurrentDisruptions) + assert.Equal(t, 1, r.NodeDisruptionBudget.Status.DisruptionsAllowed) +} + +func TestNDBTolerateDisruptionOnTaintedNode(t *testing.T) { + r := syncedTaintTestNDB(t, 1, hardTaintsSelector, + taintTestNode("node1", ciliumTaint), + taintTestNode("node2"), + ) + + assert.Equal(t, 0, r.NodeDisruptionBudget.Status.DisruptionsAllowed) + assert.True(t, r.TolerateDisruption(resolver.NewNodeSetFromStringList([]string{"node1"}))) + assert.False(t, r.TolerateDisruption(resolver.NewNodeSetFromStringList([]string{"node2"}))) + assert.False(t, r.TolerateDisruption(resolver.NewNodeSetFromStringList([]string{"node1", "node2"}))) +} diff --git a/pkg/resolver/resolver.go b/pkg/resolver/resolver.go index 2cf0951..08589c6 100644 --- a/pkg/resolver/resolver.go +++ b/pkg/resolver/resolver.go @@ -165,7 +165,6 @@ func (r *Resolver) GetNodesFromNamespacedPVCSelector(ctx context.Context, pvcSel PVsToFetch := []string{} for _, pvc := range PVCs.Items { - logger.Info("PVC status", "pvc_name", pvc.Name, "pvc_phase", pvc.Status.Phase) if pvc.Status.Phase == corev1.ClaimBound { PVsToFetch = append(PVsToFetch, pvc.Spec.VolumeName) @@ -231,6 +230,10 @@ func (r *Resolver) GetNodesFromNamespacedPVCSelector(ctx context.Context, pvcSel } func (r *Resolver) GetNodeFromNodeSelector(ctx context.Context, nodeSelector metav1.LabelSelector) (NodeSet, error) { + return r.GetMatchingNodeFromNodeSelector(ctx, nodeSelector, nil) +} + +func (r *Resolver) GetMatchingNodeFromNodeSelector(ctx context.Context, nodeSelector metav1.LabelSelector, matches func(*corev1.Node) bool) (NodeSet, error) { nodeNames := set.New() nodeSet := NodeSet{Nodes: nodeNames} @@ -247,8 +250,10 @@ func (r *Resolver) GetNodeFromNodeSelector(ctx context.Context, nodeSelector met return nodeSet, err } - for _, node := range nodes.Items { - nodeNames.Insert(node.Name) + for i := range nodes.Items { + if matches == nil || matches(&nodes.Items[i]) { + nodeNames.Insert(nodes.Items[i].Name) + } } return nodeSet, nil }
ok boolean -
+ Ok is set to true when application manager preparation is complete and ready for the NodeDisruption to continue.
+
true
preparingboolean + Preparing is set to true when the application manager started preparation. Value is kept true even when the app is ready.
true