nmstate 2.2.60

Library for networking management in a declarative manner
Documentation
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
// SPDX-License-Identifier: Apache-2.0

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

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

use crate::{
    ErrorKind, EthernetInterface, Interface, InterfaceIdentifier,
    InterfaceState, InterfaceType, MergedInterface, NetworkStateMode,
    NmstateError,
};

// The max loop count for Interfaces.set_ifaces_up_priority()
// This allows interface with 4 nested levels in any order.
// To support more nested level, user could place top controller at the
// beginning of desire state
const INTERFACES_SET_PRIORITY_MAX_RETRY: u32 = 4;

const COPY_MAC_ALLOWED_IFACE_TYPES: [InterfaceType; 3] = [
    InterfaceType::Bond,
    InterfaceType::LinuxBridge,
    InterfaceType::OvsInterface,
];

/// Represent a list of [Interface].
///
/// With special [serde::Deserializer] and [serde::Serializer].  When applying
/// complex nested interface(e.g. bridge over bond over vlan of eth1), the
/// supported maximum nest level is 4 like previous example.  For 5+ nested
/// level, you need to place controller interface before its ports.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Interfaces {
    pub(crate) kernel_ifaces: HashMap<String, Interface>,
    pub(crate) user_ifaces: HashMap<(String, InterfaceType), Interface>,
    // The insert_order is allowing user to provided ordered interface
    // to support 5+ nested dependency.
    pub(crate) insert_order: Vec<(String, InterfaceType)>,
}

impl<'de> Deserialize<'de> for Interfaces {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let mut ret = Self::new();
        for iface in <Vec<Interface> as Deserialize>::deserialize(deserializer)?
        {
            ret.push(iface);
        }
        Ok(ret)
    }
}

impl Serialize for Interfaces {
    // Serialize is also used for verification.
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let ifaces = self.to_vec();
        let mut seq = serializer.serialize_seq(Some(ifaces.len()))?;
        for iface in ifaces {
            seq.serialize_element(iface)?;
        }
        seq.end()
    }
}

impl Interfaces {
    /// Create empty [Interfaces].
    pub fn new() -> Self {
        Self::default()
    }

    pub fn is_empty(&self) -> bool {
        self.kernel_ifaces.is_empty() && self.user_ifaces.is_empty()
    }

    /// Extract internal interfaces to `Vec()`.
    pub fn to_vec(&self) -> Vec<&Interface> {
        let mut ifaces = Vec::new();
        for iface in self.kernel_ifaces.values() {
            ifaces.push(iface);
        }
        for iface in self.user_ifaces.values() {
            ifaces.push(iface);
        }
        ifaces.sort_unstable_by_key(|iface| (iface.name(), iface.iface_type()));
        // Use sort_by_key() instead of unstable one, do we can alphabet
        // activation order which is required to simulate the OS boot-up.
        ifaces.sort_by_key(|iface| iface.base_iface().up_priority);

        ifaces
    }

