Skip to content

Commit

Permalink
Implement a builder-style provisioning API (Azure#91)
Browse files Browse the repository at this point in the history
Implement a single `Provision` interface

This provides a unified interface to provision the host with the option
to select the tool used for setting the hostname, creating the user, and
so on.

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 authored and balakreddy committed Jul 19, 2024
1 parent 15eb319 commit 79a1753
Show file tree
Hide file tree
Showing 12 changed files with 488 additions and 69 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: 9 additions & 0 deletions libazureinit/src/imds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,15 @@ pub struct PublicKeys {
pub path: String,
}

impl From<&str> for PublicKeys {
fn from(value: &str) -> Self {
Self {
key_data: value.to_string(),
path: String::new(),
}
}
}

/// Deserializer that handles the string "true" and "false" that the IMDS API returns.
fn string_bool<'de, D>(deserializer: D) -> Result<bool, D::Error>
where
Expand Down
10 changes: 8 additions & 2 deletions libazureinit/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
// 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, User},
Provision,
};

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

use std::process::Command;

use tracing::instrument;

use crate::error::Error;

/// Available tools to set the host's hostname.
#[derive(strum::EnumIter, Debug, Clone)]
#[non_exhaustive]
pub enum Provisioner {
/// Use the `hostnamectl` command from `systemd`.
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,
})
}
}
179 changes: 179 additions & 0 deletions libazureinit/src/provision/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
// 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;
use crate::User;

/// The interface for applying the desired configuration to the host.
///
/// By default, all known tools for provisioning a particular resource are tried
/// until one succeeds. Particular tools can be selected via the
/// `*_provisioners()` methods ([`Provision::hostname_provisioners`],
/// [`Provision::user_provisioners`], etc).
///
/// To actually apply the configuration, use [`Provision::provision`].
#[derive(Clone)]
pub struct Provision {
hostname: String,
user: User,
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>, user: User) -> Self {
Self {
hostname: hostname.into(),
user,
hostname_backends: None,
user_backends: None,
password_backends: None,
}
}

/// 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 the [`User`].
pub fn password_provisioners(
mut self,
backend: impl Into<Vec<password::Provisioner>>,
) -> Self {
self.password_backends = Some(backend.into());
self
}

/// Provision the host.
///
/// Provisioning can fail if the host lacks the necessary tools. For example,
/// if there is no `useradd` command on the system's `PATH`, or if the command
/// returns an error, this will return an error. It does not attempt to undo
/// partial provisioning.
#[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.user)
.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.user)
.map_err(|e| {
tracing::info!(
error=?e,
backend=?backend,
resource="password",
"Provisioning did not succeed"
);
e
})
.ok()
})
.ok_or(Error::NoPasswordProvisioner)?;

if !self.user.ssh_keys.is_empty() {
let user = nix::unistd::User::from_name(&self.user.name)?.ok_or(
Error::UserMissing {
user: self.user.name,
},
)?;
ssh::provision_ssh(&user, &self.user.ssh_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 crate::User;

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

#[test]
fn test_successful_provision() {
let _p = Provision::new(
"my-hostname".to_string(),
User::new("azureuser", vec![]),
)
.hostname_provisioners([hostname::Provisioner::FakeHostnamectl])
.user_provisioners([user::Provisioner::FakeUseradd])
.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, User};

/// Available tools to set the user's password (if a password is provided).
#[derive(strum::EnumIter, Debug, Clone)]
#[non_exhaustive]
pub enum Provisioner {
/// Use the `passwd` command from `shadow-utils`.
Passwd,
#[cfg(test)]
FakePasswd,
}

impl Provisioner {
pub(crate) fn set(&self, user: &User) -> Result<(), Error> {
match self {
Self::Passwd => passwd(user),
#[cfg(test)]
Self::FakePasswd => Ok(()),
}
}
}

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

if user.password.is_none() {
let status = Command::new(path_passwd)
.arg("-d")
.arg(&user.name)
.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 79a1753

Please sign in to comment.