forked from oxidecomputer/omicron
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinventory.rs
More file actions
3189 lines (2989 loc) · 131 KB
/
Copy pathinventory.rs
File metadata and controls
3189 lines (2989 loc) · 131 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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
use super::DataStore;
use crate::authz;
use crate::context::OpContext;
use crate::db::pagination::{Paginator, paginated, paginated_multicolumn};
use crate::db::queries::ALLOW_FULL_TABLE_SCAN_SQL;
use anyhow::Context;
use async_bb8_diesel::AsyncConnection;
use async_bb8_diesel::AsyncRunQueryDsl;
use async_bb8_diesel::AsyncSimpleConnection;
use clickhouse_admin_types::ClickhouseKeeperClusterMembership;
use diesel::BoolExpressionMethods;
use diesel::ExpressionMethods;
use diesel::IntoSql;
use diesel::JoinOnDsl;
use diesel::NullableExpressionMethods;
use diesel::OptionalExtension;
use diesel::PgExpressionMethods;
use diesel::QueryDsl;
use diesel::Table;
use diesel::expression::SelectableHelper;
use diesel::sql_types::Nullable;
use futures::FutureExt;
use futures::future::BoxFuture;
use nexus_db_errors::ErrorHandler;
use nexus_db_errors::public_error_from_diesel;
use nexus_db_errors::public_error_from_diesel_lookup;
use nexus_db_model::HwBaseboardId;
use nexus_db_model::HwPowerState;
use nexus_db_model::HwRotSlot;
use nexus_db_model::InvCaboose;
use nexus_db_model::InvClickhouseKeeperMembership;
use nexus_db_model::InvCollection;
use nexus_db_model::InvCollectionError;
use nexus_db_model::InvDataset;
use nexus_db_model::InvNvmeDiskFirmware;
use nexus_db_model::InvOmicronZone;
use nexus_db_model::InvOmicronZoneNic;
use nexus_db_model::InvPhysicalDisk;
use nexus_db_model::InvRootOfTrust;
use nexus_db_model::InvRotPage;
use nexus_db_model::InvServiceProcessor;
use nexus_db_model::InvSledAgent;
use nexus_db_model::InvSledOmicronZones;
use nexus_db_model::InvZpool;
use nexus_db_model::RotImageError;
use nexus_db_model::SledRole;
use nexus_db_model::SpType;
use nexus_db_model::SqlU16;
use nexus_db_model::SqlU32;
use nexus_db_model::SwCaboose;
use nexus_db_model::SwRotPage;
use nexus_db_model::to_db_typed_uuid;
use nexus_db_schema::enums::CabooseWhichEnum;
use nexus_db_schema::enums::HwPowerStateEnum;
use nexus_db_schema::enums::HwRotSlotEnum;
use nexus_db_schema::enums::RotImageErrorEnum;
use nexus_db_schema::enums::RotPageWhichEnum;
use nexus_db_schema::enums::SledRoleEnum;
use nexus_db_schema::enums::SpTypeEnum;
use nexus_sled_agent_shared::inventory::OmicronZonesConfig;
use nexus_types::inventory::BaseboardId;
use nexus_types::inventory::Collection;
use nexus_types::inventory::PhysicalDiskFirmware;
use omicron_common::api::external::Error;
use omicron_common::api::external::InternalContext;
use omicron_common::api::external::LookupType;
use omicron_common::api::external::ResourceType;
use omicron_common::bail_unless;
use omicron_uuid_kinds::CollectionUuid;
use omicron_uuid_kinds::GenericUuid;
use omicron_uuid_kinds::SledUuid;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::num::NonZeroU32;
use std::sync::Arc;
use uuid::Uuid;
/// "limit" used in SQL queries that paginate through all SPs, RoTs, sleds,
/// omicron zones, etc.
///
/// We use a [`Paginator`] to guard against single queries returning an
/// unchecked number of rows.
// unsafe: `new_unchecked` is only unsound if the argument is 0.
const SQL_BATCH_SIZE: NonZeroU32 = NonZeroU32::new(1000).unwrap();
impl DataStore {
/// Store a complete inventory collection into the database
pub async fn inventory_insert_collection(
&self,
opctx: &OpContext,
collection: &Collection,
) -> Result<(), Error> {
opctx.authorize(authz::Action::Modify, &authz::INVENTORY).await?;
// In the database, the collection is represented essentially as a tree
// rooted at an `inv_collection` row. Other nodes in the tree point
// back at the `inv_collection` via `inv_collection_id`.
//
// It's helpful to assemble some values before entering the transaction
// so that we can produce the `Error` type that we want here.
let row_collection = InvCollection::from(collection);
let collection_id = row_collection.id();
let db_collection_id = to_db_typed_uuid(collection_id);
let baseboards = collection
.baseboards
.iter()
.map(|b| HwBaseboardId::from((**b).clone()))
.collect::<Vec<_>>();
let cabooses = collection
.cabooses
.iter()
.map(|s| SwCaboose::from((**s).clone()))
.collect::<Vec<_>>();
let rot_pages = collection
.rot_pages
.iter()
.map(|p| SwRotPage::from((**p).clone()))
.collect::<Vec<_>>();
let error_values = collection
.errors
.iter()
.enumerate()
.map(|(i, message)| {
let index = u16::try_from(i).map_err(|e| {
Error::internal_error(&format!(
"failed to convert error index to u16 (too \
many errors in inventory collection?): {}",
e
))
})?;
Ok(InvCollectionError::new(
collection_id,
index,
message.clone(),
))
})
.collect::<Result<Vec<_>, Error>>()?;
// Pull disk firmware out of sled agents
let mut nvme_disk_firmware = Vec::new();
for (sled_id, sled_agent) in &collection.sled_agents {
for disk in &sled_agent.disks {
match &disk.firmware {
PhysicalDiskFirmware::Unknown => (),
PhysicalDiskFirmware::Nvme(firmware) => nvme_disk_firmware
.push(
InvNvmeDiskFirmware::new(
collection_id,
*sled_id,
disk.slot,
firmware,
)
.map_err(|e| {
Error::internal_error(&e.to_string())
})?,
),
}
}
}
// Pull Omicron zone-related metadata out of all sled agents.
//
// TODO: InvSledOmicronZones is a vestigial table kept for backwards
// compatibility -- the only unique data within it (the generation
// number) can be moved into `InvSledAgent` in the future. See
// oxidecomputer/omicron#6770.
let sled_omicron_zones = collection
.sled_agents
.values()
.map(|sled_agent| {
InvSledOmicronZones::new(collection_id, sled_agent)
})
.collect::<Vec<_>>();
// Pull Omicron zones out of all sled agents.
let omicron_zones: Vec<_> = collection
.sled_agents
.iter()
.flat_map(|(sled_id, sled_agent)| {
sled_agent.omicron_zones.zones.iter().map(|zone| {
InvOmicronZone::new(collection_id, *sled_id, zone)
.map_err(|e| Error::internal_error(&e.to_string()))
})
})
.collect::<Result<Vec<_>, _>>()?;
// Pull disks out of all sled agents
let disks: Vec<_> = collection
.sled_agents
.iter()
.flat_map(|(sled_id, sled_agent)| {
sled_agent.disks.iter().map(|disk| {
InvPhysicalDisk::new(collection_id, *sled_id, disk.clone())
})
})
.collect();
// Pull zpools out of all sled agents
let zpools: Vec<_> = collection
.sled_agents
.iter()
.flat_map(|(sled_id, sled_agent)| {
sled_agent
.zpools
.iter()
.map(|pool| InvZpool::new(collection_id, *sled_id, pool))
})
.collect();
// Pull datasets out of all sled agents
let datasets: Vec<_> = collection
.sled_agents
.iter()
.flat_map(|(sled_id, sled_agent)| {
sled_agent.datasets.iter().map(|dataset| {
InvDataset::new(collection_id, *sled_id, dataset)
})
})
.collect();
// Partition the sled agents into those with an associated baseboard id
// and those without one. We handle these pretty differently.
let (sled_agents_baseboards, sled_agents_no_baseboards): (
Vec<_>,
Vec<_>,
) = collection
.sled_agents
.values()
.partition(|sled_agent| sled_agent.baseboard_id.is_some());
let sled_agents_no_baseboards = sled_agents_no_baseboards
.into_iter()
.map(|sled_agent| {
assert!(sled_agent.baseboard_id.is_none());
InvSledAgent::new_without_baseboard(collection_id, sled_agent)
.map_err(|e| Error::internal_error(&e.to_string()))
})
.collect::<Result<Vec<_>, Error>>()?;
let omicron_zone_nics = collection
.sled_agents
.values()
.flat_map(|sled_agent| {
sled_agent.omicron_zones.zones.iter().filter_map(|found_zone| {
InvOmicronZoneNic::new(collection_id, found_zone)
.with_context(|| format!("zone {:?}", found_zone.id))
.map_err(|e| Error::internal_error(&format!("{:#}", e)))
.transpose()
})
})
.collect::<Result<Vec<InvOmicronZoneNic>, _>>()?;
let mut inv_clickhouse_keeper_memberships = Vec::new();
for membership in &collection.clickhouse_keeper_cluster_membership {
inv_clickhouse_keeper_memberships.push(
InvClickhouseKeeperMembership::new(
collection_id,
membership.clone(),
)
.map_err(|e| Error::internal_error(&e.to_string()))?,
);
}
// This implementation inserts all records associated with the
// collection in one transaction. This is primarily for simplicity. It
// means we don't have to worry about other readers seeing a
// half-inserted collection, nor leaving detritus around if we start
// inserting records and then crash. However, it does mean this is
// likely to be a big transaction and if that becomes a problem we could
// break this up as long as we address those problems.
//
// The SQL here is written so that it doesn't have to be an
// *interactive* transaction. That is, it should in principle be
// possible to generate all this SQL up front and send it as one big
// batch rather than making a bunch of round-trips to the database.
// We'd do that if we had an interface for doing that with bound
// parameters, etc. See oxidecomputer/omicron#973.
let conn = self.pool_connection_authorized(opctx).await?;
// The risk of a serialization error is possible here, but low,
// as most of the operations should be insertions rather than in-place
// modifications of existing tables.
self.transaction_non_retry_wrapper("inventory_insert_collection")
.transaction(&conn, |conn| async move {
// Insert records (and generate ids) for any baseboards that do not
// already exist in the database. These rows are not scoped to a
// particular collection. They contain only immutable data --
// they're just a mapping between hardware-provided baseboard
// identifiers (part number and model number) and an
// Omicron-specific primary key (a UUID).
{
use nexus_db_schema::schema::hw_baseboard_id::dsl;
let _ = diesel::insert_into(dsl::hw_baseboard_id)
.values(baseboards)
.on_conflict_do_nothing()
.execute_async(&conn)
.await?;
}
// Insert records (and generate ids) for each distinct caboose that
// we've found. Like baseboards, these might already be present and
// rows in this table are not scoped to a particular collection
// because they only map (immutable) identifiers to UUIDs.
{
use nexus_db_schema::schema::sw_caboose::dsl;
let _ = diesel::insert_into(dsl::sw_caboose)
.values(cabooses)
.on_conflict_do_nothing()
.execute_async(&conn)
.await?;
}
// Insert records (and generate ids) for each distinct RoT page that
// we've found. Like baseboards, these might already be present and
// rows in this table are not scoped to a particular collection
// because they only map (immutable) identifiers to UUIDs.
{
use nexus_db_schema::schema::sw_root_of_trust_page::dsl;
let _ = diesel::insert_into(dsl::sw_root_of_trust_page)
.values(rot_pages)
.on_conflict_do_nothing()
.execute_async(&conn)
.await?;
}
// Insert a record describing the collection itself.
{
use nexus_db_schema::schema::inv_collection::dsl;
let _ = diesel::insert_into(dsl::inv_collection)
.values(row_collection)
.execute_async(&conn)
.await?;
}
// Insert rows for the service processors we found. These have a
// foreign key into the hw_baseboard_id table. We don't have those
// id values, though. We may have just inserted them, or maybe not
// (if they previously existed). To avoid dozens of unnecessary
// round-trips, we use INSERT INTO ... SELECT, which looks like
// this:
//
// INSERT INTO inv_service_processor
// SELECT
// id
// [other service_processor column values as literals]
// FROM hw_baseboard_id
// WHERE part_number = ... AND serial_number = ...;
//
// This way, we don't need to know the id. The database looks it up
// for us as it does the INSERT.
{
use nexus_db_schema::schema::hw_baseboard_id::dsl as baseboard_dsl;
use nexus_db_schema::schema::inv_service_processor::dsl as sp_dsl;
for (baseboard_id, sp) in &collection.sps {
let selection = nexus_db_schema::schema::hw_baseboard_id::table
.select((
db_collection_id
.into_sql::<diesel::sql_types::Uuid>(),
baseboard_dsl::id,
sp.time_collected
.into_sql::<diesel::sql_types::Timestamptz>(),
sp.source
.clone()
.into_sql::<diesel::sql_types::Text>(),
SpType::from(sp.sp_type).into_sql::<SpTypeEnum>(),
i32::from(sp.sp_slot)
.into_sql::<diesel::sql_types::Int4>(),
i64::from(sp.baseboard_revision)
.into_sql::<diesel::sql_types::Int8>(),
sp.hubris_archive
.clone()
.into_sql::<diesel::sql_types::Text>(),
HwPowerState::from(sp.power_state)
.into_sql::<HwPowerStateEnum>(),
))
.filter(
baseboard_dsl::part_number
.eq(baseboard_id.part_number.clone()),
)
.filter(
baseboard_dsl::serial_number
.eq(baseboard_id.serial_number.clone()),
);
let _ = diesel::insert_into(
nexus_db_schema::schema::inv_service_processor::table,
)
.values(selection)
.into_columns((
sp_dsl::inv_collection_id,
sp_dsl::hw_baseboard_id,
sp_dsl::time_collected,
sp_dsl::source,
sp_dsl::sp_type,
sp_dsl::sp_slot,
sp_dsl::baseboard_revision,
sp_dsl::hubris_archive_id,
sp_dsl::power_state,
))
.execute_async(&conn)
.await?;
// This statement is just here to force a compilation error
// if the set of columns in `inv_service_processor` changes.
// The code above attempts to insert a row into
// `inv_service_processor` using an explicit list of columns
// and values. Without the following statement, If a new
// required column were added, this would only fail at
// runtime.
//
// If you're here because of a compile error, you might be
// changing the `inv_service_processor` table. Update the
// statement below and be sure to update the code above,
// too!
//
// See also similar comments in blocks below, near other
// uses of `all_columns().
let (
_inv_collection_id,
_hw_baseboard_id,
_time_collected,
_source,
_sp_type,
_sp_slot,
_baseboard_revision,
_hubris_archive_id,
_power_state,
) = sp_dsl::inv_service_processor::all_columns();
}
}
// Insert rows for the roots of trust that we found. Like service
// processors, we do this using INSERT INTO ... SELECT.
{
use nexus_db_schema::schema::hw_baseboard_id::dsl as baseboard_dsl;
use nexus_db_schema::schema::inv_root_of_trust::dsl as rot_dsl;
for (baseboard_id, rot) in &collection.rots {
let selection = nexus_db_schema::schema::hw_baseboard_id::table
.select((
db_collection_id
.into_sql::<diesel::sql_types::Uuid>(),
baseboard_dsl::id,
rot.time_collected
.into_sql::<diesel::sql_types::Timestamptz>(),
rot.source
.clone()
.into_sql::<diesel::sql_types::Text>(),
HwRotSlot::from(rot.active_slot)
.into_sql::<HwRotSlotEnum>(),
HwRotSlot::from(rot.persistent_boot_preference)
.into_sql::<HwRotSlotEnum>(),
rot.pending_persistent_boot_preference
.map(HwRotSlot::from)
.into_sql::<Nullable<HwRotSlotEnum>>(),
rot.transient_boot_preference
.map(HwRotSlot::from)
.into_sql::<Nullable<HwRotSlotEnum>>(),
rot.slot_a_sha3_256_digest
.clone()
.into_sql::<Nullable<diesel::sql_types::Text>>(
),
rot.slot_b_sha3_256_digest
.clone()
.into_sql::<Nullable<diesel::sql_types::Text>>(
),
rot.stage0_digest
.clone()
.into_sql::<Nullable<diesel::sql_types::Text>>(
),
rot.stage0next_digest
.clone()
.into_sql::<Nullable<diesel::sql_types::Text>>(
),
rot.slot_a_error
.map(RotImageError::from)
.into_sql::<Nullable<RotImageErrorEnum>>(),
rot.slot_b_error
.map(RotImageError::from)
.into_sql::<Nullable<RotImageErrorEnum>>(),
rot.stage0_error
.map(RotImageError::from)
.into_sql::<Nullable<RotImageErrorEnum>>(),
rot.stage0next_error
.map(RotImageError::from)
.into_sql::<Nullable<RotImageErrorEnum>>(),
))
.filter(
baseboard_dsl::part_number
.eq(baseboard_id.part_number.clone()),
)
.filter(
baseboard_dsl::serial_number
.eq(baseboard_id.serial_number.clone()),
);
let _ = diesel::insert_into(
nexus_db_schema::schema::inv_root_of_trust::table,
)
.values(selection)
.into_columns((
rot_dsl::inv_collection_id,
rot_dsl::hw_baseboard_id,
rot_dsl::time_collected,
rot_dsl::source,
rot_dsl::slot_active,
rot_dsl::slot_boot_pref_persistent,
rot_dsl::slot_boot_pref_persistent_pending,
rot_dsl::slot_boot_pref_transient,
rot_dsl::slot_a_sha3_256,
rot_dsl::slot_b_sha3_256,
rot_dsl::stage0_fwid,
rot_dsl::stage0next_fwid,
rot_dsl::slot_a_error,
rot_dsl::slot_b_error,
rot_dsl::stage0_error,
rot_dsl::stage0next_error,
))
.execute_async(&conn)
.await?;
// See the comment in the previous block (where we use
// `inv_service_processor::all_columns()`). The same
// applies here.
let (
_inv_collection_id,
_hw_baseboard_id,
_time_collected,
_source,
_slot_active,
_slot_boot_pref_persistent,
_slot_boot_pref_persistent_pending,
_slot_boot_pref_transient,
_slot_a_sha3_256,
_slot_b_sha3_256,
_stage0_fwid,
_stage0next_fwid,
_slot_a_error,
_slot_b_error,
_stage0_error,
_stage0next_error,
) = rot_dsl::inv_root_of_trust::all_columns();
}
}
// Insert rows for the cabooses that we found. Like service
// processors and roots of trust, we do this using INSERT INTO ...
// SELECT. This one's a little more complicated because there are
// two foreign keys. Concretely, we have these three tables:
//
// - `hw_baseboard` with an "id" primary key and lookup columns
// "part_number" and "serial_number"
// - `sw_caboose` with an "id" primary key and lookup columns
// "board", "git_commit", "name", "version, and sign"
// - `inv_caboose` with foreign keys "hw_baseboard_id",
// "sw_caboose_id", and various other columns
//
// We want to INSERT INTO `inv_caboose` a row with:
//
// - hw_baseboard_id (foreign key) the result of looking up an
// hw_baseboard row by a specific part number and serial number
//
// - sw_caboose_id (foreign key) the result of looking up a
// specific sw_caboose row by board, git_commit, name, and version
//
// - the other columns being literals
//
// To achieve this, we're going to generate something like:
//
// INSERT INTO
// inv_caboose (
// hw_baseboard_id,
// sw_caboose_id,
// inv_collection_id,
// time_collected,
// source,
// which,
// )
// SELECT (
// hw_baseboard_id.id,
// sw_caboose.id,
// ... /* literal collection id */
// ... /* literal time collected */
// ... /* literal source */
// ... /* literal 'which' */
// )
// FROM
// hw_baseboard
// INNER JOIN
// sw_caboose
// ON hw_baseboard.part_number = ...
// AND hw_baseboard.serial_number = ...
// AND sw_caboose.board = ...
// AND sw_caboose.git_commit = ...
// AND sw_caboose.name = ...
// AND sw_caboose.version = ...
// AND sw_caboose.sign IS NOT DISTINCT FROM ...;
//
// Again, the whole point is to avoid back-and-forth between the
// client and the database. Those back-and-forth interactions can
// significantly increase latency and the probability of transaction
// conflicts. See RFD 192 for details. (Unfortunately, we still
// _are_ going back and forth here to issue each of these queries.
// But that's an artifact of the interface we currently have for
// sending queries. It should be possible to send all of these in
// one batch.
for (which, tree) in &collection.cabooses_found {
let db_which = nexus_db_model::CabooseWhich::from(*which);
for (baseboard_id, found_caboose) in tree {
use nexus_db_schema::schema::hw_baseboard_id::dsl as dsl_baseboard_id;
use nexus_db_schema::schema::inv_caboose::dsl as dsl_inv_caboose;
use nexus_db_schema::schema::sw_caboose::dsl as dsl_sw_caboose;
let selection = nexus_db_schema::schema::hw_baseboard_id::table
.inner_join(
nexus_db_schema::schema::sw_caboose::table.on(
dsl_baseboard_id::part_number
.eq(baseboard_id.part_number.clone())
.and(
dsl_baseboard_id::serial_number.eq(
baseboard_id.serial_number.clone(),
),
)
.and(dsl_sw_caboose::board.eq(
found_caboose.caboose.board.clone(),
))
.and(
dsl_sw_caboose::git_commit.eq(
found_caboose
.caboose
.git_commit
.clone(),
),
)
.and(
dsl_sw_caboose::name.eq(found_caboose
.caboose
.name
.clone()),
)
.and(dsl_sw_caboose::version.eq(
found_caboose.caboose.version.clone(),
))
.and(dsl_sw_caboose::sign.is_not_distinct_from(
found_caboose.caboose.sign.clone(),
)),
),
)
.select((
dsl_baseboard_id::id,
dsl_sw_caboose::id,
db_collection_id
.into_sql::<diesel::sql_types::Uuid>(),
found_caboose
.time_collected
.into_sql::<diesel::sql_types::Timestamptz>(),
found_caboose
.source
.clone()
.into_sql::<diesel::sql_types::Text>(),
db_which.into_sql::<CabooseWhichEnum>(),
));
let _ = diesel::insert_into(nexus_db_schema::schema::inv_caboose::table)
.values(selection)
.into_columns((
dsl_inv_caboose::hw_baseboard_id,
dsl_inv_caboose::sw_caboose_id,
dsl_inv_caboose::inv_collection_id,
dsl_inv_caboose::time_collected,
dsl_inv_caboose::source,
dsl_inv_caboose::which,
))
.execute_async(&conn)
.await?;
// See the comments above. The same applies here. If you
// update the statement below because the schema for
// `inv_caboose` has changed, be sure to update the code
// above, too!
let (
_hw_baseboard_id,
_sw_caboose_id,
_inv_collection_id,
_time_collected,
_source,
_which,
) = dsl_inv_caboose::inv_caboose::all_columns();
}
}
// Insert rows for the root of trust pages that we found. This is
// almost identical to inserting cabooses above, and just like for
// cabooses, we do this using INSERT INTO ... SELECT. We have these
// three tables:
//
// - `hw_baseboard` with an "id" primary key and lookup columns
// "part_number" and "serial_number"
// - `sw_root_of_trust_page` with an "id" primary key and lookup
// column "data_base64"
// - `inv_root_of_trust_page` with foreign keys "hw_baseboard_id",
// "sw_root_of_trust_page_id", and various other columns
//
// and generate an INSERT INTO query that is structurally the same
// as the caboose query described above.
for (which, tree) in &collection.rot_pages_found {
use nexus_db_schema::schema::hw_baseboard_id::dsl as dsl_baseboard_id;
use nexus_db_schema::schema::inv_root_of_trust_page::dsl as dsl_inv_rot_page;
use nexus_db_schema::schema::sw_root_of_trust_page::dsl as dsl_sw_rot_page;
let db_which = nexus_db_model::RotPageWhich::from(*which);
for (baseboard_id, found_rot_page) in tree {
let selection = nexus_db_schema::schema::hw_baseboard_id::table
.inner_join(
nexus_db_schema::schema::sw_root_of_trust_page::table.on(
dsl_baseboard_id::part_number
.eq(baseboard_id.part_number.clone())
.and(
dsl_baseboard_id::serial_number.eq(
baseboard_id.serial_number.clone(),
),
)
.and(dsl_sw_rot_page::data_base64.eq(
found_rot_page.page.data_base64.clone(),
)),
),
)
.select((
dsl_baseboard_id::id,
dsl_sw_rot_page::id,
db_collection_id
.into_sql::<diesel::sql_types::Uuid>(),
found_rot_page
.time_collected
.into_sql::<diesel::sql_types::Timestamptz>(),
found_rot_page
.source
.clone()
.into_sql::<diesel::sql_types::Text>(),
db_which.into_sql::<RotPageWhichEnum>(),
));
let _ = diesel::insert_into(
nexus_db_schema::schema::inv_root_of_trust_page::table,
)
.values(selection)
.into_columns((
dsl_inv_rot_page::hw_baseboard_id,
dsl_inv_rot_page::sw_root_of_trust_page_id,
dsl_inv_rot_page::inv_collection_id,
dsl_inv_rot_page::time_collected,
dsl_inv_rot_page::source,
dsl_inv_rot_page::which,
))
.execute_async(&conn)
.await?;
// See the comments above. The same applies here. If you
// update the statement below because the schema for
// `inv_root_of_trust_page` has changed, be sure to update
// the code above, too!
let (
_hw_baseboard_id,
_sw_root_of_trust_page_id,
_inv_collection_id,
_time_collected,
_source,
_which,
) = dsl_inv_rot_page::inv_root_of_trust_page::all_columns();
}
}
// Insert rows for all the physical disks we found.
{
use nexus_db_schema::schema::inv_physical_disk::dsl;
let batch_size = SQL_BATCH_SIZE.get().try_into().unwrap();
let mut disks = disks.into_iter();
loop {
let some_disks =
disks.by_ref().take(batch_size).collect::<Vec<_>>();
if some_disks.is_empty() {
break;
}
let _ = diesel::insert_into(dsl::inv_physical_disk)
.values(some_disks)
.execute_async(&conn)
.await?;
}
}
// Insert rows for all the physical disk firmware we found.
{
use nexus_db_schema::schema::inv_nvme_disk_firmware::dsl;
let batch_size = SQL_BATCH_SIZE.get().try_into().unwrap();
let mut nvme_disk_firmware = nvme_disk_firmware.into_iter();
loop {
let some_disk_firmware = nvme_disk_firmware
.by_ref()
.take(batch_size)
.collect::<Vec<_>>();
if some_disk_firmware.is_empty() {
break;
}
let _ = diesel::insert_into(dsl::inv_nvme_disk_firmware)
.values(some_disk_firmware)
.execute_async(&conn)
.await?;
}
}
// Insert rows for all the zpools we found.
{
use nexus_db_schema::schema::inv_zpool::dsl;
let batch_size = SQL_BATCH_SIZE.get().try_into().unwrap();
let mut zpools = zpools.into_iter();
loop {
let some_zpools =
zpools.by_ref().take(batch_size).collect::<Vec<_>>();
if some_zpools.is_empty() {
break;
}
let _ = diesel::insert_into(dsl::inv_zpool)
.values(some_zpools)
.execute_async(&conn)
.await?;
}
}
// Insert rows for all the datasets we found.
{
use nexus_db_schema::schema::inv_dataset::dsl;
let batch_size = SQL_BATCH_SIZE.get().try_into().unwrap();
let mut datasets = datasets.into_iter();
loop {
let some_datasets =
datasets.by_ref().take(batch_size).collect::<Vec<_>>();
if some_datasets.is_empty() {
break;
}
let _ = diesel::insert_into(dsl::inv_dataset)
.values(some_datasets)
.execute_async(&conn)
.await?;
}
}
// Insert rows for the sled agents that we found. In practice, we'd
// expect these to all have baseboards (if using Oxide hardware) or
// none have baseboards (if not).
{
use nexus_db_schema::schema::hw_baseboard_id::dsl as baseboard_dsl;
use nexus_db_schema::schema::inv_sled_agent::dsl as sa_dsl;
// For sleds with a real baseboard id, we have to use the
// `INSERT INTO ... SELECT` pattern that we used for other types
// of rows above to pull in the baseboard id's uuid.
for sled_agent in &sled_agents_baseboards {
let baseboard_id = sled_agent.baseboard_id.as_ref().expect(
"already selected only sled agents with baseboards",
);
let selection = nexus_db_schema::schema::hw_baseboard_id::table
.select((
db_collection_id
.into_sql::<diesel::sql_types::Uuid>(),
sled_agent
.time_collected
.into_sql::<diesel::sql_types::Timestamptz>(),
sled_agent
.source
.clone()
.into_sql::<diesel::sql_types::Text>(),
(sled_agent.sled_id.into_untyped_uuid())
.into_sql::<diesel::sql_types::Uuid>(),
baseboard_dsl::id.nullable(),
nexus_db_model::ipv6::Ipv6Addr::from(
sled_agent.sled_agent_address.ip(),
)
.into_sql::<diesel::sql_types::Inet>(),
SqlU16(sled_agent.sled_agent_address.port())
.into_sql::<diesel::sql_types::Int4>(),
SledRole::from(sled_agent.sled_role)
.into_sql::<SledRoleEnum>(),
SqlU32(sled_agent.usable_hardware_threads)
.into_sql::<diesel::sql_types::Int8>(),
nexus_db_model::ByteCount::from(
sled_agent.usable_physical_ram,
)
.into_sql::<diesel::sql_types::Int8>(),
nexus_db_model::ByteCount::from(
sled_agent.reservoir_size,
)
.into_sql::<diesel::sql_types::Int8>(),
nexus_db_model::Generation(
sled_agent.omicron_physical_disks_generation,
)
.into_sql::<diesel::sql_types::Int8>(),
))
.filter(
baseboard_dsl::part_number
.eq(baseboard_id.part_number.clone()),
)
.filter(
baseboard_dsl::serial_number
.eq(baseboard_id.serial_number.clone()),
);
let _ =
diesel::insert_into(nexus_db_schema::schema::inv_sled_agent::table)
.values(selection)
.into_columns((
sa_dsl::inv_collection_id,
sa_dsl::time_collected,
sa_dsl::source,
sa_dsl::sled_id,
sa_dsl::hw_baseboard_id,
sa_dsl::sled_agent_ip,
sa_dsl::sled_agent_port,
sa_dsl::sled_role,
sa_dsl::usable_hardware_threads,
sa_dsl::usable_physical_ram,
sa_dsl::reservoir_size,
sa_dsl::omicron_physical_disks_generation,
))
.execute_async(&conn)
.await?;
// See the comment in the earlier block (where we use
// `inv_service_processor::all_columns()`). The same
// applies here.
let (
_inv_collection_id,
_time_collected,
_source,
_sled_id,
_hw_baseboard_id,
_sled_agent_ip,
_sled_agent_port,
_sled_role,
_usable_hardware_threads,
_usable_physical_ram,
_reservoir_size,
_omicron_physical_disks_generation,
) = sa_dsl::inv_sled_agent::all_columns();
}
// For sleds with no baseboard information, we can't use
// the same INSERT INTO ... SELECT pattern because we
// won't find anything in the hw_baseboard_id table. It
// sucks that these are bifurcated code paths, but on
// the plus side, this is a much simpler INSERT, and we
// can insert all of them in one statement.
let _ = diesel::insert_into(nexus_db_schema::schema::inv_sled_agent::table)
.values(sled_agents_no_baseboards)
.execute_async(&conn)
.await?;
}
// Insert all the Omicron zones that we found.
{
use nexus_db_schema::schema::inv_sled_omicron_zones::dsl as sled_zones;
let _ = diesel::insert_into(sled_zones::inv_sled_omicron_zones)
.values(sled_omicron_zones)
.execute_async(&conn)
.await?;
}
{
use nexus_db_schema::schema::inv_omicron_zone::dsl as omicron_zone;
let _ = diesel::insert_into(omicron_zone::inv_omicron_zone)
.values(omicron_zones)
.execute_async(&conn)
.await?;
}
{
use nexus_db_schema::schema::inv_omicron_zone_nic::dsl as omicron_zone_nic;
let _ =
diesel::insert_into(omicron_zone_nic::inv_omicron_zone_nic)
.values(omicron_zone_nics)
.execute_async(&conn)
.await?;
}
// Insert the clickhouse keeper memberships we've received
{
use nexus_db_schema::schema::inv_clickhouse_keeper_membership::dsl;
diesel::insert_into(dsl::inv_clickhouse_keeper_membership)
.values(inv_clickhouse_keeper_memberships)
.execute_async(&conn)
.await?;
}
// Finally, insert the list of errors.