Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
171 changes: 171 additions & 0 deletions .github/test_topology_spread_constraints.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
"""Render checks for topologySpreadConstraints selectors and override order."""

import subprocess
import sys
import tempfile
import unittest
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
sys.dont_write_bytecode = True

OPTION_FILE = "charts/retool/ci/test-topology-spread-constraints-option.yaml"
# Deployments that read the global list in the option file.
SPREAD_DEPLOYMENTS = (
"retool",
"retool-workflow-backend",
"retool-workflow-worker",
"retool-agent-worker",
"retool-agent-eval-worker",
)
CODE_EXECUTOR = "retool-code-executor"
ZONE = "topology.kubernetes.io/zone"
HOSTNAME = "kubernetes.io/hostname"


def render(*extra_values):
"""Render the chart with the install values, the option file, and extra YAML snippets."""
command = [
"helm", "template", "retool", "charts/retool",
"--values", "charts/retool/ci/test-install-values.yaml",
"--values", OPTION_FILE,
]
with tempfile.TemporaryDirectory() as tmp:
for index, snippet in enumerate(extra_values):
path = Path(tmp) / f"extra-{index}.yaml"
path.write_text(snippet)
command.extend(("--values", str(path)))
return subprocess.check_output(command, cwd=ROOT, text=True)


def deployments(output):
"""Map Deployment name to its manifest text."""
found = {}
for document in output.split("\n---\n"):
if "\nkind: Deployment\n" not in f"\n{document}\n":
continue
metadata = document.split("\nmetadata:\n", 1)[1]
name = next(line.split(":", 1)[1].strip() for line in metadata.splitlines() if line.startswith(" name:"))
found[name] = document
return found


def block(text, header, indent):
"""Return the lines nested under `header` (deeper than `indent` spaces)."""
lines = text.splitlines()
start = lines.index(header) + 1
nested = []
for line in lines[start:]:
if line.strip() and len(line) - len(line.lstrip()) <= indent:
break
nested.append(line)
return nested


def labels(lines):
return dict(line.strip().split(": ", 1) for line in lines if line.strip())


def selector(deployment):
return labels(block(deployment, " matchLabels:", 4))


def constraints(deployment):
"""Parse the pod's topologySpreadConstraints into dicts with a matchLabels entry."""
if " topologySpreadConstraints:" not in deployment.splitlines():
return []
entries = []
for line in block(deployment, " topologySpreadConstraints:", 6):
if line.startswith(" - "):
entries.append([])
line = " " + line[len(" - "):]
entries[-1].append(line)
parsed = []
for entry in entries:
text = "\n".join(entry)
item = {
line.strip().split(": ", 1)[0]: line.strip().split(": ", 1)[1]
for line in entry
if line.startswith(" ") and not line.startswith(" ") and ": " in line
}
item["matchLabels"] = labels(block(text, " matchLabels:", 12)) if "matchLabels:" in text else {}
parsed.append(item)
return parsed


class TopologySpreadConstraintsTests(unittest.TestCase):
def test_default_renders_no_constraints(self):
output = subprocess.check_output(
["helm", "template", "retool", "charts/retool",
"--values", "charts/retool/ci/test-install-values.yaml",
"--set", "workflows.enabled=true", "--set", "agents.enabled=true",
"--set", "codeExecutor.enabled=true"],
cwd=ROOT, text=True,
)
self.assertNotIn("topologySpreadConstraints", output)

def test_global_list_selects_each_component_own_pods(self):
rendered = deployments(render())
for name in SPREAD_DEPLOYMENTS:
with self.subTest(deployment=name):
deployment = rendered[name]
spread = constraints(deployment)
self.assertEqual([c["topologyKey"] for c in spread], [ZONE, HOSTNAME])
self.assertEqual([c["whenUnsatisfiable"] for c in spread], ["DoNotSchedule", "ScheduleAnyway"])
for constraint in spread:
self.assertEqual(constraint["matchLabels"], selector(deployment))
selectors = [tuple(sorted(selector(rendered[name]).items())) for name in SPREAD_DEPLOYMENTS]
self.assertEqual(len(set(selectors)), len(selectors), "components must not share a selector")

