public inbox for pve-devel@lists.proxmox.com
 help / color / mirror / Atom feed
From: Aaron Lauterer <a.lauterer@proxmox.com>
To: pve-devel@lists.proxmox.com
Subject: [pve-devel] [PATCH v2 12/22] auto-installer: add auto-installer binary
Date: Wed, 21 Feb 2024 12:07:55 +0100	[thread overview]
Message-ID: <20240221110805.931925-13-a.lauterer@proxmox.com> (raw)
In-Reply-To: <20240221110805.931925-1-a.lauterer@proxmox.com>

It expects the contents of an answer file via stdin. It will then be
parsed and the JSON for the low level installer is generated.

It then calls the low level installer directly.
The output of the installaton progress is kept rather simple for now.

If configured in the answer file, commands will be run pre and post the
low level installer.

It also logs everything to the logfile, currently
'/tmp/auto_installer.log'.

Signed-off-by: Aaron Lauterer <a.lauterer@proxmox.com>
---
 Makefile                                      |   4 +-
 .../src/bin/proxmox-auto-installer.rs         | 193 ++++++++++++++++++
 2 files changed, 196 insertions(+), 1 deletion(-)
 create mode 100644 proxmox-auto-installer/src/bin/proxmox-auto-installer.rs

diff --git a/Makefile b/Makefile
index 57bd7ae..9c933d9 100644
--- a/Makefile
+++ b/Makefile
@@ -18,7 +18,9 @@ INSTALLER_SOURCES=$(shell git ls-files) country.dat
 
 PREFIX = /usr
 BINDIR = $(PREFIX)/bin
-USR_BIN := proxmox-tui-installer
+USR_BIN := \
+	   proxmox-tui-installer\
+	   proxmox-auto-installer
 
 COMPILED_BINS := \
 	$(addprefix $(CARGO_COMPILEDIR)/,$(USR_BIN))
