Class: Kube::Cluster::Manifest::Middleware::PodAntiAffinity

Inherits:
Kube::Cluster::Manifest::Middleware show all
Defined in:
lib/kube/cluster/manifest/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::Manifest::Middleware

CLUSTER_SCOPED_KINDS, POD_BEARING_KINDS

Instance Method Summary collapse

Constructor Details

#initialize(topology_key: "kubernetes.io/hostname", weight: 1) ⇒ PodAntiAffinity

Returns a new instance of PodAntiAffinity.



23
24
25
26
# File 'lib/kube/cluster/manifest/middleware/pod_anti_affinity.rb', line 23

def initialize(topology_key: "kubernetes.io/hostname", weight: 1)
  @topology_key = topology_key
  @weight = weight
end

Instance Method Details

#call(resource) ⇒ Object



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
# File 'lib/kube/cluster/manifest/middleware/pod_anti_affinity.rb', line 28

def call(resource)
  return resource unless pod_bearing?(resource)

  h = resource.to_h
  pod_spec = pod_template(h)
  return resource unless pod_spec

  # Don't overwrite existing affinity configuration.
  return resource if pod_spec[:affinity]

  match_labels = h.dig(:spec, :selector, :matchLabels)
  return resource unless match_labels && !match_labels.empty?

  pod_spec[:affinity] = {
    podAntiAffinity: {
      preferredDuringSchedulingIgnoredDuringExecution: [
        {
          weight: @weight,
          podAffinityTerm: {
            labelSelector: { matchLabels: match_labels },
            topologyKey: @topology_key,
          },
        },
      ],
    },
  }

  rebuild(resource, h)
end