alien-core 3.3.65

Deploy software into your customers' cloud accounts and keep it fully managed
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
//! Compute pools on Kubernetes use administrator-managed node capacity.
//!
//! Hardware sizes and machine counts are advisory. Execution requirements must
//! either be translated into Pod placement or rejected before workloads start.

use crate::{
    instance_catalog::Architecture, CapacityGroup, ComputeCluster, Container, Daemon, Stack,
    WorkloadPriority, ENV_ALIEN_KUBERNETES_PRIORITY_CLASSES,
};
use std::collections::{BTreeMap, HashSet};

/// Validate logical pools without querying or provisioning Kubernetes nodes.
pub fn validate_kubernetes_compute(stack: &Stack) -> Vec<String> {
    let mut errors = Vec::new();
    if let Err(message) = kubernetes_compute_architecture(stack) {
        errors.push(message);
    }
    for (_, entry) in stack.resources() {
        let Some(cluster) = entry.config.downcast_ref::<ComputeCluster>() else {
            continue;
        };
        let mut names = HashSet::new();
        if cluster.capacity_groups.is_empty() {
            errors.push(format!(
                "ComputeCluster '{}' must declare at least one pool on Kubernetes",
                cluster.id
            ));
        }
        for pool in &cluster.capacity_groups {
            if pool.group_id.is_empty() || !names.insert(pool.group_id.as_str()) {
                errors.push(format!(
                    "ComputeCluster '{}' has an empty or duplicate pool '{}'",
                    cluster.id, pool.group_id
                ));
            }
            if pool.min_size > pool.max_size {
                errors.push(format!(
                    "ComputeCluster '{}' pool '{}' has min greater than max",
                    cluster.id, pool.group_id
                ));
            }
            if pool.instance_type.is_some()
                || pool.nested_virtualization == Some(true)
                || pool
                    .profile
                    .as_ref()
                    .is_some_and(|profile| profile.gpu.is_some())
            {
                errors.push(format!("ComputeCluster '{}' pool '{}' requests instance type, GPU, or nested virtualization; Kubernetes cannot enforce these node requirements", cluster.id, pool.group_id));
            }
        }
        if cluster
            .dynamic_container_pool
            .as_ref()
            .is_some_and(|name| !names.contains(name.as_str()))
        {
            errors.push(format!(
                "ComputeCluster '{}' dynamic container pool does not exist",
                cluster.id
            ));
        }
        if !cluster.selected_failure_domains.is_empty()
            || cluster
                .container_cidr
                .as_deref()
                .is_some_and(|cidr| cidr != "10.244.0.0/16")
        {
            errors.push(format!("ComputeCluster '{}' configures provider failure domains or a container CIDR; existing Kubernetes networking and node topology are administrator-managed", cluster.id));
        }
    }
    for (_, entry) in stack.resources() {
        let placement = if let Some(container) = entry.config.downcast_ref::<Container>() {
            kubernetes_container_pool(stack, container)
        } else if let Some(daemon) = entry.config.downcast_ref::<Daemon>() {
            kubernetes_daemon_pool(stack, daemon)
        } else {
            continue;
        };
        if let Err(message) = placement {
            errors.push(message);
        }
    }
    errors
}

/// Architecture shared by source images built for this Kubernetes stack.
/// Unspecified pools and Workers inherit this build constraint, so their Pods
/// cannot land on incompatible nodes in a cluster with mixed architectures.
pub fn kubernetes_compute_architecture(stack: &Stack) -> Result<Option<Architecture>, String> {
    let mut selected = None;
    for architecture in stack
        .resources()
        .filter_map(|(_, entry)| entry.config.downcast_ref::<ComputeCluster>())
        .flat_map(|cluster| &cluster.capacity_groups)
        .filter_map(|pool| pool.profile.as_ref()?.architecture)
    {
        if selected.is_some_and(|selected| selected != architecture) {
            return Err("Kubernetes compute pools require mixed CPU architectures; one platform image cannot satisfy both".to_string());
        }
        selected = Some(architecture);
    }
    Ok(selected)
}