    /// Search interface based on interface name and interface type.
    /// When using [InterfaceType::Unknown], we only search kernel
    /// interface(which has presentation in kernel space).
    pub fn get_iface<'a>(
        &'a self,
        iface_name: &str,
        iface_type: InterfaceType,
    ) -> Option<&'a Interface> {
        if iface_type == InterfaceType::Unknown {
            self.kernel_ifaces.get(iface_name).or_else(|| {
                self.user_ifaces
                    .values()
                    .find(|&iface| iface.name() == iface_name)
            })
        } else if iface_type.is_userspace() {
            self.user_ifaces.get(&(iface_name.to_string(), iface_type))
        } else {
            self.kernel_ifaces.get(iface_name)
        }
    }

    pub fn remove_iface(
        &mut self,
        iface_name: &str,
        iface_type: InterfaceType,
    ) -> Option<Interface> {
        if iface_type == InterfaceType::Unknown {
            self.kernel_ifaces.remove(iface_name).or_else(|| {
                if let Some((n, t)) = self
                    .user_ifaces
                    .keys()
                    .find(|&(i, _)| i == iface_name)
                    .cloned()
                {
                    self.user_ifaces.remove(&(n, t))
                } else {
                    None
                }
            })
        } else if iface_type.is_userspace() {
            self.user_ifaces
                .remove(&(iface_name.to_string(), iface_type))
        } else {
            self.kernel_ifaces.remove(iface_name)
        }
    }

    /// Append specified [Interface].
    pub fn push(&mut self, iface: Interface) {
        self.insert_order
            .push((iface.name().to_string(), iface.iface_type()));
        if iface.is_userspace() {
            self.user_ifaces
                .insert((iface.name().to_string(), iface.iface_type()), iface);
        } else {
            self.kernel_ifaces.insert(iface.name().to_string(), iface);
        }
    }

    pub(crate) fn hide_secrets(&mut self) {
        for iface in self
            .kernel_ifaces
            .values_mut()
            .chain(self.user_ifaces.values_mut())
        {
            iface.base_iface_mut().hide_secrets();
            if let Interface::MacSec(macsec_iface) = iface
                && let Some(macsec_conf) = macsec_iface.macsec.as_mut()
            {
                macsec_conf.hide_secrets();
            }
            if let Interface::Ipsec(ipsec_iface) = iface {
                ipsec_iface.hide_secrets();
            }
        }
    }

    pub fn iter(&self) -> impl Iterator<Item = &Interface> {
        self.user_ifaces.values().chain(self.kernel_ifaces.values())
    }

    pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut Interface> {
        self.user_ifaces
            .values_mut()
            .chain(self.kernel_ifaces.values_mut())
    }

    // Not allowing changing veth peer away from ignored peer unless previous
    // peer changed from ignore to managed
    // Not allowing creating veth without peer config
    pub(crate) fn pre_ignore_check(
        &self,
        current: &Self,
        ignored_ifaces: &[(String, InterfaceType)],
    ) -> Result<(), NmstateError> {
        self.validate_change_veth_ignored_peer(current, ignored_ifaces)?;
        self.validate_new_veth_without_peer(current)?;
        Ok(())
    }

    fn ignored_kernel_iface_names(&self) -> HashSet<String> {
        let mut ret = HashSet::new();
        for iface in self.kernel_ifaces.values().filter(|i| i.is_ignore()) {
            ret.insert(iface.name().to_string());
        }
        ret
    }

    fn ignored_user_iface_name_types(
        &self,
    ) -> HashSet<(String, InterfaceType)> {
        let mut ret = HashSet::new();
        for iface in self.user_ifaces.values().filter(|i| i.is_ignore()) {
            ret.insert((iface.name().to_string(), iface.iface_type()));
        }
        ret
    }

    pub(crate) fn unify_veth_and_eth(&mut self) {
        for iface in self.kernel_ifaces.values_mut() {
            if let Interface::Ethernet(iface) = iface {
                iface.base.iface_type = InterfaceType::Ethernet;
            }
        }
        for nt in self.insert_order.as_mut_slice() {
            if nt.1 == InterfaceType::Veth {
                nt.1 = InterfaceType::Ethernet;
            }
        }
    }

    pub(crate) fn remove_ignored_ifaces(
        &mut self,
        ignored_ifaces: &[(String, InterfaceType)],
    ) {
        for (iface_name, iface_type) in ignored_ifaces {
            self.remove_iface(iface_name.as_str(), iface_type.clone());
        }

        let kernel_iface_names: HashSet<String> = HashSet::from_iter(
            ignored_ifaces
                .iter()
                .filter(|(_, t)| !t.is_userspace())
                .map(|(n, _)| n.to_string()),
        );

        // Remove ignored_iface from port list or veth peer also
        for iface in self
            .kernel_ifaces
            .values_mut()
            .chain(self.user_ifaces.values_mut())
            .filter(|i| i.is_controller())
        {
            if let Some(ports) = iface.ports() {
                let ports: HashSet<String> =
                    HashSet::from_iter(ports.iter().map(|p| p.to_string()));
                for ignore_port in kernel_iface_names.intersection(&ports) {
                    iface.remove_port(ignore_port);
                }
            }
            if iface.iface_type() == InterfaceType::Veth
                && let Interface::Ethernet(eth_iface) = iface
                && let Some(veth_conf) = eth_iface.veth.as_ref()
                && kernel_iface_names.contains(veth_conf.peer.as_str())
            {
                log::info!(
                    "Veth interface {} is holding ignored peer {}",
                    eth_iface.base.name,
                    veth_conf.peer.as_str()
                );
                eth_iface.veth = None;
            }
        }
    }

    // In memory_only mode, absent interface equal to down
    // action.
    pub(crate) fn apply_memory_only_mode(&mut self) {
        for iface in self.iter_mut().filter(|i| i.is_absent()) {
            iface.base_iface_mut().state = InterfaceState::Down;
        }
    }

    pub(crate) fn resolve_unknown_ifaces(
        &mut self,
        cur_ifaces: &Self,
    ) -> Result<(), NmstateError> {
        let mut resolved_ifaces: Vec<Interface> = Vec::new();
        for (iface_name, iface) in self.kernel_ifaces.iter() {
            if iface.iface_type() != InterfaceType::Unknown || iface.is_ignore()
            {
                continue;
            }
            if iface.is_absent() {
                for cur_iface in cur_ifaces.to_vec() {
                    if cur_iface.name() == iface_name {
                        let mut new_iface = cur_iface.clone_name_type_only();
                        new_iface.base_iface_mut().state =
                            InterfaceState::Absent;
                        resolved_ifaces.push(new_iface);
                    }
                }
            } else {
                let mut founds = Vec::new();
                for cur_iface in cur_ifaces.to_vec() {
                    if cur_iface.name() == iface_name {
                        let mut new_iface_value = serde_json::to_value(iface)?;
                        if let Some(obj) = new_iface_value.as_object_mut() {
                            obj.insert(
                                "type".to_string(),
                                serde_json::Value::String(
                                    cur_iface.iface_type().to_string(),
                                ),
                            );
                        }
                        founds.push(new_iface_value);
                    }
                }
                match founds.len() {
                    0 => {
                        let e = NmstateError::new(
                            ErrorKind::InvalidArgument,
                            format!(
                                "Failed to find unknown type interface \
                                 {iface_name} in current state"
                            ),
                        );
                        log::error!("{e}");
                        return Err(e);
                    }
                    1 => {
                        let new_iface = Interface::deserialize(&founds[0])?;
                        resolved_ifaces.push(new_iface);
                    }
                    _ => {
                        let e = NmstateError::new(
                            ErrorKind::InvalidArgument,
                            format!(
                                "Found 2+ interface matching desired unknown \
                                 type interface {}: {:?}",
                                iface_name, &founds
                            ),
                        );
                        log::error!("{e}");
                        return Err(e);
                    }
                }
            }
        }

        for new_iface in resolved_ifaces {
            self.kernel_ifaces.remove(new_iface.name());
            self.push(new_iface);
        }
        Ok(())
    }

    fn purge_unknown_state_iface(&mut self) {
        self.user_ifaces.retain(|_, iface| {
            iface.base_iface().state != InterfaceState::Unknown
        });
        self.kernel_ifaces.retain(|_, iface| {
            iface.base_iface().state != InterfaceState::Unknown
        });

        // Clean up insert_order Vec by removing entries for interfaces that
        // were purged. The `insert_order` is used for re-ordering
        // interfaces based on their controller-port-parent relationship
        // in `set_ifaces_up_priority()`. We must maintain consistency between
        // `insert_order` and the HashMap collections to ensure proper interface
        // dependency.
        self.insert_order.retain(|(iface_name, iface_type)| {
            if iface_type.is_userspace() {
                self.user_ifaces
                    .contains_key(&(iface_name.clone(), iface_type.clone()))
            } else {
                self.kernel_ifaces.contains_key(iface_name)
            }
        });
    }

    // If any desired interface has `identifier: mac-address`:
    //  * Resolve interface.name to MAC address match interface name.
    //  * Store interface.name to interface.profile_name.
    fn resolve_mac_identifier_in_desired(
        &mut self,
        current: &Self,
    ) -> Result<(), NmstateError> {
        let mut changed_ifaces: Vec<Interface> = Vec::new();
        for iface in self.iter().filter(|i| {
            (!i.is_absent())
                && i.base_iface().identifier
                    == Some(InterfaceIdentifier::MacAddress)
                && i.base_iface().profile_name.is_none()
        }) {
            let mac_address = match iface.base_iface().mac_address.as_deref() {
                Some(m) => m.to_ascii_uppercase(),
                None => {
                    return Err(NmstateError::new(
                        ErrorKind::InvalidArgument,
                        format!(
                            "Desired interface {} has `identifier: \
                             mac-address` but not MAC address defined",
                            iface.name()
                        ),
                    ));
                }
            };
            let mut has_match = false;
            // If `permanent_mac_address` got no matches, fallback to
            // `mac_address`
            for use_permanent_addr in [true, false] {
                for cur_iface in current.kernel_ifaces.values() {
                    if iface.iface_type() != InterfaceType::Unknown
                        && iface.iface_type() != cur_iface.iface_type()
                    {
                        continue;
                    }
                    let cur_mac_addr = if use_permanent_addr {
                        cur_iface
                            .base_iface()
                            .permanent_mac_address
                            .as_deref()
                            .map(|m| m.to_ascii_uppercase())
                    } else {
                        cur_iface
                            .base_iface()
                            .mac_address
                            .as_deref()
                            .map(|m| m.to_ascii_uppercase())
                    };
                    if cur_mac_addr.as_deref() == Some(&mac_address) {
                        let mut new_iface = if iface.iface_type()
                            == InterfaceType::Unknown
                        {
                            let mut new_iface_value =
                                serde_json::to_value(iface)?;
                            if let Some(obj) = new_iface_value.as_object_mut() {
                                obj.insert(
                                    "type".to_string(),
                                    serde_json::Value::String(
                                        cur_iface.iface_type().to_string(),
                                    ),
                                );
                            }
                            Interface::deserialize(new_iface_value)?
                        } else {
                            iface.clone()
                        };
                        new_iface.base_iface_mut().profile_name =
                            Some(iface.base_iface().name.clone());
                        new_iface.base_iface_mut().name =
                            cur_iface.name().to_string();
                        changed_ifaces.push(new_iface);
                        has_match = true;
                        break;
                    }
                }
                if has_match {
                    break;
                }
            }

            if !has_match {
                return Err(NmstateError::new(
                    ErrorKind::InvalidArgument,
                    format!(
                        "Desired interface {} has `identifier: mac-address` \
                         with MAC address {mac_address}, but no interface is \
                         holding that MAC address",
                        iface.name()
                    ),
                ));
            }
        }
        for changed_iface in changed_ifaces {
            if let Some(profile_name) =
                changed_iface.base_iface().profile_name.as_deref()
            {
                self.kernel_ifaces.remove(profile_name);
            }
            self.push(changed_iface);
        }
        Ok(())
    }

    // If any desired interface has `identifier: mac-address`:
    //  * Resolve interface.name to MAC address match interface name.
    //  * Store interface.name to interface.profile_name.
    fn resolve_pci_identifier(
        &mut self,
        current: &Self,
    ) -> Result<(), NmstateError> {
        let mut name_changed_ifaces: Vec<String> = Vec::new();
        for iface in self.iter_mut().filter(|i| {
            (!i.is_absent())
                && i.base_iface().identifier
                    == Some(InterfaceIdentifier::PciAddress)
        }) {
            let pci_address = match iface.base_iface().pci_address.as_ref() {
                Some(p) => p,
                None => {
                    return Err(NmstateError::new(
                        ErrorKind::InvalidArgument,
                        format!(
                            "Desired interface {} has `identifier: \
                             pci-address` but not PCI address defined",
                            iface.name()
                        ),
                    ));
                }
            };
            if let Some(cur_iface) =
                current.kernel_ifaces.values().find(|cur_iface| {
                    cur_iface.base_iface().pci_address.as_ref()
                        == Some(pci_address)
                })
            {
                if iface.base_iface().profile_name.is_none() {
                    // Since profile name is undefined, we should set kernel
                    // name as interface name and use the original name
                    // as profile name instead.
                    // In this case, the HashMap key of `self.kernel_ifaces()`
                    // should be changed.
                    name_changed_ifaces
                        .push(iface.base_iface_mut().name.clone());
                    iface.base_iface_mut().profile_name =
                        Some(iface.base_iface_mut().name.clone());
                    iface.base_iface_mut().name = cur_iface.name().to_string();
                } else {
                    iface.base_iface_mut().name = cur_iface.name().to_string();
                }
            } else {
                return Err(NmstateError::new(
                    ErrorKind::InvalidArgument,
                    format!(
                        "Desired interface {} has `identifier: pci-address` \
                         with PCI address {pci_address}, but no interface is \
                         holding that PCI address",
                        iface.name()
                    ),
                ));
            }
        }
        for profile_name in name_changed_ifaces {
            if let Some(iface) = self.kernel_ifaces.remove(&profile_name) {
                self.push(iface);
            }
        }

        Ok(())
    }

    // If any desired interface is referring to a mac-based current interface:
    //  * Resolve interface.name to MAC address match interface name.
    //  * Store interface.name to interface.profile_name(if not define).
    fn resolve_mac_identifier_in_current(
        &mut self,
        current: &Self,
    ) -> Result<(), NmstateError> {
        let mut changed_ifaces: Vec<Interface> = Vec::new();
        for cur_iface in current.kernel_ifaces.values().filter(|i| {
            i.base_iface().identifier == Some(InterfaceIdentifier::MacAddress)
        }) {
            if let Some(profile_name) =
                cur_iface.base_iface().profile_name.as_ref()
                && let Some(des_iface) = self.kernel_ifaces.get(profile_name)
            {
                let mut new_iface = if des_iface.iface_type()
                    == InterfaceType::Unknown
                {
                    let mut new_iface_value = serde_json::to_value(des_iface)?;
                    if let Some(obj) = new_iface_value.as_object_mut() {
                        obj.insert(
                            "type".to_string(),
                            serde_json::Value::String(
                                cur_iface.iface_type().to_string(),
                            ),
                        );
                    }
                    Interface::deserialize(new_iface_value)?
                } else {
                    des_iface.clone()
                };

                new_iface.base_iface_mut().identifier =
                    Some(InterfaceIdentifier::MacAddress);
                new_iface
                    .base_iface_mut()
                    .mac_address
                    .clone_from(&cur_iface.base_iface().mac_address);
                new_iface.base_iface_mut().name = cur_iface.name().to_string();
                new_iface.base_iface_mut().profile_name =
                    Some(profile_name.to_string());
                changed_ifaces.push(new_iface);
            }
        }
        for changed_iface in changed_ifaces {
            if let Some(profile_name) =
                changed_iface.base_iface().profile_name.as_deref()
            {
                self.kernel_ifaces.remove(profile_name);
            }
            self.push(changed_iface);
        }
        Ok(())
    }

    pub(crate) fn get_iface_mut<'a>(
        &'a mut self,
        iface_name: &str,
        iface_type: InterfaceType,
    ) -> Option<&'a mut Interface> {
        if iface_type.is_userspace() {
            self.user_ifaces
                .get_mut(&(iface_name.to_string(), iface_type))
        } else {
            self.kernel_ifaces.get_mut(iface_name)
        }
    }

    pub(crate) fn set_missing_port_to_eth(&mut self) {
        let mut iface_names_to_add = Vec::new();
        for iface in
            self.kernel_ifaces.values().chain(self.user_ifaces.values())
        {
            if let Some(ports) = iface.ports() {
                for port in ports {
                    if !self.kernel_ifaces.contains_key(port) {
                        iface_names_to_add.push(port.to_string());
                    }
                }
            }
        }
        for iface_name in iface_names_to_add {
            let mut iface = EthernetInterface::default();
            iface.base.name.clone_from(&iface_name);
            log::warn!("Assuming undefined port {iface_name} as ethernet");
            self.kernel_ifaces
                .insert(iface_name, Interface::Ethernet(Box::new(iface)));
        }
    }

    pub(crate) fn set_unknown_iface_to_eth(
        &mut self,
    ) -> Result<(), NmstateError> {
        let mut new_ifaces = Vec::new();
        for iface in self.kernel_ifaces.values() {
            if let Interface::Unknown(iface) = &iface {
                log::warn!(
                    "Setting unknown type interface {} to ethernet",
                    iface.base.name.as_str()
                );
                let iface_value = match serde_json::to_value(iface) {
                    Ok(mut v) => {
                        if let Some(v) = v.as_object_mut() {
                            v.insert(
                                "type".to_string(),
                                serde_json::Value::String(
                                    "ethernet".to_string(),
                                ),
                            );
                        }
                        v
                    }
                    Err(e) => {
                        return Err(NmstateError::new(
                            ErrorKind::Bug,
                            format!(
                                "BUG: Failed to convert {iface:?} to \
                                 serde_json value: {e}"
                            ),
                        ));
                    }
                };
                match EthernetInterface::deserialize(&iface_value) {
                    Ok(i) => new_ifaces.push(i),
                    Err(e) => {
                        return Err(NmstateError::new(
                            ErrorKind::InvalidArgument,
                            format!(
                                "Invalid property for ethernet interface: {e}"
                            ),
                        ));
                    }
                }
            }
        }
        for iface in new_ifaces {
            self.kernel_ifaces.insert(
                iface.base.name.to_string(),
                Interface::Ethernet(Box::new(iface)),
            );
        }
        Ok(())
    }

    pub(crate) fn clone_name_type_only(&self) -> Self {
        let mut ret = Self::new();

        for iface in self.to_vec() {
            ret.push(iface.clone_name_type_only())
        }
        ret
    }

    /// In gen_conf mode, for interface with `identifier: mac-address`
    /// cannot resolve to real kernel interface name. So treat `interface.name`
    /// as kernel name and also store that as profile name.
    pub(crate) fn handle_gen_conf_mac_identifer(&mut self) {
        for iface in self.kernel_ifaces.values_mut().filter(|i| i.is_up()) {
            if iface.base_iface().identifier.as_ref()
                == Some(&InterfaceIdentifier::MacAddress)
                && iface.base_iface().profile_name.is_none()
            {
                iface.base_iface_mut().profile_name =
                    Some(iface.name().to_string());
            }
        }
    }
}