def test_explicit_label_selector_is_kept(self):
spread = constraints(deployments(render())[CODE_EXECUTOR])
self.assertEqual(len(spread), 1)
self.assertEqual(spread[0]["whenUnsatisfiable"], "ScheduleAnyway")
self.assertEqual(spread[0]["matchLabels"], {"example.com/spread-group": "code-executor"})

def test_worker_override_applies_to_that_worker_only(self):
rendered = deployments(render(
"agents:\n"
" evalWorker:\n"
" topologySpreadConstraints:\n"
" - maxSkew: 3\n"
" topologyKey: kubernetes.io/hostname\n"
" whenUnsatisfiable: ScheduleAnyway\n"
))
eval_worker = constraints(rendered["retool-agent-eval-worker"])
self.assertEqual([(c["topologyKey"], c["maxSkew"]) for c in eval_worker], [(HOSTNAME, "3")])
self.assertEqual(eval_worker[0]["matchLabels"], selector(rendered["retool-agent-eval-worker"]))
for name in ("retool-agent-worker", "retool-workflow-worker"):
with self.subTest(deployment=name):
self.assertEqual([c["topologyKey"] for c in constraints(rendered[name])], [ZONE, HOSTNAME])

def test_parent_override_applies_to_its_workers(self):
rendered = deployments(render(
"agents:\n"
" topologySpreadConstraints:\n"
" - maxSkew: 4\n"
" topologyKey: topology.kubernetes.io/zone\n"
" whenUnsatisfiable: DoNotSchedule\n"
))
for name in ("retool-agent-worker", "retool-agent-eval-worker"):
with self.subTest(deployment=name):
self.assertEqual([c["maxSkew"] for c in constraints(rendered[name])], ["4"])
self.assertEqual([c["maxSkew"] for c in constraints(rendered["retool-workflow-worker"])], ["1", "2"])

def test_empty_override_disables_constraints(self):
rendered = deployments(render(
"agents:\n"
" evalWorker:\n"
" topologySpreadConstraints: []\n"
"codeExecutor:\n"
" topologySpreadConstraints: []\n"
))
for name in ("retool-agent-eval-worker", CODE_EXECUTOR):
with self.subTest(deployment=name):
self.assertEqual(constraints(rendered[name]), [])
self.assertEqual(len(constraints(rendered["retool-agent-worker"])), 2)


if __name__ == "__main__":
unittest.main()
2 changes: 2 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,8 @@ jobs:
python3 .github/test_global_pod_scheduling.py
- name: Verify js-executor capabilities and iptables env by version
run: python3 .github/test_js_executor_capabilities.py
- name: Verify topologySpreadConstraints selectors and override order
run: python3 .github/test_topology_spread_constraints.py

kubeconform-chart:
if: needs.changed.outputs.run == 'true'
Expand Down
2 changes: 1 addition & 1 deletion charts/retool/Chart.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ apiVersion: v2
name: retool
description: Deploy self-hosted Retool on Kubernetes.
type: application
version: 6.14.2
version: 6.14.3
maintainers:
- name: Retool Engineering
email: engineering+helm@retool.com
Expand Down
22 changes: 22 additions & 0 deletions charts/retool/ci/test-topology-spread-constraints-option.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
workflows:
enabled: true
agents:
enabled: true
codeExecutor:
enabled: true
# Component override with an explicit labelSelector, which is kept as-is.
topologySpreadConstraints:
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: ScheduleAnyway
labelSelector:
matchLabels:
example.com/spread-group: code-executor
# Global list without labelSelector: each component gets its own selector labels.
topologySpreadConstraints:
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: DoNotSchedule
- maxSkew: 2
topologyKey: kubernetes.io/hostname
whenUnsatisfiable: ScheduleAnyway
Comment thread
jrhuerta marked this conversation as resolved.
Resolved
35 changes: 35 additions & 0 deletions charts/retool/templates/_helpers.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -1915,3 +1915,38 @@ Usage: (include "retool.jsExecutor.requireNetAdminAndInstallIptables" .)
{{- fail (printf "rr.jsExecutor.requireNetAdminAndInstallIptables must be true, false, or null (got %s)" (kindOf $flag)) -}}
{{- end -}}
{{- end -}}

