diff --git a/charts/floci/Chart.yaml b/charts/floci/Chart.yaml index 40be30839b..afd3e8cdad 100644 --- a/charts/floci/Chart.yaml +++ b/charts/floci/Chart.yaml @@ -4,7 +4,7 @@ description: Floci, the local AWS emulator, as a single in-cluster endpoint for type: application # Chart version. Bump it on every change under charts/floci: `ct lint` fails a pull # request that changes the chart without a new version. -version: 0.1.0 +version: 0.2.0 # Floci release the chart deploys by default (image.tag falls back to it). appVersion: "2.4.0" kubeVersion: ">=1.25.0-0" diff --git a/charts/floci/templates/_helpers.tpl b/charts/floci/templates/_helpers.tpl index 9c3eb95c67..efd047dcc5 100644 --- a/charts/floci/templates/_helpers.tpl +++ b/charts/floci/templates/_helpers.tpl @@ -197,6 +197,8 @@ and extraEnv cannot set any of these. "FLOCI_SERVICES_LAMBDA_KUBERNETES_NAMESPACE" "floci.lambda.kubernetes.namespace" "FLOCI_SERVICES_LAMBDA_KUBERNETES_INIT_IMAGE" "floci.lambda.kubernetes.initImage" "FLOCI_SERVICES_LAMBDA_KUBERNETES_LABELS" "floci.lambda.kubernetes.labels" + "FLOCI_SERVICES_LAMBDA_KUBERNETES_NODE_SELECTOR" "floci.lambda.kubernetes.nodeSelector" + "FLOCI_SERVICES_LAMBDA_KUBERNETES_TOLERATIONS" "floci.lambda.kubernetes.tolerations" "FLOCI_SERVICES_LAMBDA_KUBERNETES_FLOCI_ADDRESS" "floci.lambda.kubernetes.flociAddress" | toJson }} {{- end }} @@ -245,6 +247,28 @@ sets fails the render and names the value to use instead. {{- with $k8s.labels }} {{- $_ := set $env "FLOCI_SERVICES_LAMBDA_KUBERNETES_LABELS" (join "," .) }} {{- end }} +{{- with $k8s.nodeSelector }} +{{- $terms := list }} +{{- range $key, $value := . }} +{{- $terms = append $terms (printf "%s=%s" $key $value) }} +{{- end }} +{{- $_ := set $env "FLOCI_SERVICES_LAMBDA_KUBERNETES_NODE_SELECTOR" (join "," $terms) }} +{{- end }} +{{- with $k8s.tolerations }} +{{- /* Each toleration becomes the taint it tolerates in kubectl taint syntax, the form Floci parses. */}} +{{- $taints := list }} +{{- range . }} +{{- $taint := .key }} +{{- if ne (default "Equal" .operator) "Exists" }} +{{- $taint = printf "%s=%s" $taint (default "" .value) }} +{{- end }} +{{- with .effect }} +{{- $taint = printf "%s:%s" $taint . }} +{{- end }} +{{- $taints = append $taints $taint }} +{{- end }} +{{- $_ := set $env "FLOCI_SERVICES_LAMBDA_KUBERNETES_TOLERATIONS" (join "," $taints) }} +{{- end }} {{- with $k8s.flociAddress }} {{- $_ := set $env "FLOCI_SERVICES_LAMBDA_KUBERNETES_FLOCI_ADDRESS" . }} {{- end }} diff --git a/charts/floci/tests/deployment_test.yaml b/charts/floci/tests/deployment_test.yaml index f8777a7797..39b0135fef 100644 --- a/charts/floci/tests/deployment_test.yaml +++ b/charts/floci/tests/deployment_test.yaml @@ -121,6 +121,13 @@ tests: floci.lambda.kubernetes.namespace: lambdas floci.lambda.kubernetes.initImage: busybox:1.37 floci.lambda.kubernetes.labels: [team=platform, env=ci] + floci.lambda.kubernetes.nodeSelector: + workload-type: lambda + kubernetes.io/arch: amd64 + floci.lambda.kubernetes.tolerations: + - { key: workload-type, operator: Equal, value: lambda, effect: NoSchedule } + - { key: spot, operator: Exists, effect: NoExecute } + - { key: example.com/dedicated, value: ci } floci.lambda.kubernetes.flociAddress: 10.0.0.7 asserts: - equal: @@ -146,6 +153,10 @@ tests: value: team=platform,env=ci - name: FLOCI_SERVICES_LAMBDA_KUBERNETES_NAMESPACE value: lambdas + - name: FLOCI_SERVICES_LAMBDA_KUBERNETES_NODE_SELECTOR + value: kubernetes.io/arch=amd64,workload-type=lambda + - name: FLOCI_SERVICES_LAMBDA_KUBERNETES_TOLERATIONS + value: workload-type=lambda:NoSchedule,spot:NoExecute,example.com/dedicated=ci - name: FLOCI_STORAGE_MODE value: memory - name: FLOCI_STORAGE_PERSISTENT_PATH diff --git a/charts/floci/values.schema.json b/charts/floci/values.schema.json index 61474b8a25..ea5097b1ca 100644 --- a/charts/floci/values.schema.json +++ b/charts/floci/values.schema.json @@ -81,6 +81,23 @@ "namespace": { "type": "string" }, "initImage": { "type": "string" }, "labels": { "type": "array", "items": { "type": "string", "pattern": "^[^=,]+=[^,]*$" } }, + "nodeSelector": { "type": "object", "propertyNames": { "pattern": "^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?[a-zA-Z0-9]([-a-zA-Z0-9_.]{0,61}[a-zA-Z0-9])?$" }, "additionalProperties": { "type": "string", "pattern": "^([a-zA-Z0-9]([-a-zA-Z0-9_.]{0,61}[a-zA-Z0-9])?)?$" } }, + "tolerations": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "required": ["key"], + "properties": { + "key": { "type": "string", "pattern": "^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?[a-zA-Z0-9]([-a-zA-Z0-9_.]{0,61}[a-zA-Z0-9])?$" }, + "operator": { "enum": ["Equal", "Exists"] }, + "value": { "type": "string", "pattern": "^([a-zA-Z0-9]([-a-zA-Z0-9_.]{0,61}[a-zA-Z0-9])?)?$" }, + "effect": { "enum": ["NoSchedule", "PreferNoSchedule", "NoExecute"] } + }, + "if": { "required": ["operator"], "properties": { "operator": { "const": "Exists" } } }, + "then": { "not": { "required": ["value"] } } + } + }, "flociAddress": { "type": "string", "pattern": "^$|^[A-Za-z0-9.-]+$" } } } diff --git a/charts/floci/values.yaml b/charts/floci/values.yaml index 4e60acb86d..e04675515b 100644 --- a/charts/floci/values.yaml +++ b/charts/floci/values.yaml @@ -72,6 +72,13 @@ floci: initImage: "" # -- Extra labels for Lambda pods, as "key=value" strings. labels: [] + # -- Node selector of Lambda pods + nodeSelector: {} + # -- Tolerations of Lambda pods, the same list as a pod's `tolerations`. Each takes + # `key` (required), `operator` (`Equal`, the default, or `Exists`), `value` and + # `effect`; leave out `effect` to tolerate every effect. `tolerationSeconds` and an + # empty `key` are not supported. + tolerations: [] # -- Address Lambda pods use to reach Floci. Empty lets Floci advertise its own pod # IP, which is right for an in-cluster install. flociAddress: "" diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.md index 9f22ad8b17..69ccbf8a08 100644 --- a/docs/configuration/environment-variables.md +++ b/docs/configuration/environment-variables.md @@ -335,6 +335,8 @@ See [Initialization Hooks](./initialization-hooks.md) for lifecycle phases and s | `FLOCI_SERVICES_LAMBDA_EXECUTOR` | `docker` | Execution backend for Lambda environments: `docker` (containers) or `kubernetes` (pods) | | `FLOCI_SERVICES_LAMBDA_KUBERNETES_NAMESPACE` | `default` | Namespace Lambda pods are created in | | `FLOCI_SERVICES_LAMBDA_KUBERNETES_LABELS` | _(none)_ | Extra pod labels as comma-separated `key=value` entries | +| `FLOCI_SERVICES_LAMBDA_KUBERNETES_NODE_SELECTOR` | _(none)_ | Pod node selector as comma-separated `key=value` entries; an invalid entry fails the cold start to avoid scheduling the pod on unsupported nodes | +| `FLOCI_SERVICES_LAMBDA_KUBERNETES_TOLERATIONS` | _(none)_ | Pod tolerations as comma-separated taints in `kubectl taint` syntax: `key=value:Effect` (operator `Equal`) or `key:Effect` (operator `Exists`); leave out `:Effect` to tolerate every effect | | `FLOCI_SERVICES_LAMBDA_KUBERNETES_FLOCI_ADDRESS` | _(none)_ | Host/IP Lambda pods use to reach Floci; auto-detected when Floci runs in-cluster | | `FLOCI_SERVICES_LAMBDA_KUBERNETES_INIT_IMAGE` | `busybox:1.36` | Init-container image that downloads function code into the pod (needs `sh`, `wget`, `unzip`) | diff --git a/docs/services/lambda.md b/docs/services/lambda.md index d0b87226ea..72a439a28d 100644 --- a/docs/services/lambda.md +++ b/docs/services/lambda.md @@ -729,6 +729,8 @@ Configuration resource reads and `ListFunctionsByCodeSigningConfig` return | `FLOCI_SERVICES_LAMBDA_EXECUTOR` | `docker` | Execution backend: `docker` (containers) or `kubernetes` (pods) | | `FLOCI_SERVICES_LAMBDA_KUBERNETES_NAMESPACE` | `default` | Namespace Lambda pods are created in | | `FLOCI_SERVICES_LAMBDA_KUBERNETES_LABELS` | *(unset)* | Extra pod labels as comma-separated `key=value` entries | +| `FLOCI_SERVICES_LAMBDA_KUBERNETES_NODE_SELECTOR` | *(unset)* | Pod node selector as comma-separated `key=value` entries; an invalid entry fails the cold start to avoid scheduling the pod on unsupported nodes | +| `FLOCI_SERVICES_LAMBDA_KUBERNETES_TOLERATIONS` | *(unset)* | Pod tolerations as comma-separated taints in `kubectl taint` syntax: `key=value:Effect` (operator `Equal`) or `key:Effect` (operator `Exists`); leave out `:Effect` to tolerate every effect | | `FLOCI_SERVICES_LAMBDA_KUBERNETES_FLOCI_ADDRESS` | *(unset)* | Host/IP pods use to reach Floci; auto-detected when Floci runs in-cluster | | `FLOCI_SERVICES_LAMBDA_KUBERNETES_INIT_IMAGE` | `busybox:1.36` | Init-container image that downloads function code (needs `sh`, `wget`, `unzip`) | diff --git a/src/main/java/io/floci/aws/config/EmulatorConfig.java b/src/main/java/io/floci/aws/config/EmulatorConfig.java index bbcba9f023..743ca9d857 100644 --- a/src/main/java/io/floci/aws/config/EmulatorConfig.java +++ b/src/main/java/io/floci/aws/config/EmulatorConfig.java @@ -3719,6 +3719,25 @@ public interface EmulatorConfig { */ Optional> labels(); + /** + * Node selector of Lambda pods, as {@code key=value} entries with label syntax. + * + * Env var: FLOCI_SERVICES_LAMBDA_KUBERNETES_NODE_SELECTOR (comma-separated) + */ + Optional> nodeSelector(); + + /** + * Tolerations of Lambda pods, each written as the taint it tolerates in + * {@code kubectl taint} syntax: {@code key=value:Effect} tolerates that taint + * (operator {@code Equal}), {@code key:Effect} tolerates every value of the key + * (operator {@code Exists}), and an entry without {@code :Effect} tolerates every + * effect. Effects are {@code NoSchedule}, {@code PreferNoSchedule} and + * {@code NoExecute}. + * + * Env var: FLOCI_SERVICES_LAMBDA_KUBERNETES_TOLERATIONS (comma-separated) + */ + Optional> tolerations(); + /** * Host or IP that Lambda pods use to reach Floci (the Runtime API port range * and the main port). When unset, Floci auto-detects its own pod address if diff --git a/src/main/java/io/floci/aws/services/lambda/launcher/kubernetes/LambdaPodSpecFactory.java b/src/main/java/io/floci/aws/services/lambda/launcher/kubernetes/LambdaPodSpecFactory.java index a67d70d2bd..3d0cddfbd6 100644 --- a/src/main/java/io/floci/aws/services/lambda/launcher/kubernetes/LambdaPodSpecFactory.java +++ b/src/main/java/io/floci/aws/services/lambda/launcher/kubernetes/LambdaPodSpecFactory.java @@ -15,6 +15,8 @@ import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; +import java.util.Set; +import java.util.function.Consumer; import java.util.regex.Pattern; /** @@ -31,9 +33,12 @@ public class LambdaPodSpecFactory { /** Label key: optional DNS-subdomain prefix (dot-separated valid segments), then a 63-char-max name. */ private static final Pattern LABEL_KEY = Pattern.compile("([a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?[a-zA-Z0-9]([-a-zA-Z0-9_.]{0,61}[a-zA-Z0-9])?"); + /** A label key's DNS-subdomain prefix is at most 253 characters */ + private static final int MAX_LABEL_KEY_PREFIX_LENGTH = 253; /** Label value: empty, or 63-char-max alphanumeric-bounded. */ private static final Pattern LABEL_VALUE = Pattern.compile("([a-zA-Z0-9]([-a-zA-Z0-9_.]{0,61}[a-zA-Z0-9])?)?"); + private static final Set TAINT_EFFECTS = Set.of("NoSchedule", "PreferNoSchedule", "NoExecute"); static final String MANAGED_BY_LABEL = "app.kubernetes.io/managed-by"; static final String MANAGED_BY_VALUE = "floci"; @@ -163,6 +168,19 @@ public class LambdaPodSpecFactory { ObjectNode spec = nodes.objectNode() .put("restartPolicy", "Never") .put("terminationGracePeriodSeconds", 5); + + Map nodeSelector = podNodeSelector(); + if (!nodeSelector.isEmpty()) { + ObjectNode selector = nodes.objectNode(); + nodeSelector.forEach(selector::put); + spec.set("nodeSelector", selector); + } + + ArrayNode tolerations = podTolerations(nodes); + if (!tolerations.isEmpty()) { + spec.set("tolerations", tolerations); + } + spec.set("initContainers", initContainers); spec.set("containers", nodes.arrayNode().add(runtime)); spec.set("volumes", volumes); @@ -212,21 +230,11 @@ public class LambdaPodSpecFactory { } Map podLabels(String functionName) { - LinkedHashMap labels = new LinkedHashMap<>(); - config.services().lambda().kubernetes().labels().orElse(List.of()).forEach(entry -> { - int eq = entry.indexOf('='); - String key = eq > 0 ? entry.substring(0, eq).trim() : ""; - String value = eq > 0 ? entry.substring(eq + 1).trim() : ""; - // Invalid entries are dropped, not sanitized: a silently rewritten label - // would no longer match the NetworkPolicy/selector the user wrote it for, - // and the API server would reject the pod at cold start otherwise. - if (LABEL_KEY.matcher(key).matches() && LABEL_VALUE.matcher(value).matches()) { - labels.put(key, value); - } else { - LOG.warnv("Ignoring invalid Lambda pod label entry ''{0}'' " - + "(expected key=value with Kubernetes label syntax)", entry); - } - }); + LinkedHashMap labels = + keyValues(config.services().lambda().kubernetes().labels(), + "FLOCI_SERVICES_LAMBDA_KUBERNETES_LABELS", entry -> LOG.warnv( + "Ignoring invalid Lambda pod label entry ''{0}'' " + + "(expected key=value with Kubernetes label syntax)", entry)); // Managed labels go last so user entries can never overwrite them — the // orphan sweep selects on these, and an overwritten label leaks pods forever. labels.put(MANAGED_BY_LABEL, MANAGED_BY_VALUE); @@ -235,6 +243,81 @@ public class LambdaPodSpecFactory { return labels; } + Map podNodeSelector() { + return keyValues(config.services().lambda().kubernetes().nodeSelector(), + "FLOCI_SERVICES_LAMBDA_KUBERNETES_NODE_SELECTOR", entry -> { + throw new IllegalStateException("Invalid Lambda pod node selector entry '" + entry + + "' in FLOCI_SERVICES_LAMBDA_KUBERNETES_NODE_SELECTOR (expected key=value with Kubernetes label syntax)"); + }); + } + + /** + * Each entry is the taint it tolerates in {@code kubectl taint} syntax: + * {@code key=value:Effect} (Equal), {@code key:Effect} (Exists), with {@code :Effect} + * optional to tolerate every effect. + */ + ArrayNode podTolerations(JsonNodeFactory nodes) { + ArrayNode tolerations = nodes.arrayNode(); + config.services().lambda().kubernetes().tolerations().orElse(List.of()).forEach(entry -> { + String taint = entry.trim(); + String effect = null; + int colon = taint.lastIndexOf(':'); + if (colon >= 0) { + effect = taint.substring(colon + 1).trim(); + taint = taint.substring(0, colon).trim(); + } + int eq = taint.indexOf('='); + String key = eq >= 0 ? taint.substring(0, eq).trim() : taint; + String value = eq >= 0 ? taint.substring(eq + 1).trim() : null; + if (!isValidLabelKey(key) + || (value != null && !LABEL_VALUE.matcher(value).matches()) + || (effect != null && !TAINT_EFFECTS.contains(effect))) { + LOG.warnv("Ignoring invalid Lambda pod toleration entry ''{0}'' " + + "(expected key[=value][:NoSchedule|PreferNoSchedule|NoExecute])", entry); + return; + } + ObjectNode toleration = nodes.objectNode().put("key", key); + if (value == null) { + toleration.put("operator", "Exists"); + } else { + toleration.put("operator", "Equal").put("value", value); + } + if (effect != null) { + toleration.put("effect", effect); + } + tolerations.add(toleration); + }); + return tolerations; + } + + private static LinkedHashMap keyValues(Optional> entries, String setting, + Consumer onInvalid) { + LinkedHashMap result = new LinkedHashMap<>(); + entries.orElse(List.of()).forEach(entry -> { + int eq = entry.indexOf('='); + String key = eq > 0 ? entry.substring(0, eq).trim() : ""; + String value = eq > 0 ? entry.substring(eq + 1).trim() : ""; + // Invalid entries are dropped, not sanitized: a silently rewritten entry + // would no longer match the NetworkPolicy/selector or node it was written + // for, and the API server would reject the pod at cold start otherwise. + if (isValidLabelKey(key) && LABEL_VALUE.matcher(value).matches()) { + String previous = result.put(key, value); + if (previous != null && !previous.equals(value)) { + LOG.warnv("Entry ''{0}'' in {1} replaces the earlier value ''{2}'' for key ''{3}'' " + + "(a Kubernetes label key holds one value)", entry, setting, previous, key); + } + } else { + onInvalid.accept(entry); + } + }); + return result; + } + + private static boolean isValidLabelKey(String key) { + int slash = key.indexOf('/'); + return LABEL_KEY.matcher(key).matches() && slash <= MAX_LABEL_KEY_PREFIX_LENGTH; + } + /** Selector matching every pod this Floci instance's Lambda executor manages. */ static Map managedPodSelector() { return Map.of(MANAGED_BY_LABEL, MANAGED_BY_VALUE, SERVICE_LABEL, SERVICE_VALUE); diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 47f62e3d92..66540ef836 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -519,6 +519,10 @@ floci: # namespace: default # Namespace Lambda pods are created in # labels: # Extra pod labels, key=value entries # - team=platform + # node-selector: # Pod node selector, key=value entries + # - workload-type=lambda + # tolerations: # Taints the pods tolerate: key=value:Effect (Equal) or key:Effect (Exists) + # - workload-type=lambda:NoSchedule # floci-address: # Host/IP pods use to reach Floci; auto-detected in-cluster # init-image: busybox:1.36 # Init container image (needs sh, wget, unzip) hot-reload: diff --git a/src/test/java/io/floci/aws/services/lambda/launcher/kubernetes/LambdaPodSpecFactoryTest.java b/src/test/java/io/floci/aws/services/lambda/launcher/kubernetes/LambdaPodSpecFactoryTest.java index f8f3b8563e..36a587e090 100644 --- a/src/test/java/io/floci/aws/services/lambda/launcher/kubernetes/LambdaPodSpecFactoryTest.java +++ b/src/test/java/io/floci/aws/services/lambda/launcher/kubernetes/LambdaPodSpecFactoryTest.java @@ -6,6 +6,8 @@ import io.floci.aws.config.EmulatorConfig; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoSettings; @@ -18,6 +20,7 @@ import java.util.Map; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -46,6 +49,8 @@ class LambdaPodSpecFactoryTest { when(tls.enabled()).thenReturn(false); when(kubernetes.initImage()).thenReturn("busybox:1.36"); when(kubernetes.labels()).thenReturn(Optional.empty()); + when(kubernetes.nodeSelector()).thenReturn(Optional.empty()); + when(kubernetes.tolerations()).thenReturn(Optional.empty()); factory = new LambdaPodSpecFactory(config); } @@ -144,6 +149,91 @@ class LambdaPodSpecFactoryTest { .doesNotContainKeys("malformed", "a", "bad key"); } + @Test + void podHasNoNodeSelectorOrTolerationsByDefault() { + JsonNode spec = spec(buildZipPod()); + assertThat(spec.has("nodeSelector")).isFalse(); + assertThat(spec.has("tolerations")).isFalse(); + } + + @Test + void nodeSelectorIsParsed() { + when(kubernetes.nodeSelector()).thenReturn(Optional.of( + List.of("workload-type=backend", " kubernetes.io/arch = amd64 "))); + assertThat(stringMap(spec(buildZipPod()).path("nodeSelector"))) + .containsExactly(Map.entry("workload-type", "backend"), + Map.entry("kubernetes.io/arch", "amd64")); + } + + @ParameterizedTest + @ValueSource(strings = {"bad key=x", "a=b=c", "Kubernetes.io/arch=amd64", "=x", "no-equals"}) + void invalidNodeSelectorEntryFailsTheColdStart(String invalid) { + // Dropping a selector term would widen where the pod may run, so it fails instead. + when(kubernetes.nodeSelector()).thenReturn(Optional.of(List.of("workload-type=backend", invalid))); + assertThatThrownBy(this::buildZipPod) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("'" + invalid + "'") + .hasMessageContaining("FLOCI_SERVICES_LAMBDA_KUBERNETES_NODE_SELECTOR"); + } + + @Test + void repeatedNodeSelectorKeyKeepsTheLastValue() { + when(kubernetes.nodeSelector()).thenReturn(Optional.of( + List.of("workload-type=backend", "workload-type=gpu"))); + assertThat(stringMap(spec(buildZipPod()).path("nodeSelector"))) + .containsExactly(Map.entry("workload-type", "gpu")); + } + + @Test + void labelKeyPrefixIsLimitedTo253Characters() { + String longestPrefix = "a".repeat(253); + String overlongPrefix = "a".repeat(254); + when(kubernetes.labels()).thenReturn(Optional.of( + List.of(longestPrefix + "/ok=x", overlongPrefix + "/too-long=x"))); + when(kubernetes.tolerations()).thenReturn(Optional.of( + List.of(longestPrefix + "/ok:NoSchedule", overlongPrefix + "/too-long:NoSchedule"))); + JsonNode pod = buildZipPod(); + assertThat(stringMap(pod.path("metadata").path("labels"))) + .containsKey(longestPrefix + "/ok") + .doesNotContainKey(overlongPrefix + "/too-long"); + assertThat(elements(spec(pod).path("tolerations"))) + .extracting(n -> n.path("key").asText()) + .containsExactly(longestPrefix + "/ok"); + } + + @Test + void nodeSelectorKeyWithOverlongPrefixFailsTheColdStart() { + String entry = "a".repeat(254) + "/too-long=x"; + when(kubernetes.nodeSelector()).thenReturn(Optional.of(List.of(entry))); + assertThatThrownBy(this::buildZipPod) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("'" + entry + "'"); + } + + @Test + void tolerationsAreWrittenAsTheToleratedTaint() { + when(kubernetes.tolerations()).thenReturn(Optional.of( + List.of("workload-type=backend:NoSchedule", "dedicated:NoExecute", "example.com/spot"))); + assertThat(elements(spec(buildZipPod()).path("tolerations"))) + .extracting(n -> n.path("key").asText(), n -> n.path("operator").asText(), + n -> n.path("value").asText(null), n -> n.path("effect").asText(null)) + .containsExactly( + tuple("workload-type", "Equal", "backend", "NoSchedule"), + tuple("dedicated", "Exists", null, "NoExecute"), + tuple("example.com/spot", "Exists", null, null)); + } + + @Test + void invalidTolerationsAreDropped() { + // The API server rejects an unknown effect or a key with spaces, so such + // entries must never reach the pod spec. + when(kubernetes.tolerations()).thenReturn(Optional.of( + List.of("a=b:Sometimes", "bad key:NoSchedule", "=x:NoSchedule", "team=a=b", "spot:NoSchedule"))); + assertThat(elements(spec(buildZipPod()).path("tolerations"))) + .extracting(n -> n.path("key").asText()) + .containsExactly("spot"); + } + @Test void layersAreDownloadedInOrderIntoOpt() { ObjectNode pod = factory.buildPod("floci-lambda-my-fn-abc12345", "my-fn",