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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
// SPDX-License-Identifier: Apache-2.0

use serde::{Deserialize, Serialize};

use crate::{
    BaseInterface, ErrorKind, Interface, InterfaceType, Interfaces,
    MergedInterfaces, NmstateError, SrIovConfig,
};

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
/// Ethernet(IEEE 802.3) interface.
/// Besides [BaseInterface], optionally could hold [EthernetConfig] and/or
/// [VethConfig].
/// The yaml output of [crate::NetworkState] containing ethernet interface would
/// be:
/// ```yml
/// interfaces:
/// - name: ens3
///   type: ethernet
///   state: up
///   mac-address: 00:11:22:33:44:FF
///   mtu: 1500
///   min-mtu: 68
///   max-mtu: 65535
///   wait-ip: ipv4
///   ipv4:
///     enabled: true
///     dhcp: false
///     address:
///     - ip: 192.0.2.9
///       prefix-length: 24
///   ipv6:
///     enabled: false
///   mptcp:
///     address-flags: []
///   accept-all-mac-addresses: false
///   lldp:
///     enabled: false
///   ethtool:
///     feature:
///       tx-tcp-ecn-segmentation: true
///       tx-tcp-mangleid-segmentation: false
///       tx-tcp6-segmentation: true
///       tx-tcp-segmentation: true
///       rx-gro-list: false
///       rx-udp-gro-forwarding: false
///       rx-gro-hw: true
///       tx-checksum-ip-generic: true
///       tx-generic-segmentation: true
///       rx-gro: true
///       tx-nocache-copy: false
///     coalesce:
///       rx-frames: 1
///       tx-frames: 1
///     ring:
///       rx: 256
///       rx-max: 256
///       tx: 256
///       tx-max: 256
///   ethernet:
///     auto-negotiation: false
/// ```
pub struct EthernetInterface {
    #[serde(flatten)]
    pub base: BaseInterface,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ethernet: Option<EthernetConfig>,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// When applying, the [VethConfig] is only valid when
    /// [BaseInterface.iface_type] is set to [InterfaceType::Veth] explicitly.
    pub veth: Option<VethConfig>,
}

impl Default for EthernetInterface {
    fn default() -> Self {
        let mut base = BaseInterface::new();
        base.iface_type = InterfaceType::Ethernet;
        Self {
            base,
            ethernet: None,
            veth: None,
        }
    }
}

impl EthernetInterface {
    pub(crate) fn sanitize(&mut self) -> Result<(), NmstateError> {
        // Always set interface type to ethernet for verifying and applying
        self.base.iface_type = InterfaceType::Ethernet;

        if let Some(sriov_conf) =
            self.ethernet.as_mut().and_then(|e| e.sr_iov.as_mut())
        {
            sriov_conf.sanitize();
        }

        Ok(())
    }

    pub fn new() -> Self {
        Self::default()
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
pub enum EthernetDuplex {
    /// Deserialize and serialize from/to `full`.
    Full,
    /// Deserialize and serialize from/to `half`.
    Half,
}

impl std::fmt::Display for EthernetDuplex {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            match self {
                Self::Full => "full",
                Self::Half => "half",
            }
        )
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
#[non_exhaustive]
pub struct EthernetConfig {
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Single Root I/O Virtualization(SRIOV) configuration.
    /// Deserialize and serialize from/to `sr-iov`.
    pub sr_iov: Option<SrIovConfig>,
    #[serde(
        skip_serializing_if = "Option::is_none",
        rename = "auto-negotiation",
        default,
        deserialize_with = "crate::deserializer::option_bool_or_string"
    )]
    /// Deserialize and serialize from/to `auto-negotiation`.
    pub auto_neg: Option<bool>,
    #[serde(
        skip_serializing_if = "Option::is_none",
        default,
        deserialize_with = "crate::deserializer::option_u32_or_string"
    )]
    pub speed: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub duplex: Option<EthernetDuplex>,
}

