1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
// SPDX-License-Identifier: Apache-2.0

use std::collections::{BTreeMap, HashMap};

use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::{ErrorKind, MergedOvnConfiguration, NmstateError};

#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[non_exhaustive]
#[serde(deny_unknown_fields)]
pub struct OvsDbGlobalConfig {
    #[serde(
        skip_serializing_if = "Option::is_none",
        serialize_with = "show_as_ordered_map"
    )]
    // When the value been set as None, specified key will be removed instead
    // of merging.
    // To remove all settings of external_ids or other_config, use empty
    // HashMap
    pub external_ids: Option<HashMap<String, Option<String>>>,
    #[serde(
        skip_serializing_if = "Option::is_none",
        serialize_with = "show_as_ordered_map"
    )]
    pub other_config: Option<HashMap<String, Option<String>>>,
}

impl OvsDbGlobalConfig {
    pub(crate) const OVN_BRIDGE_MAPPINGS_KEY: &'static str =
        "ovn-bridge-mappings";

    // User want to remove all settings except OVN.
    pub(crate) fn is_purge(&self) -> bool {
        match (self.external_ids.as_ref(), self.other_config.as_ref()) {
            (None, None) => true,
            (Some(eids), Some(oids)) => eids.is_empty() && oids.is_empty(),
            _ => false,
        }
    }

    pub(crate) fn sanitize(&self) -> Result<(), NmstateError> {
        if self
            .external_ids
            .as_ref()
            .map(|e| e.contains_key(Self::OVN_BRIDGE_MAPPINGS_KEY))
            == Some(true)
        {
            Err(NmstateError::new(
                ErrorKind::InvalidArgument,
                format!(
                    "The `{}` is reserved for OVN mapping, please use \
                    `ovn` section instead of `ovs-db` section",
                    Self::OVN_BRIDGE_MAPPINGS_KEY
                ),
            ))
        } else {
            Ok(())
        }
    }
}

fn show_as_ordered_map<S>(
    v: &Option<HashMap<String, Option<String>>>,
    s: S,
) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    if let Some(v) = v {
        let ordered: BTreeMap<_, _> = v.iter().collect();
        ordered.serialize(s)
    } else {
        s.serialize_none()
    }
}

impl OvsDbGlobalConfig {
    pub fn is_none(&self) -> bool {
        self.external_ids.is_none() && self.other_config.is_none()
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
#[non_exhaustive]
pub struct OvsDbIfaceConfig {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub external_ids: Option<HashMap<String, Option<String>>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// OpenvSwitch specific `other_config`. Please refer to
    /// manpage `ovs-vswitchd.conf.db(5)` for more detail.
    /// When setting to None, nmstate will try to preserve current
    /// `other_config`, otherwise, nmstate will override all `other_config`
    /// for specified interface.
    pub other_config: Option<HashMap<String, Option<String>>>,
}

impl OvsDbIfaceConfig {
    pub(crate) fn get_external_ids(&self) -> HashMap<&str, &str> {
        let mut ret = HashMap::new();
        if let Some(eids) = self.external_ids.as_ref() {
            for (k, v) in eids {
                if let Some(v) = v {
                    ret.insert(k.as_str(), v.as_str());
                }
            }
        }
        ret
    }

    pub(crate) fn get_other_config(&self) -> HashMap<&str, &str> {
        let mut ret = HashMap::new();
        if let Some(cfgs) = self.other_config.as_ref() {
            for (k, v) in cfgs {
                if let Some(v) = v {
                    ret.insert(k.as_str(), v.as_str());
                }
            }
        }
        ret
    }
}

impl<'de> Deserialize<'de> for OvsDbIfaceConfig {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let mut ret = Self::default();
        let mut v = serde_json::Value::deserialize(deserializer)?;
        if let Some(v) = v.as_object_mut() {
            if let Some(v) = v.remove("external_ids") {
                ret.external_ids = Some(value_to_hash_map(&v));
            }
            if let Some(v) = v.remove("other_config") {
                ret.other_config = Some(value_to_hash_map(&v));
            }
            if !v.is_empty() {
                let remain_keys: Vec<String> = v.keys().cloned().collect();
                return Err(serde::de::Error::custom(format!(
                    "Unsupported section names '{}', only supports \
                    `external_ids` and `other_config`",
                    remain_keys.join(", ")
                )));
            }
        } else {
            return Err(serde::de::Error::custom(format!(
                "Expecting dict/HashMap, but got {v:?}"
            )));
        }
        Ok(ret)
    }
}

fn value_to_hash_map(
    value: &serde_json::Value,
) -> HashMap<String, Option<String>> {
    let mut ret: HashMap<String, Option<String>> = HashMap::new();
    if let Some(value) = value.as_object() {
        for (k, v) in value.iter() {
            let v = match &v {
                serde_json::Value::Number(i) => Some({
                    if let Some(i) = i.as_i64() {
                        format!("{i}")
                    } else if let Some(i) = i.as_u64() {
                        format!("{i}")
                    } else if let Some(i) = i.as_f64() {
                        format!("{i}")
                    } else {
                        continue;
                    }
                }),
                serde_json::Value::String(s) => Some(s.to_string()),
                serde_json::Value::Bool(b) => Some(format!("{b}")),
                serde_json::Value::Null => None,
                _ => continue,
            };
            ret.insert(k.to_string(), v);
        }
    }
    ret
}

#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct MergedOvsDbGlobalConfig {
    pub(crate) desired: Option<OvsDbGlobalConfig>,
    pub(crate) current: OvsDbGlobalConfig,
    pub(crate) external_ids: HashMap<String, Option<String>>,
    pub(crate) other_config: HashMap<String, Option<String>>,
    pub(crate) is_changed: bool,
}

