Class: Kube::Cluster::Middleware::HPAForDeployment

Inherits:
Kube::Cluster::Middleware show all
Defined in:
lib/kube/cluster/middleware/hpa_for_deployment.rb

Overview

Generates a HorizontalPodAutoscaler for every pod-bearing resource that carries the app.kubernetes.io/autoscale label.

The label value encodes the min and max replicas as “min-max”:

.labels = { "app.kubernetes.io/autoscale": "1-5" }

Options:

cpu:    — target CPU utilization percentage (default: 75)
memory: — target memory utilization percentage (default: 80)

stack do
  use Middleware::HPAForDeployment
  use Middleware::HPAForDeployment, cpu: 60, memory: 70
end

Constant Summary collapse

LABEL =
:"app.kubernetes.io/autoscale"

Constants inherited from Kube::Cluster::Middleware

DEFAULT_FILTER

Instance Method Summary collapse

Methods inherited from Kube::Cluster::Middleware

build, #filter, #initialize

Constructor Details

This class inherits a constructor from Kube::Cluster::Middleware

Instance Method Details

#call(manifest) ⇒ 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/kube/cluster/middleware/hpa_for_deployment.rb', line 28

def call(manifest)
  generated = []
  cpu_target    = @opts.fetch(:cpu, 75)
  memory_target = @opts.fetch(:memory, 80)

  manifest.resources.each do |resource|
    filter(resource) do
      next unless resource.pod_bearing?

      value = resource.label(LABEL)
      next unless value

      min, max = parse_range(value)

      h = resource.to_h
      name      = h.dig(:metadata, :name)
      namespace = h.dig(:metadata, :namespace)
      labels    = h.dig(:metadata, :labels) || {}
      api_version = h[:apiVersion] || "apps/v1"
      resource_kind = resource.kind

      generated << Kube::Cluster["HorizontalPodAutoscaler"].new {
        .name      = name
        .namespace = namespace if namespace
        .labels    = labels.reject { |k, _| k == LABEL }

        spec.scaleTargetRef = {
          apiVersion: api_version,
          kind:       resource_kind,
          name:       name,
        }
        spec.minReplicas = min
        spec.maxReplicas = max
        spec.metrics = [
          {
            type: "Resource",
            resource: {
              name: "cpu",
              target: { type: "Utilization", averageUtilization: cpu_target },
            },
          },
          {
            type: "Resource",
            resource: {
              name: "memory",
              target: { type: "Utilization", averageUtilization: memory_target },
            },
          },
        ]
      }
    end
  end

  manifest.resources.concat(generated)
end