diff --git a/proxmox-auto-installer/src/bin/proxmox-auto-installer.rs b/proxmox-auto-installer/src/bin/proxmox-auto-installer.rs
new file mode 100644
index 0000000..ea8aa00
--- /dev/null
+++ b/proxmox-auto-installer/src/bin/proxmox-auto-installer.rs
@@ -0,0 +1,193 @@
+use anyhow::{anyhow, bail, Error, Result};
+use log::{error, info, LevelFilter};
+use std::{
+    env,
+    io::{BufRead, BufReader, Write},
+    path::PathBuf,
+    process::ExitCode,
+};
+
+use proxmox_installer_common::setup::{
+    installer_setup, read_json, spawn_low_level_installer, LocaleInfo, RuntimeInfo, SetupInfo,
+};
+
+use proxmox_auto_installer::{
+    answer::Answer,
+    log::AutoInstLogger,
+    udevinfo::UdevInfo,
+    utils,
+    utils::{parse_answer, LowLevelMessage},
+};
+
+static LOGGER: AutoInstLogger = AutoInstLogger;
+
+pub fn init_log() -> Result<()> {
+    AutoInstLogger::init("/tmp/auto_installer.log")?;
+    log::set_logger(&LOGGER)
+        .map(|()| log::set_max_level(LevelFilter::Info))
+        .map_err(|err| anyhow!(err))
+}
+
+fn auto_installer_setup(in_test_mode: bool) -> Result<(Answer, UdevInfo)> {
+    let base_path = if in_test_mode { "./testdir" } else { "/" };
+    let mut path = PathBuf::from(base_path);
+
+    path.push("run");
+    path.push("proxmox-installer");
+
+    let udev_info: UdevInfo = {
+        let mut path = path.clone();
+        path.push("run-env-udev.json");
+
+        read_json(&path).map_err(|err| anyhow!("Failed to retrieve udev info details: {err}"))?
+    };
+
+    let mut buffer = String::new();
+    let lines = std::io::stdin().lock().lines();
+    for line in lines {
+        buffer.push_str(&line.unwrap());
+        buffer.push('\n');
+    }
+
+    let answer: Answer =
+        toml::from_str(&buffer).map_err(|err| anyhow!("Failed parsing answer file: {err}"))?;
+
+    Ok((answer, udev_info))
+}
+
+fn main() -> ExitCode {
+    if let Err(err) = init_log() {
+        panic!("could not initilize logging: {}", err);
+    }
+
+    let in_test_mode = match env::args().nth(1).as_deref() {
+        Some("-t") => true,
+        // Always force the test directory in debug builds
+        _ => cfg!(debug_assertions),
+    };
+    info!("Starting auto installer");
+
+    let (setup_info, locales, runtime_info) = match installer_setup(in_test_mode) {
+        Ok(result) => result,
+        Err(err) => {
+            error!("Installer setup error: {err}");
+            return ExitCode::FAILURE;
+        }
+    };
+
+    let (answer, udevadm_info) = match auto_installer_setup(in_test_mode) {
+        Ok(result) => result,
+        Err(err) => {
+            error!("Autoinstaller setup error: {err}");
+            return ExitCode::FAILURE;
+        }
+    };
+
+    match utils::run_cmds("Pre", &answer.global.pre_command) {
+        Ok(_) => (),
+        Err(err) => {
+            error!("Error when running Pre-Commands: {}", err);
+            return exit_failure(answer.global.reboot_on_error);
+        }
+    };
+    match run_installation(&answer, &locales, &runtime_info, &udevadm_info, &setup_info) {
+        Ok(_) => info!("Installation done."),
+        Err(err) => {
+            error!("Installation failed: {err}");
+            return exit_failure(answer.global.reboot_on_error);
+        }
+    }
+    match utils::run_cmds("Post", &answer.global.post_command) {
+        Ok(_) => (),
+        Err(err) => {
+            error!("Error when running Post-Commands: {}", err);
+            return exit_failure(answer.global.reboot_on_error);
+        }
+    };
+    ExitCode::SUCCESS
+}
+
+/// When we exit with a failure, the installer will not automatically reboot.
+/// Default value for reboot_on_error is false
+fn exit_failure(reboot_on_error: Option<bool>) -> ExitCode {
+    if let Some(true) = reboot_on_error {
+        ExitCode::SUCCESS
+    } else {
+        ExitCode::FAILURE
+    }
+}
+
+fn run_installation(
+    answer: &Answer,
+    locales: &LocaleInfo,
+    runtime_info: &RuntimeInfo,
+    udevadm_info: &UdevInfo,
+    setup_info: &SetupInfo,
+) -> Result<()> {
+    let config = parse_answer(answer, udevadm_info, runtime_info, locales, setup_info)?;
+    info!("Calling low-level installer");
+
+    let mut child = match spawn_low_level_installer(false) {
+        Ok(child) => child,
+        Err(err) => {
+            bail!("Low level installer could not be started: {}", err);
+        }
+    };
+
+    let mut cur_counter = 111;
+    let mut inner = || -> Result<()> {
+        let reader = child
+            .stdout
+            .take()
+            .map(BufReader::new)
+            .ok_or(anyhow!("failed to get stdout reader"))?;
+        let mut writer = child
+            .stdin
+            .take()
+            .ok_or(anyhow!("failed to get stdin writer"))?;
+
+        serde_json::to_writer(&mut writer, &config)
+            .map_err(|err| anyhow!("failed to serialize install config: {err}"))?;
+        writeln!(writer).map_err(|err| anyhow!("failed to write install config: {err}"))?;
+
+        for line in reader.lines() {
+            let line = match line {
+                Ok(line) => line,
+                Err(_) => break,
+            };
+            let msg = match serde_json::from_str::<LowLevelMessage>(&line) {
+                Ok(msg) => msg,
+                Err(_) => {
+                    // Not a fatal error, so don't abort the installation by returning
+                    continue;
+                }
+            };
+
+            match msg.clone() {
+                LowLevelMessage::Info { message } => info!("{message}"),
+                LowLevelMessage::Error { message } => error!("{message}"),
+                LowLevelMessage::Prompt { query } => info!("Got Query: {query}"),
+                LowLevelMessage::Progress { ratio, text: _ } => {
+                    let counter = (ratio * 100.).floor() as usize;
+                    if counter != cur_counter {
+                        cur_counter = counter;
+                        info!("Progress: {counter:>3}%");
+                    }
+                }
+                LowLevelMessage::Finished { state, message } => {
+                    if state == "err" {
+                        bail!("{message}");
+                    }
+                    info!("Finished: '{state}' {message}");
+                }
+            };
+        }
+        Ok(())
+    };
+    match inner() {
+        Err(err) => Err(Error::msg(format!(
+            "low level installer returned early: {err}"
+        ))),
+        _ => Ok(()),
+    }
+}
-- 
2.39.2





  parent reply	other threads:[~2024-02-21 11:08 UTC|newest]

