Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
models: Add Strength enum and Setting-Generator struct
Browse files Browse the repository at this point in the history
We need to add these to match changes in Bottlerocket-core-kit
Refer commit:
bottlerocket-os/bottlerocket-core-kit@a72f6bd

PR: bottlerocket-os/bottlerocket-core-kit#294
vyaghras committed Jan 31, 2025
1 parent bbf7b7b commit 663467b
Showing 3 changed files with 243 additions and 4 deletions.
1 change: 1 addition & 0 deletions sources/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions sources/models/Cargo.toml
Original file line number Diff line number Diff line change
@@ -14,6 +14,7 @@ bottlerocket-release.workspace = true
libc.workspace = true
serde = { workspace = true, features = ["derive"] }
serde_json.workspace = true
serde_plain.workspace = true
toml.workspace = true

# settings plugins
245 changes: 241 additions & 4 deletions sources/models/src/lib.rs
Original file line number Diff line number Diff line change
@@ -5,15 +5,15 @@ Bottlerocket has different variants supporting different features and use cases.
Each variant has its own set of software, and therefore needs its own configuration.
We support having an API model for each variant to support these different configurations.
The model here defines a top-level `Settings` structure, and delegates the actual implementation to a ["settings plugin"](https://github.com/bottlerocket-os/bottlerocket-settings-sdk/tree/develop/bottlerocket-settings-plugin).
The model here defines a top-level `Settings` structure, and delegates the actual implementation to a ["settings plugin"](https://github.com/bottlerocket/bottlerocket-settings-sdk/tree/settings-plugins).
Settings plugin are written in Rust as a "cdylib" crate, and loaded at runtime.
Each settings plugin must define its own private `Settings` structure.
It can use pre-defined structures inside, or custom ones as needed.
`apiserver::datastore` offers serialization and deserialization modules that make it easy to map between Rust types and the data store, and thus, all inputs and outputs are type-checked.
At the field level, standard Rust types can be used, or ["modeled types"](https://github.com/bottlerocket-os/bottlerocket-settings-sdk/tree/develop/bottlerocket-settings-models/modeled-types) that add input validation.
At the field level, standard Rust types can be used, or ["modeled types"](src/modeled_types) that add input validation.
The `#[model]` attribute on Settings and its sub-structs reduces duplication and adds some required metadata; see [its docs](model-derive/) for details.
*/
@@ -24,8 +24,12 @@ pub mod exec;
use bottlerocket_release::BottlerocketRelease;
use bottlerocket_settings_models::model_derive::model;
use bottlerocket_settings_plugin::BottlerocketSettings;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use serde::{
de::{self, MapAccess, Visitor},
Deserialize, Deserializer, Serialize,
};
use serde_plain::derive_fromstr_from_deserialize;
use std::{collections::HashMap, fmt};

use bottlerocket_settings_models::modeled_types::SingleLineString;

@@ -87,3 +91,236 @@ struct Report {
name: String,
description: String,
}

/// Weak settings are ephemeral and deleted on reboot, regardless of whether or not it
/// is written by a setting generator.
#[derive(Default, Deserialize, Serialize, Debug, Clone, Copy, PartialEq)]
#[serde(rename_all = "kebab-case")]
pub enum Strength {
#[default]
Strong,
Weak,
}

impl std::fmt::Display for Strength {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Strength::Strong => write!(f, "strong"),
Strength::Weak => write!(f, "weak"),
}
}
}

derive_fromstr_from_deserialize!(Strength);

/// Struct to hold the setting generator definition containing
/// command, strength, depth
// This will only be be used for processing generator from defaults.
#[derive(Clone, Default, Serialize, std::fmt::Debug, PartialEq)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct RawSettingsGenerator {
pub command: String,
pub strength: Strength,
pub depth: u32,
}

impl RawSettingsGenerator {
pub fn is_weak(&self) -> bool {
self.strength == Strength::Weak
}
}