fn is_opt_str_empty(opt_string: &Option<String>) -> bool {
    if let Some(s) = opt_string {
        s.is_empty()
    } else {
        true
    }
}

// When merging desire interface with current, we perform actions in the order
// of:
//  * Action might alter the results of follow-up actions:
//    `MergedInterface.pre_inter_ifaces_process()` # For example, empty OVS
//    bridge will get a auto created ovs internal # interface.
//  * Actions required the knowledge of multiple interfaces:
//    `MergedInterfaces.process()` # For example, mark changed port as changed
//    and complex controller/port # validation
//  * Actions required both the knowledge of desired and current of single
//    interface: `MergedInterface.post_inter_ifaces_process()`. # Validations
//    after controller/port information are ready.
//  * Actions self-contained of each `Interface` -- `Interface.sanitize()`. #
//    Self clean up.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct MergedInterfaces {
    pub(crate) kernel_ifaces: HashMap<String, MergedInterface>,
    pub(crate) user_ifaces: HashMap<(String, InterfaceType), MergedInterface>,
    pub(crate) insert_order: Vec<(String, InterfaceType)>,
    pub(crate) ignored_ifaces: Vec<(String, InterfaceType)>,
    pub(crate) memory_only: bool,
    pub(crate) mode: NetworkStateMode,
    pub(crate) iface_name_search: InterfaceNameSearch,
}

