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
Constant Summary
Constants inherited from Kube::Cluster::Middleware
Instance Method Summary collapse
Methods inherited from Kube::Cluster::Middleware
Constructor Details
This class inherits a constructor from Kube::Cluster::Middleware
Instance Method Details
#call(manifest) ⇒ Object
25 26 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 58 59 60 |
# File 'lib/kube/cluster/middleware/pod_anti_affinity.rb', line 25 def call(manifest) topology_key = @opts.fetch(:topology_key, "kubernetes.io/hostname") weight = @opts.fetch(:weight, 1) manifest.resources.map! do |resource| filter(resource) do 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 end |