Skip to content

Commit 4782f22

Browse files
committed
feat(server): add auto-detection of compute driver at startup
When no drivers are explicitly configured, the server now automatically detects the appropriate compute driver by checking the runtime environment: - Kubernetes: detected via KUBERNETES_SERVICE_HOST env var (set inside pods) - Podman: detected by checking if podman binary is available on PATH - Docker: detected by checking if docker binary is available on PATH Priority order: Kubernetes → Podman → Docker. VM is never auto-detected and must be selected explicitly via --drivers vm. The Auto variant is internal-only and does not serialize to config files. The default --drivers value is now empty, triggering auto-detection.
1 parent 0845054 commit 4782f22

3 files changed

Lines changed: 118 additions & 23 deletions

File tree

‎crates/openshell-core/src/config.rs‎

Lines changed: 79 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ use serde::{Deserialize, Serialize};
77
use std::fmt;
88
use std::net::SocketAddr;
99
use std::path::PathBuf;
10+
use std::process::Command;
1011
use std::str::FromStr;
1112

1213
// ── Public default constants ────────────────────────────────────────────
@@ -50,6 +51,8 @@ pub enum ComputeDriverKind {
5051
Vm,
5152
Docker,
5253
Podman,
54+
#[serde(skip)]
55+
Auto,
5356
}
5457

5558
impl ComputeDriverKind {
@@ -60,6 +63,7 @@ impl ComputeDriverKind {
6063
Self::Vm => "vm",
6164
Self::Docker => "docker",
6265
Self::Podman => "podman",
66+
Self::Auto => "auto",
6367
}
6468
}
6569
}
@@ -79,13 +83,48 @@ impl FromStr for ComputeDriverKind {
7983
"vm" => Ok(Self::Vm),
8084
"docker" => Ok(Self::Docker),
8185
"podman" => Ok(Self::Podman),
86+
"auto" => Ok(Self::Auto),
8287
other => Err(format!(
83-
"unsupported compute driver '{other}'. expected one of: kubernetes, vm, docker, podman"
88+
"unsupported compute driver '{other}'. expected one of: kubernetes, vm, docker, podman, auto"
8489
)),
8590
}
8691
}
8792
}
8893