impl EthernetConfig {
    pub fn new() -> Self {
        Self::default()
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[non_exhaustive]
pub struct VethConfig {
    /// The name of veth peer.
    pub peer: String,
}

impl MergedInterfaces {
    // Raise error if new veth interface has no peer defined.
    // Mark old veth peer as absent when veth changed its peer.
    // Mark veth peer as absent also when veth is marked as absent.
    pub(crate) fn process_veth_peer_changes(
        &mut self,
    ) -> Result<(), NmstateError> {
        let mut veth_peers: Vec<&str> = Vec::new();
        for iface in self.iter().filter(|i| {
            i.merged.iface_type() == InterfaceType::Ethernet && i.merged.is_up()
        }) {
            if let Interface::Ethernet(eth_iface) = &iface.merged {
                if let Some(v) =
                    eth_iface.veth.as_ref().map(|v| v.peer.as_str())
                {
                    veth_peers.push(v);
                }
            }
        }
        for iface in self.iter().filter(|i| {
            i.merged.iface_type() == InterfaceType::Ethernet
                && i.is_desired()
                && i.current.is_none()
                && i.merged.is_up()
        }) {
            if let Some(Interface::Ethernet(eth_iface)) = &iface.desired {
                if eth_iface.veth.is_none()
                    && !self.gen_conf_mode
                    && !veth_peers.contains(&eth_iface.base.name.as_str())
                {
                    return Err(NmstateError::new(
                        ErrorKind::InvalidArgument,
                        format!(
                            "Ethernet interface {} does not exists",
                            eth_iface.base.name.as_str()
                        ),
                    ));
                }
            }
        }

        let mut pending_deletions: Vec<String> = Vec::new();

        for iface in self.iter().filter(|i| {
            i.merged.iface_type() == InterfaceType::Ethernet
                && i.is_desired()
                && i.merged.is_up()
                && i.current.is_some()
        }) {
            if let (
                Some(Interface::Ethernet(des_eth_iface)),
                Some(Interface::Ethernet(cur_eth_iface)),
            ) = (iface.desired.as_ref(), iface.current.as_ref())
            {
                if let (Some(veth_conf), Some(cur_veth_conf)) =
                    (des_eth_iface.veth.as_ref(), cur_eth_iface.veth.as_ref())
                {
                    if veth_conf.peer != cur_veth_conf.peer {
                        pending_deletions.push(cur_veth_conf.peer.to_string());
                    }
                }
            }
        }

        for iface in self.iter().filter(|i| {
            i.merged.iface_type() == InterfaceType::Ethernet
                && i.is_desired()
                && i.merged.is_absent()
                && i.current.is_some()
        }) {
            if let Some(Interface::Ethernet(cur_eth_iface)) =
                iface.current.as_ref()
            {
                if let Some(veth_conf) = cur_eth_iface.veth.as_ref() {
                    pending_deletions.push(veth_conf.peer.to_string());
                }
            }
        }

        for del_peer in pending_deletions {
            if let Some(iface) = self.kernel_ifaces.get_mut(&del_peer) {
                iface.mark_as_absent();
            }
        }
        Ok(())
    }
}

impl Interfaces {
    // Not allowing changing veth peer away from ignored peer unless previous
    // peer changed from ignore to managed
    pub(crate) fn validate_change_veth_ignored_peer(
        &self,
        current: &Self,
        ignored_ifaces: &[(String, InterfaceType)],
    ) -> Result<(), NmstateError> {
        let ignored_veth_ifaces: Vec<&String> = ignored_ifaces
            .iter()
            .filter_map(|(n, t)| {
                if t == &InterfaceType::Ethernet {
                    Some(n)
                } else {
                    None
                }
            })
            .collect();

        for iface in self.kernel_ifaces.values().filter(|i| {
            if let Interface::Ethernet(i) = i {
                i.veth.is_some()
            } else {
                false
            }
        }) {
            if let (
                Interface::Ethernet(des_iface),
                Some(Interface::Ethernet(cur_iface)),
            ) = (iface, current.get_iface(iface.name(), InterfaceType::Veth))
            {
                if let (Some(des_peer), cur_peer) = (
                    des_iface.veth.as_ref().map(|v| v.peer.as_str()),
                    cur_iface.veth.as_ref().map(|v| v.peer.as_str()),
                ) {
                    let cur_peer = if let Some(c) = cur_peer {
                        c
                    } else {
                        // The veth peer is in another namespace.
                        let e = NmstateError::new(
                            ErrorKind::InvalidArgument,
                            format!(
                                "Veth interface {} is currently holding \
                                peer assigned to other namespace \
                                Please remove this veth pair \
                                before changing veth peer to {des_peer}",
                                iface.name(),
                            ),
                        );
                        log::error!("{}", e);
                        return Err(e);
                    };

                    if des_peer != cur_peer
                        && ignored_veth_ifaces.contains(&&cur_peer.to_string())
                    {
                        let e = NmstateError::new(
                            ErrorKind::InvalidArgument,
                            format!(
                                "Veth interface {} is currently holding \
                                peer {} which is marked as ignored. \
                                Hence not allowing changing its peer \
                                to {}. Please remove this veth pair \
                                before changing veth peer",
                                iface.name(),
                                cur_peer,
                                des_peer
                            ),
                        );
                        log::error!("{}", e);
                        return Err(e);
                    }
                }
            }
        }
        Ok(())
    }

    pub(crate) fn validate_new_veth_without_peer(
        &self,
        current: &Self,
    ) -> Result<(), NmstateError> {
        for iface in self.kernel_ifaces.values().filter(|i| {
            i.is_up()
                && i.iface_type() == InterfaceType::Veth
                && current.kernel_ifaces.get(i.name()).is_none()
        }) {
            if let Interface::Ethernet(eth_iface) = iface {
                if eth_iface.veth.is_none() {
                    return Err(NmstateError::new(
                        ErrorKind::InvalidArgument,
                        format!(
                            "Veth interface {} does not exist, \
                            peer name is required for creating it",
                            iface.name()
                        ),
                    ));
                }
            }
        }
        Ok(())
    }
}