/// Match Pod placement to the architecture used by the stack's source images.
/// This does not associate Workers with a compute pool or reserve node capacity.
pub fn kubernetes_compute_node_selector(
    stack: &Stack,
    pool: Option<&CapacityGroup>,
) -> Result<Option<BTreeMap<String, String>>, String> {
    let built_architecture = kubernetes_compute_architecture(stack)?;
    let architecture = pool
        .and_then(|pool| pool.profile.as_ref())
        .and_then(|profile| profile.architecture)
        .or(built_architecture);
    Ok(architecture.map(|architecture| {
        BTreeMap::from([(
            "kubernetes.io/arch".to_string(),
            match architecture {
                Architecture::Arm64 => "arm64",
                Architecture::X86_64 => "amd64",
            }
            .to_string(),
        )])
    }))
}

/// Map a workload's priority level to the PriorityClass the cluster administrator chose for it.
///
/// Returns `None` when the workload declares no level or the administrator mapped none, so
/// pod specs stay exactly as they were. The map comes from the Operator's
/// `ALIEN_KUBERNETES_PRIORITY_CLASSES` environment variable, which the Helm chart sets only
/// when `runtime.workloadPriority.classes` has an entry.
pub fn kubernetes_priority_class_name(
    priority: Option<WorkloadPriority>,
) -> Result<Option<String>, String> {
    priority_class_name_from(
        priority,
        std::env::var(ENV_ALIEN_KUBERNETES_PRIORITY_CLASSES)
            .ok()
            .as_deref(),
    )
}

fn parse_priority_class_map(raw: &str) -> Result<BTreeMap<String, String>, String> {
    serde_json::from_str(raw).map_err(|error| {
        format!(
            "{ENV_ALIEN_KUBERNETES_PRIORITY_CLASSES} must be a JSON object mapping \
             critical, high, normal and low to PriorityClass names (chart value \
             runtime.workloadPriority.classes): {error}"
        )
    })
}

fn priority_class_name_from(
    priority: Option<WorkloadPriority>,
    raw_map: Option<&str>,
) -> Result<Option<String>, String> {
    let (Some(priority), Some(raw)) = (priority, raw_map) else {
        return Ok(None);
    };
    Ok(parse_priority_class_map(raw)?
        .remove(priority.as_str())
        .filter(|name| !name.is_empty()))
}

/// Add the chart value to fix when Kubernetes rejects a pod because its PriorityClass is missing.
/// Other messages pass through unchanged.
pub fn kubernetes_priority_class_failure_hint(message: &str) -> String {
    priority_class_failure_hint_from(
        message,
        std::env::var(ENV_ALIEN_KUBERNETES_PRIORITY_CLASSES)
            .ok()
            .as_deref(),
    )
}

fn priority_class_failure_hint_from(message: &str, raw_map: Option<&str>) -> String {
    const MARKER: &str = "no PriorityClass with name ";
    let Some(start) = message.find(MARKER).map(|index| index + MARKER.len()) else {
        return message.to_string();
    };
    let class = message[start..]
        .split(" was found")
        .next()
        .unwrap_or_default()
        .trim_matches('"');
    let levels: Vec<String> = raw_map
        .and_then(|raw| parse_priority_class_map(raw).ok())
        .map(|map| {
            map.into_iter()
                .filter(|(_, name)| name == class)
                .map(|(level, _)| format!("runtime.workloadPriority.classes.{level}"))
                .collect()
        })
        .unwrap_or_default();
    let keys = if levels.is_empty() {
        "runtime.workloadPriority.classes".to_string()
    } else {
        levels.join(", ")
    };
    format!(
        "{message}. Create the PriorityClass '{class}' or set {keys} in the Helm values to an \
         existing PriorityClass (or set runtime.workloadPriority.create=true)"
    )
}

/// Resolve placement, inferring a single declared cluster and its general or
/// sole pool. Legacy stacks without a declaration keep default scheduling.
pub fn kubernetes_container_pool<'a>(
    stack: &'a Stack,
    container: &Container,
) -> Result<Option<&'a CapacityGroup>, String> {
    kubernetes_workload_pool(
        stack,
        &container.id,
        container.cluster.as_deref(),
        container.pool.as_deref(),
    )
}

/// Resolve a daemon's pool without changing its per-node DaemonSet behavior.
pub fn kubernetes_daemon_pool<'a>(
    stack: &'a Stack,
    daemon: &Daemon,
) -> Result<Option<&'a CapacityGroup>, String> {
    kubernetes_workload_pool(
        stack,
        &daemon.id,
        daemon.cluster.as_deref(),
        daemon.pool.as_deref(),
    )
}