impl<'de> Deserialize<'de> for RawSettingsGenerator {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct SettingsGeneratorVisitor;
impl<'de> Visitor<'de> for SettingsGeneratorVisitor {
type Value = RawSettingsGenerator;

fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a string or a map")
}

fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
// If the value is a string, use it as the `command` with defaults for other fields.
Ok(RawSettingsGenerator {
command: value.to_string(),
..RawSettingsGenerator::default()
})
}

fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
where
M: MapAccess<'de>,
{
// Extract values from the map
let mut command = None;
let mut strength = None;
let mut depth = None;
while let Some(key) = map.next_key::<String>()? {
match key.as_str() {
"command" => command = Some(map.next_value()?),
"strength" => strength = Some(map.next_value()?),
"depth" => depth = Some(map.next_value()?),
_ => {
return Err(de::Error::unknown_field(
&key,
&["command", "strength", "depth"],
))
}
}
}
Ok(RawSettingsGenerator {
command: command.ok_or_else(|| de::Error::missing_field("command"))?,
strength: strength.unwrap_or_default(),
depth: depth.unwrap_or(0),
})
}
}
deserializer.deserialize_any(SettingsGeneratorVisitor)
}
}

#[cfg(test)]
mod test {
use super::*;

#[test]
fn test_setting_generator_deserialization() {
let api_response = r#"
{
"host-containers.admin.source": "generator1",
"host-containers.control.source": {
"command": "generator2",
"strength": "weak",
"depth": 0
},
"host-containers.no_depth.source": {
"command": "generator3",
"strength": "weak"
},
"host-containers.depth_given.source": {
"command": "generator4",
"strength": "weak",
"depth": 1
}
}"#;

let expected_admin = RawSettingsGenerator {
command: "generator1".to_string(),
strength: Strength::Strong,
depth: 0,
};

let expected_control = RawSettingsGenerator {
command: "generator2".to_string(),
strength: Strength::Weak,
depth: 0,
};

let expected_no_depth = RawSettingsGenerator {
command: "generator3".to_string(),
strength: Strength::Weak,
depth: 0,
};

let expected_depth_given = RawSettingsGenerator {
command: "generator4".to_string(),
strength: Strength::Weak,
depth: 1,
};

let result: HashMap<String, RawSettingsGenerator> =
serde_json::from_str(api_response).unwrap();

assert_eq!(
result.get("host-containers.admin.source").unwrap(),
&expected_admin
);
assert_eq!(
result.get("host-containers.control.source").unwrap(),
&expected_control
);
assert_eq!(
result.get("host-containers.no_depth.source").unwrap(),
&expected_no_depth
);
assert_eq!(
result.get("host-containers.depth_given.source").unwrap(),
&expected_depth_given
);
}
}

#[derive(Default, Serialize, std::fmt::Debug, PartialEq)]
pub struct SettingsGenerator {
pub command: String,
pub strength: Strength,
}

impl From<RawSettingsGenerator> for SettingsGenerator {
fn from(value: RawSettingsGenerator) -> Self {
SettingsGenerator {
command: value.command,
strength: value.strength,
}
}
}

impl<'de> Deserialize<'de> for SettingsGenerator {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct SettingsGeneratorVisitor;
impl<'de> Visitor<'de> for SettingsGeneratorVisitor {
type Value = SettingsGenerator;

fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a string or a map")
}

fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
// If the value is a string, use it as the `command` with defaults for other fields.
Ok(SettingsGenerator {
command: value.to_string(),
..SettingsGenerator::default()
})
}

fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
where
M: MapAccess<'de>,
{
// Extract values from the map
let mut command = None;
let mut strength = None;
while let Some(key) = map.next_key::<String>()? {
match key.as_str() {
"command" => command = Some(map.next_value()?),
"strength" => strength = Some(map.next_value()?),
_ => {
return Err(de::Error::unknown_field(
&key,
&["command", "strength"],
))
}
}
}
Ok(SettingsGenerator {
command: command.ok_or_else(|| de::Error::missing_field("command"))?,
strength: strength.unwrap_or_default(),
})
}
}
deserializer.deserialize_any(SettingsGeneratorVisitor)
}
}

0 comments on commit 663467b

Please sign in to comment.