impl MergedInterfaces {
    // The gen_conf mode will do extra stuff:
    //  * Set unknown interface as ethernet instead of raising failure.
    //  * Set unknown port as ethernet instead of raising failure.
    pub(crate) fn new(
        mut desired: Interfaces,
        mut current: Interfaces,
        mode: NetworkStateMode,
        memory_only: bool,
    ) -> Result<Self, NmstateError> {
        let mut merged_kernel_ifaces: HashMap<String, MergedInterface> =
            HashMap::new();
        let mut merged_user_ifaces: HashMap<
            (String, InterfaceType),
            MergedInterface,
        > = HashMap::new();

        desired.unify_veth_and_eth();
        current.unify_veth_and_eth();

        desired.purge_unknown_state_iface();

        if mode == NetworkStateMode::GenerateConfig {
            desired.set_unknown_iface_to_eth()?;
            desired.set_missing_port_to_eth();
            desired.handle_gen_conf_mac_identifer();
        } else {
            // SRIOV VF might not exist in pre-apply current, hence
            // we do not resolve SRIOV refer for gen_diff() call.
            if mode != NetworkStateMode::GenerateDiff {
                desired.resolve_sriov_reference(&current)?;
            }
            desired.resolve_mac_identifier_in_current(&current)?;
            desired.resolve_pci_identifier(&current)?;
            desired.resolve_unknown_ifaces(&current)?;
            desired.resolve_mac_identifier_in_desired(&current)?;
            desired.resolve_alt_name_reference_in_desired(&current)?;
        }

        desired.auto_managed_controller_ports(&current);

        let ignored_ifaces = get_ignored_ifaces(&desired, &current);
        desired.pre_ignore_check(&current, ignored_ifaces.as_slice())?;

        if memory_only {
            desired.apply_memory_only_mode();
        }

        for (iface_name, iface_type) in ignored_ifaces.as_slice() {
            log::info!("Ignoring interface {iface_name} type {iface_type}");
        }

        desired.remove_ignored_ifaces(ignored_ifaces.as_slice());
        current.remove_ignored_ifaces(ignored_ifaces.as_slice());

        for (iface_name, des_iface) in desired
            .kernel_ifaces
            .drain()
            .chain(desired.user_ifaces.drain().map(|((n, _), i)| (n, i)))
        {
            let merged_iface = MergedInterface::new(
                Some(des_iface.clone()),
                current.remove_iface(&iface_name, des_iface.iface_type()),
            )?;
            if merged_iface.merged.is_userspace() {
                merged_user_ifaces.insert(
                    (
                        merged_iface.merged.name().to_string(),
                        merged_iface.merged.iface_type(),
                    ),
                    merged_iface,
                );
            } else {
                merged_kernel_ifaces.insert(
                    merged_iface.merged.name().to_string(),
                    merged_iface,
                );
            }
        }

        // Interfaces only exists in current
        for cur_iface in current
            .kernel_ifaces
            .drain()
            .chain(current.user_ifaces.drain().map(|((n, _), i)| (n, i)))
            .map(|(_, i)| i)
        {
            let merged_iface = MergedInterface::new(None, Some(cur_iface))?;
            if merged_iface.merged.is_userspace() {
                merged_user_ifaces.insert(
                    (
                        merged_iface.merged.name().to_string(),
                        merged_iface.merged.iface_type(),
                    ),
                    merged_iface,
                );
            } else {
                merged_kernel_ifaces.insert(
                    merged_iface.merged.name().to_string(),
                    merged_iface,
                );
            }
        }
        let iface_name_search =
            InterfaceNameSearch::new(merged_kernel_ifaces.values());
        let mut ret = Self {
            kernel_ifaces: merged_kernel_ifaces,
            user_ifaces: merged_user_ifaces,
            insert_order: desired.insert_order,
            ignored_ifaces,
            memory_only,
            mode,
            iface_name_search,
        };

        ret.process()?;

        Ok(ret)
    }

