diff --git a/src/LibreQoS.py b/src/LibreQoS.py index a959f570..e6969053 100755 --- a/src/LibreQoS.py +++ b/src/LibreQoS.py @@ -360,28 +360,31 @@ def _current_topology_source_generation(): def _topology_runtime_status_supports_shaping_inputs(shaping_inputs_path): - if not topology_import_ingress_enabled(): - return False - current_generation = _current_topology_source_generation() if current_generation is None: - return False + return None status_path = get_topology_runtime_status_path() try: with open(status_path, 'r', encoding='utf-8') as handle: status = json.load(handle) + except FileNotFoundError: + return None except Exception: - return False + return None if not isinstance(status, dict): return False - if not bool(status.get('ready')): - return False status_generation = str(status.get('source_generation', '') or '').strip() if status_generation != current_generation: return False + if not bool(status.get('ready')): + return False + + status_shaping_generation = str(status.get('shaping_generation', '') or '').strip() + if status_shaping_generation == '': + return False status_shaping_inputs_path = str(status.get('shaping_inputs_path', '') or '').strip() if status_shaping_inputs_path != '': @@ -390,6 +393,8 @@ def _topology_runtime_status_supports_shaping_inputs(shaping_inputs_path): return False except Exception: return False + if not os.path.isfile(status_shaping_inputs_path): + return False return True @@ -397,8 +402,11 @@ def _topology_runtime_status_supports_shaping_inputs(shaping_inputs_path): def _shaping_inputs_are_fresh(shaping_inputs_path, shaped_devices_file, network_json_file, circuit_anchors_file=None): if not os.path.isfile(shaping_inputs_path): return False - if _topology_runtime_status_supports_shaping_inputs(shaping_inputs_path): + topology_runtime_ready = _topology_runtime_status_supports_shaping_inputs(shaping_inputs_path) + if topology_runtime_ready is True: return True + if topology_runtime_ready is False: + return False try: shaping_inputs_mtime = os.path.getmtime(shaping_inputs_path) if os.path.isfile(shaped_devices_file) and shaping_inputs_mtime < os.path.getmtime(shaped_devices_file): diff --git a/src/bin/lqos_setup.service.example b/src/bin/lqos_setup.service.example new file mode 100644 index 00000000..b73fbbb2 --- /dev/null +++ b/src/bin/lqos_setup.service.example @@ -0,0 +1,11 @@ +[Unit] +Wants=network-online.target +After=network-online.target systemd-resolved.service + +[Service] +WorkingDirectory=/opt/libreqos/src/bin +ExecStart=/opt/libreqos/src/bin/lqos_setup web +Restart=on-failure + +[Install] +WantedBy=multi-user.target diff --git a/src/build_dpkg.sh b/src/build_dpkg.sh index 8ac45696..39c04614 100755 --- a/src/build_dpkg.sh +++ b/src/build_dpkg.sh @@ -52,6 +52,7 @@ LQOS_BIN_FILES=( lqos_scheduler.service.example lqosd.service.example lqos_api.service.example + lqos_setup.service.example ) RUSTPROGS=( @@ -123,21 +124,6 @@ cat <<'EOF' > postinst #!/bin/bash set -euo pipefail -if /opt/libreqos/src/systemd_hotfix.sh should-offer >/dev/null 2>&1; then -cat >&2 <<'HOTFIX' -LibreQoS detected the Ubuntu 24.04 systemd-networkd hotfix requirement on this host. - -Run: - sudo /opt/libreqos/src/systemd_hotfix.sh install - -The hotfix installer bootstraps the LibreQoS APT repo at https://repo.libreqos.com and will offer to schedule a reboot. - -After the reboot, finish the LibreQoS package configuration with: - sudo dpkg --configure -a -HOTFIX -exit 1 -fi - # Install Python Dependencies pushd /opt/libreqos > /dev/null # - Setup Python dependencies as a post-install task. Use --ignore-installed so @@ -152,20 +138,23 @@ fi # Ensure folder permissions are correct post-install sudo chown -R root:root /opt/libreqos -# - Run lqsetup -/opt/libreqos/src/bin/lqos_setup --skip-if-ready # - Setup the services install -m 0644 /opt/libreqos/src/bin/lqosd.service.example /etc/systemd/system/lqosd.service install -m 0644 /opt/libreqos/src/bin/lqos_scheduler.service.example /etc/systemd/system/lqos_scheduler.service install -m 0644 /opt/libreqos/src/bin/lqos_api.service.example /etc/systemd/system/lqos_api.service +install -m 0644 /opt/libreqos/src/bin/lqos_setup.service.example /etc/systemd/system/lqos_setup.service /bin/rm -f /etc/systemd/system/lqos_netplan_helper.service || true /bin/systemctl daemon-reload || true /bin/systemctl stop lqos_node_manager || true # In case it's running from a previous release /bin/systemctl disable lqos_node_manager || true # In case it's running from a previous release /bin/systemctl stop lqos_netplan_helper || true /bin/systemctl disable lqos_netplan_helper || true -/bin/systemctl enable lqosd lqos_scheduler lqos_api || true -/bin/systemctl restart lqosd lqos_scheduler lqos_api || true +if /opt/libreqos/src/bin/lqos_setup is-ready; then +/opt/libreqos/src/bin/lqos_setup activate-runtime +else +/opt/libreqos/src/bin/lqos_setup activate-setup +/opt/libreqos/src/bin/lqos_setup print-link || true +fi popd > /dev/null EOF @@ -173,8 +162,8 @@ EOF cat < postrm #!/bin/bash set +e -/bin/systemctl stop lqos_netplan_helper lqosd lqos_scheduler lqos_api || true -/bin/systemctl disable lqos_netplan_helper lqosd lqos_scheduler lqos_api || true +/bin/systemctl stop lqos_netplan_helper lqosd lqos_scheduler lqos_api lqos_setup || true +/bin/systemctl disable lqos_netplan_helper lqosd lqos_scheduler lqos_api lqos_setup || true /bin/rm -f /etc/systemd/system/lqos_netplan_helper.service || true /bin/systemctl daemon-reload || true exit 0 diff --git a/src/build_rust.sh b/src/build_rust.sh index 6331e104..097167cc 100755 --- a/src/build_rust.sh +++ b/src/build_rust.sh @@ -179,6 +179,7 @@ SERVICE_UNITS_UPDATED=0 refresh_service_unit lqosd refresh_service_unit lqos_scheduler refresh_service_unit lqos_api +refresh_service_unit lqos_setup if [ "$SERVICE_UNITS_UPDATED" -eq 1 ]; then echo "Reloading systemd unit definitions." @@ -212,6 +213,10 @@ if service_exists lqos_api; then echo "lqos_api is running as a service. Restarting it. You may need to enter your sudo password." sudo systemctl restart lqos_api fi +if service_exists lqos_setup; then + echo "lqos_setup is running as a service. Restarting it. You may need to enter your sudo password." + sudo systemctl restart lqos_setup +fi echo "-----------------------------------------------------------------" echo "Don't forget to setup /etc/lqos.conf!" diff --git a/src/rust/Cargo.lock b/src/rust/Cargo.lock index b637645a..fc6bb3d5 100644 --- a/src/rust/Cargo.lock +++ b/src/rust/Cargo.lock @@ -2280,13 +2280,21 @@ name = "lqos_setup" version = "0.1.0" dependencies = [ "anyhow", + "axum", + "clap", "cursive", "ip_network", + "libc", "lqos_config", "lqos_netplan_helper", "nix", "once_cell", "parking_lot", + "serde", + "serde_json", + "tokio", + "toml", + "uuid", ] [[package]] diff --git a/src/rust/lqos_config/src/authentication.rs b/src/rust/lqos_config/src/authentication.rs index 6461f4f3..ba457db5 100644 --- a/src/rust/lqos_config/src/authentication.rs +++ b/src/rust/lqos_config/src/authentication.rs @@ -113,6 +113,8 @@ pub struct WebUsers { allow_unauthenticated_to_view: bool, #[serde(default)] users: Vec, + #[serde(skip)] + base_path_override: Option, } impl Default for WebUsers { @@ -122,12 +124,13 @@ impl Default for WebUsers { auth_epoch: INITIAL_AUTH_EPOCH, allow_unauthenticated_to_view: false, users: Vec::new(), + base_path_override: None, } } } impl WebUsers { - fn base_path() -> Result { + fn default_base_path() -> Result { let base_path = crate::load_config() .map_err(|_| AuthenticationError::UnableToLoadEtcLqos)? .lqos_directory @@ -135,12 +138,27 @@ impl WebUsers { Ok(PathBuf::from(base_path)) } + fn primary_path_for(base_path: &Path) -> PathBuf { + base_path.join(CURRENT_AUTH_FILE_NAME) + } + + fn legacy_path_for(base_path: &Path) -> PathBuf { + base_path.join(LEGACY_AUTH_FILE_NAME) + } + + fn resolved_base_path(&self) -> Result { + if let Some(path) = &self.base_path_override { + return Ok(path.clone()); + } + Self::default_base_path() + } + fn primary_path() -> Result { - Ok(Self::base_path()?.join(CURRENT_AUTH_FILE_NAME)) + Ok(Self::primary_path_for(&Self::default_base_path()?)) } fn legacy_path() -> Result { - Ok(Self::base_path()?.join(LEGACY_AUTH_FILE_NAME)) + Ok(Self::legacy_path_for(&Self::default_base_path()?)) } /// Returns the current `lqusers.toml` path. @@ -178,7 +196,8 @@ impl WebUsers { } fn save_to_disk(&self) -> Result<(), AuthenticationError> { - let path = Self::primary_path()?; + let base_path = self.resolved_base_path()?; + let path = Self::primary_path_for(&base_path); let tmp_path = path.with_extension(format!("toml.tmp-{}", Uuid::new_v4())); let normalized = self.normalize_for_save(); let new_contents = toml_edit::ser::to_string(&normalized) @@ -210,7 +229,7 @@ impl WebUsers { AuthenticationError::UnableToWrite })?; - let legacy_path = Self::legacy_path()?; + let legacy_path = Self::legacy_path_for(&base_path); if legacy_path != path && legacy_path.exists() && let Err(e) = remove_file(&legacy_path) @@ -222,7 +241,7 @@ impl WebUsers { } fn migrate_if_needed(&mut self, loaded_from: &Path) -> Result<(), AuthenticationError> { - let current_path = Self::primary_path()?; + let current_path = Self::primary_path_for(&self.resolved_base_path()?); let loaded_from_legacy_path = loaded_from != current_path; let mut needs_rewrite = false; @@ -264,6 +283,7 @@ impl WebUsers { error!("Unable to deserialize auth file {:?}: {e}", path); AuthenticationError::UnableToParse })?; + users.base_path_override = Some(Self::default_base_path()?); users.migrate_if_needed(&path)?; Ok(users) } else { @@ -273,6 +293,41 @@ impl WebUsers { } } + /// Try to load `lqusers.toml` from an explicit LibreQoS directory, creating + /// a new version 2 file there if none exists yet. + pub fn load_or_create_in(base_path: &Path) -> Result { + let current = Self::primary_path_for(base_path); + let legacy = Self::legacy_path_for(base_path); + let existing = if current.exists() { + Some(current) + } else if legacy.exists() { + Some(legacy) + } else { + None + }; + + if let Some(path) = existing { + let raw = read_to_string(&path).map_err(|e| { + error!("Unable to read auth file {:?}: {e}", path); + AuthenticationError::UnableToRead + })?; + let mut users: Self = toml_edit::de::from_str(&raw).map_err(|e| { + error!("Unable to deserialize auth file {:?}: {e}", path); + AuthenticationError::UnableToParse + })?; + users.base_path_override = Some(base_path.to_path_buf()); + users.migrate_if_needed(&path)?; + Ok(users) + } else { + let new_users = Self { + base_path_override: Some(base_path.to_path_buf()), + ..Self::default() + }; + new_users.save_to_disk()?; + Ok(new_users) + } + } + fn hash_password(password: &str) -> Result { let salt = SaltString::generate(&mut OsRng); Argon2::default() diff --git a/src/rust/lqos_setup/Cargo.toml b/src/rust/lqos_setup/Cargo.toml index 25a0634b..eccd9c2a 100644 --- a/src/rust/lqos_setup/Cargo.toml +++ b/src/rust/lqos_setup/Cargo.toml @@ -13,3 +13,11 @@ anyhow.workspace = true once_cell = { workspace = true} ip_network = { workspace = true } parking_lot = { workspace = true } +clap = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +toml = { workspace = true } +uuid = { workspace = true } +tokio = { workspace = true } +axum = { version = "0.7.7" } +libc = "0.2" diff --git a/src/rust/lqos_setup/src/bootstrap.rs b/src/rust/lqos_setup/src/bootstrap.rs new file mode 100644 index 00000000..ffb571ac --- /dev/null +++ b/src/rust/lqos_setup/src/bootstrap.rs @@ -0,0 +1,536 @@ +//! Persistent bootstrap/setup state for first-run setup workflows. + +use crate::hotfix; +use anyhow::{Context, Result}; +use lqos_config::{Config, UserRole}; +use nix::{ + ifaddrs::getifaddrs, + sys::socket::{AddressFamily, SockaddrLike}, +}; +use serde::{Deserialize, Serialize}; +use std::{ + collections::BTreeSet, + fs, + path::{Path, PathBuf}, + time::{Duration, SystemTime, UNIX_EPOCH}, +}; +use uuid::Uuid; + +const BOOTSTRAP_STATE_VERSION: u32 = 1; +const DEFAULT_LQOS_DIRECTORY: &str = "/opt/libreqos/src"; +const DEFAULT_STATE_DIRECTORY: &str = "/opt/libreqos/state"; +const SETUP_PORT: u16 = 9123; +const TOKEN_TTL: Duration = Duration::from_secs(2 * 60 * 60); + +/// High-level setup status visible to operators. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum SetupStatus { + /// Setup is not complete yet. + Incomplete, + /// Setup completed, but subscriber topology inputs are still missing. + CompleteWaitingForSubscriberData, + /// Setup completed and subscriber topology inputs exist. + CompleteShapingActive, +} + +impl SetupStatus { + /// Human-readable label for operator-facing status output. + pub fn as_str(self) -> &'static str { + match self { + Self::Incomplete => "Setup Incomplete", + Self::CompleteWaitingForSubscriberData => { + "Setup Complete, Waiting for Subscriber Data" + } + Self::CompleteShapingActive => "Setup Complete, Shaping Active", + } + } +} + +/// Current bootstrap token metadata for the temporary setup surface. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub struct BootstrapToken { + /// Opaque setup token. + pub token: String, + /// Expiration time in Unix seconds. + pub expires_at_unix: u64, +} + +/// Persistent first-run setup state stored under the LibreQoS state directory. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub struct BootstrapState { + /// On-disk schema version for setup state. + pub version: u32, + /// Whether setup has been completed. + pub setup_complete: bool, + /// Whether runtime subscriber inputs exist and shaping can become active. + pub shaping_ready: bool, + /// Whether an admin user exists. + pub first_admin_exists: bool, + /// Current setup token. + pub token: BootstrapToken, +} + +impl Default for BootstrapState { + fn default() -> Self { + Self { + version: BOOTSTRAP_STATE_VERSION, + setup_complete: false, + shaping_ready: false, + first_admin_exists: false, + token: new_bootstrap_token(), + } + } +} + +/// Computed setup status snapshot for CLI surfaces. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct StatusSnapshot { + /// Synced bootstrap state. + pub state: BootstrapState, + /// Operator-visible status derived for the current snapshot. + pub display_status: SetupStatus, + /// Hostname and IP hints for the operator. + pub host_hints: Vec, + /// Whether `network.json` exists. + pub network_json_present: bool, + /// Whether `ShapedDevices.csv` exists. + pub shaped_devices_present: bool, + /// Whether `/etc/lqos.conf` currently parses. + pub config_loads: bool, + /// Whether the Noble systemd hotfix is still required. + pub hotfix_required: bool, + /// Operator-visible hotfix status detail. + pub hotfix_detail: String, +} + +#[derive(Default, Deserialize)] +struct AuthUsersFile { + #[serde(default)] + users: Vec, +} + +#[derive(Deserialize)] +struct AuthUserEntry { + role: UserRole, +} + +#[derive(Clone, Debug)] +struct RuntimePaths { + lqos_directory: PathBuf, + state_directory: PathBuf, +} + +#[derive(Clone, Debug)] +struct LiveInputs { + config_loads: bool, + network_json_present: bool, + shaped_devices_present: bool, + first_admin_exists: bool, +} + +fn current_unix_seconds() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs() +} + +fn new_bootstrap_token() -> BootstrapToken { + BootstrapToken { + token: Uuid::new_v4().simple().to_string(), + expires_at_unix: current_unix_seconds() + TOKEN_TTL.as_secs(), + } +} + +fn runtime_paths() -> RuntimePaths { + if let Ok(config) = lqos_config::load_config() { + return RuntimePaths { + lqos_directory: PathBuf::from(&config.lqos_directory), + state_directory: config.resolved_state_directory(), + }; + } + + RuntimePaths { + lqos_directory: PathBuf::from(DEFAULT_LQOS_DIRECTORY), + state_directory: PathBuf::from(DEFAULT_STATE_DIRECTORY), + } +} + +/// Returns the active or default LibreQoS runtime directory used by first-run setup. +pub fn runtime_lqos_directory() -> PathBuf { + runtime_paths().lqos_directory +} + +fn bootstrap_state_path() -> PathBuf { + runtime_paths() + .state_directory + .join("setup") + .join("bootstrap_state.json") +} + +fn completion_report_path() -> PathBuf { + runtime_paths() + .state_directory + .join("setup") + .join("completion_report.txt") +} + +fn auth_file_has_admin(lqos_directory: &Path) -> bool { + let path = lqos_directory.join("lqusers.toml"); + let Ok(raw) = fs::read_to_string(path) else { + return false; + }; + let Ok(users) = toml::from_str::(&raw) else { + return false; + }; + users.users.iter().any(|user| user.role == UserRole::Admin) +} + +fn collect_live_inputs() -> LiveInputs { + let paths = runtime_paths(); + LiveInputs { + config_loads: lqos_config::load_config().is_ok(), + network_json_present: paths.lqos_directory.join("network.json").exists(), + shaped_devices_present: paths.lqos_directory.join("ShapedDevices.csv").exists(), + first_admin_exists: auth_file_has_admin(&paths.lqos_directory), + } +} + +fn display_status(setup_complete: bool, shaping_ready: bool) -> SetupStatus { + if !setup_complete { + SetupStatus::Incomplete + } else if shaping_ready { + SetupStatus::CompleteShapingActive + } else { + SetupStatus::CompleteWaitingForSubscriberData + } +} + +fn detect_host_hints() -> Vec { + let mut hints = BTreeSet::new(); + + if let Ok(hostname) = fs::read_to_string("/etc/hostname") { + let hostname = hostname.trim(); + if !hostname.is_empty() { + hints.insert(hostname.to_string()); + } + } + + if let Ok(ifaddrs) = getifaddrs() { + for iface in ifaddrs { + if iface.interface_name == "lo" { + continue; + } + let Some(address) = iface.address else { + continue; + }; + if address.family() != Some(AddressFamily::Inet) { + continue; + } + let Some(inet) = address.as_sockaddr_in() else { + continue; + }; + let ip = inet.ip(); + if !ip.is_loopback() { + hints.insert(ip.to_string()); + } + } + } + + if hints.is_empty() { + hints.insert("127.0.0.1".to_string()); + } + + hints.into_iter().collect() +} + +fn detect_setup_hosts() -> Vec { + let hosts = detect_host_hints() + .into_iter() + .filter(|hint| hint.parse::().is_ok()) + .collect::>(); + if hosts.is_empty() { + vec!["127.0.0.1".to_string()] + } else { + hosts + } +} + +fn build_setup_urls(token: &BootstrapToken) -> Vec { + detect_setup_hosts() + .iter() + .map(|host| format!("http://{host}:{SETUP_PORT}/setup?token={}", token.token)) + .collect() +} + +fn hydrate_state( + mut state: BootstrapState, + refresh_expired_token: bool, +) -> BootstrapState { + if refresh_expired_token && state.token.expires_at_unix <= current_unix_seconds() { + state.token = new_bootstrap_token(); + } + state.version = BOOTSTRAP_STATE_VERSION; + state +} + +fn read_persisted_state() -> Result { + let path = bootstrap_state_path(); + if !path.exists() { + return Ok(BootstrapState::default()); + } + let raw = fs::read_to_string(&path) + .with_context(|| format!("Unable to read bootstrap state {}", path.display()))?; + serde_json::from_str::(&raw) + .with_context(|| format!("Unable to parse bootstrap state {}", path.display())) +} + +fn bootstrap_state_from_live(live: &LiveInputs) -> BootstrapState { + BootstrapState { + setup_complete: live.config_loads && live.first_admin_exists, + shaping_ready: live.config_loads + && live.first_admin_exists + && live.network_json_present + && live.shaped_devices_present, + first_admin_exists: live.first_admin_exists, + ..BootstrapState::default() + } +} + +/// Loads persisted bootstrap state, creating it if needed and syncing derived fields. +fn load_or_create_state() -> Result { + let path = bootstrap_state_path(); + let live = collect_live_inputs(); + let loaded = if path.exists() { + read_persisted_state()? + } else { + bootstrap_state_from_live(&live) + }; + let synced = hydrate_state(loaded, true); + if let Some(parent) = path.parent() + && let Err(err) = fs::create_dir_all(parent) + { + if path.exists() { + return Err(err).with_context(|| { + format!("Unable to create setup state directory {}", parent.display()) + }); + } + return Ok(synced); + } + + if let Err(err) = save_state(&synced) + && path.exists() + { + return Err(err); + } + Ok(synced) +} + +/// Persists bootstrap state to disk. +pub fn save_state(state: &BootstrapState) -> Result<()> { + let path = bootstrap_state_path(); + if let Some(parent) = path.parent() { + fs::create_dir_all(parent) + .with_context(|| format!("Unable to create setup state directory {}", parent.display()))?; + } + let raw = serde_json::to_string_pretty(state).context("Unable to serialize bootstrap state")?; + fs::write(&path, raw) + .with_context(|| format!("Unable to write bootstrap state {}", path.display()))?; + Ok(()) +} + +/// Stores the most recent setup completion report for the setup web UI. +pub fn store_setup_completion_report(report: &str) -> Result<()> { + let path = completion_report_path(); + if let Some(parent) = path.parent() { + fs::create_dir_all(parent).with_context(|| { + format!("Unable to create setup state directory {}", parent.display()) + })?; + } + fs::write(&path, report) + .with_context(|| format!("Unable to write setup completion report {}", path.display()))?; + Ok(()) +} + +/// Loads the most recent setup completion report for the setup web UI. +pub fn load_setup_completion_report() -> Result { + let path = completion_report_path(); + fs::read_to_string(&path) + .with_context(|| format!("Unable to read setup completion report {}", path.display())) +} + +/// Records that setup successfully committed configuration. +pub fn record_setup_success(config: &Config) -> Result { + let mut state = load_or_create_state()?; + let live = LiveInputs { + config_loads: true, + network_json_present: Path::new(&config.lqos_directory).join("network.json").exists(), + shaped_devices_present: Path::new(&config.lqos_directory) + .join("ShapedDevices.csv") + .exists(), + first_admin_exists: auth_file_has_admin(Path::new(&config.lqos_directory)), + }; + state.setup_complete = live.first_admin_exists; + state.shaping_ready = live.network_json_present && live.shaped_devices_present; + state.first_admin_exists = live.first_admin_exists; + state = hydrate_state(state, true); + save_state(&state)?; + Ok(state) +} + +/// Returns true when an admin user exists for the current or default runtime directory. +pub fn first_admin_exists() -> bool { + auth_file_has_admin(&runtime_paths().lqos_directory) +} + +/// Builds a current status snapshot for operator-facing CLI output. +pub fn status_snapshot() -> Result { + let live = collect_live_inputs(); + let hotfix_status = hotfix::status()?; + let mut state = if bootstrap_state_path().exists() { + hydrate_state(read_persisted_state()?, false) + } else { + bootstrap_state_from_live(&live) + }; + state.first_admin_exists = live.first_admin_exists; + state.shaping_ready = + state.setup_complete && live.network_json_present && live.shaped_devices_present; + let host_hints = detect_host_hints(); + let display_status = display_status(state.setup_complete, state.shaping_ready); + + Ok(StatusSnapshot { + state, + display_status, + host_hints, + network_json_present: live.network_json_present, + shaped_devices_present: live.shaped_devices_present, + config_loads: live.config_loads, + hotfix_required: hotfix_status.required, + hotfix_detail: hotfix_status.detail, + }) +} + +/// Renders a text report for `lqos_setup status`. +pub fn render_status_report() -> Result { + let snapshot = status_snapshot()?; + let mut report = format!("lqos_setup status\n\nStatus: {}", snapshot.display_status.as_str()); + report.push_str("\nSource: persisted setup state plus current runtime diagnostics"); + + report.push_str(&format!( + "\n- setup_complete: {}", + yes_no(snapshot.state.setup_complete) + )); + report.push_str(&format!( + "\n- shaping_ready: {}", + yes_no(snapshot.state.shaping_ready) + )); + report.push_str(&format!( + "\n- config_loads: {}", + yes_no(snapshot.config_loads) + )); + report.push_str(&format!( + "\n- first_admin_exists: {}", + yes_no(snapshot.state.first_admin_exists) + )); + report.push_str(&format!( + "\n- network.json present: {}", + yes_no(snapshot.network_json_present) + )); + report.push_str(&format!( + "\n- ShapedDevices.csv present: {}", + yes_no(snapshot.shaped_devices_present) + )); + report.push_str(&format!( + "\n- hotfix required: {}", + yes_no(snapshot.hotfix_required) + )); + report.push_str(&format!( + "\n- hotfix detail: {}", + snapshot.hotfix_detail + )); + + if !snapshot.state.setup_complete { + report.push_str("\n\nHost hints:"); + for host in &snapshot.host_hints { + report.push_str(&format!("\n- {host}")); + } + report.push_str("\n\nRun `lqos_setup print-link` to print the current tokenized setup URL."); + } + + Ok(report) +} + +/// Returns true when setup is complete enough for runtime services to start. +/// +/// Side effects: none. +pub fn runtime_services_should_start() -> Result { + let live = collect_live_inputs(); + let hotfix_status = hotfix::status()?; + let state = if bootstrap_state_path().exists() { + hydrate_state(read_persisted_state()?, false) + } else { + bootstrap_state_from_live(&live) + }; + Ok( + state.setup_complete + && live.first_admin_exists + && live.config_loads + && !hotfix_status.required, + ) +} + +/// Returns true when first-run setup has not yet been completed. +pub fn setup_is_incomplete() -> Result { + let live = collect_live_inputs(); + let state = if bootstrap_state_path().exists() { + hydrate_state(read_persisted_state()?, false) + } else { + bootstrap_state_from_live(&live) + }; + Ok(!state.setup_complete || !live.first_admin_exists) +} + +/// Returns the current tokenized setup URLs if setup is still incomplete. +/// +/// Side effects: may create `bootstrap_state.json` or refresh an expired setup token so the +/// returned links are durable and immediately usable. +pub fn current_setup_urls() -> Result> { + let state = load_or_create_state()?; + if state.setup_complete { + return Ok(Vec::new()); + } + Ok(build_setup_urls(&state.token)) +} + +/// Validates a setup token against the persisted bootstrap state. +/// +/// Side effects: none. +pub fn validate_setup_token(token: &str) -> Result { + let state = if bootstrap_state_path().exists() { + read_persisted_state()? + } else { + return Ok(false); + }; + if state.setup_complete { + return Ok(false); + } + Ok(state.token.expires_at_unix > current_unix_seconds() && state.token.token == token) +} + +fn yes_no(value: bool) -> &'static str { + if value { "yes" } else { "no" } +} + +#[cfg(test)] +mod tests { + use super::{TOKEN_TTL, current_unix_seconds, new_bootstrap_token}; + + #[test] + fn bootstrap_tokens_expire_in_future() { + let now = current_unix_seconds(); + let token = new_bootstrap_token(); + assert!(!token.token.is_empty()); + assert!(token.expires_at_unix >= now + TOKEN_TTL.as_secs() - 1); + } +} diff --git a/src/rust/lqos_setup/src/bridge_mode.rs b/src/rust/lqos_setup/src/bridge_mode.rs index 4c37f4d8..e09d0998 100644 --- a/src/rust/lqos_setup/src/bridge_mode.rs +++ b/src/rust/lqos_setup/src/bridge_mode.rs @@ -7,7 +7,7 @@ use cursive::{ use crate::config_builder::{BridgeMode, CURRENT_CONFIG}; pub fn bridge_mode(s: &mut Cursive) { - let mode = CURRENT_CONFIG.lock().bridge_mode; + let single_selected = CURRENT_CONFIG.lock().bridge_mode == BridgeMode::Single; // create the group and buttons let mut group = RadioGroup::new().on_change(|_s, mode| { @@ -19,24 +19,19 @@ pub fn bridge_mode(s: &mut Cursive) { BridgeMode::Linux, "Linux Bridge (2 interfaces) - LibreQoS will inspect and stage the managed Netplan change", ); - let mut xdp_btn = group.button( - BridgeMode::XDP, - "XDP Bridge (2 interfaces) - Manual Netplan workflow; do not create a bridge in Netplan", - ); let mut single_btn = group.button(BridgeMode::Single, "Single Interface (1 interface)"); // mark the one we want as selected - match mode { - BridgeMode::Linux => linux_btn.select(), - BridgeMode::XDP => xdp_btn.select(), - BridgeMode::Single => single_btn.select(), - }; + if single_selected { + single_btn.select(); + } else { + linux_btn.select(); + } // now add them (in any order) to your layout let layout = LinearLayout::vertical() .child(TextView::new("Select the bridge mode you want to use:")) .child(linux_btn) - .child(xdp_btn) .child(single_btn); s.add_layer( diff --git a/src/rust/lqos_setup/src/config_builder.rs b/src/rust/lqos_setup/src/config_builder.rs index 289d1eb2..53801b61 100644 --- a/src/rust/lqos_setup/src/config_builder.rs +++ b/src/rust/lqos_setup/src/config_builder.rs @@ -70,8 +70,8 @@ impl ConfigBuilder { to_network: String::new(), internet_vlan: 0, network_vlan: 0, - mbps_to_internet: 1_000, - mbps_to_network: 1_000, + mbps_to_internet: 9_400, + mbps_to_network: 9_400, allow_subnets: vec![ "172.16.0.0/12".to_string(), "10.0.0.0/8".to_string(), diff --git a/src/rust/lqos_setup/src/hotfix.rs b/src/rust/lqos_setup/src/hotfix.rs new file mode 100644 index 00000000..26a99523 --- /dev/null +++ b/src/rust/lqos_setup/src/hotfix.rs @@ -0,0 +1,97 @@ +//! Ubuntu 24.04 systemd hotfix helpers for first-run setup. + +use anyhow::{Context, Result, bail}; +use std::process::Command; + +const HOTFIX_SCRIPT: &str = "/opt/libreqos/src/systemd_hotfix.sh"; + +/// Current systemd hotfix state for operator-facing setup surfaces. +pub struct HotfixStatus { + pub required: bool, + pub detail: String, +} + +/// Result of running the hotfix installer. +pub struct HotfixInstallResult { + pub summary: String, + pub detail: String, +} + +fn script_exists() -> bool { + std::path::Path::new(HOTFIX_SCRIPT).exists() +} + +/// Returns the current hotfix status by invoking the shipped helper script. +/// +/// Side effects: executes `systemd_hotfix.sh status`. +pub fn status() -> Result { + if !script_exists() { + bail!("Hotfix helper script not found at {HOTFIX_SCRIPT}."); + } + + let output = Command::new(HOTFIX_SCRIPT) + .arg("status") + .output() + .with_context(|| format!("Unable to run {HOTFIX_SCRIPT} status"))?; + + let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string(); + let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string(); + let detail = if !stdout.is_empty() { + stdout + } else if !stderr.is_empty() { + stderr + } else if output.status.success() { + "Hotfix is not required.".to_string() + } else { + "Hotfix helper did not return any status text.".to_string() + }; + + Ok(HotfixStatus { + required: output.status.success(), + detail, + }) +} + +/// Installs the Ubuntu 24.04 systemd hotfix without prompting for reboot. +/// +/// Side effects: executes `systemd_hotfix.sh install`, which can modify APT +/// sources, install packages, and write the marker file. +pub fn install() -> Result { + if !script_exists() { + bail!("Hotfix helper script not found at {HOTFIX_SCRIPT}."); + } + + let output = Command::new(HOTFIX_SCRIPT) + .arg("install") + .env("HOTFIX_SKIP_REBOOT_PROMPT", "1") + .output() + .with_context(|| format!("Unable to run {HOTFIX_SCRIPT} install"))?; + + let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string(); + let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string(); + + if !output.status.success() { + let detail = if !stderr.is_empty() { + stderr + } else if !stdout.is_empty() { + stdout + } else { + format!("Hotfix installer exited with status {}", output.status) + }; + bail!("{detail}"); + } + + let detail = if !stdout.is_empty() { + stdout + } else { + "Hotfix installed.".to_string() + }; + let summary = match status() { + Ok(current) if !current.required => "Hotfix installed successfully.".to_string(), + Ok(_) => "Hotfix installer completed, but the host still reports the hotfix as required." + .to_string(), + Err(_) => "Hotfix installer completed. Setup checks were refreshed.".to_string(), + }; + + Ok(HotfixInstallResult { summary, detail }) +} diff --git a/src/rust/lqos_setup/src/interfaces.rs b/src/rust/lqos_setup/src/interfaces.rs index 141dd137..951f93ea 100644 --- a/src/rust/lqos_setup/src/interfaces.rs +++ b/src/rust/lqos_setup/src/interfaces.rs @@ -1,4 +1,7 @@ -use std::path::Path; +use std::{ + path::Path, + process::Command, +}; use cursive::{ Cursive, @@ -8,12 +11,33 @@ use cursive::{ use crate::config_builder::{BridgeMode, CURRENT_CONFIG}; +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct InterfaceOption { + pub name: String, + pub label: String, +} + pub fn get_interfaces() -> anyhow::Result> { - let interfaces = nix::ifaddrs::getifaddrs()? + Ok(get_interface_options()? + .into_iter() + .map(|iface| iface.name) + .collect()) +} + +pub fn get_interface_options() -> anyhow::Result> { + let mut interfaces = nix::ifaddrs::getifaddrs()? .filter(|iface| interface_supports_lqos(&iface.interface_name).is_ok()) .map(|iface| iface.interface_name) .collect::>(); - Ok(interfaces) + interfaces.sort(); + interfaces.dedup(); + Ok(interfaces + .into_iter() + .map(|name| InterfaceOption { + label: interface_label(&name), + name, + }) + .collect()) } pub(crate) fn interface_supports_lqos(interface: &str) -> anyhow::Result<()> { @@ -57,17 +81,102 @@ pub(crate) fn interface_supports_lqos(interface: &str) -> anyhow::Result<()> { Ok(()) } +fn interface_label(interface: &str) -> String { + let mut parts = vec![interface.to_string()]; + if let Some(speed) = interface_speed_label(interface) { + parts.push(speed); + } + if let Some(kind) = interface_kind_label(interface) { + parts.push(kind); + } + parts.join(" - ") +} + +fn interface_speed_label(interface: &str) -> Option { + let path = Path::new("/sys/class/net").join(interface).join("speed"); + let raw = std::fs::read_to_string(path).ok()?; + let speed = raw.trim().parse::().ok()?; + if speed == 0 || speed == u32::MAX as u64 || speed == u64::MAX { + return None; + } + + let label = match speed { + 1000 => "1G".to_string(), + 2500 => "2.5G".to_string(), + 5000 => "5G".to_string(), + 10000 => "10G".to_string(), + 25000 => "25G".to_string(), + 40000 => "40G".to_string(), + 50000 => "50G".to_string(), + 100000 => "100G".to_string(), + value if value >= 1000 && value % 1000 == 0 => format!("{}G", value / 1000), + value => format!("{value}M"), + }; + Some(label) +} + +fn interface_kind_label(interface: &str) -> Option { + if let Some(port) = interface_port_label(interface) { + return Some(port); + } + + let driver_path = Path::new("/sys/class/net").join(interface).join("device/driver"); + if let Ok(target) = std::fs::read_link(driver_path) + && let Some(driver) = target.file_name().and_then(|name| name.to_str()) + { + return Some(driver.to_string()); + } + + let device_path = Path::new("/sys/class/net").join(interface).join("device"); + if !device_path.exists() { + return Some("virtual".to_string()); + } + + None +} + +fn interface_port_label(interface: &str) -> Option { + let output = Command::new("ethtool").arg(interface).output().ok()?; + if !output.status.success() { + return None; + } + let stdout = String::from_utf8_lossy(&output.stdout); + for line in stdout.lines() { + let Some((key, value)) = line.split_once(':') else { + continue; + }; + if key.trim() != "Port" { + continue; + } + return normalize_port_label(value.trim()); + } + None +} + +fn normalize_port_label(port: &str) -> Option { + match port { + "FIBRE" => Some("fiber".to_string()), + "Twisted Pair" => Some("RJ45".to_string()), + "Direct Attach Copper" => Some("DAC".to_string()), + "Backplane" => Some("backplane".to_string()), + "AUI" | "MII" | "BNC" => Some(port.to_ascii_lowercase()), + "Other" | "Unknown" | "Internal" => None, + _ if port.is_empty() => None, + _ => Some(port.to_string()), + } +} + fn build_interface_list( - interfaces: &[String], + interfaces: &[InterfaceOption], group: &mut RadioGroup, active: String, ) -> Vec> { let mut buttons = Vec::new(); for iface in interfaces { - if *iface != active { - buttons.push(group.button(iface.clone(), iface)); + if iface.name != active { + buttons.push(group.button(iface.name.clone(), iface.label.clone())); } else { - let mut button = group.button(iface.clone(), iface); + let mut button = group.button(iface.name.clone(), iface.label.clone()); button.select(); buttons.push(button); } @@ -79,16 +188,16 @@ fn build_layout() -> LinearLayout { let bridge_mode = CURRENT_CONFIG.lock().bridge_mode; match bridge_mode { BridgeMode::Linux | BridgeMode::XDP => { - let interfaces = get_interfaces().expect("Failed to get interfaces"); + let interfaces = get_interface_options().expect("Failed to get interfaces"); // If the configuration has empty interface fields, set them to the first available interface { let mut config = CURRENT_CONFIG.lock(); if config.to_internet.is_empty() && !interfaces.is_empty() { - config.to_internet = interfaces[0].clone(); + config.to_internet = interfaces[0].name.clone(); } if config.to_network.is_empty() && !interfaces.is_empty() { - config.to_network = interfaces[0].clone(); + config.to_network = interfaces[0].name.clone(); } } @@ -133,13 +242,13 @@ fn build_layout() -> LinearLayout { .child(network_layout) } BridgeMode::Single => { - let interfaces = get_interfaces().expect("Failed to get interfaces"); + let interfaces = get_interface_options().expect("Failed to get interfaces"); // If the configuration has empty interface field, set it to the first available interface { let mut config = CURRENT_CONFIG.lock(); if config.to_internet.is_empty() && !interfaces.is_empty() { - config.to_internet = interfaces[0].clone(); + config.to_internet = interfaces[0].name.clone(); } } diff --git a/src/rust/lqos_setup/src/lib.rs b/src/rust/lqos_setup/src/lib.rs new file mode 100644 index 00000000..9c89ed69 --- /dev/null +++ b/src/rust/lqos_setup/src/lib.rs @@ -0,0 +1,4 @@ +//! Shared setup support for the `lqos_setup` binary. + +pub mod bootstrap; +pub mod hotfix; diff --git a/src/rust/lqos_setup/src/main.rs b/src/rust/lqos_setup/src/main.rs index e5de92bf..d4cf97f5 100644 --- a/src/rust/lqos_setup/src/main.rs +++ b/src/rust/lqos_setup/src/main.rs @@ -4,10 +4,14 @@ mod config_builder; mod interfaces; mod ip_range; mod preflight; +mod service_handoff; +mod setup_actions; +mod web; mod webusers; +use clap::{Parser, Subcommand}; +use lqos_setup::{bootstrap, hotfix}; use std::path::Path; -use std::sync::Arc; use std::{env, fmt::Write as _}; use bandwidth::bandwidth_view; @@ -17,18 +21,44 @@ use cursive::{ view::{Margins, Nameable, Resizable, Scrollable}, views::{Checkbox, Dialog, EditView, FixedLayout, Layer, LinearLayout, OnLayoutView, TextView}, }; -use lqos_netplan_helper::protocol::{ApplyMode, ApplyRequest}; use lqos_netplan_helper::transaction::{ - HelperPaths, PendingChildren, apply_transaction, confirm_transaction, inspect_with_paths, - revert_transaction, + HelperPaths, inspect_with_paths, }; -use parking_lot::Mutex; const VERSION: &str = include_str!("../../../VERSION_STRING"); -const DEFAULT_NETWORK_JSON: &str = include_str!("../../../network.example.json"); -const DEFAULT_SHAPED_DEVICES: &str = include_str!("../../../ShapedDevices.example.csv"); const SKIP_IF_READY_FLAG: &str = "--skip-if-ready"; +#[derive(Parser)] +#[command(about = "LibreQoS first-run setup")] +struct Args { + #[arg(long)] + skip_if_ready: bool, + #[command(subcommand)] + command: Option, +} + +#[derive(Subcommand)] +enum Command { + /// Launch the interactive Cursive setup UI + Tui, + /// Launch the setup-only web server + Web, + /// Print the current setup status + Status, + /// Print the current Ubuntu 24.04 systemd hotfix status + HotfixStatus, + /// Install the Ubuntu 24.04 systemd hotfix without prompting for reboot + InstallHotfix, + /// Exit 0 when runtime services should start, or 1 when setup is still required + IsReady, + /// Internal helper: stop setup and activate runtime services now + ActivateRuntime, + /// Internal helper: stop runtime and activate the first-run setup service now + ActivateSetup, + /// Create or refresh and print the current tokenized setup link(s) + PrintLink, +} + fn config_exists() -> bool { let config_path = Path::new("/etc/lqos.conf"); config_path.exists() @@ -140,12 +170,8 @@ fn upgrade_readiness() -> UpgradeReadiness { }) } -fn should_skip_interactive_setup() -> bool { - env::args().skip(1).any(|arg| arg == SKIP_IF_READY_FLAG) -} - -fn main() { - if should_skip_interactive_setup() { +fn run_tui(skip_if_ready: bool) { + if skip_if_ready { let readiness = upgrade_readiness(); println!("{}", readiness.summary()); if readiness.all_ready() { @@ -254,89 +280,110 @@ fn main() { .button("Interfaces", interfaces::interface_menu) .button("Bandwidth", bandwidth_view) .button("IP Range", ip_range::ranges) + .button("Systemd Hotfix", show_hotfix_dialog) .button("Web Users", webusers::webusers_menu) .button("SAVE CONFIG", finalize), ); ui.run(); } -fn build_candidate_config(existing: Option) -> lqos_config::Config { - let mut config = existing.unwrap_or_default(); - let new_config = CURRENT_CONFIG.lock(); - config.node_name = new_config.node_name.clone(); - config.queues.downlink_bandwidth_mbps = new_config.mbps_to_internet; - config.queues.uplink_bandwidth_mbps = new_config.mbps_to_network; - config.queues.generated_pn_download_mbps = new_config.mbps_to_internet; - config.queues.generated_pn_upload_mbps = new_config.mbps_to_network; - match new_config.bridge_mode { - config_builder::BridgeMode::Linux => { - config.single_interface = None; - config.bridge = Some(lqos_config::BridgeConfig { - use_xdp_bridge: false, - to_internet: new_config.to_internet.clone(), - to_network: new_config.to_network.clone(), - }); - } - config_builder::BridgeMode::XDP => { - config.single_interface = None; - config.bridge = Some(lqos_config::BridgeConfig { - use_xdp_bridge: true, - to_internet: new_config.to_internet.clone(), - to_network: new_config.to_network.clone(), - }); - } - config_builder::BridgeMode::Single => { - config.single_interface = Some(lqos_config::SingleInterfaceConfig { - interface: new_config.to_internet.clone(), - internet_vlan: new_config.internet_vlan, - network_vlan: new_config.network_vlan, - }); - config.bridge = None; - } - } - config.ip_ranges.allow_subnets = new_config.allow_subnets.clone(); - config -} - -fn inspection_report(inspection: &lqos_netplan_helper::NetworkModeInspection) -> String { - let mut report = format!( - "State: {}\n{}\n", - inspection.inspector_state, inspection.summary +fn main() { + let args = Args::parse_from( + env::args().map(|arg| { + if arg == SKIP_IF_READY_FLAG { + "--skip-if-ready".to_string() + } else { + arg + } + }), ); - if !inspection.warnings.is_empty() { - report.push_str("\nWarnings:\n"); - for warning in &inspection.warnings { - let _ = writeln!(&mut report, "- {warning}"); - } - } - if !inspection.dangerous_changes.is_empty() { - report.push_str("\nStrong confirmations required:\n"); - for warning in &inspection.dangerous_changes { - let _ = writeln!(&mut report, "- {warning}"); - } - } - if !inspection.conflicts.is_empty() { - report.push_str("\nConflicts:\n"); - for conflict in &inspection.conflicts { - let _ = writeln!(&mut report, "- {conflict}"); + + match args.command { + Some(Command::Status) => match bootstrap::render_status_report() { + Ok(report) => println!("{report}"), + Err(err) => { + eprintln!("Unable to render setup status: {err:#}"); + std::process::exit(1); + } + }, + Some(Command::HotfixStatus) => match hotfix::status() { + Ok(status) => println!("{}", status.detail), + Err(err) => { + eprintln!("Unable to determine hotfix status: {err:#}"); + std::process::exit(1); + } + }, + Some(Command::InstallHotfix) => match hotfix::install() { + Ok(result) => { + println!("{}", result.summary); + println!(); + println!("{}", result.detail); + } + Err(err) => { + eprintln!("Unable to install hotfix: {err:#}"); + std::process::exit(1); + } + }, + Some(Command::IsReady) => match bootstrap::runtime_services_should_start() { + Ok(true) => {} + Ok(false) => std::process::exit(1), + Err(err) => { + eprintln!("Unable to determine setup readiness: {err:#}"); + std::process::exit(1); + } + }, + Some(Command::ActivateRuntime) => match service_handoff::activate_runtime_services() { + Ok(message) => println!("{message}"), + Err(err) => { + eprintln!("Unable to activate runtime services: {err:#}"); + std::process::exit(1); + } + }, + Some(Command::ActivateSetup) => match service_handoff::activate_setup_service() { + Ok(message) => println!("{message}"), + Err(err) => { + eprintln!("Unable to activate setup service: {err:#}"); + std::process::exit(1); + } + }, + Some(Command::Web) => { + if let Err(err) = web::run() { + eprintln!("Unable to run setup web server: {err:#}"); + std::process::exit(1); + } } + Some(Command::PrintLink) => match bootstrap::current_setup_urls() { + Ok(urls) => { + if urls.is_empty() { + println!("Setup is already complete. No active setup link."); + } else { + println!(); + println!("============================================================"); + println!("LibreQoS first-run setup is waiting for you."); + println!("Click one of the LibreQoS Setup URLs below, or copy it into a web browser on another machine on the same network."); + println!(); + for url in urls { + println!(" {url}"); + } + println!("============================================================"); + println!(); + } + } + Err(err) => { + eprintln!("Unable to print setup link: {err:#}"); + std::process::exit(1); + } + }, + Some(Command::Tui) | None => run_tui(args.skip_if_ready), } - if let Some(preview) = &inspection.managed_preview_yaml { - report.push_str("\nManaged Preview:\n"); - report.push_str(preview); - } else if let Some(note) = &inspection.preview_note { - report.push('\n'); - report.push_str(note); - } - report } pub(crate) fn preview_selected_network_mode(s: &mut cursive::Cursive) { let existing = lqos_config::load_config().ok().map(|cfg| (*cfg).clone()); - let candidate = build_candidate_config(existing); + let candidate = setup_actions::build_candidate_config(existing); let inspection = inspect_with_paths(&HelperPaths::default(), &candidate); s.add_layer( - Dialog::around(TextView::new(inspection_report(&inspection)).scrollable()) + Dialog::around(TextView::new(setup_actions::inspection_report(&inspection)).scrollable()) .title("Detected Netplan State") .button("OK", |s| { s.pop_layer(); @@ -350,33 +397,21 @@ fn finish_setup( config: &lqos_config::Config, mut event_log: Vec, ) { - let state_root = config.resolved_state_directory(); - for category in [ - "topology", - "shaping", - "stats", - "cache", - "debug", - "quarantine", - ] { - std::fs::create_dir_all(state_root.join(category)) - .expect("Unable to create state directory"); - } - - if !network_json_exists() { - let path = Path::new(&config.lqos_directory).join("network.json"); - std::fs::write(path, DEFAULT_NETWORK_JSON).expect("Unable to write file"); - event_log.push("Network.json created.".to_string()); - } else { - event_log.push("Network.json already exists - not updated.".to_string()); + if let Err(err) = setup_actions::persist_setup_success(config, &mut event_log) { + ui.add_layer( + Dialog::around(TextView::new(format!( + "Configuration was written, but setup state could not be persisted:\n{err:#}\n\nSetup cannot be marked complete until bootstrap_state.json is saved successfully." + ))) + .title("Unable To Persist Setup State") + .button("OK", |s| { + s.pop_layer(); + }), + ); + return; } - - if !shaped_devices_exists() { - let path = Path::new(&config.lqos_directory).join("ShapedDevices.csv"); - std::fs::write(path, DEFAULT_SHAPED_DEVICES).expect("Unable to write file"); - event_log.push("ShapedDevices.csv created.".to_string()); - } else { - event_log.push("ShapedDevices.csv already exists - not updated.".to_string()); + match service_handoff::schedule_runtime_handoff() { + Ok(notice) => event_log.push(notice.message), + Err(err) => event_log.push(format!("WARNING: {err:#}")), } let report = cursive::With::with(LinearLayout::vertical(), |layout| { @@ -393,32 +428,50 @@ fn finish_setup( } fn finalize(ui: &mut cursive::Cursive) { - // If we cannot load the config but a file exists, warn the user and - // take a backup before proceeding to create a new config. + match hotfix::status() { + Ok(status) if status.required => { + ui.add_layer( + Dialog::around(TextView::new(format!( + "{}\n\nInstall the Noble systemd hotfix before completing setup.", + status.detail + ))) + .title("Hotfix Required") + .button("Install Hotfix", |s| { + s.pop_layer(); + install_hotfix_from_tui(s); + }) + .button("Cancel", |s| { + s.pop_layer(); + }), + ); + return; + } + Ok(_) => {} + Err(err) => { + ui.add_layer( + Dialog::around(TextView::new(format!( + "Unable to determine hotfix status:\n{err:#}" + ))) + .title("Hotfix Check Failed") + .button("OK", |s| { + s.pop_layer(); + }), + ); + return; + } + } + + // If we cannot load the config but a file exists, warn the user that + // continuing will replace it after saving a backup. let config_path = Path::new("/etc/lqos.conf"); let load_result = lqos_config::load_config(); if load_result.is_err() && config_path.exists() { - let backup_path = "/etc/lqos.conf.setupbackup"; - let backup_result = std::fs::copy(config_path, backup_path); - - let msg = match backup_result { - Ok(_) => format!( - "An existing configuration file was found at /etc/lqos.conf,\n\ + let msg = "An existing configuration file was found at /etc/lqos.conf,\n\ but it could not be read or parsed.\n\n\ -A backup has been saved to: {}\n\n\ -Press Continue to create a new configuration using defaults,\n\ -or Cancel to exit and investigate.", - backup_path - ), - Err(e) => format!( - "An existing configuration file was found at /etc/lqos.conf,\n\ -but it could not be read or parsed.\n\n\ -Attempted to back it up, but failed: {:?}\n\n\ -Press Continue to create a new configuration using defaults,\n\ -or Cancel to exit and investigate.", - e - ), - }; +Press Continue to replace it with a new configuration using defaults.\n\ +LibreQoS will first try to save a backup to /etc/lqos.conf.setupbackup.\n\n\ +Press Cancel to exit and investigate." + .to_string(); ui.add_layer( Dialog::around(TextView::new(msg)) @@ -438,173 +491,130 @@ or Cancel to exit and investigate.", continue_finalize(ui); } -fn continue_finalize(ui: &mut cursive::Cursive) { - let mut event_log = Vec::new(); - - let existing_config = if let Ok(config) = lqos_config::load_config() { - event_log.push("Loaded existing configuration".to_string()); - (*config).clone() - } else { - // If the file exists but couldn't be read, ensure we also log that a - // backup was attempted (final safeguard; may already have been done - // before showing the warning dialog). - if Path::new("/etc/lqos.conf").exists() { - let backup_path = "/etc/lqos.conf.setupbackup"; - match std::fs::copy("/etc/lqos.conf", backup_path) { - Ok(_) => event_log.push(format!( - "Existing /etc/lqos.conf could not be loaded. Backup saved to {}.", - backup_path - )), - Err(e) => event_log.push(format!( - "Existing /etc/lqos.conf could not be loaded. Backup attempt failed: {:?}.", - e - )), +fn show_hotfix_dialog(ui: &mut cursive::Cursive) { + match hotfix::status() { + Ok(status) => { + let detail = if status.required { + format!("{}\n\nThe hotfix is required before setup can complete.", status.detail) + } else { + status.detail + }; + let mut dialog = Dialog::around(TextView::new(detail)).title("Systemd Hotfix"); + if status.required { + dialog.add_button("Install Hotfix", |s| { + s.pop_layer(); + install_hotfix_from_tui(s); + }); } + dialog.add_button("OK", |s| { + s.pop_layer(); + }); + ui.add_layer(dialog); } - event_log.push("Creating new configuration".to_string()); - lqos_config::Config::default() - }; - let config = build_candidate_config(Some(existing_config)); - let using_helper = !matches!( - CURRENT_CONFIG.lock().bridge_mode, - config_builder::BridgeMode::XDP - ); + Err(err) => ui.add_layer( + Dialog::around(TextView::new(format!("Unable to determine hotfix status:\n{err:#}"))) + .title("Systemd Hotfix") + .button("OK", |s| { + s.pop_layer(); + }), + ), + } +} - if !using_helper { - if let Err(e) = lqos_config::update_config(&config) { - event_log.push(format!("ERROR: Unable to write configuration: {e:?}")); - let msg = format!("ERROR: Unable to write configuration: {e:?}"); +fn install_hotfix_from_tui(ui: &mut cursive::Cursive) { + match hotfix::install() { + Ok(result) => { ui.add_layer( - Dialog::around(TextView::new(msg)) - .title("Error") + Dialog::around(TextView::new(format!( + "{}\n\nOpen the details only if you need the installer log.\n\n{}", + result.summary, result.detail + ))) + .title("Hotfix Installed") .button("OK", |s| { s.pop_layer(); }), ); - return; } - event_log.push("Configuration updated.".to_string()); - event_log.push("XDP bridge mode remains a manual Netplan workflow.".to_string()); - finish_setup(ui, &config, event_log); - return; - } - - let helper_paths = HelperPaths::default(); - let pending_children = Arc::new(Mutex::new(PendingChildren::default())); - let inspection = inspect_with_paths(&helper_paths, &config); - let requires_confirmation = !inspection.dangerous_changes.is_empty(); - let apply_mode = if inspection.can_take_over { - ApplyMode::TakeOver - } else if inspection.can_adopt { - ApplyMode::Adopt - } else { - ApplyMode::Apply - }; - let apply_request = ApplyRequest { - config: config.clone(), - source: "setup".to_string(), - operator_username: None, - mode: apply_mode, - confirm_dangerous_changes: requires_confirmation, - }; - - let response = { - let mut pending = pending_children.lock(); - apply_transaction(&helper_paths, &mut pending, apply_request) - }; - let response = match response { - Ok(response) => response, Err(err) => { ui.add_layer( - Dialog::around(TextView::new(format!( - "Unable to stage network-mode changes:\n{err:#}" - ))) - .title("Helper Error") - .button("OK", |s| { - s.pop_layer(); - }), + Dialog::around(TextView::new(format!("Unable to install hotfix:\n{err:#}"))) + .title("Hotfix Install Failed") + .button("OK", |s| { + s.pop_layer(); + }), ); - return; } - }; - - let Some(operation) = response.operation.clone() else { - finish_setup(ui, &config, event_log); - return; - }; - - let confirm_paths = helper_paths.clone(); - let confirm_pending = Arc::clone(&pending_children); - let confirm_config = config.clone(); - let confirm_log = event_log.clone(); - let confirm_operation_id = operation.operation_id.clone(); - let revert_paths = helper_paths.clone(); - let revert_pending = Arc::clone(&pending_children); - let revert_operation_id = operation.operation_id.clone(); + } +} - ui.add_layer( - Dialog::around(TextView::new(format!( - "{}\n\n{}\n\nConfirm the change to keep the managed netplan update, or revert it now.", - response.message, - inspection_report(&inspection) - ))) - .title("Confirm Netplan Change") - .button("Confirm", move |s| { - let result = { - let mut pending = confirm_pending.lock(); - confirm_transaction(&confirm_paths, &mut pending, &confirm_operation_id) - }; - match result { - Ok(confirm) => { - let mut log = confirm_log.clone(); - log.push(confirm.message); - s.pop_layer(); - finish_setup(s, &confirm_config, log); - } - Err(err) => { - s.add_layer( - Dialog::around(TextView::new(format!( - "Unable to confirm the pending network change:\n{err:#}" - ))) - .title("Helper Error") - .button("OK", |s| { - s.pop_layer(); - }), - ); - } - } - }) - .button("Revert", move |s| { - let result = { - let mut pending = revert_pending.lock(); - revert_transaction(&revert_paths, &mut pending, &revert_operation_id) - }; - match result { - Ok(revert) => { - s.add_layer( - Dialog::around(TextView::new(revert.message)) - .title("Network Change Reverted") - .button("OK", |s| { - s.pop_layer(); +fn continue_finalize(ui: &mut cursive::Cursive) { + match setup_actions::prepare_commit() { + Ok(setup_actions::CommitOutcome::Complete(success)) => { + finish_setup(ui, &success.config, success.event_log); + } + Ok(setup_actions::CommitOutcome::Pending(pending)) => { + let operation_id = pending.operation_id.clone(); + let revert_operation_id = pending.operation_id.clone(); + ui.add_layer( + Dialog::around(TextView::new(pending.prompt)) + .title("Confirm Netplan Change") + .button("Confirm", move |s| { + match setup_actions::confirm_pending_commit(&operation_id) { + Ok(success) => { s.pop_layer(); - }), - ); - } - Err(err) => { - s.add_layer( - Dialog::around(TextView::new(format!( - "Unable to revert the pending network change:\n{err:#}" - ))) - .title("Helper Error") - .button("OK", |s| { - s.pop_layer(); - }), - ); - } - } - }) - .full_screen(), - ); + finish_setup(s, &success.config, success.event_log); + } + Err(err) => { + s.add_layer( + Dialog::around(TextView::new(format!( + "Unable to confirm the pending network change:\n{err:#}" + ))) + .title("Helper Error") + .button("OK", |s| { + s.pop_layer(); + }), + ); + } + } + }) + .button("Revert", move |s| { + match setup_actions::revert_pending_commit(&revert_operation_id) { + Ok(message) => { + s.add_layer( + Dialog::around(TextView::new(message)) + .title("Network Change Reverted") + .button("OK", |s| { + s.pop_layer(); + s.pop_layer(); + }), + ); + } + Err(err) => { + s.add_layer( + Dialog::around(TextView::new(format!( + "Unable to revert the pending network change:\n{err:#}" + ))) + .title("Helper Error") + .button("OK", |s| { + s.pop_layer(); + }), + ); + } + } + }) + .full_screen(), + ); + } + Err(err) => { + ui.add_layer( + Dialog::around(TextView::new(format!("{err:#}"))) + .title("Unable To Save Setup") + .button("OK", |s| { + s.pop_layer(); + }), + ); + } + } } #[cfg(test)] diff --git a/src/rust/lqos_setup/src/service_handoff.rs b/src/rust/lqos_setup/src/service_handoff.rs new file mode 100644 index 00000000..5205df8f --- /dev/null +++ b/src/rust/lqos_setup/src/service_handoff.rs @@ -0,0 +1,176 @@ +//! Runtime service handoff helpers for completing first-run setup. + +use anyhow::{Context, Result, bail}; +use std::process::Command; +use uuid::Uuid; + +const SYSTEMD_RUN_BIN: &str = "/usr/bin/systemd-run"; +const SYSTEMCTL_BIN: &str = "/bin/systemctl"; + +pub(crate) struct HandoffNotice { + pub(crate) message: String, + pub(crate) automatic: bool, +} + +fn ensure_root_with_systemctl() -> Result<()> { + if unsafe { libc::geteuid() } != 0 { + bail!("This operation requires root privileges."); + } + if !std::path::Path::new(SYSTEMCTL_BIN).exists() { + bail!("{SYSTEMCTL_BIN} is not available on this host."); + } + Ok(()) +} + +fn run_systemctl(args: &[&str], required: bool) -> Result<()> { + let status = Command::new(SYSTEMCTL_BIN) + .args(args) + .status() + .with_context(|| format!("Unable to invoke {SYSTEMCTL_BIN} {}", args.join(" ")))?; + if required && !status.success() { + bail!( + "{SYSTEMCTL_BIN} {} failed with exit status {status}", + args.join(" ") + ); + } + Ok(()) +} + +fn stop_and_disable(services: &[&str]) -> Result<()> { + if services.is_empty() { + return Ok(()); + } + + let mut stop_args = vec!["stop"]; + stop_args.extend_from_slice(services); + run_systemctl(&stop_args, false)?; + + let mut disable_args = vec!["disable"]; + disable_args.extend_from_slice(services); + run_systemctl(&disable_args, false) +} + +fn enable_and_restart(services: &[&str]) -> Result<()> { + if services.is_empty() { + return Ok(()); + } + + let mut enable_args = vec!["enable"]; + enable_args.extend_from_slice(services); + run_systemctl(&enable_args, true)?; + + let mut restart_args = vec!["restart"]; + restart_args.extend_from_slice(services); + run_systemctl(&restart_args, true) +} + +fn switch_service_mode( + stop_disable: &[&str], + enable_restart: &[&str], + success_message: &str, +) -> Result { + ensure_root_with_systemctl()?; + stop_and_disable(stop_disable)?; + + if let Err(err) = enable_and_restart(enable_restart) { + let _ = stop_and_disable(enable_restart); + let rollback = enable_and_restart(stop_disable); + match rollback { + Ok(()) => { + bail!( + "Unable to activate the target service mode: {err:#}. Restored the previous service mode." + ) + } + Err(rollback_err) => { + bail!( + "Unable to activate the target service mode: {err:#}. Rollback to the previous service mode also failed: {rollback_err:#}" + ) + } + } + } + + Ok(success_message.to_string()) +} + +/// Stops setup and starts the runtime services immediately. +/// +/// Side effects: disables and stops `lqos_setup.service`, then enables and +/// restarts `lqosd.service` and `lqos_scheduler.service`. +pub(crate) fn activate_runtime_services() -> Result { + switch_service_mode( + &["lqos_setup.service"], + &["lqosd.service", "lqos_scheduler.service", "lqos_api.service"], + "Activated runtime services: lqosd, lqos_scheduler, and lqos_api.", + ) +} + +/// Stops runtime services and starts the setup service immediately. +/// +/// Side effects: stops and disables `lqosd.service` and +/// `lqos_scheduler.service`, then enables and restarts `lqos_setup.service`. +pub(crate) fn activate_setup_service() -> Result { + switch_service_mode( + &[ + "lqosd.service", + "lqos_scheduler.service", + "lqos_api.service", + ], + &["lqos_setup.service"], + "Activated first-run setup service: lqos_setup.", + ) +} + +/// Schedules a transient systemd unit that stops setup and starts runtime services. +/// +/// Side effects: spawns a transient systemd service, disables and stops +/// `lqos_setup.service`, and enables and restarts `lqosd.service` and +/// `lqos_scheduler.service` after a short delay. +pub(crate) fn schedule_runtime_handoff() -> Result { + if std::env::var_os("INVOCATION_ID").is_none() { + return Ok(HandoffNotice { + message: "Setup saved. Start lqosd, lqos_scheduler, and lqos_api manually because this setup run is not being managed by systemd.".to_string(), + automatic: false, + }); + } + + if unsafe { libc::geteuid() } != 0 { + return Ok(HandoffNotice { + message: "Setup saved. Start lqosd, lqos_scheduler, and lqos_api manually because the current setup process is not running as root.".to_string(), + automatic: false, + }); + } + + if !std::path::Path::new(SYSTEMD_RUN_BIN).exists() { + return Ok(HandoffNotice { + message: "Setup saved. Start lqosd, lqos_scheduler, and lqos_api manually because systemd-run is not available on this host.".to_string(), + automatic: false, + }); + } + + ensure_root_with_systemctl()?; + let unit_name = format!("lqos-setup-handoff-{}", Uuid::new_v4().simple()); + let current_exe = std::env::current_exe().context("Unable to determine lqos_setup path")?; + let status = Command::new(SYSTEMD_RUN_BIN) + .args([ + "--unit", + &unit_name, + "--on-active=2s", + current_exe.to_string_lossy().as_ref(), + "activate-runtime", + ]) + .status() + .with_context(|| format!("Unable to invoke {SYSTEMD_RUN_BIN} for setup handoff"))?; + + if !status.success() { + bail!( + "Unable to schedule runtime handoff via systemd-run (exit status: {status}). Start lqosd and lqos_scheduler manually." + ); + } + + Ok(HandoffNotice { + message: format!( + "Scheduled runtime handoff via transient unit {unit_name}. LibreQoS setup will stop and lqosd/lqos_scheduler/lqos_api will start shortly." + ), + automatic: true, + }) +} diff --git a/src/rust/lqos_setup/src/setup_actions.rs b/src/rust/lqos_setup/src/setup_actions.rs new file mode 100644 index 00000000..3219a23c --- /dev/null +++ b/src/rust/lqos_setup/src/setup_actions.rs @@ -0,0 +1,273 @@ +//! Shared setup commit/apply helpers used by both Cursive and the setup WebUI. + +use crate::config_builder::{BridgeMode, CURRENT_CONFIG}; +use anyhow::{Context, Result, bail}; +use lqos_netplan_helper::protocol::{ApplyMode, ApplyRequest}; +use lqos_netplan_helper::transaction::{ + HelperPaths, PendingChildren, apply_transaction, confirm_transaction, inspect_with_paths, + revert_transaction, +}; +use once_cell::sync::Lazy; +use parking_lot::Mutex; +use std::collections::HashMap; +use std::fmt::Write as _; +use std::path::Path; + +static PENDING_CHILDREN: Lazy> = + Lazy::new(|| Mutex::new(PendingChildren::default())); +static PENDING_COMMITS: Lazy>> = + Lazy::new(|| Mutex::new(HashMap::new())); + +struct PendingCommitState { + config: lqos_config::Config, + event_log: Vec, +} + +/// Successful setup commit result. +pub(crate) struct CommitSuccess { + pub(crate) config: lqos_config::Config, + pub(crate) event_log: Vec, +} + +/// Pending network confirmation data. +pub(crate) struct PendingCommit { + pub(crate) operation_id: String, + pub(crate) prompt: String, +} + +/// Outcome of attempting to commit setup settings. +pub(crate) enum CommitOutcome { + Complete(Box), + Pending(PendingCommit), +} + +pub(crate) fn build_candidate_config(existing: Option) -> lqos_config::Config { + let mut config = existing.unwrap_or_default(); + let new_config = CURRENT_CONFIG.lock(); + config.node_name = new_config.node_name.clone(); + config.queues.downlink_bandwidth_mbps = new_config.mbps_to_internet; + config.queues.uplink_bandwidth_mbps = new_config.mbps_to_network; + config.queues.generated_pn_download_mbps = new_config.mbps_to_internet; + config.queues.generated_pn_upload_mbps = new_config.mbps_to_network; + match new_config.bridge_mode { + BridgeMode::Linux => { + config.single_interface = None; + config.bridge = Some(lqos_config::BridgeConfig { + use_xdp_bridge: false, + to_internet: new_config.to_internet.clone(), + to_network: new_config.to_network.clone(), + }); + } + BridgeMode::XDP => { + config.single_interface = None; + config.bridge = Some(lqos_config::BridgeConfig { + use_xdp_bridge: true, + to_internet: new_config.to_internet.clone(), + to_network: new_config.to_network.clone(), + }); + } + BridgeMode::Single => { + config.single_interface = Some(lqos_config::SingleInterfaceConfig { + interface: new_config.to_internet.clone(), + internet_vlan: new_config.internet_vlan, + network_vlan: new_config.network_vlan, + }); + config.bridge = None; + } + } + config.ip_ranges.allow_subnets = new_config.allow_subnets.clone(); + config +} + +pub(crate) fn inspection_report( + inspection: &lqos_netplan_helper::NetworkModeInspection, +) -> String { + let mut report = format!( + "State: {}\n{}\n", + inspection.inspector_state, inspection.summary + ); + if !inspection.warnings.is_empty() { + report.push_str("\nWarnings:\n"); + for warning in &inspection.warnings { + let _ = writeln!(&mut report, "- {warning}"); + } + } + if !inspection.dangerous_changes.is_empty() { + report.push_str("\nStrong confirmations required:\n"); + for warning in &inspection.dangerous_changes { + let _ = writeln!(&mut report, "- {warning}"); + } + } + if !inspection.conflicts.is_empty() { + report.push_str("\nConflicts:\n"); + for conflict in &inspection.conflicts { + let _ = writeln!(&mut report, "- {conflict}"); + } + } + if let Some(preview) = &inspection.managed_preview_yaml { + report.push_str("\nManaged Preview:\n"); + report.push_str(preview); + } else if let Some(note) = &inspection.preview_note { + report.push('\n'); + report.push_str(note); + } + report +} + +pub(crate) fn prepare_commit() -> Result { + if !lqos_setup::bootstrap::first_admin_exists() { + bail!("Setup requires at least one admin user before configuration can be committed."); + } + + let mut event_log = Vec::new(); + let existing_config = load_existing_or_default(&mut event_log)?; + let config = build_candidate_config(Some(existing_config)); + let using_helper = !matches!(CURRENT_CONFIG.lock().bridge_mode, BridgeMode::XDP); + + if !using_helper { + lqos_config::update_config(&config)?; + event_log.push("Configuration updated.".to_string()); + return Ok(CommitOutcome::Complete(Box::new(CommitSuccess { + config, + event_log, + }))); + } + + let helper_paths = HelperPaths::default(); + let inspection = inspect_with_paths(&helper_paths, &config); + let bootstrap_incomplete = lqos_setup::bootstrap::setup_is_incomplete() + .unwrap_or(true); + let apply_mode = if inspection.can_take_over { + ApplyMode::TakeOver + } else if inspection.can_adopt { + ApplyMode::Adopt + } else { + ApplyMode::Apply + }; + let response = { + let mut pending = PENDING_CHILDREN.lock(); + apply_transaction( + &helper_paths, + &mut pending, + ApplyRequest { + config: config.clone(), + source: "setup".to_string(), + operator_username: None, + mode: apply_mode, + confirm_dangerous_changes: bootstrap_incomplete + || !inspection.dangerous_changes.is_empty(), + }, + ) + }?; + + let Some(operation) = response.operation else { + return Ok(CommitOutcome::Complete(Box::new(CommitSuccess { + config, + event_log, + }))); + }; + + PENDING_COMMITS.lock().insert( + operation.operation_id.clone(), + PendingCommitState { + config, + event_log, + }, + ); + + Ok(CommitOutcome::Pending(PendingCommit { + operation_id: operation.operation_id, + prompt: format!( + "{}\n\n{}\n\nConfirm the change to keep the managed netplan update, or revert it now.", + response.message, + inspection_report(&inspection) + ), + })) +} + +pub(crate) fn confirm_pending_commit(operation_id: &str) -> Result { + let confirm = { + let mut pending = PENDING_CHILDREN.lock(); + confirm_transaction(&HelperPaths::default(), &mut pending, operation_id) + }?; + + let Some(mut pending_state) = PENDING_COMMITS.lock().remove(operation_id) else { + bail!("Pending setup confirmation state for {operation_id} was not found."); + }; + pending_state.event_log.push(confirm.message); + Ok(CommitSuccess { + config: pending_state.config, + event_log: pending_state.event_log, + }) +} + +pub(crate) fn revert_pending_commit(operation_id: &str) -> Result { + let revert = { + let mut pending = PENDING_CHILDREN.lock(); + revert_transaction(&HelperPaths::default(), &mut pending, operation_id) + }?; + PENDING_COMMITS.lock().remove(operation_id); + Ok(revert.message) +} + +pub(crate) fn persist_setup_success( + config: &lqos_config::Config, + event_log: &mut Vec, +) -> Result<()> { + let state_root = config.resolved_state_directory(); + for category in [ + "topology", + "shaping", + "stats", + "cache", + "debug", + "quarantine", + ] { + std::fs::create_dir_all(state_root.join(category)).with_context(|| { + format!( + "Unable to create setup runtime state directory {}", + state_root.join(category).display() + ) + })?; + } + + let state = lqos_setup::bootstrap::record_setup_success(config)?; + event_log.push(format!( + "Setup state updated: {}", + if state.shaping_ready { + "Setup Complete, Shaping Active" + } else { + "Setup Complete, Waiting for Subscriber Data" + } + )); + if !state.shaping_ready { + event_log.push( + "Subscriber topology inputs are still missing. Runtime will remain degraded until network.json and ShapedDevices.csv exist.".to_string(), + ); + } + Ok(()) +} + +fn load_existing_or_default(event_log: &mut Vec) -> Result { + if let Ok(config) = lqos_config::load_config() { + event_log.push("Loaded existing configuration".to_string()); + return Ok((*config).clone()); + } + + let config_path = Path::new("/etc/lqos.conf"); + if config_path.exists() { + let backup_path = "/etc/lqos.conf.setupbackup"; + std::fs::copy(config_path, backup_path).with_context(|| { + format!( + "Existing /etc/lqos.conf could not be loaded and could not be backed up to {backup_path}" + ) + })?; + event_log.push(format!( + "Existing /etc/lqos.conf could not be loaded. Backup saved to {backup_path}." + )); + } else { + event_log.push("Creating new configuration".to_string()); + } + + Ok(lqos_config::Config::default()) +} diff --git a/src/rust/lqos_setup/src/web.rs b/src/rust/lqos_setup/src/web.rs new file mode 100644 index 00000000..ff49e568 --- /dev/null +++ b/src/rust/lqos_setup/src/web.rs @@ -0,0 +1,651 @@ +//! Minimal setup-only web server for first-run LibreQoS configuration. + +use crate::{ + config_builder::{BridgeMode, CURRENT_CONFIG}, + interfaces, + service_handoff, + setup_actions::{self, CommitOutcome}, +}; +use anyhow::{Context, Result, bail}; +use axum::{ + Form, Router, + extract::Query, + http::StatusCode, + response::{Html, IntoResponse, Redirect, Response}, + routing::{get, post}, +}; +use lqos_config::{UserRole, WebUsers}; +use lqos_setup::{bootstrap, hotfix}; +use serde::Deserialize; +use std::fmt::Write as _; + +const BIND_ADDR: &str = "0.0.0.0:9123"; + +#[derive(Debug, Deserialize)] +struct SetupQuery { + token: Option, + notice: Option, +} + +#[derive(Debug, Deserialize)] +struct CompletedQuery { + auto: Option, +} + +#[derive(Debug, Deserialize)] +struct AdminForm { + token: String, + username: String, + password: String, + confirm_password: String, +} + +#[derive(Debug, Deserialize)] +struct SaveForm { + token: String, + node_name: String, + downlink_mbps: String, + uplink_mbps: String, + bridge_mode: String, + to_internet: String, + to_network: Option, + single_interface: Option, + internet_vlan: Option, + network_vlan: Option, + allow_subnets: String, +} + +#[derive(Debug, Deserialize)] +struct HotfixForm { + token: String, +} + +#[derive(Debug, Deserialize)] +struct PendingForm { + token: String, + operation_id: String, +} + +pub(crate) fn run() -> Result<()> { + if let Ok(urls) = bootstrap::current_setup_urls() + && !urls.is_empty() + { + for url in urls { + println!("Setup URL: {url}"); + } + } + + let runtime = tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + .context("Unable to create Tokio runtime for setup web server")?; + runtime.block_on(async { + let listener = tokio::net::TcpListener::bind(BIND_ADDR) + .await + .with_context(|| format!("Unable to bind setup web server to {BIND_ADDR}"))?; + let app = Router::new() + .route("/", get(root)) + .route("/setup", get(setup_page)) + .route("/setup/completed", get(completed_page)) + .route("/setup/install-hotfix", post(install_hotfix)) + .route("/setup/create-admin", post(create_admin)) + .route("/setup/save", post(save_setup)) + .route("/setup/confirm", get(root).post(confirm_setup)) + .route("/setup/revert", get(root).post(revert_setup)); + axum::serve(listener, app) + .await + .context("Setup web server exited unexpectedly") + }) +} + +async fn root() -> Redirect { + let target = match bootstrap::status_snapshot() { + Ok(snapshot) if snapshot.state.setup_complete => "/setup/completed?auto=1", + _ => "/setup", + }; + Redirect::temporary(target) +} + +async fn setup_page(Query(query): Query) -> Response { + match render_setup_page(query.token.as_deref(), query.notice.as_deref(), None) { + Ok(html) => Html(html).into_response(), + Err(err) => error_response(StatusCode::FORBIDDEN, &err.to_string()), + } +} + +async fn completed_page(Query(query): Query) -> Response { + let automatic = query.auto.as_deref() == Some("1"); + match render_completed_page(automatic) { + Ok(html) => Html(html).into_response(), + Err(err) => error_response(StatusCode::INTERNAL_SERVER_ERROR, &err.to_string()), + } +} + +async fn create_admin(Form(form): Form) -> Response { + if let Err(err) = ensure_valid_setup_token(&form.token) { + return error_response(StatusCode::FORBIDDEN, &err.to_string()); + } + if form.password != form.confirm_password { + return error_response(StatusCode::BAD_REQUEST, "Passwords did not match."); + } + if form.username.trim().is_empty() || form.password.is_empty() { + return error_response(StatusCode::BAD_REQUEST, "Username and password are required."); + } + + match WebUsers::load_or_create_in(&bootstrap::runtime_lqos_directory()).and_then(|mut users| { + users.add_or_update_user(form.username.trim(), &form.password, UserRole::Admin) + }) { + Ok(()) => match render_setup_page(Some(&form.token), Some("Admin account created."), None) + { + Ok(html) => Html(html).into_response(), + Err(err) => error_response(StatusCode::INTERNAL_SERVER_ERROR, &err.to_string()), + }, + Err(err) => error_response( + StatusCode::INTERNAL_SERVER_ERROR, + &format!("Unable to create admin user: {err}"), + ), + } +} + +async fn install_hotfix(Form(form): Form) -> Response { + if let Err(err) = ensure_valid_setup_token(&form.token) { + return error_response(StatusCode::FORBIDDEN, &err.to_string()); + } + match hotfix::install() { + Ok(result) => { + match render_setup_page(Some(&form.token), Some(&result.summary), Some(&result.detail)) + { + Ok(html) => Html(html).into_response(), + Err(err) => error_response(StatusCode::INTERNAL_SERVER_ERROR, &err.to_string()), + } + } + Err(err) => error_response(StatusCode::BAD_REQUEST, &err.to_string()), + } +} + +async fn save_setup(Form(form): Form) -> Response { + if let Err(err) = ensure_valid_setup_token(&form.token) { + return error_response(StatusCode::FORBIDDEN, &err.to_string()); + } + match hotfix::status() { + Ok(status) if status.required => { + return error_response( + StatusCode::BAD_REQUEST, + "Install the Noble systemd hotfix before saving setup.", + ); + } + Ok(_) => {} + Err(err) => return error_response(StatusCode::INTERNAL_SERVER_ERROR, &err.to_string()), + } + if !bootstrap::first_admin_exists() { + return error_response( + StatusCode::BAD_REQUEST, + "Create the first admin account before saving setup settings.", + ); + } + if let Err(err) = apply_form_to_current_config(&form) { + return error_response(StatusCode::BAD_REQUEST, &err.to_string()); + } + + match setup_actions::prepare_commit() { + Ok(CommitOutcome::Complete(success)) => match finalize_success_html(&success.config, success.event_log) { + Ok(html) => Html(html).into_response(), + Err(err) => error_response(StatusCode::INTERNAL_SERVER_ERROR, &err.to_string()), + }, + Ok(CommitOutcome::Pending(pending)) => { + Html(render_pending_page(&form.token, &pending.operation_id, &pending.prompt)) + .into_response() + } + Err(err) => error_response(StatusCode::BAD_REQUEST, &err.to_string()), + } +} + +async fn confirm_setup(Form(form): Form) -> Response { + if let Err(err) = ensure_valid_setup_token(&form.token) { + return error_response(StatusCode::FORBIDDEN, &err.to_string()); + } + match setup_actions::confirm_pending_commit(&form.operation_id) { + Ok(success) => match finalize_success_html(&success.config, success.event_log) { + Ok(html) => Html(html).into_response(), + Err(err) => error_response(StatusCode::INTERNAL_SERVER_ERROR, &err.to_string()), + }, + Err(err) => error_response(StatusCode::BAD_REQUEST, &err.to_string()), + } +} + +async fn revert_setup(Form(form): Form) -> Response { + if let Err(err) = ensure_valid_setup_token(&form.token) { + return error_response(StatusCode::FORBIDDEN, &err.to_string()); + } + match setup_actions::revert_pending_commit(&form.operation_id) { + Ok(message) => match render_setup_page(Some(&form.token), Some(&message), None) { + Ok(html) => Html(html).into_response(), + Err(err) => error_response(StatusCode::INTERNAL_SERVER_ERROR, &err.to_string()), + }, + Err(err) => error_response(StatusCode::BAD_REQUEST, &err.to_string()), + } +} + +fn render_setup_page( + token: Option<&str>, + notice: Option<&str>, + notice_detail: Option<&str>, +) -> Result { + let snapshot = bootstrap::status_snapshot()?; + let token = token.ok_or_else(|| anyhow::anyhow!("Setup requires a valid tokenized URL."))?; + ensure_valid_setup_token(token)?; + let interface_options = interfaces::get_interface_options().unwrap_or_default(); + let config = CURRENT_CONFIG.lock().clone(); + let mode_label = match config.bridge_mode { + BridgeMode::Single => "single", + _ => "linux", + }; + + let mut html = page_shell("LibreQoS Setup"); + html.push_str("
"); + html.push_str("
LibreQoSFirst-Run Setup

LibreQoS Setup

"); + html.push_str(&format!( + "

Status: {}

", + escape_html(snapshot.display_status.as_str()) + )); + if let Some(notice) = notice { + html.push_str("
"); + let _ = write!(html, "{}", escape_html(notice)); + if let Some(detail) = notice_detail { + let _ = write!( + html, + "
Show details
{}
", + escape_html(detail) + ); + } + html.push_str("
"); + } + html.push_str("
    "); + html.push_str(&format!( + "
  • Admin user exists: {}
  • ", + yes_no(snapshot.state.first_admin_exists) + )); + html.push_str(&format!( + "
  • Config loads: {}
  • ", + yes_no(snapshot.config_loads) + )); + html.push_str(&format!( + "
  • network.json present: {}
  • ", + yes_no(snapshot.network_json_present) + )); + html.push_str(&format!( + "
  • ShapedDevices.csv present: {}
  • ", + yes_no(snapshot.shaped_devices_present) + )); + html.push_str(&format!( + "
  • Hotfix required: {}
  • ", + yes_no(snapshot.hotfix_required) + )); + html.push_str("
"); + + if snapshot.hotfix_required { + html.push_str("

Ubuntu 24.04 Hotfix Required

"); + html.push_str(&format!( + "

{}

", + escape_html(&snapshot.hotfix_detail) + )); + html.push_str("

This can take around 30 seconds while LibreQoS upgrades the required systemd packages.

"); + html.push_str("
"); + hidden_token(&mut html, token); + html.push_str("
"); + } + + if !snapshot.state.first_admin_exists { + html.push_str("

Create First Admin

"); + html.push_str("
"); + hidden_token(&mut html, token); + html.push_str(""); + html.push_str(""); + html.push_str(""); + html.push_str("
"); + } else if !snapshot.hotfix_required { + html.push_str("

Core Setup

"); + html.push_str("
"); + hidden_token(&mut html, token); + html.push_str(&format!( + "", + escape_html(&config.node_name) + )); + html.push_str(&format!( + "", + config.mbps_to_internet + )); + html.push_str(&format!( + "", + config.mbps_to_network + )); + html.push_str(""); + html.push_str("
"); + html.push_str("

Recommended for most installs. Select the WAN-facing and subscriber-facing interfaces.

"); + html.push_str(""); + html.push_str(""); + html.push_str(""); + html.push_str("
"); + html.push_str("
"); + html.push_str("

Use this when a single interface carries both internet and subscriber traffic with optional VLAN tags.

"); + html.push_str(""); + html.push_str(&format!( + "", + config.internet_vlan + )); + html.push_str(&format!( + "", + config.network_vlan + )); + html.push_str("
"); + html.push_str(&format!( + "", + escape_html(&config.allow_subnets.join("\n")) + )); + html.push_str("
"); + } + + html.push_str("

Host Hints

    "); + for host in snapshot.host_hints { + html.push_str(&format!("
  • {}
  • ", escape_html(&host))); + } + html.push_str("

Use lqos_setup print-link to mint or refresh the current setup link.

"); + html.push_str(""); + html.push_str("
"); + Ok(html) +} + +fn apply_form_to_current_config(form: &SaveForm) -> Result<()> { + let downlink = form + .downlink_mbps + .trim() + .parse::() + .context("Downlink bandwidth must be a positive integer.")?; + let uplink = form + .uplink_mbps + .trim() + .parse::() + .context("Uplink bandwidth must be a positive integer.")?; + let allow_subnets = form + .allow_subnets + .lines() + .map(str::trim) + .filter(|line| !line.is_empty()) + .map(ToOwned::to_owned) + .collect::>(); + let mut config = CURRENT_CONFIG.lock(); + config.node_name = form.node_name.trim().to_string(); + config.mbps_to_internet = downlink; + config.mbps_to_network = uplink; + config.allow_subnets = allow_subnets; + match form.bridge_mode.as_str() { + "single" => { + config.bridge_mode = BridgeMode::Single; + let interface = form + .single_interface + .as_deref() + .map(str::trim) + .filter(|value| !value.is_empty()) + .ok_or_else(|| anyhow::anyhow!("A shaping interface is required."))?; + config.to_internet = interface.to_string(); + config.to_network.clear(); + config.internet_vlan = parse_vlan(form.internet_vlan.as_deref())?; + config.network_vlan = parse_vlan(form.network_vlan.as_deref())?; + } + "linux" => { + let to_network = form + .to_network + .as_deref() + .map(str::trim) + .filter(|value| !value.is_empty()) + .ok_or_else(|| anyhow::anyhow!("A network-facing interface is required."))?; + if form.to_internet.trim() == to_network { + bail!("Internet and network interfaces must be different."); + } + config.bridge_mode = BridgeMode::Linux; + config.to_internet = form.to_internet.trim().to_string(); + config.to_network = to_network.to_string(); + config.internet_vlan = 0; + config.network_vlan = 0; + } + _ => bail!("Unsupported bridge mode."), + } + Ok(()) +} + +fn parse_vlan(raw: Option<&str>) -> Result { + let value = raw.unwrap_or("0").trim(); + if value.is_empty() { + return Ok(0); + } + value + .parse::() + .with_context(|| format!("Invalid VLAN value: {value}")) +} + +fn ensure_valid_setup_token(token: &str) -> Result<()> { + if bootstrap::validate_setup_token(token)? { + Ok(()) + } else { + bail!("Setup token is missing, invalid, or expired. Run `lqos_setup print-link` for a current setup URL."); + } +} + +fn hidden_token(html: &mut String, token: &str) { + let _ = write!( + html, + "", + escape_html(token) + ); +} + +fn render_pending_page(token: &str, operation_id: &str, prompt: &str) -> String { + let mut html = page_shell("Confirm Network Change"); + html.push_str("
"); + html.push_str("

Confirm Network Change

"); + html.push_str(&format!( + "
{}
", + escape_html(prompt) + )); + html.push_str("
"); + html.push_str("
"); + hidden_token(&mut html, token); + let _ = write!( + html, + "", + escape_html(operation_id) + ); + html.push_str("
"); + html.push_str("
"); + hidden_token(&mut html, token); + let _ = write!( + html, + "", + escape_html(operation_id) + ); + html.push_str("
"); + html.push_str("
"); + html +} + +fn finalize_success_html( + config: &lqos_config::Config, + mut event_log: Vec, +) -> Result { + setup_actions::persist_setup_success(config, &mut event_log)?; + let handoff_notice = match service_handoff::schedule_runtime_handoff() { + Ok(notice) => { + event_log.push(notice.message.clone()); + Some(notice) + } + Err(err) => { + event_log.push(format!("WARNING: {err:#}")); + None + } + }; + let snapshot = bootstrap::status_snapshot()?; + let report = event_log.join("\n"); + let _ = bootstrap::store_setup_completion_report(&report); + let mut html = page_shell("Setup Complete"); + html.push_str("

Setup Saved

"); + html.push_str(&format!( + "

Current status: {}

", + escape_html(snapshot.display_status.as_str()) + )); + html.push_str(&format!( + "
Show setup actions
{}
", + escape_html(&report) + )); + if handoff_notice + .as_ref() + .is_some_and(|notice| notice.automatic) + { + html.push_str("

This setup page may stop while LibreQoS runtime services start. Refresh this address after the handoff if you want to load the normal runtime UI.

"); + html.push_str( + "", + ); + } + html.push_str("
"); + Ok(html) +} + +fn render_completed_page(automatic: bool) -> Result { + let snapshot = bootstrap::status_snapshot()?; + let report = bootstrap::load_setup_completion_report().unwrap_or_default(); + let mut html = page_shell("Setup Complete"); + html.push_str("

Setup Saved

"); + html.push_str(&format!( + "

Current status: {}

", + escape_html(snapshot.display_status.as_str()) + )); + if !report.is_empty() { + html.push_str(&format!( + "
Show setup actions
{}
", + escape_html(&report) + )); + } + if automatic { + html.push_str("

This setup page may stop while LibreQoS runtime services start. Refresh this address after the handoff if you want to load the normal runtime UI.

"); + html.push_str( + "", + ); + } + html.push_str("
"); + Ok(html) +} + +fn page_shell(title: &str) -> String { + format!( + "{}", + escape_html(title), + base_css(), + base_js() + ) +} + +fn base_css() -> &'static str { + ":root{--lqos-font-sans:\"InterVar\",system-ui,-apple-system,\"Segoe UI\",Roboto,\"Helvetica Neue\",Arial,sans-serif;--lqos-bg:radial-gradient(1200px 800px at 10% 0%,rgba(59,130,246,.14),transparent 60%),radial-gradient(900px 600px at 90% 20%,rgba(16,185,129,.12),transparent 55%),linear-gradient(180deg,#f7f8fb 0%,#eef4fb 100%);--lqos-surface:rgba(255,255,255,.82);--lqos-surface-2:rgba(248,250,252,.94);--lqos-border:rgba(15,23,42,.12);--lqos-shadow:0 18px 50px rgba(0,0,0,.10),0 6px 18px rgba(0,0,0,.06);--lqos-primary:#2563eb;--lqos-primary-dark:#1d4ed8;--lqos-accent:#0f766e;--lqos-text:#0f172a;--lqos-muted:#5b6471}\ + *{box-sizing:border-box}\ + body{margin:0;font-family:var(--lqos-font-sans);background:var(--lqos-bg);color:var(--lqos-text);min-height:100vh}\ + .setup-shell{max-width:900px;margin:0 auto;padding:32px 20px 64px}\ + .card{background:var(--lqos-surface);border:1px solid var(--lqos-border);border-radius:18px;padding:24px;margin-bottom:18px;box-shadow:var(--lqos-shadow);backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px)}\ + .card-hero{background:linear-gradient(180deg,rgba(255,255,255,.94),rgba(255,255,255,.82));position:relative;overflow:hidden}\ + .card-hero::after{content:\"\";position:absolute;inset:auto -10% -30% auto;width:280px;height:280px;background:radial-gradient(circle,rgba(37,99,235,.16) 0%,rgba(15,118,110,.08) 45%,transparent 72%);pointer-events:none}\ + .brand-row{display:flex;align-items:center;gap:10px;margin-bottom:12px;flex-wrap:wrap}\ + .brand-badge{display:inline-flex;align-items:center;padding:6px 10px;border-radius:999px;background:linear-gradient(135deg,var(--lqos-primary),var(--lqos-accent));color:#fff;font-size:.78rem;font-weight:800;letter-spacing:.04em;text-transform:uppercase}\ + .brand-caption{font-size:.85rem;font-weight:700;color:var(--lqos-primary-dark);text-transform:uppercase;letter-spacing:.08em}\ + h1,h2{margin:0 0 14px}\ + h1{font-size:2rem;line-height:1.1}\ + label{display:block;font-weight:700;margin:14px 0 6px}\ + input,select,textarea{width:100%;box-sizing:border-box;border:1px solid rgba(15,23,42,.14);border-radius:12px;padding:10px 12px;font:inherit;background:rgba(255,255,255,.98);box-shadow:inset 0 1px 2px rgba(15,23,42,.04)}\ + input:focus,select:focus,textarea:focus{outline:none;border-color:rgba(37,99,235,.45);box-shadow:0 0 0 4px rgba(59,130,246,.16)}\ + button{margin-top:16px;background:linear-gradient(135deg,var(--lqos-primary),var(--lqos-accent));color:#fff;border:0;border-radius:999px;padding:11px 18px;font:inherit;font-weight:800;cursor:pointer;box-shadow:0 12px 24px rgba(37,99,235,.18)}\ + button[disabled]{opacity:.7;cursor:progress}\ + button.secondary{background:linear-gradient(135deg,#64748b,#475569)}.button-row{display:flex;gap:12px;flex-wrap:wrap}.button-row form{margin:0}\ + .muted{color:var(--lqos-muted)}.notice{background:#fff7d6;border:1px solid #e7d48b;padding:12px 14px;border-radius:12px}\ + .notice-details{margin-top:10px}.notice-details summary{cursor:pointer;font-weight:700}\ + .mode-section[hidden]{display:none}\ + .status-list{margin:0;padding-left:18px}.status-list li{margin:6px 0}.report{white-space:pre-wrap;background:var(--lqos-surface-2);border:1px solid #d5dde7;border-radius:12px;padding:16px;overflow:auto}\ + .busy-overlay{position:fixed;inset:0;background:rgba(15,23,42,.28);display:flex;align-items:center;justify-content:center;padding:20px;z-index:9999}\ + .busy-overlay[hidden]{display:none !important}\ + .busy-card{width:min(520px,100%);background:#fff;border-radius:16px;padding:24px;box-shadow:0 18px 40px rgba(15,23,42,.18)}\ + .busy-bar{height:12px;border-radius:999px;background:linear-gradient(90deg,var(--lqos-primary) 0%,#14b8a6 30%,#d1fae5 50%,#14b8a6 70%,var(--lqos-primary) 100%);background-size:200% 100%;animation:busy-slide 1.2s linear infinite;margin-bottom:14px}\ + @keyframes busy-slide{0%{background-position:200% 0}100%{background-position:-200% 0}}\ + .validation-message{margin:10px 0 0;color:#b91c1c;font-weight:700}\ + code{background:#eef2f7;padding:2px 6px;border-radius:6px}" +} + +fn base_js() -> &'static str { + "function syncModeSections(){const mode=document.querySelector('select[name=\"bridge_mode\"]')?.value||'linux';document.querySelectorAll('.mode-section').forEach((section)=>{section.hidden=section.dataset.mode!==mode;});updateCoreSetupValidation();}\ + function showBusy(message){const overlay=document.getElementById('busyOverlay');const target=document.getElementById('busyMessage');if(target&&message){target.textContent=message;}if(overlay){overlay.hidden=false;}}\ + function hideBusy(){const overlay=document.getElementById('busyOverlay');if(overlay){overlay.hidden=true;}}\ + function setSubmitDisabled(form,disabled){const button=form?.querySelector('button[type=\"submit\"]');if(button){button.disabled=!!disabled;}}\ + function submitWithProgress(form,message){setSubmitDisabled(form,true);showBusy(message);return true;}\ + function currentBridgeMode(){return document.querySelector('select[name=\"bridge_mode\"]')?.value||'linux';}\ + function linuxInterfacesAreDistinct(){const toInternet=document.querySelector('select[name=\"to_internet\"]')?.value||'';const toNetwork=document.querySelector('select[name=\"to_network\"]')?.value||'';return !toInternet||!toNetwork||toInternet!==toNetwork;}\ + function updateCoreSetupValidation(){const form=document.getElementById('coreSetupForm');if(!form){return true;}const message=document.getElementById('interfaceValidationMessage');const invalid=currentBridgeMode()==='linux'&&!linuxInterfacesAreDistinct();if(message){message.hidden=!invalid;}setSubmitDisabled(form,invalid);return !invalid;}\ + function validateAndSubmitSetup(form){if(!updateCoreSetupValidation()){hideBusy();setSubmitDisabled(form,false);return false;}return submitWithProgress(form,'Saving setup and applying managed network changes...');}\ + function resetBusyState(){hideBusy();document.querySelectorAll('form').forEach((form)=>setSubmitDisabled(form,false));updateCoreSetupValidation();}\ + function setupPage(){const mode=document.querySelector('select[name=\"bridge_mode\"]');if(mode){mode.addEventListener('change',syncModeSections);}const toInternet=document.querySelector('select[name=\"to_internet\"]');if(toInternet){toInternet.addEventListener('change',updateCoreSetupValidation);}const toNetwork=document.querySelector('select[name=\"to_network\"]');if(toNetwork){toNetwork.addEventListener('change',updateCoreSetupValidation);}window.addEventListener('pageshow',resetBusyState);syncModeSections();resetBusyState();}" +} + +fn escape_html(input: &str) -> String { + input + .replace('&', "&") + .replace('<', "<") + .replace('>', ">") + .replace('"', """) + .replace('\'', "'") +} + +fn error_response(status: StatusCode, message: &str) -> Response { + let mut html = page_shell("Setup Error"); + html.push_str("

Setup Error

"); + html.push_str(&format!("

{}

", escape_html(message))); + html.push_str("
"); + (status, Html(html)).into_response() +} + +fn yes_no(value: bool) -> &'static str { + if value { "yes" } else { "no" } +} + +fn selected(value: bool) -> &'static str { + if value { " selected" } else { "" } +} diff --git a/src/rust/lqos_setup/src/webusers.rs b/src/rust/lqos_setup/src/webusers.rs index 697bc181..c7bf580f 100644 --- a/src/rust/lqos_setup/src/webusers.rs +++ b/src/rust/lqos_setup/src/webusers.rs @@ -4,12 +4,17 @@ use cursive::{ view::{Nameable, Resizable}, views::{Button, Dialog, EditView, LinearLayout, SelectView, TextView}, }; +use lqos_setup::bootstrap; use lqos_config::{UserRole, WebUsers}; +fn load_or_create_setup_users() -> Result { + WebUsers::load_or_create_in(&bootstrap::runtime_lqos_directory()) +} + /// Shows and manages the list of web users. pub fn webusers_menu(s: &mut Cursive) { // Load or create the web users config - let webusers = match WebUsers::load_or_create() { + let webusers = match load_or_create_setup_users() { Ok(wu) => wu, Err(e) => { s.add_layer(Dialog::info(format!("Failed to load web users: {e}"))); @@ -35,7 +40,7 @@ pub fn webusers_menu(s: &mut Cursive) { .child(TextView::new("Web Users:")) .child(select_view) .child(Button::new("Remove Selected", move |s| { - let mut webusers = match WebUsers::load_or_create() { + let mut webusers = match load_or_create_setup_users() { Ok(wu) => wu, Err(e) => { s.add_layer(Dialog::info(format!("Failed to load web users: {e}"))); @@ -107,7 +112,7 @@ pub fn webusers_menu(s: &mut Cursive) { .unwrap() .to_string(); let role = UserRole::from(role_str.as_str()); - let mut webusers = match WebUsers::load_or_create() { + let mut webusers = match load_or_create_setup_users() { Ok(wu) => wu, Err(e) => { s.add_layer(Dialog::info(format!("Failed to load web users: {e}"))); @@ -155,7 +160,7 @@ pub fn webusers_menu(s: &mut Cursive) { }) .unwrap() .to_string(); - let mut webusers = match WebUsers::load_or_create() { + let mut webusers = match load_or_create_setup_users() { Ok(wu) => wu, Err(e) => { s.add_layer(Dialog::info(format!( @@ -164,7 +169,6 @@ pub fn webusers_menu(s: &mut Cursive) { return; } }; - // Default to Admin role for password change (could be improved) let user = webusers .get_users() .into_iter() diff --git a/src/rust/lqosd/src/lts2_sys/control_channel.rs b/src/rust/lqosd/src/lts2_sys/control_channel.rs index 3618619b..24154ad8 100644 --- a/src/rust/lqosd/src/lts2_sys/control_channel.rs +++ b/src/rust/lqosd/src/lts2_sys/control_channel.rs @@ -1491,10 +1491,13 @@ async fn circuit_snapshot_streaming( for (xdp_ip, te) in raw.iter() { let device = catalog .device_by_hashes(te.device_hash, te.circuit_hash) - .or_else(|| catalog.device_longest_match_for_ip(xdp_ip).map(|(_, device)| device)); - let matches_desired = - te.circuit_hash == Some(circuit_hash) - || device.is_some_and(|device| device.circuit_hash == circuit_hash); + .or_else(|| { + catalog + .device_longest_match_for_ip(xdp_ip) + .map(|(_, device)| device) + }); + let matches_desired = te.circuit_hash == Some(circuit_hash) + || device.is_some_and(|device| device.circuit_hash == circuit_hash); if !matches_desired { continue; } @@ -1599,9 +1602,8 @@ async fn circuit_snapshot_streaming( .device_longest_match_for_ip(&key.local_ip) .map(|(_, device)| device) }); - let matches_desired = - local.circuit_hash == Some(circuit_hash) - || device.is_some_and(|device| device.circuit_hash == circuit_hash); + let matches_desired = local.circuit_hash == Some(circuit_hash) + || device.is_some_and(|device| device.circuit_hash == circuit_hash); if !matches_desired { continue; } diff --git a/src/rust/lqosd/src/node_manager.rs b/src/rust/lqosd/src/node_manager.rs index daf80a84..9e1ad720 100644 --- a/src/rust/lqosd/src/node_manager.rs +++ b/src/rust/lqosd/src/node_manager.rs @@ -1,6 +1,7 @@ mod auth; pub(crate) mod local_api; mod run; +mod runtime_onboarding; mod shaper_queries_actor; mod static_pages; mod template; diff --git a/src/rust/lqosd/src/node_manager/auth.rs b/src/rust/lqosd/src/node_manager/auth.rs index d0faac37..a2057954 100644 --- a/src/rust/lqosd/src/node_manager/auth.rs +++ b/src/rust/lqosd/src/node_manager/auth.rs @@ -1,5 +1,6 @@ //! Provides authentication for the Node Manager. +use crate::node_manager::runtime_onboarding::runtime_onboarding_state; use axum::Json; use axum::http::StatusCode; use axum::response::{Html, IntoResponse, Redirect, Response}; @@ -379,7 +380,7 @@ pub async fn login_page(jar: CookieJar) -> Response { Redirect::temporary("/first-run.html").into_response() } AuthBootstrapState::Ready => match session_from_cookie(&jar, &snapshot) { - Ok(Some(_)) => Redirect::temporary("/index.html").into_response(), + Ok(Some(_)) => Redirect::temporary(post_login_destination()).into_response(), Ok(None) => serve_standalone_page("login.html") .unwrap_or_else(|status| (status, "Unable to serve login page").into_response()), Err(status) => (status, "Unable to validate login session").into_response(), @@ -432,6 +433,33 @@ fn login_result_for_session(user: Option, allow_anonymous: bool) -> } } +fn post_login_destination() -> &'static str { + if runtime_onboarding_state().required { + "/setup_runtime.html" + } else { + "/index.html" + } +} + +fn runtime_onboarding_exempt_path(path: &str) -> bool { + matches!( + path, + "/setup_runtime.html" + | "/config_integration.html" + | "/config_splynx.html" + | "/config_netzur.html" + | "/config_visp.html" + | "/config_uisp.html" + | "/config_powercode.html" + | "/config_sonar.html" + | "/config_wispgate.html" + | "/config_network.html" + | "/config_devices.html" + | "/help.html" + | "/configuration.html" + ) +} + /// Checks an incoming request for a `User-Token` cookie. If found, /// it validates the request against the signed session and current auth epoch. /// Missing or empty auth state redirects to first-run; invalid sessions redirect @@ -460,6 +488,13 @@ pub async fn auth_layer( match login_result { LoginResult::Admin | LoginResult::ReadOnly => { record_first_login_timestamp_if_needed(); + let path = req.uri().path().to_string(); + if path.ends_with(".html") + && !runtime_onboarding_exempt_path(&path) + && runtime_onboarding_state().required + { + return Redirect::temporary("/setup_runtime.html").into_response(); + } req.extensions_mut().insert(login_result); next.run(req).await } diff --git a/src/rust/lqosd/src/node_manager/js_build/entrypoints.txt b/src/rust/lqosd/src/node_manager/js_build/entrypoints.txt index 3854a804..d5b4afef 100644 --- a/src/rust/lqosd/src/node_manager/js_build/entrypoints.txt +++ b/src/rust/lqosd/src/node_manager/js_build/entrypoints.txt @@ -2,6 +2,7 @@ index.js template.js login.js first-run.js +setup_runtime.js shaped-devices.js tree.js topology_manager.js diff --git a/src/rust/lqosd/src/node_manager/js_build/src/setup_runtime.js b/src/rust/lqosd/src/node_manager/js_build/src/setup_runtime.js new file mode 100644 index 00000000..354fe822 --- /dev/null +++ b/src/rust/lqosd/src/node_manager/js_build/src/setup_runtime.js @@ -0,0 +1,56 @@ +import { activeTopologySourceIntegrations, loadConfig } from "./config/config_helper"; + +function setText(id, text) { + const element = document.getElementById(id); + if (!element) return; + element.textContent = text; +} + +function setStatusAlert(state) { + const element = document.getElementById("runtimeSetupStatus"); + if (!element) return; + + const label = state?.status_label || "Setup Required"; + const summary = state?.summary || "Choose a topology source before expecting scheduler activity."; + const alertClass = state?.required ? "alert-warning" : "alert-success"; + element.className = `alert ${alertClass} mb-4`; + element.innerHTML = ` +
${label}
+
${summary}
`; +} + +function renderState(state) { + const config = window.config || {}; + const activeIntegrations = state?.active_integrations?.length + ? state.active_integrations + : activeTopologySourceIntegrations(config); + + setStatusAlert(state); + setText( + "runtimeActiveIntegrations", + activeIntegrations.length ? activeIntegrations.join(", ") : "None configured", + ); + setText("runtimeNetworkJson", state?.network_json_present ? "Present" : "Missing"); + setText("runtimeShapedDevices", state?.shaped_devices_present ? "Present" : "Missing"); +} + +function initActions() { + const button = document.getElementById("btnOpenIntegrationProvider"); + const select = document.getElementById("runtimeIntegrationProvider"); + if (!button || !select) return; + button.addEventListener("click", () => { + window.location.href = select.value; + }); +} + +loadConfig((msg) => { + renderState(msg?.data?.runtime_onboarding || {}); + initActions(); +}, () => { + setStatusAlert({ + required: true, + status_label: "Setup Required", + summary: "Unable to load runtime setup status right now.", + }); + initActions(); +}); diff --git a/src/rust/lqosd/src/node_manager/js_build/src/template.js b/src/rust/lqosd/src/node_manager/js_build/src/template.js index 4218ebb0..d90a7d05 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/template.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/template.js @@ -124,6 +124,7 @@ function schedulerStateDescriptor(data) { const hasError = !!(data?.error && String(data.error).trim().length > 0); const available = !!data?.available; const active = !!progress?.active; + const setupRequired = !!data?.setup_required; if (hasError) { return { @@ -136,6 +137,17 @@ function schedulerStateDescriptor(data) { icon: "fa-triangle-exclamation", }; } + if (setupRequired) { + return { + tone: "warning", + badgeClass: "text-bg-warning", + label: "Setup Required", + title: "Choose a topology source", + subtitle: data?.setup_message || "LibreQoS needs subscriber data before the scheduler can run", + ringTone: "tone-warning", + icon: "fa-list-check", + }; + } if (active) { return { tone: "info", @@ -190,7 +202,21 @@ function summarizeSchedulerOutput(output, error) { return lines[lines.length - 1]; } -function schedulerActivityItems(output, error) { +function schedulerSetupMessage(data) { + if (data?.setup_required && data?.setup_message) { + return String(data.setup_message).trim(); + } + return ""; +} + +function schedulerActivityItems(output, error, data) { + const setupMessage = schedulerSetupMessage(data); + if (setupMessage.length > 0) { + return [ + setupMessage, + "Open Complete Setup to choose an integration or provide manual subscriber data.", + ]; + } if (error && String(error).trim().length > 0) { return [String(error).trim()]; } @@ -215,14 +241,19 @@ function renderSchedulerDetails(data) { const updatedText = progress?.updated_unix ? schedulerRelativeTime(progress.updated_unix) : "Update time unavailable"; - const availabilityText = data?.available ? "Healthy" : "Unavailable"; - const recentResult = summarizeSchedulerOutput(data?.output, data?.error); - const activity = schedulerActivityItems(data?.output, data?.error); - const progressMeta = progress?.active - ? `${percent}% complete` - : descriptor.label === "Idle" - ? "Last run complete" - : "Waiting for activity"; + const availabilityText = data?.setup_required ? "Setup Required" : (data?.available ? "Healthy" : "Unavailable"); + const recentResult = schedulerSetupMessage(data) || summarizeSchedulerOutput(data?.output, data?.error); + const activity = schedulerActivityItems(data?.output, data?.error, data); + const progressMeta = data?.setup_required + ? "Complete runtime setup to enable scheduler work" + : progress?.active + ? `${percent}% complete` + : descriptor.label === "Idle" + ? "Last run complete" + : "Waiting for activity"; + const setupAlert = data?.setup_required + ? `` + : ""; const alertMarkup = data?.error ? `` : ""; @@ -248,6 +279,7 @@ function renderSchedulerDetails(data) {
${escapeHtml(updatedText)}
+ ${setupAlert} ${alertMarkup}
@@ -332,6 +364,10 @@ function renderSchedulerStatus(container, state, progress) { color = "text-danger"; label = "Scheduler has an internal error"; indicator = schedulerRingMarkup(100, "tone-danger", "fa-triangle-exclamation"); + } else if (state === "setup") { + color = "text-warning"; + label = "Scheduler needs topology setup"; + indicator = schedulerRingMarkup(100, "tone-warning", "fa-list-check"); } container.innerHTML = ` @@ -381,6 +417,7 @@ function loadSchedulerStatus(force = false) { const isHealthy = !!data.available && !hasError; const progress = data.progress || null; const progressActive = !!(progress && progress.active); + const setupRequired = !!data.setup_required; const elapsed = schedulerStatusFirstRequestedAt === null ? 0 : (Date.now() - schedulerStatusFirstRequestedAt); if (hasError) { @@ -389,6 +426,12 @@ function loadSchedulerStatus(force = false) { return; } + if (setupRequired) { + renderSchedulerStatus(container, "setup", progress); + scheduleNextSchedulerStatusPoll(); + return; + } + if (progressActive) { renderSchedulerStatus(container, "progress", progress); scheduleNextSchedulerStatusPoll(); diff --git a/src/rust/lqosd/src/node_manager/local_api/config.rs b/src/rust/lqosd/src/node_manager/local_api/config.rs index 8a58560a..5830c193 100644 --- a/src/rust/lqosd/src/node_manager/local_api/config.rs +++ b/src/rust/lqosd/src/node_manager/local_api/config.rs @@ -1,5 +1,6 @@ use crate::node_manager::auth::LoginResult; use crate::node_manager::local_api::network_mode::NetworkModeInspection; +use crate::node_manager::runtime_onboarding::RuntimeOnboardingState; use crate::shaping_runtime::ShapingRuntimeStatus; use axum::http::StatusCode; use default_net::get_interfaces; @@ -160,6 +161,8 @@ pub struct ConfigView { pub shaping_status: ShapingRuntimeStatus, #[serde(default)] pub network_mode_inspection: NetworkModeInspection, + #[serde(default)] + pub runtime_onboarding: RuntimeOnboardingState, } pub fn admin_check_data(login: LoginResult) -> bool { @@ -324,6 +327,8 @@ pub fn get_config_data(login: LoginResult) -> Result { shaping_status: crate::shaping_runtime::get_status(), network_mode_inspection: crate::node_manager::local_api::network_mode::inspect_network_mode(&config), + runtime_onboarding: + crate::node_manager::runtime_onboarding::runtime_onboarding_state(), config, secret_state, } diff --git a/src/rust/lqosd/src/node_manager/local_api/executive_cache.rs b/src/rust/lqosd/src/node_manager/local_api/executive_cache.rs index ae7f80b5..5c9495b0 100644 --- a/src/rust/lqosd/src/node_manager/local_api/executive_cache.rs +++ b/src/rust/lqosd/src/node_manager/local_api/executive_cache.rs @@ -690,13 +690,13 @@ fn build_oversubscribed_sites( lqos_network_devices::shaped_devices_catalog().circuit_rate_caps_by_circuit_id(); for circuit in lqos_network_devices::dynamic_circuits_snapshot().iter() { let shaped = &circuit.shaped; - circuit_caps.entry(shaped.circuit_id.clone()).or_insert_with(|| { - lqos_network_devices::CircuitRateCaps { + circuit_caps + .entry(shaped.circuit_id.clone()) + .or_insert_with(|| lqos_network_devices::CircuitRateCaps { parent_node: shaped.parent_node.clone(), download_max_mbps: shaped.download_max_mbps, upload_max_mbps: shaped.upload_max_mbps, - } - }); + }); } let entity_map = entities diff --git a/src/rust/lqosd/src/node_manager/local_api/flow_explorer.rs b/src/rust/lqosd/src/node_manager/local_api/flow_explorer.rs index e4a2f35c..87444806 100644 --- a/src/rust/lqosd/src/node_manager/local_api/flow_explorer.rs +++ b/src/rust/lqosd/src/node_manager/local_api/flow_explorer.rs @@ -1,4 +1,3 @@ -use crate::throughput_tracker::THROUGHPUT_TRACKER; use crate::throughput_tracker::flow_data::{ AsnCountryListEntry, AsnListEntry, AsnProtocolListEntry, FlowAnalysis, FlowbeeLocalData, RECENT_FLOWS, RttData, diff --git a/src/rust/lqosd/src/node_manager/local_api/scheduler.rs b/src/rust/lqosd/src/node_manager/local_api/scheduler.rs index 228b501a..0506842e 100644 --- a/src/rust/lqosd/src/node_manager/local_api/scheduler.rs +++ b/src/rust/lqosd/src/node_manager/local_api/scheduler.rs @@ -2,6 +2,7 @@ use serde::Serialize; use lqos_bus::SchedulerProgressReport; +use crate::node_manager::runtime_onboarding::runtime_onboarding_state; use crate::tool_status::{ is_scheduler_available, scheduler_error_message, scheduler_output_message, scheduler_progress_state, @@ -68,6 +69,8 @@ pub struct SchedulerStatus { pub available: bool, pub error: Option, pub progress: Option, + pub setup_required: bool, + pub setup_message: Option, } #[derive(Serialize, Debug, Clone)] @@ -76,6 +79,8 @@ pub struct SchedulerDetails { pub error: Option, pub output: Option, pub progress: Option, + pub setup_required: bool, + pub setup_message: Option, pub details: String, } @@ -102,6 +107,17 @@ fn scheduler_output() -> Option { } pub fn scheduler_status_data() -> SchedulerStatus { + let onboarding = runtime_onboarding_state(); + if onboarding.required { + return SchedulerStatus { + available: false, + error: None, + progress: None, + setup_required: true, + setup_message: Some(onboarding.summary), + }; + } + let available = is_scheduler_available(); let error = scheduler_error(); let progress = scheduler_progress_state(); @@ -109,6 +125,8 @@ pub fn scheduler_status_data() -> SchedulerStatus { available, error, progress, + setup_required: false, + setup_message: None, } } @@ -116,6 +134,26 @@ pub fn scheduler_details_data() -> SchedulerDetails { let status = scheduler_status_data(); let output = scheduler_output(); let mut body = String::new(); + if status.setup_required { + let message = status.setup_message.clone().unwrap_or_else(|| { + "Choose a topology source in Complete Setup before expecting scheduler activity." + .to_string() + }); + body.push_str("Scheduler status: setup required\n\n"); + body.push_str("LibreQoS runtime onboarding is incomplete.\n"); + body.push_str(&message); + body.push('\n'); + return SchedulerDetails { + available: false, + error: None, + output: None, + progress: None, + setup_required: true, + setup_message: Some(message), + details: body, + }; + } + body.push_str(&format!("Scheduler available: {}\n\n", status.available)); match status.progress.as_ref() { Some(progress) => { @@ -165,6 +203,8 @@ pub fn scheduler_details_data() -> SchedulerDetails { error: status.error, output, progress: status.progress, + setup_required: false, + setup_message: None, details: body, } } diff --git a/src/rust/lqosd/src/node_manager/local_api/search.rs b/src/rust/lqosd/src/node_manager/local_api/search.rs index b1cb6ca0..68cb43bf 100644 --- a/src/rust/lqosd/src/node_manager/local_api/search.rs +++ b/src/rust/lqosd/src/node_manager/local_api/search.rs @@ -240,8 +240,7 @@ pub fn search_results(search: SearchRequest) -> Vec { }; let n = IpNetwork::V6(v6net); if ipv6_overlap(&n, query_v6) { - let name = - format!("{} ({})", dev.device_name, pretty_net(&n)); + let name = format!("{} ({})", dev.device_name, pretty_net(&n)); push_result( &mut results, &mut seen, @@ -266,8 +265,7 @@ pub fn search_results(search: SearchRequest) -> Vec { }; let n = IpNetwork::V6(v6net); if ipv6_overlap(&n, query_v6) { - let name = - format!("{} ({})", dev.device_name, pretty_net(&n)); + let name = format!("{} ({})", dev.device_name, pretty_net(&n)); push_result( &mut results, &mut seen, diff --git a/src/rust/lqosd/src/node_manager/local_api/shaped_devices_page.rs b/src/rust/lqosd/src/node_manager/local_api/shaped_devices_page.rs index 08efe5e3..dc21a98f 100644 --- a/src/rust/lqosd/src/node_manager/local_api/shaped_devices_page.rs +++ b/src/rust/lqosd/src/node_manager/local_api/shaped_devices_page.rs @@ -64,32 +64,31 @@ pub fn shaped_devices_page(query: ShapedDevicesPageQuery) -> ShapedDevicesPage { let search = query.search.as_deref().unwrap_or("").trim().to_lowercase(); let kind = query.kind.clone().unwrap_or(ShapedDevicesPageKind::Static); - let matches_search = |device: &ShapedDevice| { - if search.is_empty() { - return true; - } - device.device_name.to_lowercase().contains(&search) - || device.circuit_name.to_lowercase().contains(&search) - || device.parent_node.to_lowercase().contains(&search) - || device.circuit_id.to_lowercase().contains(&search) - || device.device_id.to_lowercase().contains(&search) - || device.mac.to_lowercase().contains(&search) - || device.comment.to_lowercase().contains(&search) - || device - .sqm_override - .as_deref() - .unwrap_or("") - .to_lowercase() - .contains(&search) - || device - .ipv4 - .iter() - .any(|(addr, prefix)| format!("{addr}/{prefix}").to_lowercase().contains(&search)) - || device - .ipv6 - .iter() - .any(|(addr, prefix)| format!("{addr}/{prefix}").to_lowercase().contains(&search)) - }; + let matches_search = + |device: &ShapedDevice| { + if search.is_empty() { + return true; + } + device.device_name.to_lowercase().contains(&search) + || device.circuit_name.to_lowercase().contains(&search) + || device.parent_node.to_lowercase().contains(&search) + || device.circuit_id.to_lowercase().contains(&search) + || device.device_id.to_lowercase().contains(&search) + || device.mac.to_lowercase().contains(&search) + || device.comment.to_lowercase().contains(&search) + || device + .sqm_override + .as_deref() + .unwrap_or("") + .to_lowercase() + .contains(&search) + || device.ipv4.iter().any(|(addr, prefix)| { + format!("{addr}/{prefix}").to_lowercase().contains(&search) + }) + || device.ipv6.iter().any(|(addr, prefix)| { + format!("{addr}/{prefix}").to_lowercase().contains(&search) + }) + }; let mut filtered: Vec = match kind { ShapedDevicesPageKind::Static => lqos_network_devices::shaped_devices_catalog() diff --git a/src/rust/lqosd/src/node_manager/local_api/tree_attached_circuits.rs b/src/rust/lqosd/src/node_manager/local_api/tree_attached_circuits.rs index 886a75e3..0bdc42cc 100644 --- a/src/rust/lqosd/src/node_manager/local_api/tree_attached_circuits.rs +++ b/src/rust/lqosd/src/node_manager/local_api/tree_attached_circuits.rs @@ -195,15 +195,15 @@ fn effective_or_canonical_parent(device: &ShapedDevice) -> Option<(String, Optio &device.parent_node, device.parent_node_id.as_deref(), ) - .map(|resolved| (resolved.name, resolved.id)) - .or_else(|| { - let trimmed = device.parent_node.trim(); - if trimmed.is_empty() { - None - } else { - Some((trimmed.to_string(), device.parent_node_id.clone())) - } - }) + .map(|resolved| (resolved.name, resolved.id)) + .or_else(|| { + let trimmed = device.parent_node.trim(); + if trimmed.is_empty() { + None + } else { + Some((trimmed.to_string(), device.parent_node_id.clone())) + } + }) } fn aggregate_attached_circuit_rows<'a>( @@ -392,8 +392,8 @@ pub fn tree_attached_circuits(query: TreeAttachedCircuitsQuery) -> TreeAttachedC #[cfg(test)] mod tests { use super::*; - use std::str::FromStr; use lqos_config::ConfigShapedDevices; + use std::str::FromStr; fn sample_device( circuit_id: &str, diff --git a/src/rust/lqosd/src/node_manager/runtime_onboarding.rs b/src/rust/lqosd/src/node_manager/runtime_onboarding.rs new file mode 100644 index 00000000..a03d0bf0 --- /dev/null +++ b/src/rust/lqosd/src/node_manager/runtime_onboarding.rs @@ -0,0 +1,197 @@ +//! Determines whether runtime topology onboarding is still required after +//! `lqos_setup` has handed control to `lqosd`. + +use lqos_config::{Config, load_config}; +use serde::{Deserialize, Serialize}; +use std::path::Path; + +use crate::node_manager::local_api::config::active_topology_source_integrations; + +/// Describes the topology source family currently detected by `lqosd`. +#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub(crate) enum RuntimeTopologySourceKind { + #[default] + None, + Integration, + ManualFiles, +} + +/// Reports whether the operator still needs to finish runtime topology setup. +#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)] +pub(crate) struct RuntimeOnboardingState { + /// True when the UI should keep steering the operator into topology setup. + pub required: bool, + /// Short operator-facing state label. + pub status_label: String, + /// Short guidance text explaining the next required action. + pub summary: String, + /// Topology source family currently present. + pub source_kind: RuntimeTopologySourceKind, + /// Enabled integration names that currently own topology input. + pub active_integrations: Vec, + /// Whether `network.json` exists in the configured LibreQoS directory. + pub network_json_present: bool, + /// Whether `ShapedDevices.csv` exists in the configured LibreQoS directory. + pub shaped_devices_present: bool, +} + +fn topology_files_present(config: &Config) -> (bool, bool) { + let base = Path::new(&config.lqos_directory); + ( + base.join("network.json").exists(), + base.join("ShapedDevices.csv").exists(), + ) +} + +fn from_config(config: &Config) -> RuntimeOnboardingState { + let active_integrations = active_topology_source_integrations(config) + .into_iter() + .map(str::to_string) + .collect::>(); + let (network_json_present, shaped_devices_present) = topology_files_present(config); + + if !active_integrations.is_empty() { + return RuntimeOnboardingState { + required: false, + status_label: "Ready".to_string(), + summary: format!( + "Topology source is configured through {}.", + active_integrations.join(", ") + ), + source_kind: RuntimeTopologySourceKind::Integration, + active_integrations, + network_json_present, + shaped_devices_present, + }; + } + + if network_json_present && shaped_devices_present { + return RuntimeOnboardingState { + required: false, + status_label: "Ready".to_string(), + summary: "Manual topology files are present.".to_string(), + source_kind: RuntimeTopologySourceKind::ManualFiles, + active_integrations, + network_json_present, + shaped_devices_present, + }; + } + + let source_kind = if network_json_present || shaped_devices_present { + RuntimeTopologySourceKind::ManualFiles + } else { + RuntimeTopologySourceKind::None + }; + let summary = match (network_json_present, shaped_devices_present) { + (false, false) => { + "Choose a topology source before expecting scheduler activity.".to_string() + } + (false, true) => "ShapedDevices.csv exists, but network.json is still missing.".to_string(), + (true, false) => "network.json exists, but ShapedDevices.csv is still missing.".to_string(), + (true, true) => unreachable!("handled above"), + }; + + RuntimeOnboardingState { + required: true, + status_label: "Setup Required".to_string(), + summary, + source_kind, + active_integrations, + network_json_present, + shaped_devices_present, + } +} + +/// Loads the current runtime onboarding state from config and topology files. +/// +/// On config-read failure this returns a conservative non-blocking state so the +/// UI does not loop on an internal error. +pub(crate) fn runtime_onboarding_state() -> RuntimeOnboardingState { + match load_config() { + Ok(config) => from_config(config.as_ref()), + Err(_) => RuntimeOnboardingState { + required: false, + status_label: "Unknown".to_string(), + summary: "Unable to determine topology onboarding state.".to_string(), + source_kind: RuntimeTopologySourceKind::None, + active_integrations: Vec::new(), + network_json_present: false, + shaped_devices_present: false, + }, + } +} + +#[cfg(test)] +mod tests { + use super::{RuntimeTopologySourceKind, from_config}; + use lqos_config::Config; + use std::fs; + use std::path::PathBuf; + use std::time::{SystemTime, UNIX_EPOCH}; + + fn test_dir(label: &str) -> PathBuf { + let unique = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("clock before epoch") + .as_nanos(); + let dir = std::env::temp_dir().join(format!( + "libreqos-runtime-onboarding-{label}-{}-{unique}", + std::process::id() + )); + fs::create_dir_all(&dir).expect("create temp dir"); + dir + } + + #[test] + fn requires_setup_when_no_integrations_or_manual_files_exist() { + let dir = test_dir("missing"); + let mut config = Config::default(); + config.lqos_directory = dir.to_string_lossy().into_owned(); + + let state = from_config(&config); + + assert!(state.required); + assert_eq!(state.source_kind, RuntimeTopologySourceKind::None); + assert!(!state.network_json_present); + assert!(!state.shaped_devices_present); + + fs::remove_dir_all(dir).expect("remove temp dir"); + } + + #[test] + fn manual_files_complete_runtime_onboarding() { + let dir = test_dir("manual"); + fs::write(dir.join("network.json"), "{}\n").expect("write network json"); + fs::write(dir.join("ShapedDevices.csv"), "Circuit ID,Device ID\n") + .expect("write shaped devices"); + + let mut config = Config::default(); + config.lqos_directory = dir.to_string_lossy().into_owned(); + + let state = from_config(&config); + + assert!(!state.required); + assert_eq!(state.source_kind, RuntimeTopologySourceKind::ManualFiles); + assert!(state.network_json_present); + assert!(state.shaped_devices_present); + + fs::remove_dir_all(dir).expect("remove temp dir"); + } + + #[test] + fn enabled_integration_counts_as_ready_topology_source() { + let dir = test_dir("integration"); + let mut config = Config::default(); + config.lqos_directory = dir.to_string_lossy().into_owned(); + config.splynx_integration.enable_splynx = true; + + let state = from_config(&config); + + assert!(!state.required); + assert_eq!(state.source_kind, RuntimeTopologySourceKind::Integration); + assert_eq!(state.active_integrations, vec!["Splynx".to_string()]); + + fs::remove_dir_all(dir).expect("remove temp dir"); + } +} diff --git a/src/rust/lqosd/src/node_manager/static2/setup_runtime.html b/src/rust/lqosd/src/node_manager/static2/setup_runtime.html new file mode 100644 index 00000000..9f016c6b --- /dev/null +++ b/src/rust/lqosd/src/node_manager/static2/setup_runtime.html @@ -0,0 +1,122 @@ +
+
+
+
+
Complete Setup
+
LibreQoS is running, but it still needs a topology source before the scheduler can build subscriber queues.
+
+ + Help + +
+ + + +
+
+
+
+ Recommended for CRM/NMS +
CRM / NMS Integration
+

+ Choose the system that already owns your subscribers and let LibreQoS reuse its existing integration page. +

+ + +
+ Save your provider settings there, then return here if the scheduler still says setup is required. +
+
+ +
+
+
+
+ +
+
+
+ Custom importer workflow +
My Own In-House Integration
+

+ Use this if another internal process writes network.json and ShapedDevices.csv for LibreQoS. +

+
    +
  • Set shared topology behavior under Integration - Common.
  • +
  • Write both files into the LibreQoS directory.
  • +
  • Reload the scheduler after your importer publishes data.
  • +
+ +
+
+
+ +
+
+
+ Manual editing +
Manually Edit Subscriber List
+

+ Build and maintain the topology directly in LibreQoS with the existing network and shaped-device editors. +

+ +
+
+
+
+ +
+
+
Detected Runtime State
+
+
+
+
Active Integrations
+
Loading...
+
+
+
+
+
network.json
+
Loading...
+
+
+
+
+
ShapedDevices.csv
+
Loading...
+
+
+
+
+
+
+
+ + diff --git a/src/rust/lqosd/src/node_manager/static_pages.rs b/src/rust/lqosd/src/node_manager/static_pages.rs index ab8286a2..d749cc2e 100644 --- a/src/rust/lqosd/src/node_manager/static_pages.rs +++ b/src/rust/lqosd/src/node_manager/static_pages.rs @@ -73,6 +73,7 @@ pub(super) fn static_routes() -> Result { "config_uisp.html", "config_powercode.html", "config_sonar.html", + "setup_runtime.html", "config_interface.html", "config_network.html", "config_devices.html", diff --git a/src/rust/lqosd/src/shaped_devices_tracker/circuit_live.rs b/src/rust/lqosd/src/shaped_devices_tracker/circuit_live.rs index 1bf4ad6b..3639e233 100644 --- a/src/rust/lqosd/src/shaped_devices_tracker/circuit_live.rs +++ b/src/rust/lqosd/src/shaped_devices_tracker/circuit_live.rs @@ -90,7 +90,11 @@ pub fn rebuild_circuit_live_snapshot() -> Arc { for (ip_key, data) in THROUGHPUT_TRACKER.raw_data.lock().iter() { let device = catalog .device_by_hashes(data.device_hash, data.circuit_hash) - .or_else(|| catalog.device_longest_match_for_ip(ip_key).map(|(_, dev)| dev)); + .or_else(|| { + catalog + .device_longest_match_for_ip(ip_key) + .map(|(_, dev)| dev) + }); let Some(device) = device else { continue; }; diff --git a/src/rust/lqosd/src/shaped_devices_tracker/mod.rs b/src/rust/lqosd/src/shaped_devices_tracker/mod.rs index 606afa56..66ffb4de 100644 --- a/src/rust/lqosd/src/shaped_devices_tracker/mod.rs +++ b/src/rust/lqosd/src/shaped_devices_tracker/mod.rs @@ -288,8 +288,8 @@ fn load_shaped_devices_from_preferred_source( } } - let shaped_devices = ConfigShapedDevices::load_for_config(config) - .context("Unable to load ShapedDevices.csv")?; + let shaped_devices = + ConfigShapedDevices::load_for_config(config).context("Unable to load ShapedDevices.csv")?; Ok((shaped_devices, ShapedDevicesLoadSource::ShapedDevicesCsv)) } @@ -421,7 +421,6 @@ fn build_network_tree_summaries( summaries } - pub fn get_one_network_map_layer(parent_idx: usize) -> BusResponse { lqos_network_devices::with_network_json_read(|net_json| { let nodes_ref = net_json.get_nodes_when_ready(); @@ -1319,8 +1318,8 @@ mod tests { }; config.uisp_integration.enable_uisp = true; - let (loaded, source) = load_shaped_devices_from_preferred_source(&config) - .expect("CSV fallback should load"); + let (loaded, source) = + load_shaped_devices_from_preferred_source(&config).expect("CSV fallback should load"); assert_eq!(source, ShapedDevicesLoadSource::ShapedDevicesCsv); assert_eq!(loaded.devices.len(), 1); assert_eq!(loaded.devices[0].circuit_id, "csv-circuit"); diff --git a/src/rust/lqosd/src/throughput_tracker/mod.rs b/src/rust/lqosd/src/throughput_tracker/mod.rs index ba2977e5..7172b941 100644 --- a/src/rust/lqosd/src/throughput_tracker/mod.rs +++ b/src/rust/lqosd/src/throughput_tracker/mod.rs @@ -11,7 +11,6 @@ use self::throughput_entry::ThroughputEntry; use crate::system_stats::SystemStats; use crate::throughput_tracker::flow_data::FlowbeeEffectiveDirection; use crate::{ - lts2_sys::{get_lts_license_status, shared_types::LtsStatus}, stats::TIME_TO_POLL_HOSTS, throughput_tracker::tracking_data::{FlowApplyContext, ThroughputTracker}, }; diff --git a/src/rust/lqosd/src/throughput_tracker/stats_submission.rs b/src/rust/lqosd/src/throughput_tracker/stats_submission.rs index 3e3a9766..57bc0091 100644 --- a/src/rust/lqosd/src/throughput_tracker/stats_submission.rs +++ b/src/rust/lqosd/src/throughput_tracker/stats_submission.rs @@ -324,8 +324,12 @@ pub(crate) fn submit_throughput_stats( let mut plan_lookup: FxHashMap = FxHashMap::default(); for device in catalog.iter_all_devices() { let entry = plan_lookup.entry(device.circuit_hash).or_insert((0, 0)); - entry.0 = entry.0.max(device.download_max_mbps.round() as u64 * 1_000_000 * CRAZY_LIMIT); - entry.1 = entry.1.max(device.upload_max_mbps.round() as u64 * 1_000_000 * CRAZY_LIMIT); + entry.0 = entry + .0 + .max(device.download_max_mbps.round() as u64 * 1_000_000 * CRAZY_LIMIT); + entry.1 = entry + .1 + .max(device.upload_max_mbps.round() as u64 * 1_000_000 * CRAZY_LIMIT); } THROUGHPUT_TRACKER @@ -333,8 +337,7 @@ pub(crate) fn submit_throughput_stats( .lock() .iter() .filter_map(|(ip, h)| { - let circuit_hash = - resolved_circuit_hash_for_submission(&catalog, ip, h)?; + let circuit_hash = resolved_circuit_hash_for_submission(&catalog, ip, h)?; h.actual_bytes_per_second .not_zero() .then_some((circuit_hash, h)) @@ -376,8 +379,7 @@ pub(crate) fn submit_throughput_stats( .lock() .iter() .filter_map(|(ip, h)| { - let circuit_hash = - resolved_circuit_hash_for_submission(&catalog, ip, h)?; + let circuit_hash = resolved_circuit_hash_for_submission(&catalog, ip, h)?; (h.tcp_retransmits.not_zero() && !crazy_values.contains(&circuit_hash)) .then_some((circuit_hash, h)) }) @@ -677,8 +679,15 @@ fn load_local_shaped_devices() -> anyhow::Result> { if integration_ingress_enabled(cfg.as_ref()) { let topology_import = TopologyImportFile::load(cfg.as_ref())? .ok_or_else(|| anyhow::anyhow!("topology_import.json does not exist"))?; - let mut devices = topology_import.into_imported_bundle().shaped_devices.devices; - devices.extend(dynamic_snapshot.iter().map(|circuit| circuit.shaped.clone())); + let mut devices = topology_import + .into_imported_bundle() + .shaped_devices + .devices; + devices.extend( + dynamic_snapshot + .iter() + .map(|circuit| circuit.shaped.clone()), + ); return Ok(devices); } let sd_path = Path::new(&cfg.lqos_directory).join("ShapedDevices.csv"); @@ -700,7 +709,11 @@ fn load_local_shaped_devices() -> anyhow::Result> { anyhow::bail!("Error reading ShapedDevices.csv"); } } - devices.extend(dynamic_snapshot.iter().map(|circuit| circuit.shaped.clone())); + devices.extend( + dynamic_snapshot + .iter() + .map(|circuit| circuit.shaped.clone()), + ); Ok(devices) } diff --git a/src/rust/lqosd/src/throughput_tracker/tracking_data.rs b/src/rust/lqosd/src/throughput_tracker/tracking_data.rs index c6472062..baab0b89 100644 --- a/src/rust/lqosd/src/throughput_tracker/tracking_data.rs +++ b/src/rust/lqosd/src/throughput_tracker/tracking_data.rs @@ -173,9 +173,8 @@ impl ThroughputTracker { let catalog = lqos_network_devices::network_devices_catalog(); let mut capacity_lookup: FxHashMap = FxHashMap::default(); - capacity_lookup.reserve( - catalog.shaped_devices().devices_len() + catalog.dynamic_circuits().len(), - ); + capacity_lookup + .reserve(catalog.shaped_devices().devices_len() + catalog.dynamic_circuits().len()); catalog.iter_all_devices().for_each(|device| { let entry = capacity_lookup .entry(device.circuit_hash) @@ -675,7 +674,8 @@ impl ThroughputTracker { device_hash, circuit_hash, ); - if shaped_device.is_none() && observations.len() < MAX_UNKNOWN_OBSERVATIONS_PER_TICK { + if shaped_device.is_none() && observations.len() < MAX_UNKNOWN_OBSERVATIONS_PER_TICK + { observations.push(lqos_network_devices::CircuitObservation { ip: *xdp_ip, device_hash, @@ -1423,9 +1423,9 @@ mod tests { use lqos_bus::TcHandle; use lqos_config::{ConfigShapedDevices, ShapedDevice}; use lqos_network_devices::{NetworkDevicesCatalog, ShapedDevicesCatalog}; - use lqos_utils::{XdpIpAddress, hash_to_i64}; use lqos_utils::qoo::QoqScores; use lqos_utils::units::DownUpOrder; + use lqos_utils::{XdpIpAddress, hash_to_i64}; use std::ffi::OsString; use std::net::Ipv4Addr; use std::path::{Path, PathBuf}; diff --git a/src/rust/lqosd/src/treeguard/actor.rs b/src/rust/lqosd/src/treeguard/actor.rs index 0ffb2c65..7cacbca8 100644 --- a/src/rust/lqosd/src/treeguard/actor.rs +++ b/src/rust/lqosd/src/treeguard/actor.rs @@ -655,9 +655,8 @@ fn build_circuit_inventory( dynamic_signature: u64, ) -> CircuitInventory { let mut circuits_by_device_id: FxHashMap> = FxHashMap::default(); - circuits_by_device_id.reserve( - shaped.shaped_devices().devices_len() + shaped.dynamic_circuits().len(), - ); + circuits_by_device_id + .reserve(shaped.shaped_devices().devices_len() + shaped.dynamic_circuits().len()); for device in shaped.iter_all_devices() { let device_id = device.device_id.trim(); let circuit_id = device.circuit_id.trim(); diff --git a/src/scheduler.py b/src/scheduler.py index dca740d2..09376f7d 100644 --- a/src/scheduler.py +++ b/src/scheduler.py @@ -1104,6 +1104,28 @@ def topology_runtime_readiness_detail(): current_generation, ) + shaping_generation = str(status.get("shaping_generation") or "").strip() + if not shaping_generation: + return ( + False, + "Topology runtime has not published shaping inputs for the current source generation.", + current_generation, + ) + + shaping_inputs_path = str(status.get("shaping_inputs_path") or "").strip() + if not shaping_inputs_path: + return ( + False, + "Topology runtime did not publish a shaping inputs path for the current source generation.", + current_generation, + ) + if not os.path.isfile(shaping_inputs_path): + return ( + False, + f"Topology runtime shaping inputs are not available at {shaping_inputs_path}.", + current_generation, + ) + return (True, "", current_generation) diff --git a/src/test_libreqos_shaping_inputs.py b/src/test_libreqos_shaping_inputs.py index 933c30cd..02c2f460 100644 --- a/src/test_libreqos_shaping_inputs.py +++ b/src/test_libreqos_shaping_inputs.py @@ -139,6 +139,7 @@ class TestLibreQoSShapingInputs(unittest.TestCase): json.dump( { "source_generation": "test-generation", + "shaping_generation": "shape-1", "ready": True, "shaping_inputs_path": shaping_inputs, }, @@ -146,12 +147,11 @@ class TestLibreQoSShapingInputs(unittest.TestCase): ) with patch.object(LibreQoS, "get_libreqos_directory", return_value=temp_dir): - with patch.object(LibreQoS, "topology_import_ingress_enabled", return_value=True): - self.assertTrue( - LibreQoS._shaping_inputs_are_fresh( - shaping_inputs, shaped_devices, network_json - ) + self.assertTrue( + LibreQoS._shaping_inputs_are_fresh( + shaping_inputs, shaped_devices, network_json ) + ) def test_shaping_inputs_freshness_rejects_stale_topology_runtime_status_generation(self): with tempfile.TemporaryDirectory() as temp_dir: @@ -173,6 +173,35 @@ class TestLibreQoSShapingInputs(unittest.TestCase): json.dump( { "source_generation": "old-generation", + "shaping_generation": "shape-1", + "ready": True, + "shaping_inputs_path": shaping_inputs, + }, + handle, + ) + + with patch.object(LibreQoS, "get_libreqos_directory", return_value=temp_dir): + self.assertFalse( + LibreQoS._shaping_inputs_are_fresh( + shaping_inputs, shaped_devices, network_json + ) + ) + + def test_shaping_inputs_freshness_rejects_ready_status_without_shaping_generation(self): + with tempfile.TemporaryDirectory() as temp_dir: + shaping_inputs = os.path.join(temp_dir, "shaping_inputs.json") + shaped_devices = os.path.join(temp_dir, "ShapedDevices.csv") + network_json = os.path.join(temp_dir, "network.effective.json") + status_path = os.path.join(temp_dir, "topology_runtime_status.json") + + for path in (shaping_inputs, shaped_devices, network_json): + with open(path, "w", encoding="utf-8") as handle: + handle.write("{}\n") + + with open(status_path, "w", encoding="utf-8") as handle: + json.dump( + { + "source_generation": "test-generation", "ready": True, "shaping_inputs_path": shaping_inputs, }, @@ -180,12 +209,11 @@ class TestLibreQoSShapingInputs(unittest.TestCase): ) with patch.object(LibreQoS, "get_libreqos_directory", return_value=temp_dir): - with patch.object(LibreQoS, "topology_import_ingress_enabled", return_value=True): - self.assertFalse( - LibreQoS._shaping_inputs_are_fresh( - shaping_inputs, shaped_devices, network_json - ) + self.assertFalse( + LibreQoS._shaping_inputs_are_fresh( + shaping_inputs, shaped_devices, network_json ) + ) def test_load_subscriber_circuits_accepts_diy_id_alias(self): header = [ diff --git a/src/test_scheduler.py b/src/test_scheduler.py index d0017e4b..c2a5a48a 100644 --- a/src/test_scheduler.py +++ b/src/test_scheduler.py @@ -452,10 +452,15 @@ class TestTopologyRuntimeReadiness(unittest.TestCase): def test_ready_true_matching_status_allows_current_generation(self): with tempfile.TemporaryDirectory() as tempdir: + shaping_inputs = os.path.join(tempdir, "shaping_inputs.json") + with open(shaping_inputs, "w", encoding="utf-8") as handle: + handle.write("{}\n") with open(os.path.join(tempdir, "topology_runtime_status.json"), "w", encoding="utf-8") as handle: json.dump( { "source_generation": "generation-1", + "shaping_generation": "shape-1", + "shaping_inputs_path": shaping_inputs, "ready": True, "error": None, }, @@ -473,6 +478,57 @@ class TestTopologyRuntimeReadiness(unittest.TestCase): self.assertEqual(detail, "") self.assertEqual(generation, "generation-1") + def test_ready_true_without_shaping_generation_is_not_ready(self): + with tempfile.TemporaryDirectory() as tempdir: + shaping_inputs = os.path.join(tempdir, "shaping_inputs.json") + with open(shaping_inputs, "w", encoding="utf-8") as handle: + handle.write("{}\n") + with open(os.path.join(tempdir, "topology_runtime_status.json"), "w", encoding="utf-8") as handle: + json.dump( + { + "source_generation": "generation-1", + "shaping_inputs_path": shaping_inputs, + "ready": True, + }, + handle, + ) + with patch.object(scheduler, "get_libreqos_directory", return_value=tempdir): + with patch.object( + scheduler, + "calculate_topology_source_generation", + return_value="generation-1", + ): + ready, detail, generation = scheduler.topology_runtime_readiness_detail() + + self.assertFalse(ready) + self.assertEqual(generation, "generation-1") + self.assertIn("has not published shaping inputs", detail) + + def test_ready_true_without_shaping_inputs_file_is_not_ready(self): + with tempfile.TemporaryDirectory() as tempdir: + missing_path = os.path.join(tempdir, "shaping_inputs.json") + with open(os.path.join(tempdir, "topology_runtime_status.json"), "w", encoding="utf-8") as handle: + json.dump( + { + "source_generation": "generation-1", + "shaping_generation": "shape-1", + "shaping_inputs_path": missing_path, + "ready": True, + }, + handle, + ) + with patch.object(scheduler, "get_libreqos_directory", return_value=tempdir): + with patch.object( + scheduler, + "calculate_topology_source_generation", + return_value="generation-1", + ): + ready, detail, generation = scheduler.topology_runtime_readiness_detail() + + self.assertFalse(ready) + self.assertEqual(generation, "generation-1") + self.assertIn("shaping inputs are not available", detail) + class TestTopologyRuntimeGating(unittest.TestCase): def test_full_reload_skips_refresh_when_topology_runtime_not_ready(self):