-
Notifications
You must be signed in to change notification settings - Fork 157
Expand file tree
/
Copy pathmachine_interface.rs
More file actions
2700 lines (2514 loc) · 100 KB
/
Copy pathmachine_interface.rs
File metadata and controls
2700 lines (2514 loc) · 100 KB
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
/*
* SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use std::collections::HashMap;
use std::net::IpAddr;
use carbide_network::ip::{IdentifyAddressFamily, IpAddressFamily};
use carbide_utils::redfish::BmcAccessInfo;
use carbide_uuid::domain::DomainId;
use carbide_uuid::machine::{MachineId, MachineInterfaceId};
use carbide_uuid::network::{NetworkPrefixId, NetworkSegmentId};
use carbide_uuid::power_shelf::PowerShelfId;
use carbide_uuid::switch::SwitchId;
use chrono::{DateTime, Utc};
use ipnetwork::IpNetwork;
use itertools::Itertools;
use mac_address::MacAddress;
use model::address_selection_strategy::AddressSelectionStrategy;
use model::allocation_type::AllocationType;
use model::expected_machine::ExpectedHostNic;
use model::hardware_info::HardwareInfo;
use model::machine::MachineInterfaceSnapshot;
use model::machine_interface::InterfaceType;
use model::machine_interface_address::MachineInterfaceAssociation;
use model::network_prefix::NetworkPrefix;
use model::network_segment::{AllocationStrategy, NetworkSegment, NetworkSegmentType};
use model::predicted_machine_interface::PredictedMachineInterface;
use sqlx::{FromRow, PgConnection, PgTransaction};
use super::{ColumnInfo, FilterableQueryBuilder, ObjectColumnFilter};
use crate::db_read::DbReader;
use crate::host_naming::{self, NamingContext};
use crate::ip_allocator::{DhcpError, IpAllocator, UsedIpResolver};
use crate::machine_interface_address::{AddressAlreadyInUseError, MachineInterfaceAddressWithType};
use crate::{DatabaseError, DatabaseResult, Transaction, network_segment as db_network_segment};
const SQL_VIOLATION_DUPLICATE_MAC: &str = "machine_interfaces_segment_id_mac_address_key";
const SQL_VIOLATION_ONE_PRIMARY_INTERFACE: &str = "one_primary_interface_per_machine";
const SQL_VIOLATION_MAX_ONE_ASSOCIATION: &str = "chk_max_one_association";
const FAST_PATH_MAX_RETRIES: usize = 128;
const FAST_PATH_CANDIDATE_BATCH: i64 = 32;
pub struct UsedAdminNetworkIpResolver {
pub segment_id: NetworkSegmentId,
// All the IPs which can not be allocated, e.g. SVI IP.
pub busy_ips: Vec<IpAddr>,
}
#[derive(Debug)]
struct AdminInterfaceForReconcile {
id: MachineInterfaceId,
segment_id: NetworkSegmentId,
hostname: String,
domain_id: Option<DomainId>,
primary_interface: bool,
is_dpu_backed_host_link: bool,
mac_address: MacAddress,
addresses: Vec<MachineInterfaceAddressWithType>,
}
#[derive(FromRow)]
struct AdminInterfaceForReconcileRow {
id: MachineInterfaceId,
segment_id: NetworkSegmentId,
hostname: String,
domain_id: Option<DomainId>,
primary_interface: bool,
is_dpu_backed_host_link: bool,
mac_address: MacAddress,
address: Option<IpAddr>,
allocation_type: Option<AllocationType>,
}
#[derive(Clone, Copy)]
pub struct IdColumn;
impl ColumnInfo<'_> for IdColumn {
type TableType = MachineInterfaceSnapshot;
type ColumnType = MachineInterfaceId;
fn column_name(&self) -> &'static str {
"id"
}
}
#[cfg(test)]
mod ip_allocator;
#[cfg(test)]
mod test_duplicate_mac;
#[cfg(test)]
mod tests;
#[derive(Clone, Copy)]
pub struct MacAddressColumn;
impl ColumnInfo<'_> for MacAddressColumn {
type TableType = MachineInterfaceSnapshot;
type ColumnType = MacAddress;
fn column_name(&self) -> &'static str {
"mac_address"
}
}
#[derive(Clone, Copy)]
pub struct MachineIdColumn;
impl ColumnInfo<'_> for MachineIdColumn {
type TableType = MachineInterfaceSnapshot;
type ColumnType = MachineId;
fn column_name(&self) -> &'static str {
"machine_id"
}
}
#[derive(Clone, Copy)]
pub struct PowerShelfIdColumn;
impl ColumnInfo<'_> for PowerShelfIdColumn {
type TableType = MachineInterfaceSnapshot;
type ColumnType = PowerShelfId;
fn column_name(&self) -> &'static str {
"power_shelf_id"
}
}
#[derive(Clone, Copy)]
pub struct SwitchIdColumn;
impl ColumnInfo<'_> for SwitchIdColumn {
type TableType = MachineInterfaceSnapshot;
type ColumnType = SwitchId;
fn column_name(&self) -> &'static str {
"switch_id"
}
}
/// A denormalized view on machine_interfaces that aggregates the addresses and vendors using
/// JSON_AGG. This query is also used by machines.rs as a subquery when collecting machine
/// snapshots.
macro_rules! machine_interface_snapshot_query {
() => {
r#"
SELECT mi.*,
COALESCE(addresses_agg.json, '[]'::json) AS addresses,
COALESCE(vendors_agg.json, '[]'::json) AS vendors,
ns.network_segment_type
FROM machine_interfaces mi
JOIN network_segments ns ON ns.id = mi.segment_id
LEFT JOIN LATERAL (
SELECT a.interface_id,
json_agg(a.address) AS json
FROM machine_interface_addresses a
WHERE a.interface_id = mi.id
GROUP BY a.interface_id
) AS addresses_agg ON true
LEFT JOIN LATERAL (
SELECT d.machine_interface_id,
json_agg(d.vendor_string) AS json
FROM dhcp_entries d
WHERE d.machine_interface_id = mi.id
GROUP BY d.machine_interface_id
) AS vendors_agg ON true"#
};
}
/// Sets current machine interface primary attribute to provided value.
pub async fn set_primary_interface(
interface_id: &MachineInterfaceId,
primary: bool,
txn: &mut PgConnection,
) -> Result<MachineInterfaceId, DatabaseError> {
let query = "UPDATE machine_interfaces SET primary_interface=$1 where id=$2::uuid RETURNING id";
sqlx::query_as(query)
.bind(primary)
.bind(*interface_id)
.fetch_one(txn)
.await
.map_err(|e| DatabaseError::query(query, e))
}
/// Clears `primary_interface` on every interface a machine currently owns.
///
/// Used when a new interface takes over as the machine's sole primary -- e.g. a
/// declared integrated host NIC promoted ahead of the DPU admin link it replaces
/// on a DpuMode host -- so the incoming primary never collides with the outgoing
/// one on the `one_primary_interface_per_machine` index.
pub async fn demote_primary_interfaces_for_machine(
machine_id: &MachineId,
txn: &mut PgConnection,
) -> Result<(), DatabaseError> {
let query = "UPDATE machine_interfaces SET primary_interface=false WHERE machine_id=$1 AND primary_interface=true";
sqlx::query(query)
.bind(machine_id)
.execute(txn)
.await
.map(|_| ())
.map_err(|e| DatabaseError::query(query, e))
}
/// Whether a machine owns any interface flagged `primary_interface`, in any segment.
///
/// Lets admin-address reconciliation distinguish a genuinely broken host (no
/// primary at all) from one that legitimately boots from a non-admin primary --
/// a HostInband integrated NIC on a DpuMode host -- whose DPU admin links are
/// then all dormant.
pub async fn machine_has_primary_interface(
machine_id: &MachineId,
txn: &mut PgConnection,
) -> Result<bool, DatabaseError> {
let query = "SELECT EXISTS(SELECT 1 FROM machine_interfaces WHERE machine_id=$1 AND primary_interface=true)";
let (exists,): (bool,) = sqlx::query_as(query)
.bind(machine_id)
.fetch_one(txn)
.await
.map_err(|e| DatabaseError::query(query, e))?;
Ok(exists)
}
/// Records the vendor-native Redfish `EthernetInterface.Id` on the machine_interface
/// row(s) with the given MAC. Captured by site-explorer per exploration; callers only
/// invoke this when the id resolves from the current report, so a wiped MAC leaves the
/// last-known-good id in place.
pub async fn set_boot_interface_id(
mac_address: MacAddress,
boot_interface_id: &str,
txn: &mut PgConnection,
) -> Result<(), DatabaseError> {
let query = "UPDATE machine_interfaces SET boot_interface_id=$1 WHERE mac_address=$2";
sqlx::query(query)
.bind(boot_interface_id)
.bind(mac_address)
.execute(txn)
.await
.map(|_| ())
.map_err(|e| DatabaseError::query(query, e))
}
pub async fn associate_interface_with_dpu_machine(
interface_id: &MachineInterfaceId,
dpu_machine_id: &MachineId,
txn: &mut PgConnection,
) -> Result<MachineInterfaceId, DatabaseError> {
let query =
"UPDATE machine_interfaces SET attached_dpu_machine_id=$1 where id=$2::uuid RETURNING id";
sqlx::query_as(query)
.bind(dpu_machine_id)
.bind(*interface_id)
.fetch_one(txn)
.await
.map_err(|e| DatabaseError::query(query, e))
}
pub async fn associate_bmc_interface_with_machine(
interface_id: &MachineInterfaceId,
machine_id: &MachineId,
txn: &mut PgConnection,
) -> DatabaseResult<MachineInterfaceId> {
let query = "UPDATE machine_interfaces
SET machine_id=$1,
association_type='Machine'::association_type,
interface_type='Bmc'::interface_type,
primary_interface=false
WHERE id=$2::uuid
RETURNING id";
sqlx::query_as(query)
.bind(machine_id)
.bind(*interface_id)
.fetch_one(txn)
.await
.map_err(|err: sqlx::Error| match err {
sqlx::Error::Database(e)
if e.constraint() == Some(SQL_VIOLATION_MAX_ONE_ASSOCIATION) =>
{
DatabaseError::MaxOneInterfaceAssociation
}
_ => DatabaseError::query(query, err),
})
}
pub async fn set_interface_type(
interface_id: &MachineInterfaceId,
interface_type: InterfaceType,
txn: &mut PgConnection,
) -> DatabaseResult<MachineInterfaceId> {
let query = "UPDATE machine_interfaces SET interface_type=$1 WHERE id=$2::uuid RETURNING id";
sqlx::query_as(query)
.bind(interface_type)
.bind(*interface_id)
.fetch_one(txn)
.await
.map_err(|e| DatabaseError::query(query, e))
}
pub async fn associate_interface_with_machine(
interface_id: &MachineInterfaceId,
association: MachineInterfaceAssociation,
txn: &mut PgConnection,
) -> DatabaseResult<MachineInterfaceId> {
let (query, association_type, id_value) = match association {
MachineInterfaceAssociation::Machine(id) => (
"UPDATE machine_interfaces SET machine_id=$1, association_type=$2::association_type where id=$3::uuid RETURNING id",
"Machine",
id.to_string(),
),
MachineInterfaceAssociation::Switch(id) => (
"UPDATE machine_interfaces SET switch_id=$1, association_type=$2::association_type where id=$3::uuid RETURNING id",
"Switch",
id.to_string(),
),
MachineInterfaceAssociation::PowerShelf(id) => (
"UPDATE machine_interfaces SET power_shelf_id=$1, association_type=$2::association_type where id=$3::uuid RETURNING id",
"PowerShelf",
id.to_string(),
),
};
sqlx::query_as(query)
.bind(id_value)
.bind(association_type)
.bind(*interface_id)
.fetch_one(txn)
.await
.map_err(|err: sqlx::Error| match err {
sqlx::Error::Database(e)
if e.constraint() == Some(SQL_VIOLATION_ONE_PRIMARY_INTERFACE) =>
{
DatabaseError::OnePrimaryInterface
}
sqlx::Error::Database(e)
if e.constraint() == Some(SQL_VIOLATION_MAX_ONE_ASSOCIATION) =>
{
DatabaseError::MaxOneInterfaceAssociation
}
_ => DatabaseError::query(query, err),
})
}
pub async fn find_by_mac_address(
txn: impl DbReader<'_>,
macaddr: MacAddress,
) -> Result<Vec<MachineInterfaceSnapshot>, DatabaseError> {
find_by(txn, ObjectColumnFilter::One(MacAddressColumn, &macaddr)).await
}
/// This function returns only an IP for efficiency, we don't need to fetch/deserialize the entire
/// MachineInterfaceSnapshot
pub async fn lookup_bmc_ip_by_mac_address(
db: impl DbReader<'_>,
mac_address: MacAddress,
) -> DatabaseResult<Vec<IpAddr>> {
let query = r"SELECT mia.address FROM machine_interfaces mi
INNER JOIN machine_interface_addresses mia ON (mia.interface_id = mi.id)
WHERE mi.mac_address = $1";
sqlx::query_scalar(query)
.bind(mac_address)
.fetch_all(db)
.await
.map_err(|e| DatabaseError::query(query, e))
}
pub async fn lookup_bmc_access_info(
db: impl DbReader<'_>,
ip: IpAddr,
port: Option<u16>,
) -> DatabaseResult<BmcAccessInfo> {
// Resolve the BMC interface MAC and the owning machine's vendor override in
// one query so every client_by_info caller can act on the override.
let query = r"SELECT mi.mac_address, m.bmc_vendor_override
FROM machine_interface_addresses mia
INNER JOIN machine_interfaces mi ON mi.id = mia.interface_id
LEFT JOIN machines m ON m.id = mi.machine_id
WHERE mia.address = $1::inet
LIMIT 1";
let row: Option<(MacAddress, Option<String>)> = sqlx::query_as(query)
.bind(ip)
.fetch_optional(db)
.await
.map_err(|e| DatabaseError::query(query, e))?;
let (mac_address, bmc_vendor_override) = row.ok_or_else(|| DatabaseError::NotFoundError {
kind: "Machine Interface",
id: ip.to_string(),
})?;
Ok(BmcAccessInfo {
host: ip.to_string(),
port,
mac_address,
bmc_vendor_override,
})
}
pub async fn find_by_ip(
txn: impl DbReader<'_>,
ip: IpAddr,
) -> Result<Option<MachineInterfaceSnapshot>, DatabaseError> {
static QUERY: &str = concat!(
machine_interface_snapshot_query!(),
r#" INNER JOIN machine_interface_addresses mia on mia.interface_id=mi.id
WHERE mia.address = $1::inet"#,
);
sqlx::query_as(QUERY)
.bind(ip)
.fetch_optional(txn)
.await
.map_err(|e| DatabaseError::query(QUERY, e))
}
pub async fn find_all(txn: &mut PgConnection) -> DatabaseResult<Vec<MachineInterfaceSnapshot>> {
find_by(txn, ObjectColumnFilter::All::<IdColumn>).await
}
pub async fn find_by_machine_ids(
txn: &mut PgConnection,
machine_ids: &[MachineId],
) -> Result<std::collections::HashMap<MachineId, Vec<MachineInterfaceSnapshot>>, DatabaseError> {
use itertools::Itertools;
// The .unwrap() in the `group_map_by` call is ok - because we are only
// searching for Machines which have associated MachineIds
Ok(
find_by(txn, ObjectColumnFilter::List(MachineIdColumn, machine_ids))
.await?
.into_iter()
.filter(|interface| interface.interface_type != InterfaceType::Bmc)
.into_group_map_by(|interface| interface.machine_id.unwrap()),
)
}
pub async fn count_by_segment_id(
txn: &mut PgConnection,
segment_id: &NetworkSegmentId,
) -> Result<usize, DatabaseError> {
let query = "SELECT count(*) FROM machine_interfaces WHERE segment_id = $1";
let (address_count,): (i64,) = sqlx::query_as(query)
.bind(segment_id)
.fetch_one(txn)
.await
.map_err(|e| DatabaseError::query(query, e))?;
Ok(address_count.max(0) as usize)
}
pub async fn find_one(
txn: impl DbReader<'_>,
interface_id: MachineInterfaceId,
) -> DatabaseResult<MachineInterfaceSnapshot> {
let mut interfaces = find_by(txn, ObjectColumnFilter::One(IdColumn, &interface_id)).await?;
match interfaces.len() {
0 => Err(DatabaseError::FindOneReturnedNoResultsError(
interface_id.into(),
)),
1 => Ok(interfaces.remove(0)),
_ => Err(DatabaseError::FindOneReturnedManyResultsError(
interface_id.into(),
)),
}
}
// Returns (MachineInterface, newly_created_interface).
// newly_created_interface indicates that we couldn't find a
// MachineInterface, so created new one.
//
// `is_primary` carries the declared `ExpectedHostNic.primary` for this MAC:
// `Some(true)` -- this NIC is the host's declared boot interface, `Some(false)`
// -- a different NIC is, `None` -- nothing was declared. On a newly created (and
// thus still machine-less) row we make that declaration stick, promoting to or
// demoting from the creation default as needed, so the boot interface is right
// from the first lease. `None` keeps the creation default.
//
// If we're not making a new interface, then existing interfaces
// are returned untouched.
pub async fn find_or_create_machine_interface(
txn: &mut PgConnection,
machine_id: Option<MachineId>,
mac_address: MacAddress,
relays: &[IpAddr],
host_nic: Option<ExpectedHostNic>,
is_primary: Option<bool>,
retained_window: Option<chrono::Duration>,
) -> DatabaseResult<MachineInterfaceSnapshot> {
let relaystr = relays
.iter()
.map(|v| v.to_string())
.collect::<Vec<String>>()
.join(", ");
match machine_id {
None => {
tracing::info!(
%mac_address,
"Found no existing machine with mac address {mac_address} using networks with relays {relaystr}",
);
let mut interface = validate_existing_mac_and_create(
&mut *txn,
mac_address,
relays,
host_nic,
retained_window,
)
.await?;
// Make the declaration authoritative on this machine-less row.
// `validate_existing_mac_and_create` defaults a freshly created row to
// primary, so the demote covers "a different NIC is declared primary"
// and the promote covers a row we *found* (rather than created) that is
// the declared primary. Safe on a NULL machine_id row: the
// one_primary_interface_per_machine index does not constrain it.
match is_primary {
Some(false) if interface.primary_interface => {
set_primary_interface(&interface.id, false, &mut *txn).await?;
interface.primary_interface = false;
}
Some(true) if !interface.primary_interface => {
set_primary_interface(&interface.id, true, &mut *txn).await?;
interface.primary_interface = true;
}
_ => {}
}
Ok(interface)
}
Some(_) => {
let mut ifcs = find_by_mac_address(&mut *txn, mac_address).await?;
match ifcs.len() {
1 => Ok(ifcs.remove(0)),
n => {
tracing::warn!(
%mac_address,
relay_ips = %relaystr,
num_mac_address = n,
"Duplicate mac address for network segment",
);
Err(DatabaseError::NetworkSegmentDuplicateMacAddress(
mac_address,
))
}
}
}
}
}
/// Do basic validating on existing macs and create the interface if it does not exist
pub async fn validate_existing_mac_and_create(
txn: &mut PgConnection,
mac_address: MacAddress,
relays: &[IpAddr],
host_nic: Option<ExpectedHostNic>,
retained_window: Option<chrono::Duration>,
) -> DatabaseResult<MachineInterfaceSnapshot> {
let mut interface_snapshot = find_by_mac_address(&mut *txn, mac_address).await?;
match &interface_snapshot.len() {
0 => {
tracing::debug!(
%mac_address,
"No existing machine_interface with mac address exists yet, creating one",
);
// A declared NIC narrows segment selection to a specific type: when
// the relay's prefix matches more than one segment (nested or
// overlapping prefixes), pick the one of the declared type -- the
// typed `network_segment_type`, or the legacy `nic_type` it
// supersedes. Otherwise the relay's matching segment(s) stand.
let segment_type = host_nic
.as_ref()
.and_then(ExpectedHostNic::resolved_network_segment_type);
let network_segments = if let Some(network_segment_type) = segment_type {
// Declared type -> the relay's segments of that type only.
db_network_segment::for_segment_type_all(txn, relays, network_segment_type).await?
} else {
// No declaration -> every segment the relay's prefix matches.
db_network_segment::for_relay_all(txn, relays).await?
};
if !network_segments.is_empty() {
// If the segment only allows static reservations, reject
// dynamic allocation. The device must have a pre-existing
// static reservation to get an IP on this segment.
for segment in network_segments.iter() {
if segment.config.allocation_strategy == AllocationStrategy::Reserved {
return Err(DatabaseError::internal(format!(
"segment {} configured for static DHCP leases only; no static reservation for MAC {mac_address}",
segment.config.name,
)));
}
}
// Dynamic-pool allocation.
// Any AddressSelectionStrategy::StaticIp flows will have happened as part of
// preallocate_machine_interface or preallocate_bmc_machine_interface.
// (`create` recovers any retained boot interface id onto the new row.)
let v = create(
txn,
&network_segments,
&mac_address,
true,
AddressSelectionStrategy::NextAvailableIp,
retained_window,
)
.await?;
Ok(v)
} else {
Err(DatabaseError::internal(format!(
"No network segment defined for relay addresses: {:?}",
relays
)))
}
}
1 => {
tracing::debug!(
%mac_address,
"Mac address exists, validating the relay and returning it",
);
// TODO(chet): I don't like that it's mut here, but this seems to be
// a pattern in this module in general, especially since we may or may
// not update the interface. Consider having reconcile_interface_segment
// just return the interface, which would probably look a lot better.
let mut existing_interface = interface_snapshot.remove(0);
reconcile_interface_segment(txn, &mut existing_interface, relays).await?;
Ok(existing_interface)
}
_ => {
tracing::warn!(
%mac_address,
// A MAC address should identify a single machine interface within a segment.
"More than one existing mac address for network segment",
);
Err(DatabaseError::NetworkSegmentDuplicateMacAddress(
mac_address,
))
}
}
}
/// Ensure a a `machine_interface` exists for the `mac_address` with its
/// reserved allocation, either falling into a Carbide-managed segment (when
/// there is a match within a managed prefix), or into the `static_assignments`
/// segment for IPs that are outside of managed networks.
///
/// Calls are idempotent on the input `(mac_address, static_ip)`, meaning
/// repeat calls return `Ok(())` if/once the end state matches the request.
///
/// Errors on conflicts that need operator attention, e.g.
/// - The interface for this MAC exists but carries different addresses, or,
/// - The IP is already allocated to a different MAC.
///
/// Called as part of site-explorer iterations (when an ExpectedMachine has a
/// static assignment/reservation configured), and from the DHCP `discover()`
/// path (when a client whose configuration expects a static address) to ensure
/// the fixed-address is returned.
pub async fn preallocate_machine_interface(
txn: &mut PgConnection,
mac_address: MacAddress,
static_ip: IpAddr,
retained_window: Option<chrono::Duration>,
) -> DatabaseResult<()> {
preallocate_machine_interface_with_type(
txn,
mac_address,
static_ip,
InterfaceType::Data,
retained_window,
)
.await
}
pub async fn preallocate_bmc_machine_interface(
txn: &mut PgConnection,
mac_address: MacAddress,
static_ip: IpAddr,
retained_window: Option<chrono::Duration>,
) -> DatabaseResult<()> {
preallocate_machine_interface_with_type(
txn,
mac_address,
static_ip,
InterfaceType::Bmc,
retained_window,
)
.await
}
/// If a machine interface row already exists for `mac_address`, reconcile it against the
/// requested (`static_ip`, `interface_type`):
/// - Returns `Ok(true)` when an existing row carries `static_ip`. Promotes `interface_type`
/// (and clears `primary_interface` for Bmc) if those don't already match.
/// - Returns `Ok(false)` when no row exists for `mac_address` — caller should create.
/// - Returns `Err(InvalidArgument)` when a row exists but carries different addresses.
async fn reconcile_existing_preallocation(
txn: &mut PgConnection,
mac_address: MacAddress,
static_ip: IpAddr,
interface_type: InterfaceType,
) -> DatabaseResult<bool> {
let existing = find_by_mac_address(&mut *txn, mac_address).await?;
let Some(iface) = existing.first() else {
return Ok(false);
};
if !iface.addresses.contains(&static_ip) {
return Err(DatabaseError::InvalidArgument(format!(
"a machine interface already exists for MAC {mac_address} with addresses {:?}; use update to change the IP address",
iface.addresses,
)));
}
if iface.interface_type != interface_type {
set_interface_type(&iface.id, interface_type, txn).await?;
}
if interface_type == InterfaceType::Bmc && iface.primary_interface {
set_primary_interface(&iface.id, false, txn).await?;
}
Ok(true)
}
async fn preallocate_machine_interface_with_type(
txn: &mut PgConnection,
mac_address: MacAddress,
static_ip: IpAddr,
interface_type: InterfaceType,
retained_window: Option<chrono::Duration>,
) -> DatabaseResult<()> {
// If there's already a matching record for (ip, mac), just return Ok,
// instead of attempting to insert, getting a duplicate error, and then
// handling.
if reconcile_existing_preallocation(txn, mac_address, static_ip, interface_type).await? {
return Ok(());
}
if let Some(existing_addr) =
crate::machine_interface_address::find_by_address(&mut *txn, static_ip).await?
{
return Err(DatabaseError::InvalidArgument(format!(
"IP address {static_ip} is already allocated to interface {} on segment {}; use 'machine-interfaces assign-address' to reassign it",
existing_addr.id, existing_addr.name,
)));
}
let segment = match db_network_segment::for_relay(&mut *txn, static_ip).await? {
Some(seg) => seg,
None => db_network_segment::static_assignments(&mut *txn).await?,
};
match create_with_type(
txn,
std::slice::from_ref(&segment),
&mac_address,
interface_type != InterfaceType::Bmc,
AddressSelectionStrategy::StaticAddress(static_ip),
interface_type,
retained_window,
)
.await
{
Ok(_) => {
tracing::info!(
%mac_address,
%static_ip,
segment_id = %segment.id,
"Pre-allocated static machine interface"
);
Ok(())
}
Err(DatabaseError::NetworkSegmentDuplicateMacAddress(_)) => {
// Looks like we might have lost a race with anohter inserter. Try to
// uphold our idempotency by re-fetching to reconcile. If the conflicting
// row carries our `static_ip`, our work is already done!
// Otherwise return an error.
if reconcile_existing_preallocation(txn, mac_address, static_ip, interface_type).await?
{
Ok(())
} else {
Err(DatabaseError::internal(format!(
"duplicate-MAC error for {mac_address}, but could not reconcile",
)))
}
}
Err(e) => Err(e),
}
}
pub async fn create(
txn: &mut PgConnection,
segments: &[NetworkSegment],
macaddr: &MacAddress,
primary_interface: bool,
address_strategy: AddressSelectionStrategy,
retained_window: Option<chrono::Duration>,
) -> DatabaseResult<MachineInterfaceSnapshot> {
create_with_type(
txn,
segments,
macaddr,
primary_interface,
address_strategy,
InterfaceType::Data,
retained_window,
)
.await
}
pub async fn create_with_type(
txn: &mut PgConnection,
segments: &[NetworkSegment],
macaddr: &MacAddress,
primary_interface: bool,
address_strategy: AddressSelectionStrategy,
interface_type: InterfaceType,
retained_window: Option<chrono::Duration>,
) -> DatabaseResult<MachineInterfaceSnapshot> {
let mut snapshot = match address_strategy {
AddressSelectionStrategy::NextAvailableIp | AddressSelectionStrategy::Automatic => {
create_fast_path(txn, segments, macaddr, primary_interface, interface_type).await
}
AddressSelectionStrategy::StaticAddress(addr) => {
create_static_path(
txn,
segments,
macaddr,
primary_interface,
addr,
interface_type,
)
.await
}
//
AddressSelectionStrategy::NextAvailablePrefix(_) => {
let [segment] = segments else {
return Err(DatabaseError::InvalidArgument(
"NextAvailablePrefix allocation requires exactly one candidate segment"
.to_string(),
));
};
create_slow_path(
txn,
segment,
macaddr,
primary_interface,
address_strategy,
interface_type,
)
.await
}
}?;
// Every brand-new row passes through here, whatever created it --
// dynamic DHCP, a static preallocation, or predicted-interface
// promotion. A prior row for this MAC may have been deleted with its
// boot interface id retained; recover the pair onto the new row and
// consume the retention record.
if snapshot.boot_interface_id.is_none()
&& let Some(boot_interface_id) =
crate::retained_boot_interface::take_by_mac(&mut *txn, *macaddr, retained_window)
.await?
{
set_boot_interface_id(*macaddr, &boot_interface_id, &mut *txn).await?;
snapshot.boot_interface_id = Some(boot_interface_id);
}
Ok(snapshot)
}
#[allow(txn_held_across_await)]
async fn create_fast_path(
txn: &mut PgConnection,
segments: &[NetworkSegment],
macaddr: &MacAddress,
primary_interface: bool,
interface_type: InterfaceType,
) -> DatabaseResult<MachineInterfaceSnapshot> {
for segments_idx in 0..segments.len() {
let segment = &segments[segments_idx];
for _ in 0..FAST_PATH_MAX_RETRIES {
let mut fast_txn = Transaction::begin_inner(txn).await?;
// Keep IPv4-only allocation concurrent, but serialize any segment
// containing IPv6 because the Rust allocator reads used addresses
// without taking per-IP candidate locks.
if segment
.prefixes
.iter()
.any(|prefix| prefix.prefix.is_ipv6())
{
lock_network_segment_exclusive(&mut fast_txn, segment).await?;
} else {
lock_network_segment_shared(&mut fast_txn, segment).await?;
}
let segment_exhausted = match try_create_fast_path(
&mut fast_txn,
segment,
macaddr,
primary_interface,
interface_type,
)
.await
{
Ok(interface_id) => {
fast_txn.commit().await?;
return Ok(
find_by(txn, ObjectColumnFilter::One(IdColumn, &interface_id))
.await?
.remove(0),
);
}
Err(err) if err.is_fqdn_conflict() => {
// Another simultaneous create got the same FQDN, try again.
false
}
Err(DatabaseError::TryAgain) => {
// All the IP's in the batch we grabbed from the database got taken by other
// concurrent calls to create_fast_path. Try again.
false
}
Err(DatabaseError::ResourceExhausted(_)) if segments_idx < segments.len() - 1 => {
// If there are more segments to check, we just need to signal that this one was exhausted.
true
}
Err(err) => {
// Some other error, roll back the inner transaction
fast_txn.rollback().await?;
return Err(err);
}
};
fast_txn.rollback().await?;
tokio::task::yield_now().await;
// If this segment is exhausted, go to the next segment.
if segment_exhausted {
break;
}
}
}
Err(DatabaseError::internal(format!(
"unable to create machine interface in fast path out of segments {:?} after {} retries",
segments, FAST_PATH_MAX_RETRIES
)))
}
/// Create a machine interface with a specific static IP address.
/// A perfect compliment to create_fast_path and create_slow_path.
///
/// If the target IP is already allocated to an interface with
/// same MAC, just return the existing interface snapshot.
///
/// Otherwise, if the target IP is allocated to a different MAC,
/// return with an AddressAlreadyInUse error.
async fn create_static_path(
txn: &mut PgConnection,
segments: &[NetworkSegment],
macaddr: &MacAddress,
primary_interface: bool,
address: IpAddr,
interface_type: InterfaceType,
) -> DatabaseResult<MachineInterfaceSnapshot> {
// For the staic path, we need to be a little forgiving since
// we expect to allow static assignment even if the requested
// assignment is outside any network segment as long as
// there is a "static assignment segment".
// To identify the owning segment:
// - pick a segment whose prefix contains the static IP (we guard against overlap so there could be at most 1)
// - otherwise allow the special static-assignments segment
// - otherwise return an error
let segment = segments
.iter()
.find(|s| s.prefixes.iter().any(|p| p.prefix.contains(address)))
.or_else(|| segments.iter().find(|s| s.config.name == crate::network_segment::STATIC_ASSIGNMENTS_SEGMENT_NAME))
.ok_or_else(|| DatabaseError::internal(format!(
"unable to find network segment that contains requested IP {address} in network segments: {}",
segments.iter().map(|s| s.id.to_string()).join(", "),
))
)?;
if let Some(existing) = find_by_ip(&mut *txn, address).await? {
if existing.mac_address == *macaddr {
return Ok(existing);
}
return Err(AddressAlreadyInUseError(
address,
existing.mac_address,
existing.segment_id,
existing.id,
)
.into());
}
let interface_id = create_inner(
txn,
segment,
macaddr,
segment.config.subdomain_id,
primary_interface,
&[address],
AllocationType::Static,