    pub(crate) fn get_iface<'a>(
        &'a self,
        iface_name: &str,
        iface_type: InterfaceType,
    ) -> Option<&'a MergedInterface> {
        if iface_type == InterfaceType::Unknown {
            self.kernel_ifaces.get(iface_name).or_else(|| {
                self.user_ifaces
                    .values()
                    .find(|&iface| iface.merged.name() == iface_name)
            })
        } else if iface_type.is_userspace() {
            self.user_ifaces.get(&(iface_name.to_string(), iface_type))
        } else {
            self.kernel_ifaces.get(iface_name)
        }
    }

    pub(crate) fn iter(&self) -> impl Iterator<Item = &MergedInterface> {
        self.user_ifaces.values().chain(self.kernel_ifaces.values())
    }

    pub(crate) fn iter_mut(
        &mut self,
    ) -> impl Iterator<Item = &mut MergedInterface> {
        self.user_ifaces
            .values_mut()
            .chain(self.kernel_ifaces.values_mut())
    }

    // Contains all the smart modifications, validations among interfaces
    fn process(&mut self) -> Result<(), NmstateError> {
        self.process_allow_extra_ovs_patch_ports_for_apply();
        self.process_allow_extra_bridge_ports_for_apply();
        self.apply_copy_mac_from()?;
        self.validate_hsr_mac()?;
        self.copy_hsr_mac()?;
        self.validate_controller_and_port_list_confliction()?;
        self.resolve_port_name_ref()?;
        self.resolve_parent_name_ref()?;
        self.handle_changed_ports()?;
        self.resolve_port_iface_controller_type()?;
        self._set_up_priority()?;
        self.check_overbook_ports()?;
        self.check_infiniband_as_ports()?;
        self.mark_orphan_interface_as_absent()?;
        self.process_veth_peer_changes()?;
        self.validate_dispatch_script_has_no_checkpoint()?;
        self.validate_alt_names()?;
        for iface in self
            .kernel_ifaces
            .values_mut()
            .chain(self.user_ifaces.values_mut())
            .filter(|i| i.is_changed())
        {
            iface.post_inter_ifaces_process()?;
        }
        Ok(())
    }

    fn _set_up_priority(&mut self) -> Result<(), NmstateError> {
        for _ in 0..INTERFACES_SET_PRIORITY_MAX_RETRY {
            if self.set_ifaces_up_priority() {
                return Ok(());
            }
        }
        log::error!(
            "Failed to set up priority: please order the interfaces in desire \
             state to place controller before its ports"
        );
        Err(NmstateError::new(
            ErrorKind::InvalidArgument,
            "Failed to set up priority: nmstate only support nested interface \
             up to 4 levels. To support more nest level, please order the \
             interfaces in desire state to place controller before its ports"
                .to_string(),
        ))
    }

    fn process_allow_extra_bridge_ports_for_apply(&mut self) {
        for merged_iface in self
            .iter_mut()
            .filter(|mi| mi.desired.as_ref().map(|i| i.is_up()) == Some(true))
        {
            merged_iface.process_allow_extra_bridge_ports();
        }
    }

    fn apply_copy_mac_from(&mut self) -> Result<(), NmstateError> {
        let mut pending_changes: HashMap<String, String> = HashMap::new();
        for (iface_name, merged_iface) in self.kernel_ifaces.iter() {
            if !merged_iface.is_desired()
                || !COPY_MAC_ALLOWED_IFACE_TYPES
                    .contains(&merged_iface.merged.iface_type())
            {
                continue;
            }
            if let Some(src_iface_name) =
                &merged_iface.merged.base_iface().copy_mac_from
            {
                if let Some(src_iface) =
                    self.kernel_ifaces.get(src_iface_name).map(|i| &i.merged)
                {
                    if !is_opt_str_empty(
                        &src_iface.base_iface().permanent_mac_address,
                    ) {
                        if let Some(mac) = src_iface
                            .base_iface()
                            .permanent_mac_address
                            .as_ref()
                        {
                            pending_changes.insert(
                                iface_name.to_string(),
                                mac.to_string(),
                            );
                        }
                    } else if !is_opt_str_empty(
                        &src_iface.base_iface().mac_address,
                    ) {
                        if let Some(mac) =
                            src_iface.base_iface().mac_address.as_ref()
                        {
                            pending_changes.insert(
                                iface_name.to_string(),
                                mac.to_string(),
                            );
                        }
                    } else {
                        let e = NmstateError::new(
                            ErrorKind::InvalidArgument,
                            format!(
                                "Failed to find mac address of interface \
                                 {src_iface_name} for copy-mac-from of iface \
                                 {iface_name}"
                            ),
                        );
                        log::error!("{e}");
                        return Err(e);
                    }
                } else {
                    let e = NmstateError::new(
                        ErrorKind::InvalidArgument,
                        format!(
                            "Failed to find interface {src_iface_name} for \
                             copy-mac-from of iface {iface_name}"
                        ),
                    );
                    log::error!("{e}");
                    return Err(e);
                }
            }
        }
        for (iface_name, mac) in pending_changes.drain() {
            if let Some(iface) = self.kernel_ifaces.get_mut(&iface_name) {
                iface.set_copy_from_mac(mac);
            }
        }
        Ok(())
    }

    // Unlike orphan check in `apply_ctrller_change()`, this function is for
    // orphan interface without controller.
    fn mark_orphan_interface_as_absent(&mut self) -> Result<(), NmstateError> {
        let gone_ifaces: Vec<String> = self
            .kernel_ifaces
            .values()
            .filter(|i| {
                // User can still have VLAN over ethernet even ethernet is
                // marked as absent.
                // For veth, it is hard for us to know whether absent action
                // delete it not, hence treat it as ethernet.
                i.is_changed()
                    && i.merged.is_absent()
                    && i.merged.iface_type() != InterfaceType::Ethernet
            })
            .map(|i| i.merged.name().to_string())
            .collect();

        // OvsInterface is already checked by `apply_ctrller_change()`.
        for iface in self.kernel_ifaces.values_mut().filter(|i| {
            i.merged.is_up()
                && i.merged.iface_type() != InterfaceType::OvsInterface
        }) {
            if let Some(parent) = iface.merged.parent()
                && gone_ifaces.contains(&parent.to_string())
            {
                if iface.is_desired() && iface.merged.is_up() {
                    return Err(NmstateError::new(
                        ErrorKind::InvalidArgument,
                        format!(
                            "Interface {} cannot be in up state as its parent \
                             {parent} has been marked as absent",
                            iface.merged.name(),
                        ),
                    ));
                }
                log::info!(
                    "Marking interface {} as absent as its parent {} is so",
                    iface.merged.name(),
                    parent
                );
                iface.mark_as_absent();
            }
        }
        Ok(())
    }

    // Use kernel interface name first, then fallback to profile name
    // Raise error when referring to a profile name has multiple interfaces.
    fn resolve_parent_name_ref(&mut self) -> Result<(), NmstateError> {
        let iface_name_search = &self.iface_name_search;
        for iface in self.kernel_ifaces.values_mut() {
            let des_iface = if let Some(d) = iface.desired.as_mut() {
                d
            } else {
                continue;
            };
            if !des_iface.is_up() {
                continue;
            }
            let parent = if let Some(p) = des_iface.parent() {
                p
            } else {
                continue;
            };

            let for_apply = if let Some(i) = iface.for_apply.as_mut() {
                i
            } else {
                continue;
            };
            let for_verify = if let Some(i) = iface.for_verify.as_mut() {
                i
            } else {
                continue;
            };

            let kernel_names = iface_name_search.get(parent);

            // Prefer kernel name as port name
            if kernel_names.contains(&parent) {
                continue;
            }
            if kernel_names.len() > 1 {
                return Err(NmstateError::new(
                    ErrorKind::InvalidArgument,
                    format!(
                        "Interface {} ({}) defined with parent {} but \
                         multiple interfaces are sharing the this profile name",
                        des_iface.name(),
                        des_iface.iface_type(),
                        parent,
                    ),
                ));
            } else if let Some(kernel_name) = kernel_names.first() {
                des_iface.change_parent_name(kernel_name);
                for_apply.change_parent_name(kernel_name);
                for_verify.change_parent_name(kernel_name);
                iface.merged.change_parent_name(kernel_name);
            } else {
                // This function is not responsible to validate whether
                // port interface exists or not. For example,
                // gen_diff() do not need to validate whether interface
                // exist or not.
                // Please do not raise error here.
            }
        }
        Ok(())
    }
}

