Repository: bottlerocket-os/bottlerocket
File: sources/settings-migrations/v1.40.0/kubelet-device-plugins-cdi-settings/src/main.rs (Rust)

Code before:

#[snafu::report]
fn main() -> Result<()> {
    migrate(ReplaceDeviceListStrategy(&[
        "settings.kubelet-device-plugins.nvidia.device-list-strategy",
    ]))
}

/// We change the k8s api nvidia list strategy settings from a string to a list
/// or "cdi-cri" to "volume-mounts"
pub struct ReplaceDeviceListStrategy<'a>(pub &'a [&'static str]);

impl Migration for ReplaceDeviceListStrategy<'_> {
    /// New versions must either have a default for the settings or generate them; we don't need to
    /// do anything.
    fn forward(&mut self, input: MigrationData) -> Result<MigrationData> {
        println!("ReplaceDeviceListStrategy has no work to do on upgrade.",);
        Ok(input)
    }

    /// Older versions don't know about the settings; we remove them so that old versions don't see
    /// them and fail deserialization.  (The settings must be defaulted or generated in new versions,
    /// and safe to remove.)
    fn backward(&mut self, mut input: MigrationData) -> Result<MigrationData> {
        for setting in self.0 {
            if let Some(data) = input.data.get_mut(*setting) {
                match data {
                    serde_json::Value::Array(arr) => {
                        let list: Vec<&str> = arr
                            .iter()
                            .map(|v| v.as_str())
                            .collect::<Option<Vec<&str>>>()
                            .context(error::ReplaceListContentsSnafu {
                                setting: *setting,
                                data: arr.clone(),
                            })?;

                        let new_value = if list.is_empty() {
                            "volume-mounts".to_string()
                        } else if list[0] == "cdi-cri" {
                            "volume-mounts".to_string()
                        } else {
                            list[0].to_string()
                        };

                        *data = serde_json::Value::String(new_value.to_string());
                    }

                    serde_json::Value::String(setting_str) => {
                        if setting_str == "cdi-cri" {
                            *data = serde_json::Value::String("volume-mounts".to_string());

Review comment (refactor):
If you change the inputs to the migration, and you use the constant, you can remove this `for` as we only care about the one setting.

Code after:

const DEVICE_LIST_STRATEGY_SETTING: &str =
    "settings.kubelet-device-plugins.nvidia.device-list-strategy";

#[snafu::report]
fn main() -> Result<()> {
    migrate(ReplaceDeviceListStrategy)
}

/// We changed the type of the device-list-strategy in the NVIDIA Kubernetes Device
/// plugin API from a string to a list, and accept "cdi-cri" as a valid value
pub struct ReplaceDeviceListStrategy;

impl Migration for ReplaceDeviceListStrategy {
    /// New versions must either have a default for the settings or generate them; we don't need to
    /// do anything.
    fn forward(&mut self, input: MigrationData) -> Result<MigrationData> {
        println!("ReplaceDeviceListStrategy has no work to do on upgrade.");
        Ok(input)
    }

    /// Older versions don't know about the setting now accepting both a string, a list and a new accepted value "cdi-cri";
    /// we remove the list option and the "cdi-cri" value so that old versions don't see them and fail deserialization.
    /// (The settings must be defaulted or generated in new versions, and safe to remove.)
    fn backward(&mut self, mut input: MigrationData) -> Result<MigrationData> {
        let setting = DEVICE_LIST_STRATEGY_SETTING;
        if let Some(data) = input.data.get_mut(setting) {
            match data {
                serde_json::Value::Array(arr) => {
                    let list: Vec<&str> = arr
                        .iter()
                        .map(|v| v.as_str())
                        .collect::<Option<Vec<&str>>>()
                        .context(error::ReplaceListContentsSnafu {
                            setting,
                            data: arr.clone(),
                        })?;

                    let new_value = match list.first() {
                        None | Some(&"cdi-cri") => "volume-mounts".to_string(),
                        Some(value) => value.to_string(),
                    };

                    *data = serde_json::Value::String(new_value.to_string());
                }

                serde_json::Value::String(setting_str) => {
                    if setting_str == "cdi-cri" {
                        *data = serde_json::Value::String("volume-mounts".to_string());
                    } else {
                        *data = serde_json::Value::String(setting_str.to_string());