Thread overview: 29+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2024-02-21 11:07 [pve-devel] [PATCH v2 00/22] add automated/unattended installation Aaron Lauterer
2024-02-21 11:07 ` [pve-devel] [PATCH v2 01/22] tui: common: move InstallConfig struct to common crate Aaron Lauterer
2024-02-21 11:07 ` [pve-devel] [PATCH v2 02/22] common: make InstallZfsOption members public Aaron Lauterer
2024-02-21 11:07 ` [pve-devel] [PATCH v2 03/22] common: tui: use BTreeMap for predictable ordering Aaron Lauterer
2024-02-21 11:07 ` [pve-devel] [PATCH v2 04/22] low-level: add dump-udev command Aaron Lauterer
2024-02-21 11:07 ` [pve-devel] [PATCH v2 05/22] add auto-installer crate Aaron Lauterer
2024-02-21 11:07 ` [pve-devel] [PATCH v2 06/22] auto-installer: add dependencies Aaron Lauterer
2024-02-21 11:07 ` [pve-devel] [PATCH v2 07/22] auto-installer: add answer file definition Aaron Lauterer
2024-02-21 11:07 ` [pve-devel] [PATCH v2 08/22] auto-installer: add struct to hold udev info Aaron Lauterer
2024-02-21 11:07 ` [pve-devel] [PATCH v2 09/22] auto-installer: add utils Aaron Lauterer
2024-02-21 11:07 ` [pve-devel] [PATCH v2 10/22] auto-installer: add simple logging Aaron Lauterer
2024-02-21 11:07 ` [pve-devel] [PATCH v2 11/22] auto-installer: add tests for answer file parsing Aaron Lauterer
2024-02-21 11:07 ` Aaron Lauterer [this message]
2024-02-21 11:07 ` [pve-devel] [PATCH v2 13/22] auto-installer: add fetch answer binary Aaron Lauterer
2024-02-21 11:07 ` [pve-devel] [PATCH v2 14/22] unconfigured: add proxauto as option to start auto installer Aaron Lauterer
2024-02-21 11:07 ` [pve-devel] [PATCH v2 15/22] auto-installer: use glob crate for pattern matching Aaron Lauterer
2024-02-21 11:07 ` [pve-devel] [PATCH v2 16/22] auto-installer: utils: make get_udev_index functions public Aaron Lauterer
2024-02-21 11:08 ` [pve-devel] [PATCH v2 17/22] auto-installer: add proxmox-autoinst-helper tool Aaron Lauterer
2024-02-21 11:08 ` [pve-devel] [PATCH v2 18/22] auto-installer: fetch: add gathering of system identifiers and restructure code Aaron Lauterer
2024-02-21 14:09   ` Christoph Heiss
2024-02-21 16:07     ` Aaron Lauterer
2024-02-21 11:08 ` [pve-devel] [PATCH v2 19/22] auto-installer: helper: add subcommand to view indentifiers Aaron Lauterer
2024-02-21 11:08 ` [pve-devel] [PATCH v2 20/22] auto-installer: fetch: add http post utility module Aaron Lauterer
2024-02-21 12:21   ` Christoph Heiss
2024-02-21 11:08 ` [pve-devel] [PATCH v2 21/22] auto-installer: fetch: add http plugin to fetch answer Aaron Lauterer
2024-02-21 11:08 ` [pve-devel] [PATCH v2 22/22] control: update build depends for auto installer Aaron Lauterer
2024-02-21 13:39 ` [pve-devel] [PATCH v2 00/22] add automated/unattended installation Christoph Heiss
2024-02-23 10:19 ` Friedrich Weber
2024-02-23 11:37   ` Aaron Lauterer

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20240221110805.931925-13-a.lauterer@proxmox.com \
    --to=a.lauterer@proxmox.com \
    --cc=pve-devel@lists.proxmox.com \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox
Service provided by Proxmox Server Solutions GmbH | Privacy | Legal