// Special cases:
//  * Inherit the ignore state from current if desire not mentioned in interface
//    section
//  * Return Vec<> has all InterfaceType::Veth is converted to
//    InterfaceType::Ethernet
fn get_ignored_ifaces(
    desired: &Interfaces,
    current: &Interfaces,
) -> Vec<(String, InterfaceType)> {
    let mut ignored_kernel_ifaces = desired.ignored_kernel_iface_names();
    let mut ignored_user_ifaces = desired.ignored_user_iface_name_types();
    let desired_kernel_ifaces: HashSet<String> = desired
        .kernel_ifaces
        .values()
        .filter(|i| !i.is_ignore())
        .map(|i| i.name().to_string())
        .collect();
    let desired_user_ifaces: HashSet<(String, InterfaceType)> = desired
        .user_ifaces
        .values()
        .filter(|i| !i.is_ignore())
        .map(|i| (i.name().to_string(), i.iface_type()))
        .collect();

    for iface_name in current.ignored_kernel_iface_names().drain() {
        if !desired_kernel_ifaces.contains(&iface_name) {
            ignored_kernel_ifaces.insert(iface_name);
        }
    }
    for (iface_name, iface_type) in
        current.ignored_user_iface_name_types().drain()
    {
        if !desired_user_ifaces
            .contains(&(iface_name.clone(), iface_type.clone()))
        {
            ignored_user_ifaces.insert((iface_name, iface_type));
        }
    }

    let mut ignored_ifaces: Vec<(String, InterfaceType)> =
        ignored_user_ifaces.drain().collect();

    for iface_name in ignored_kernel_ifaces {
        if let Some(iface) = desired
            .get_iface(&iface_name, InterfaceType::Unknown)
            .or_else(|| current.get_iface(&iface_name, InterfaceType::Unknown))
        {
            let iface_type = match iface.iface_type() {
                InterfaceType::Veth => InterfaceType::Ethernet,
                t => t,
            };
            ignored_ifaces.push((iface_name, iface_type));
        }
    }

    ignored_ifaces
}

