- 
                Notifications
    You must be signed in to change notification settings 
- Fork 14
Implement a builder-style provisioning API #91
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Merged
      
      
    
  
     Merged
                    Changes from all commits
      Commits
    
    
  File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | 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; | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | 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, | ||
| }) | ||
| } | ||
| } | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | 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, | ||
|         
                  dongsupark marked this conversation as resolved.
              Show resolved
            Hide resolved | ||
| 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(); | ||
| } | ||
| } | ||
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | 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(()) | ||
| } | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
      
      Oops, something went wrong.
        
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
Uh oh!
There was an error while loading. Please reload this page.