fn kubernetes_workload_pool<'a>(
    stack: &'a Stack,
    resource_id: &str,
    cluster: Option<&str>,
    pool: Option<&str>,
) -> Result<Option<&'a CapacityGroup>, String> {
    let cluster = match cluster {
        Some(cluster_id) => stack
            .resources
            .get(cluster_id)
            .and_then(|entry| entry.config.downcast_ref::<ComputeCluster>())
            .ok_or_else(|| {
                format!("Workload '{resource_id}' references missing ComputeCluster '{cluster_id}'")
            })?,
        None => {
            let mut clusters = stack
                .resources()
                .filter_map(|(_, entry)| entry.config.downcast_ref::<ComputeCluster>());
            let Some(cluster) = clusters.next() else {
                return if pool.is_some() {
                    Err(format!(
                        "Workload '{resource_id}' selects a pool without a ComputeCluster"
                    ))
                } else {
                    Ok(None)
                };
            };
            if clusters.next().is_some() {
                return Err(format!(
                    "Workload '{resource_id}' must select a ComputeCluster explicitly"
                ));
            }
            cluster
        }
    };
    let selected = match pool {
        Some(name) => cluster
            .capacity_groups
            .iter()
            .find(|pool| pool.group_id == name),
        None => cluster
            .capacity_groups
            .iter()
            .find(|pool| pool.group_id == "general")
            .or_else(|| (cluster.capacity_groups.len() == 1).then(|| &cluster.capacity_groups[0])),
    };
    selected.map(Some).ok_or_else(|| format!("Workload '{resource_id}' references missing or ambiguous pool '{}' in ComputeCluster '{}'", pool.unwrap_or("general"), cluster.id))
}

