-
Notifications
You must be signed in to change notification settings - Fork 19
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Settings and Models for Bootstrap Commands
- Loading branch information
1 parent
cebbd4c
commit 329e1e7
Showing
10 changed files
with
272 additions
and
17 deletions.
There are no files selected for viewing
This file contains 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 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 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
19 changes: 19 additions & 0 deletions
19
bottlerocket-settings-models/settings-extensions/bootstrap-commands/Cargo.toml
This file contains 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,19 @@ | ||
[package] | ||
name = "settings-extension-bootstrap-commands" | ||
version = "0.1.0" | ||
authors = ["Piyush Jena <[email protected]>"] | ||
license = "Apache-2.0 OR MIT" | ||
edition = "2021" | ||
publish = false | ||
|
||
[dependencies] | ||
bottlerocket-modeled-types.workspace = true | ||
bottlerocket-model-derive.workspace = true | ||
bottlerocket-settings-sdk.workspace = true | ||
env_logger.workspace = true | ||
serde = { workspace = true, features = ["derive"] } | ||
serde_json.workspace = true | ||
snafu.workspace = true | ||
|
||
[lints] | ||
workspace = true |
13 changes: 13 additions & 0 deletions
13
bottlerocket-settings-models/settings-extensions/bootstrap-commands/bootstrap-commands.toml
This file contains 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,13 @@ | ||
[extension] | ||
supported-versions = [ | ||
"v1" | ||
] | ||
default-version = "v1" | ||
|
||
[v1] | ||
[v1.validation.cross-validates] | ||
|
||
[v1.templating] | ||
helpers = [] | ||
|
||
[v1.generation.requires] |
200 changes: 200 additions & 0 deletions
200
bottlerocket-settings-models/settings-extensions/bootstrap-commands/src/lib.rs
This file contains 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,200 @@ | ||
//! Settings related to bootstrap commands. | ||
use bottlerocket_model_derive::model; | ||
use bottlerocket_modeled_types::{BootstrapMode, Identifier}; | ||
use bottlerocket_settings_sdk::{GenerateResult, SettingsModel}; | ||
use serde::{Deserialize, Deserializer, Serialize, Serializer}; | ||
use snafu::ensure; | ||
use std::{collections::BTreeMap, convert::Infallible}; | ||
|
||
#[derive(Clone, Debug, Default, PartialEq)] | ||
pub struct BootstrapCommandsSettingsV1 { | ||
pub bootstrap_commands: BTreeMap<Identifier, BootstrapCommand>, | ||
} | ||
|
||
// Custom serializer/deserializer added to maintain backwards | ||
// compatibility with models created prior to settings extensions. | ||
impl Serialize for BootstrapCommandsSettingsV1 { | ||
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> | ||
where | ||
S: Serializer, | ||
{ | ||
self.bootstrap_commands.serialize(serializer) | ||
} | ||
} | ||
|
||
impl<'de> Deserialize<'de> for BootstrapCommandsSettingsV1 { | ||
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error> | ||
where | ||
D: Deserializer<'de>, | ||
{ | ||
let bootstrap_commands = BTreeMap::deserialize(deserializer)?; | ||
Ok(Self { bootstrap_commands }) | ||
} | ||
} | ||
|
||
#[model(impl_default = true)] | ||
struct BootstrapCommand { | ||
commands: Vec<ValidCommand>, | ||
mode: BootstrapMode, | ||
essential: bool, | ||
} | ||
|
||
impl SettingsModel for BootstrapCommandsSettingsV1 { | ||
type PartialKind = Self; | ||
type ErrorKind = Infallible; | ||
|
||
fn get_version() -> &'static str { | ||
"v1" | ||
} | ||
|
||
fn set(_current_value: Option<Self>, _target: Self) -> Result<()> { | ||
// Set anything that parses as BootstrapCommandsSettingsV1. | ||
Ok(()) | ||
} | ||
|
||
fn generate( | ||
existing_partial: Option<Self::PartialKind>, | ||
_dependent_settings: Option<serde_json::Value>, | ||
) -> Result<GenerateResult<Self::PartialKind, Self>> { | ||
Ok(GenerateResult::Complete( | ||
existing_partial.unwrap_or_default(), | ||
)) | ||
} | ||
|
||
fn validate(_value: Self, _validated_settings: Option<serde_json::Value>) -> Result<()> { | ||
// Validate anything that parses as BootstrapCommandsSettingsV1. | ||
Ok(()) | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod test_bootstrap_command { | ||
use super::*; | ||
use serde_json::json; | ||
|
||
#[test] | ||
fn test_generate_bootstrap_command_settings() { | ||
let generated = BootstrapCommandsSettingsV1::generate(None, None).unwrap(); | ||
|
||
assert_eq!( | ||
generated, | ||
GenerateResult::Complete(BootstrapCommandsSettingsV1 { | ||
bootstrap_commands: BTreeMap::new(), | ||
}) | ||
) | ||
} | ||
|
||
#[test] | ||
fn test_serde_bootstrap_command() { | ||
let test_json = json!({ | ||
"mybootstrap": { | ||
"commands": [ ["apiclient", "motd=hello"], ], | ||
"mode": "once", | ||
"essential": true, | ||
} | ||
}); | ||
|
||
let bootstrap_commands: BootstrapCommandsSettingsV1 = | ||
serde_json::from_value(test_json.clone()).unwrap(); | ||
|
||
let mut expected_bootstrap_commands: BTreeMap<Identifier, BootstrapCommand> = | ||
BTreeMap::new(); | ||
expected_bootstrap_commands.insert( | ||
Identifier::try_from("mybootstrap").unwrap(), | ||
BootstrapCommand { | ||
commands: Some(vec![ValidCommand::try_from(vec![ | ||
"apiclient".to_string(), | ||
"motd=hello".to_string(), | ||
]) | ||
.unwrap()]), | ||
mode: Some(BootstrapMode::try_from("once").unwrap()), | ||
essential: Some(true), | ||
}, | ||
); | ||
|
||
assert_eq!( | ||
bootstrap_commands, | ||
BootstrapCommandsSettingsV1 { | ||
bootstrap_commands: expected_bootstrap_commands | ||
} | ||
); | ||
|
||
let serialized_json: serde_json::Value = serde_json::to_string(&bootstrap_commands) | ||
.map(|s| serde_json::from_str(&s).unwrap()) | ||
.unwrap(); | ||
|
||
assert_eq!(serialized_json, test_json); | ||
} | ||
} | ||
|
||
/// ValidCommand represents a valid Bootstrap Command. It stores the command as a vector of | ||
/// strings and ensures that the first argument is apiclient. | ||
#[derive(Debug, Clone, Eq, PartialEq, Hash, Default, Serialize, Deserialize)] | ||
pub struct ValidCommand(Vec<String>); | ||
|
||
impl ValidCommand { | ||
pub fn get_args(&self) -> (String, Vec<String>) { | ||
self.0 | ||
.clone() | ||
.split_first() | ||
.map_or(("".to_string(), Vec::new()), |(command, arguments)| { | ||
(command.to_string(), arguments.to_vec()) | ||
}) | ||
} | ||
} | ||
|
||
impl TryFrom<Vec<String>> for ValidCommand { | ||
type Error = error::Error; | ||
|
||
fn try_from(input: Vec<String>) -> std::result::Result<Self, error::Error> { | ||
let first_word = input.first().map(String::as_str); | ||
ensure!( | ||
matches!(first_word, Some("apiclient")), | ||
error::InvalidCommandSnafu { input }, | ||
); | ||
|
||
Ok(ValidCommand(input)) | ||
} | ||
} | ||
|
||
pub mod error { | ||
use snafu::Snafu; | ||
|
||
#[derive(Debug, Snafu)] | ||
#[snafu(visibility(pub(super)))] | ||
pub enum Error { | ||
#[snafu(display("Invalid Bottlerocket API Command '{:?}'", input))] | ||
InvalidCommand { input: Vec<String> }, | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod test_valid_apiclient_command { | ||
use super::ValidCommand; | ||
use std::convert::TryFrom; | ||
|
||
#[test] | ||
fn valid_apiclient_command() { | ||
assert!(ValidCommand::try_from(vec![ | ||
"apiclient".to_string(), | ||
"motd=helloworld".to_string() | ||
]) | ||
.is_ok()); | ||
} | ||
|
||
#[test] | ||
fn empty_apiclient_command() { | ||
assert!(ValidCommand::try_from(Vec::new()).is_err()); | ||
} | ||
|
||
#[test] | ||
fn invalid_apiclient_command() { | ||
assert!(ValidCommand::try_from(vec![ | ||
"/usr/bin/touch".to_string(), | ||
"helloworld".to_string() | ||
]) | ||
.is_err()); | ||
} | ||
} | ||
|
||
type Result<T> = std::result::Result<T, Infallible>; |
20 changes: 20 additions & 0 deletions
20
bottlerocket-settings-models/settings-extensions/bootstrap-commands/src/main.rs
This file contains 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,20 @@ | ||
use bottlerocket_settings_sdk::{BottlerocketSetting, NullMigratorExtensionBuilder}; | ||
use settings_extension_bootstrap_commands::BootstrapCommandsSettingsV1; | ||
use std::process::ExitCode; | ||
|
||
fn main() -> ExitCode { | ||
env_logger::init(); | ||
|
||
match NullMigratorExtensionBuilder::with_name("bootstrap-commands") | ||
.with_models(vec![ | ||
BottlerocketSetting::<BootstrapCommandsSettingsV1>::model(), | ||
]) | ||
.build() | ||
{ | ||
Ok(extension) => extension.run(), | ||
Err(e) => { | ||
println!("{}", e); | ||
ExitCode::FAILURE | ||
} | ||
} | ||
} |
This file contains 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 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 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