From 9a5a3898823065df1f60dc3f5240ac2914217d90 Mon Sep 17 00:00:00 2001 From: Shikha Vyaghra Date: Fri, 22 Nov 2024 18:29:28 +0000 Subject: [PATCH] models: Add Strength enum and Setting-Generator struct We need to add these to match changes in Bottlerocket-core-kit Refer commit: https://github.com/bottlerocket-os/bottlerocket-core-kit/pull/294/commits/a72f6bd16f7de0d628e80fb03bbf827ebd4892e2 PR: https://github.com/bottlerocket-os/bottlerocket-core-kit/pull/294 --- sources/Cargo.lock | 1 + sources/models/Cargo.toml | 1 + sources/models/src/lib.rs | 243 +++++++++++++++++++++++++++++++++++++- 3 files changed, 241 insertions(+), 4 deletions(-) diff --git a/sources/Cargo.lock b/sources/Cargo.lock index 0444c88cacc..5a7b32fd11f 100644 --- a/sources/Cargo.lock +++ b/sources/Cargo.lock @@ -1816,6 +1816,7 @@ dependencies = [ "libc", "serde", "serde_json", + "serde_plain", "toml", ] diff --git a/sources/models/Cargo.toml b/sources/models/Cargo.toml index ce679bbbc6d..3d8cfa2ab16 100644 --- a/sources/models/Cargo.toml +++ b/sources/models/Cargo.toml @@ -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 diff --git a/sources/models/src/lib.rs b/sources/models/src/lib.rs index 8dd88bc4e78..97164f316c2 100644 --- a/sources/models/src/lib.rs +++ b/sources/models/src/lib.rs @@ -5,7 +5,7 @@ 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. @@ -13,7 +13,7 @@ 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,15 @@ 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::{self, Display}, +}; use bottlerocket_settings_models::modeled_types::SingleLineString; @@ -87,3 +94,231 @@ 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 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, 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(deserializer: D) -> Result + 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(self, value: &str) -> Result + 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(self, mut map: M) -> Result + 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::()? { + 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 = + 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 for SettingsGenerator { + fn from(value: RawSettingsGenerator) -> Self { + SettingsGenerator { + command: value.command, + strength: value.strength, + } + } +} + +impl<'de> Deserialize<'de> for SettingsGenerator { + fn deserialize(deserializer: D) -> Result + 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(self, value: &str) -> Result + 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(self, mut map: M) -> Result + where + M: MapAccess<'de>, + { + // Extract values from the map + let mut command = None; + let mut strength = None; + while let Some(key) = map.next_key::()? { + 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) + } +}