/// Resolve the one pool admitted for release-independent containers.
pub fn kubernetes_dynamic_pool(stack: &Stack) -> Result<Option<&CapacityGroup>, String> {
    let mut clusters = stack
        .resources()
        .filter_map(|(_, entry)| entry.config.downcast_ref::<ComputeCluster>());
    let Some(cluster) = clusters.next() else {
        return Ok(None);
    };
    if clusters.next().is_some() {
        return Err("Dynamic containers require exactly one ComputeCluster".to_string());
    }
    let name = cluster
        .dynamic_container_pool
        .as_deref()
        .unwrap_or("general");
    cluster
        .capacity_groups
        .iter()
        .find(|pool| pool.group_id == name)
        .map(Some)
        .ok_or_else(|| {
            format!(
                "ComputeCluster '{}' has no dynamic container pool '{name}'",
                cluster.id
            )
        })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{instance_catalog::Architecture, ContainerCode, ResourceLifecycle};

    fn cluster() -> ComputeCluster {
        ComputeCluster::new("compute".to_string())
            .capacity_group(CapacityGroup {
                group_id: "apps".to_string(),
                instance_type: None,
                profile: Some(crate::MachineProfile {
                    cpu: "2".to_string(),
                    memory_bytes: 4 << 30,
                    ephemeral_storage_bytes: 20 << 30,
                    architecture: Some(Architecture::X86_64),
                    gpu: None,
                    data_disk: None,
                }),
                min_size: 1,
                max_size: 3,
                scale_policy: None,
                nested_virtualization: None,
                data_disk_gib_range: None,
            })
            .dynamic_container_pool("apps".to_string())
            .build()
    }

    fn stack(cluster: ComputeCluster) -> Stack {
        let container = Container::new("api".to_string())
            .code(ContainerCode::Image {
                image: "example.test/api:1".to_string(),
            })
            .cpu(crate::ResourceSpec {
                min: "1".to_string(),
                desired: "1".to_string(),
            })
            .memory(crate::ResourceSpec {
                min: "128Mi".to_string(),
                desired: "128Mi".to_string(),
            })
            .permissions("default".to_string())
            .cluster("compute".to_string())
            .pool("apps".to_string())
            .build();
        Stack::new("test".to_string())
            .add(cluster, ResourceLifecycle::Frozen)
            .add(container, ResourceLifecycle::Live)
            .build()
    }

    #[test]
    fn portable_pool_preserves_placement_and_dynamic_admission() {
        let stack = stack(cluster());
        assert!(validate_kubernetes_compute(&stack).is_empty());
        let pool = kubernetes_dynamic_pool(&stack).unwrap().unwrap();
        assert_eq!(pool.group_id, "apps");
        assert_eq!(
            pool.profile.as_ref().unwrap().architecture,
            Some(Architecture::X86_64)
        );
    }

    #[test]
    fn rejects_execution_requirements_and_invalid_references() {
        let mut cluster = cluster();
        cluster.capacity_groups[0].nested_virtualization = Some(true);
        cluster.dynamic_container_pool = Some("missing".to_string());
        let errors = validate_kubernetes_compute(&stack(cluster));
        assert!(errors
            .iter()
            .any(|message| message.contains("nested virtualization")));
        assert!(errors
            .iter()
            .any(|message| message.contains("dynamic container pool")));
        let mut cluster = self::cluster();
        cluster.capacity_groups[0].group_id = "other".to_string();
        assert!(validate_kubernetes_compute(&stack(cluster))
            .iter()
            .any(|message| message.contains("pool 'apps'")));
    }

    #[test]
    fn implicit_placement_uses_the_declared_pool_architecture() {
        let stack = stack(cluster());
        let mut container = stack
            .resources
            .get("api")
            .unwrap()
            .config
            .downcast_ref::<Container>()
            .unwrap()
            .clone();
        container.cluster = None;
        container.pool = None;
        let pool = kubernetes_container_pool(&stack, &container)
            .unwrap()
            .unwrap();
        assert_eq!(pool.group_id, "apps");
        assert_eq!(
            pool.profile.as_ref().unwrap().architecture,
            Some(Architecture::X86_64)
        );
    }

    #[test]
    fn unspecified_pool_and_unpooled_worker_use_the_build_architecture() {
        let mut compute = cluster();
        let mut unspecified = compute.capacity_groups[0].clone();
        unspecified.group_id = "other".to_string();
        unspecified.profile.as_mut().unwrap().architecture = None;
        compute.capacity_groups.push(unspecified.clone());
        let stack = stack(compute);
        let expected = Some(BTreeMap::from([(
            "kubernetes.io/arch".to_string(),
            "amd64".to_string(),
        )]));
        assert_eq!(
            kubernetes_compute_node_selector(&stack, Some(&unspecified)).unwrap(),
            expected
        );
        assert_eq!(
            kubernetes_compute_node_selector(&stack, None).unwrap(),
            expected
        );
    }

    #[test]
    fn priority_class_maps_declared_level_only_when_mapped() {
        let map = r#"{"critical":"vendor-core","high":""}"#;
        let class = |level, map| priority_class_name_from(level, map).unwrap();
        assert_eq!(
            class(Some(WorkloadPriority::Critical), Some(map)).as_deref(),
            Some("vendor-core")
        );
        assert_eq!(class(Some(WorkloadPriority::High), Some(map)), None);
        assert_eq!(class(Some(WorkloadPriority::Low), Some(map)), None);
        assert_eq!(class(None, Some(map)), None);
        assert_eq!(class(Some(WorkloadPriority::Critical), None), None);
        assert!(priority_class_name_from(Some(WorkloadPriority::Low), Some("nope")).is_err());
    }

    #[test]
    fn missing_priority_class_error_names_class_and_values_key() {
        let message = r#"FailedCreate: pods "api-1" is forbidden: no PriorityClass with name vendor-core was found"#;
        let hint = priority_class_failure_hint_from(message, Some(r#"{"critical":"vendor-core"}"#));
        assert!(hint.contains("'vendor-core'"), "{hint}");
        assert!(
            hint.contains("runtime.workloadPriority.classes.critical"),
            "{hint}"
        );
        assert_eq!(
            priority_class_failure_hint_from("quota exceeded", None),
            "quota exceeded"
        );
    }

    #[test]
    fn legacy_stack_keeps_default_placement() {
        let stack = Stack::new("legacy".to_string()).build();
        assert!(validate_kubernetes_compute(&stack).is_empty());
        assert!(kubernetes_dynamic_pool(&stack).unwrap().is_none());
    }
}