#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct InterfaceNameSearch {
    kernel_nics: HashSet<String>,
    profile_2_kernel: HashMap<String, Vec<String>>,
    alt_name_2_kernel: HashMap<String, String>,
}

impl InterfaceNameSearch {
    pub(crate) fn new<'a, T>(merged_ifaces: T) -> Self
    where
        T: Iterator<Item = &'a MergedInterface> + Clone,
    {
        let mut kernel_nics: HashSet<String> = HashSet::new();

        for iface in merged_ifaces.clone().filter(|i| i.merged.is_up()) {
            if let Some(cur_iface) = iface.current.as_ref() {
                // Existing kernel interface
                kernel_nics.insert(cur_iface.name().to_string());
            } else if let Some(des_iface) = iface.desired.as_ref() {
                // Creating new kernel interface
                if des_iface.base_iface().identifier.as_ref()
                    != Some(&InterfaceIdentifier::MacAddress)
                {
                    kernel_nics.insert(des_iface.name().to_string());
                }
            }
        }

        let mut profile_2_kernel: HashMap<String, Vec<String>> = HashMap::new();
        for iface in merged_ifaces.clone() {
            let base_iface = iface.merged.base_iface();
            if let Some(profile_name) = base_iface.profile_name.as_deref() {
                profile_2_kernel
                    .entry(profile_name.to_string())
                    .or_default()
                    .push(base_iface.name.to_string());
            }
        }

        let mut alt_name_2_kernel: HashMap<String, String> = HashMap::new();
        for iface in merged_ifaces.clone().filter(|i| i.merged.is_up()) {
            let base_iface = iface.merged.base_iface();
            if let Some(alt_names) = base_iface.alt_names.as_deref() {
                for alt_name in alt_names.iter().filter(|a| !a.is_absent()) {
                    alt_name_2_kernel.insert(
                        alt_name.name.to_string(),
                        base_iface.name.to_string(),
                    );
                }
            }
        }

        Self {
            kernel_nics,
            profile_2_kernel,
            alt_name_2_kernel,
        }
    }

    /// Search interface kernel name by specified name:
    ///  * Kernel interface name
    ///  * Kernel alternative name
    ///  * Profile name. Because profile name can be duplicate among interfaces,
    ///    return all matches.
    pub(crate) fn get<'a>(&'a self, name: &str) -> Vec<&'a str> {
        if let Some(n) = self
            .kernel_nics
            .get(name)
            .or_else(|| self.alt_name_2_kernel.get(name))
        {
            vec![n]
        } else if let Some(nics) = self.profile_2_kernel.get(name) {
            nics.as_slice().iter().map(|s| s.as_str()).collect()
        } else {
            Vec::new()
        }
    }
}