{{/*
Render the topologySpreadConstraints of one component.
"sources" lists the values blocks to read, most specific first (for example
the worker block, then its parent block, then .Values). The first block that
sets the topologySpreadConstraints key wins, so an explicit empty list
disables constraints for that component. Blocks without the key fall through.
A constraint that sets no labelSelector gets the component's selector labels,
so a single list (for example the global .Values.topologySpreadConstraints)
spreads each component on its own pods only.
Renders nothing when the resolved list is empty.
Usage:
include "retool.topologySpreadConstraints" (dict "sources" (list .Values.workflows .Values) "selectorLabels" (include "retool.workflowBackend.selectorLabels" . | fromYaml))
*/}}
{{- define "retool.topologySpreadConstraints" -}}
{{- $constraints := list -}}
{{- $found := false -}}
{{- range $source := .sources -}}
{{- if and (not $found) (kindIs "map" $source) (hasKey $source "topologySpreadConstraints") -}}
{{- $constraints = $source.topologySpreadConstraints | default list -}}
{{- $found = true -}}
{{- end -}}
{{- end -}}
{{- $out := list -}}
{{- range $constraints -}}
{{- $c := deepCopy . -}}
{{- if not (hasKey $c "labelSelector") -}}
{{- $_ := set $c "labelSelector" (dict "matchLabels" $.selectorLabels) -}}
{{- end -}}
{{- $out = append $out $c -}}
{{- end -}}
{{- if $out -}}
{{- toYaml $out -}}
{{- end -}}
{{- end -}}
5 changes: 5 additions & 0 deletions charts/retool/templates/_workers.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,11 @@ spec:
{{- if $affinity }}
affinity:
{{ toYaml $affinity | indent 8 }}
{{- end }}
{{- $topologySpreadConstraints := include "retool.topologySpreadConstraints" (dict "sources" (list $workerValues $parentValues $.Values) "selectorLabels" (include (printf "retool.%sWorker.selectorLabels" $workerType) $ | fromYaml)) }}
{{- if $topologySpreadConstraints }}
topologySpreadConstraints:
{{ $topologySpreadConstraints | indent 8 }}
{{- end }}
{{- if $.Values.nodeSelector }}
nodeSelector:
Expand Down
5 changes: 5 additions & 0 deletions charts/retool/templates/deployment_backend.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -442,6 +442,11 @@ spec:
{{- if .Values.affinity }}
affinity:
{{ toYaml .Values.affinity | indent 8 }}
{{- end }}
{{- $topologySpreadConstraints := include "retool.topologySpreadConstraints" (dict "sources" (list .Values) "selectorLabels" (include "retool.selectorLabels" . | fromYaml)) }}
{{- if $topologySpreadConstraints }}
topologySpreadConstraints:
{{ $topologySpreadConstraints | indent 8 }}
{{- end }}
{{- if .Values.nodeSelector }}
nodeSelector:
Expand Down
5 changes: 5 additions & 0 deletions charts/retool/templates/deployment_code_executor.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,11 @@ spec:
affinity:
{{ toYaml .Values.codeExecutor.affinity | indent 8 }}
{{- end }}
{{- $topologySpreadConstraints := include "retool.topologySpreadConstraints" (dict "sources" (list .Values.codeExecutor .Values) "selectorLabels" (include "retool.codeExecutor.selectorLabels" . | fromYaml)) }}
{{- if $topologySpreadConstraints }}
topologySpreadConstraints:
{{ $topologySpreadConstraints | indent 8 }}
{{- end }}
{{- if .Values.nodeSelector }}
nodeSelector:
{{ toYaml .Values.nodeSelector | indent 8 }}
Expand Down
5 changes: 5 additions & 0 deletions charts/retool/templates/deployment_workflows.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,11 @@ spec:
{{- if .Values.affinity }}
affinity:
{{ toYaml .Values.affinity | indent 8 }}
{{- end }}
{{- $topologySpreadConstraints := include "retool.topologySpreadConstraints" (dict "sources" (list .Values.workflows.backend .Values.workflows .Values) "selectorLabels" (include "retool.workflowBackend.selectorLabels" . | fromYaml)) }}
{{- if $topologySpreadConstraints }}
topologySpreadConstraints:
{{ $topologySpreadConstraints | indent 8 }}
{{- end }}
{{- if .Values.nodeSelector }}
nodeSelector:
Expand Down
25 changes: 25 additions & 0 deletions charts/retool/values.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

25 changes: 25 additions & 0 deletions values.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading