Skip to content

Commit

Permalink
Implement a builder-style provisioning API
Browse files Browse the repository at this point in the history
As discussed in PR #86, this is a builder-style interface to allow
library users to select the backend for tools when provisioning.

By default, the library will try all the provisioning methods it knows
of until one succeeds. Users of the library can optionally specify a
subset to attempt when provisioning.

This allows users to decide which tool or tools to use when
provisioning. Some feature flags have been added to `azure-init` which
enable provisioning with a tool, letting you build binaries for a
particular platform relatively easily.
  • Loading branch information
jeremycline committed Jul 5, 2024
1 parent 773f4cf commit bd29ce6
Show file tree
Hide file tree
Showing 11 changed files with 392 additions and 62 deletions.
9 changes: 9 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,12 @@ path = "tests/functional_tests.rs"
members = [
"libazureinit",
]

[features]
passwd = []
hostnamectl = []
useradd = []

systemd_linux = ["passwd", "hostnamectl", "useradd"]

default = ["systemd_linux"]
1 change: 1 addition & 0 deletions libazureinit/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ serde_json = "1.0.96"
nix = {version = "0.29.0", features = ["fs", "user"]}
block-utils = "0.11.1"
tracing = "0.1.40"
strum = { version = "0.26.3", features = ["derive"] }

[dev-dependencies]
tempfile = "3"
Expand Down
12 changes: 12 additions & 0 deletions libazureinit/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,16 @@ pub enum Error {
NonEmptyPassword,
#[error("Unable to get list of block devices")]
BlockUtils(#[from] block_utils::BlockUtilsError),
#[error(
"Failed to set the hostname; none of the provided backends succeeded"
)]
NoHostnameProvisioner,
#[error(
"Failed to create a user; none of the provided backends succeeded"
)]
NoUserProvisioner,
#[error(
"Failed to set the user password; none of the provided backends succeeded"
)]
NoPasswordProvisioner,
}
9 changes: 7 additions & 2 deletions libazureinit/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

pub mod distro;
pub mod error;
pub mod goalstate;
pub mod imds;
pub mod media;
pub mod user;

mod provision;
pub use provision::{
hostname::Provisioner as HostnameProvisioner,
password::Provisioner as PasswordProvisioner,
user::Provisioner as UserProvisioner, Provision,
};

// Re-export as the Client is used in our API.
pub use reqwest;
44 changes: 44 additions & 0 deletions libazureinit/src/provision/hostname.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

use std::process::Command;

use tracing::instrument;

use crate::error::Error;

#[derive(strum::EnumIter, Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Provisioner {
Hostnamectl,
#[cfg(test)]
FakeHostnamectl,
}

impl Provisioner {
pub(crate) fn set(self, hostname: impl AsRef<str>) -> Result<(), Error> {
match self {
Self::Hostnamectl => hostnamectl(hostname.as_ref()),
#[cfg(test)]
Self::FakeHostnamectl => Ok(()),
}
}
}

#[instrument(skip_all)]
fn hostnamectl(hostname: &str) -> Result<(), Error> {
let path_hostnamectl = env!("PATH_HOSTNAMECTL");

let status = Command::new(path_hostnamectl)
.arg("set-hostname")
.arg(hostname)
.status()?;
if status.success() {
Ok(())
} else {
Err(Error::SubprocessFailed {
command: path_hostnamectl.to_string(),
status,
})
}
}
186 changes: 186 additions & 0 deletions libazureinit/src/provision/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
pub mod hostname;
pub mod password;
pub(crate) mod ssh;
pub mod user;

use strum::IntoEnumIterator;
use tracing::instrument;

use crate::{error::Error, imds::PublicKeys};

/// The interface for applying the desired configuration to the host.
///
/// Optional settings, like a password for the user account, can be provided
/// after constructing this object. By default, all known methods for
/// provisioning a particular setting are tried until one succeeds. Particular
/// methods can be selected via the `*_provisioners()` methods
/// ([`Provision::hostname_provisioners`], [`Provision::user_provisioners`],
/// etc).
///
/// To actually apply the configuration, use [`Provision::provision`].
#[derive(Default, Clone, PartialEq)]
pub struct Provision {
hostname: String,
username: String,
keys: Vec<PublicKeys>,
password: Option<String>,
hostname_backends: Option<Vec<hostname::Provisioner>>,
user_backends: Option<Vec<user::Provisioner>>,
password_backends: Option<Vec<password::Provisioner>>,
}

impl Provision {
pub fn new(
hostname: impl Into<String>,
username: impl Into<String>,
ssh_keys: impl Into<Vec<PublicKeys>>,
) -> Self {
Self {
hostname: hostname.into(),
username: username.into(),
keys: ssh_keys.into(),
..Default::default()
}
}

/// Specify the ways to set the virtual machine's hostname.
///
/// By default, all known methods will be attempted. Use this function to
/// restrict which methods are attempted. These will be attempted in the
/// order provided until one succeeds.
pub fn hostname_provisioners(
mut self,
backends: impl Into<Vec<hostname::Provisioner>>,
) -> Self {
self.hostname_backends = Some(backends.into());
self
}

/// Specify the ways to create a user in the virtual machine
///
/// By default, all known methods will be attempted. Use this function to
/// restrict which methods are attempted. These will be attempted in the
/// order provided until one succeeds.
pub fn user_provisioners(
mut self,
backends: impl Into<Vec<user::Provisioner>>,
) -> Self {
self.user_backends = Some(backends.into());
self
}

/// Specify the ways to set a users password.
///
/// By default, all known methods will be attempted. Use this function to
/// restrict which methods are attempted. These will be attempted in the
/// order provided until one succeeds. Only relevant if a password has been
/// provided with [`Provision::password`].
pub fn password_provisioners(
mut self,
backend: impl Into<Vec<password::Provisioner>>,
) -> Self {
self.password_backends = Some(backend.into());
self
}

/// Set the given password for the provisioned user.
pub fn password(mut self, password: String) -> Self {
self.password = Some(password);
self
}

/// Provision the host.
#[instrument(skip_all)]
pub fn provision(self) -> Result<(), Error> {
self.user_backends
.unwrap_or_else(|| user::Provisioner::iter().collect())
.iter()
.find_map(|backend| {
backend
.create(&self.username)
.map_err(|e| {
tracing::info!(
error=?e,
backend=?backend,
resource="user",
"Provisioning did not succeed"
);
e
})
.ok()
})
.ok_or(Error::NoUserProvisioner)?;

self.password_backends
.unwrap_or_else(|| password::Provisioner::iter().collect())
.iter()
.find_map(|backend| {
backend
.set(&self.username, self.password.as_deref().unwrap_or(""))
.map_err(|e| {
tracing::info!(
error=?e,
backend=?backend,
resource="password",
"Provisioning did not succeed"
);
e
})
.ok()
})
.ok_or(Error::NoPasswordProvisioner)?;

if !self.keys.is_empty() {
let user = nix::unistd::User::from_name(&self.username)?.ok_or(
Error::UserMissing {
user: self.username,
},
)?;
ssh::provision_ssh(&user, &self.keys)?;
}

self.hostname_backends
.unwrap_or_else(|| hostname::Provisioner::iter().collect())
.iter()
.find_map(|backend| {
backend
.set(&self.hostname)
.map_err(|e| {
tracing::info!(
error=?e,
backend=?backend,
resource="hostname",
"Provisioning did not succeed"
);
e
})
.ok()
})
.ok_or(Error::NoHostnameProvisioner)?;

Ok(())
}
}

#[cfg(test)]
mod tests {

use super::{hostname, password, user, Provision};

#[test]
fn test_successful_provision() {
let _p = Provision::new(
"my-hostname".to_string(),
"my-user".to_string(),
vec![],
)
.hostname_provisioners([hostname::Provisioner::FakeHostnamectl])
.user_provisioners([user::Provisioner::FakeUseradd])
.password("password".to_string())
.password_provisioners([password::Provisioner::FakePasswd])
.provision()
.unwrap();
}
}
51 changes: 51 additions & 0 deletions libazureinit/src/provision/password.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

use std::process::Command;

use tracing::instrument;

use crate::error::Error;

#[derive(strum::EnumIter, Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Provisioner {
Passwd,
#[cfg(test)]
FakePasswd,
}

impl Provisioner {
pub(crate) fn set(
self,
username: impl AsRef<str>,
password: impl AsRef<str>,
) -> Result<(), Error> {
match self {
Self::Passwd => passwd(username.as_ref(), password.as_ref()),
#[cfg(test)]
Self::FakePasswd => Ok(()),
}
}
}

#[instrument(skip_all)]
fn passwd(username: &str, password: &str) -> Result<(), Error> {
let path_passwd = env!("PATH_PASSWD");

if password.is_empty() {
let status =
Command::new(path_passwd).arg("-d").arg(username).status()?;
if !status.success() {
return Err(Error::SubprocessFailed {
command: path_passwd.to_string(),
status,
});
}
} else {
// creating user with a non-empty password is not allowed.
return Err(Error::NonEmptyPassword);
}

Ok(())
}
13 changes: 0 additions & 13 deletions libazureinit/src/user.rs → libazureinit/src/provision/ssh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,6 @@ use tracing::instrument;
use crate::error::Error;
use crate::imds::PublicKeys;

pub fn set_ssh_keys(
keys: Vec<PublicKeys>,
username: impl AsRef<str>,
) -> Result<(), Error> {
let user =
nix::unistd::User::from_name(username.as_ref())?.ok_or_else(|| {
Error::UserMissing {
user: username.as_ref().to_string(),
}
})?;
provision_ssh(&user, &keys)
}

#[instrument(skip_all, name = "ssh")]
pub(crate) fn provision_ssh(
user: &nix::unistd::User,
Expand Down
Loading

0 comments on commit bd29ce6

Please sign in to comment.