94+
/// Auto-detect the appropriate compute driver based on the runtime environment.
95+
///
96+
/// Priority order: Kubernetes → Podman → Docker.
97+
/// VM is never auto-detected (requires explicit `--drivers vm`).
98+
///
99+
/// Returns the first driver where the environment check passes.
100+
/// Returns `None` if no compatible driver is found.
101+
pub fn detect_driver() -> Option<ComputeDriverKind> {
102+
// Kubernetes: check for KUBERNETES_SERVICE_HOST env var (set inside pods)
103+
if std::env::var_os("KUBERNETES_SERVICE_HOST").is_some() {
104+
return Some(ComputeDriverKind::Kubernetes);
105+
}
106+
107+
// Podman: check if podman binary is available
108+
if is_binary_available("podman") {
109+
return Some(ComputeDriverKind::Podman);
110+
}
111+
112+
// Docker: check if docker binary is available
113+
if is_binary_available("docker") {
114+
return Some(ComputeDriverKind::Docker);
115+
}
116+
117+
None
118+
}
119+
120+
/// Check if a binary is available on the system PATH.
121+
fn is_binary_available(name: &str) -> bool {
122+
Command::new(name)
123+
.arg("--version")
124+
.output()
125+
.is_ok_and(|output| output.status.success())
126+
}
127+
89128
/// Server configuration.
90129
#[derive(Debug, Clone, Serialize, Deserialize)]
91130
pub struct Config {
@@ -124,7 +163,7 @@ pub struct Config {
124163
/// The config shape allows multiple drivers so the gateway can evolve
125164
/// toward multi-backend routing. Current releases require exactly one
126165
/// configured driver.
127-
#[serde(default = "default_compute_drivers")]
166+
#[serde(default)]
128167
pub compute_drivers: Vec<ComputeDriverKind>,
129168

130169
/// Kubernetes namespace for sandboxes.
@@ -296,7 +335,7 @@ impl Config {
296335
tls,
297336
oidc: None,
298337
database_url: String::new(),
299-
compute_drivers: default_compute_drivers(),
338+
compute_drivers: vec![],
300339
sandbox_namespace: default_sandbox_namespace(),
301340
sandbox_image: default_sandbox_image(),
302341
sandbox_image_pull_policy: String::new(),
@@ -472,10 +511,6 @@ fn default_sandbox_image() -> String {
472511
format!("{}/base:latest", crate::image::DEFAULT_COMMUNITY_REGISTRY)
473512
}
474513

475-
fn default_compute_drivers() -> Vec<ComputeDriverKind> {
476-
vec![ComputeDriverKind::Kubernetes]
477-
}
478-
479514
fn default_ssh_gateway_host() -> String {
480515
"127.0.0.1".to_string()
481516
}
@@ -506,7 +541,7 @@ const fn default_ssh_session_ttl_secs() -> u64 {
506541

507542
#[cfg(test)]
508543
mod tests {
509-
use super::{ComputeDriverKind, Config};
544+
use super::{ComputeDriverKind, Config, detect_driver};
510545
use std::net::SocketAddr;
511546

512547
#[test]
@@ -527,6 +562,10 @@ mod tests {
527562
"docker".parse::<ComputeDriverKind>().unwrap(),
528563
ComputeDriverKind::Docker
529564
);
565+
assert_eq!(
566+
"auto".parse::<ComputeDriverKind>().unwrap(),
567+
ComputeDriverKind::Auto
568+
);
530569
}
531570

532571
#[test]
@@ -535,14 +574,6 @@ mod tests {
535574
assert!(err.contains("unsupported compute driver 'firecracker'"));
536575
}
537576

538-
#[test]
539-
fn config_defaults_to_kubernetes_driver() {
540-
assert_eq!(
541-
Config::new(None).compute_drivers,
542-
vec![ComputeDriverKind::Kubernetes]
543-
);
544-
}
545-
546577
#[test]
547578
fn config_new_disables_health_bind_by_default() {
548579
let cfg = Config::new(None);
@@ -555,4 +586,36 @@ mod tests {
555586
let cfg = Config::new(None).with_health_bind_address(addr);
556587
assert_eq!(cfg.health_bind_address, Some(addr));
557588
}
589+
590+
#[test]
591+
fn detect_driver_returns_none_without_k8s_env_or_binaries() {
592+
// When KUBERNETES_SERVICE_HOST is not set and no docker/podman binaries
593+
// are available, detect_driver should return None.
594+
// This test may pass or fail depending on the test environment,
595+
// but it documents the expected behavior.
596+
let _ = detect_driver(); // Returns Some or None based on environment
597+
}
598+
599+
#[test]
600+
#[allow(unsafe_code)] // std::env::set_var/remove_var require unsafe in Rust 2024
601+
fn detect_driver_prefers_kubernetes_when_k8s_env_is_set() {
602+
// Save the original env var
603+
let original = std::env::var("KUBERNETES_SERVICE_HOST").ok();
604+
605+
// Set the env var
606+
unsafe {
607+
std::env::set_var("KUBERNETES_SERVICE_HOST", "127.0.0.1");
608+
}
609+
610+
let result = detect_driver();
611+
assert_eq!(result, Some(ComputeDriverKind::Kubernetes));
612+
613+
// Restore the original env var
614+
unsafe {
615+
match original {
616+
Some(val) => std::env::set_var("KUBERNETES_SERVICE_HOST", val),
617+
None => std::env::remove_var("KUBERNETES_SERVICE_HOST"),
618+
}
619+
}
620+
}
558621
}

‎crates/openshell-server/src/cli.rs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,12 +61,14 @@ struct Args {
6161
/// Accepts a comma-delimited list such as `kubernetes` or
6262
/// `kubernetes,podman`. The configuration format is future-proofed for
6363
/// multiple drivers, but the gateway currently requires exactly one.
64+
/// When unset, the gateway auto-detects the driver based on the runtime
65+
/// environment (Kubernetes → Podman → Docker). VM is never auto-detected
66+
/// and requires explicit configuration.
6467
#[arg(
6568
long,
6669
alias = "driver",
6770
env = "OPENSHELL_DRIVERS",
6871
value_delimiter = ',',
69-
default_value = "kubernetes",
7072
value_parser = parse_compute_driver
7173
)]
7274
drivers: Vec<ComputeDriverKind>,

‎crates/openshell-server/src/lib.rs‎

Lines changed: 36 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -493,14 +493,21 @@ async fn build_compute_runtime(
493493
.await
494494
.map_err(|e| Error::execution(format!("failed to create compute runtime: {e}")))
495495
}
496+
ComputeDriverKind::Auto => unreachable!(
497+
"Auto should never reach build_compute_runtime; \
498+
it is resolved by configured_compute_driver"
499+
),
496500
}
497501
}
498502

499503
fn configured_compute_driver(config: &Config) -> Result<ComputeDriverKind> {
500504
match config.compute_drivers.as_slice() {
501-
[] => Err(Error::config(
502-
"at least one compute driver must be configured",
503-
)),
505+
[] => openshell_core::config::detect_driver().ok_or_else(|| {
506+
Error::config(
507+
"no compute driver configured and auto-detection found no suitable driver; \
508+
set --drivers or OPENSHELL_DRIVERS to auto, kubernetes, podman, docker, or vm",
509+
)
510+
}),
504511
[
505512
driver @ (ComputeDriverKind::Kubernetes
506513
| ComputeDriverKind::Vm
@@ -545,10 +552,33 @@ mod tests {
545552
}
546553

547554
#[test]
548-
fn configured_compute_driver_rejects_empty_drivers() {
555+
fn configured_compute_driver_triggers_auto_detection_when_empty() {
549556
let config = Config::new(None).with_compute_drivers([]);
550-
let err = configured_compute_driver(&config).unwrap_err();
551-
assert!(err.to_string().contains("at least one compute driver"));
557+
// Empty drivers triggers auto-detection, which may return Some or None
558+
// depending on the environment. This test verifies the auto-detection path
559+
// is taken rather than immediately returning an error.
560+
let result = configured_compute_driver(&config);
561+
// Either we get a detected driver or an error about none being detected
562+
match result {
563+
Ok(driver) => {
564+
assert!(
565+
matches!(
566+
driver,
567+
ComputeDriverKind::Kubernetes
568+
| ComputeDriverKind::Docker
569+
| ComputeDriverKind::Podman
570+
),
571+
"auto-detected unexpected driver: {driver:?}"
572+
);
573+
}
574+
Err(e) => {
575+
assert!(
576+
e.to_string()
577+
.contains("no compute driver configured and none detected"),
578+
"unexpected error: {e}"
579+
);
580+
}
581+
}
552582
}
553583

554584
#[test]

0 commit comments

Comments
 (0)