impl MergedOvsDbGlobalConfig {
    // Partial editing for ovsdb:
    //  * Merge desire with current and do overriding.
    //  * Use `ovsdb: {}` to remove all settings.
    //  * To remove a key from existing, use `foo: None`.
    pub(crate) fn new(
        mut desired: Option<OvsDbGlobalConfig>,
        current: OvsDbGlobalConfig,
        merged_ovn: &MergedOvnConfiguration,
    ) -> Result<Self, NmstateError> {
        let mut external_ids: HashMap<String, Option<String>> = HashMap::new();
        let mut other_config: HashMap<String, Option<String>> = HashMap::new();

        let empty_map: HashMap<String, Option<String>> = HashMap::new();

        let mut cur_external_ids: HashMap<String, Option<String>> =
            current.external_ids.as_ref().unwrap_or(&empty_map).clone();

        let cur_other_config: HashMap<String, Option<String>> =
            current.other_config.as_ref().unwrap_or(&empty_map).clone();

        if let Some(desired) = &mut desired {
            if !desired.is_purge() {
                desired.sanitize()?;

                merge_ovsdb_confs(
                    desired.external_ids.as_ref(),
                    current.external_ids.as_ref().unwrap_or(&empty_map),
                    &mut external_ids,
                );

                merge_ovsdb_confs(
                    desired.other_config.as_ref(),
                    current.other_config.as_ref().unwrap_or(&empty_map),
                    &mut other_config,
                );
            }
        } else {
            external_ids.clone_from(&cur_external_ids);
            other_config.clone_from(&cur_other_config);
        }

        if let Some(v) = merged_ovn.to_ovsdb_external_id_value() {
            external_ids.insert(
                OvsDbGlobalConfig::OVN_BRIDGE_MAPPINGS_KEY.to_string(),
                Some(v),
            );
        }

        if let Some(v) = merged_ovn.current.to_ovsdb_external_id_value() {
            cur_external_ids.insert(
                OvsDbGlobalConfig::OVN_BRIDGE_MAPPINGS_KEY.to_string(),
                Some(v),
            );
        }

        let is_changed = cur_other_config != other_config
            || cur_external_ids != external_ids;

        Ok(Self {
            desired,
            current,
            external_ids,
            other_config,
            is_changed,
        })
    }
}

fn merge_ovsdb_confs(
    desired: Option<&HashMap<String, Option<String>>>,
    current: &HashMap<String, Option<String>>,
    output: &mut HashMap<String, Option<String>>,
) {
    if let Some(desired) = desired {
        // User want to purge this section
        if desired.is_empty() {
            return;
        }

        let removed_keys: Vec<&str> = desired
            .iter()
            .filter_map(
                |(k, v)| if v.is_none() { Some(k.as_str()) } else { None },
            )
            .collect();

        for (cur_k, cur_v) in current.iter() {
            if let Some(cur_v) = cur_v {
                if !removed_keys.contains(&cur_k.as_str()) {
                    output.insert(cur_k.to_string(), Some(cur_v.to_string()));
                }
            }
        }
        for (des_k, des_v) in desired.iter() {
            if let Some(des_v) = des_v {
                output.insert(des_k.to_string(), Some(des_v.to_string()));
            }
        }
    } else {
        // User never mentioned this section, hence copy from current
        for (cur_k, cur_v) in current.iter() {
            output.insert(cur_k.to_string(), cur_v.clone());
        }
    }
}