Class: Kube::Cluster::Middleware::PodAntiAffinity
- Inherits:
-
Kube::Cluster::Middleware
- Object
- Kube::Cluster::Middleware
- Kube::Cluster::Middleware::PodAntiAffinity
- Defined in:
- lib/kube/cluster/middleware/pod_anti_affinity.rb
Overview
Injects soft pod anti-affinity on pod-bearing resources so that pods prefer to spread across nodes.
The anti-affinity uses the resource’s own matchLabels from spec.selector.matchLabels as the label selector, and kubernetes.io/hostname as the topology key.
Resources that already have spec.template.spec.affinity set are left untouched.
stack do
use Middleware::PodAntiAffinity
use Middleware::PodAntiAffinity, topology_key: "topology.kubernetes.io/zone"
end
Instance Method Summary collapse
- #call(manifest) ⇒ Object
-
#initialize(topology_key: "kubernetes.io/hostname", weight: 1) ⇒ PodAntiAffinity
constructor
A new instance of PodAntiAffinity.
Constructor Details
#initialize(topology_key: "kubernetes.io/hostname", weight: 1) ⇒ PodAntiAffinity
Returns a new instance of PodAntiAffinity.
22 23 24 25 |
# File 'lib/kube/cluster/middleware/pod_anti_affinity.rb', line 22 def initialize(topology_key: "kubernetes.io/hostname", weight: 1) @topology_key = topology_key @weight = weight end |
Instance Method Details
#call(manifest) ⇒ Object
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
# File 'lib/kube/cluster/middleware/pod_anti_affinity.rb', line 27 def call(manifest) manifest.resources.map! do |resource| next resource unless resource.pod_bearing? h = resource.to_h pod_spec = resource.pod_template(h) next resource unless pod_spec # Don't overwrite existing affinity configuration. next resource if pod_spec[:affinity] match_labels = h.dig(:spec, :selector, :matchLabels) next resource unless match_labels && !match_labels.empty? pod_spec[:affinity] = { podAntiAffinity: { preferredDuringSchedulingIgnoredDuringExecution: [ { weight: @weight, podAffinityTerm: { labelSelector: { matchLabels: match_labels }, topologyKey: @topology_key, }, }, ], }, } resource.rebuild(h) end end |