-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathmod.rs
2251 lines (2028 loc) · 77.5 KB
/
mod.rs
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/.
//! Primary control plane interface for database read and write operations
// TODO-scalability review all queries for use of indexes (may need
// "time_deleted IS NOT NULL" conditions) Figure out how to automate this.
//
// TODO-design Better support for joins?
// The interfaces here often require that to do anything with an object, a
// caller must first look up the id and then do operations with the id. For
// example, the caller of project_list_disks() always looks up the project to
// get the project_id, then lists disks having that project_id. It's possible
// to implement this instead with a JOIN in the database so that we do it with
// one database round-trip. We could use CTEs similar to what we do with
// conditional updates to distinguish the case where the project didn't exist
// vs. there were no disks in it. This seems likely to be a fair bit more
// complicated to do safely and generally compared to what we have now.
use super::Pool;
use super::pool::DbConnection;
use crate::authz;
use crate::context::OpContext;
use crate::db::{
self,
error::{ErrorHandler, public_error_from_diesel},
};
use ::oximeter::types::ProducerRegistry;
use anyhow::{Context, bail};
use async_bb8_diesel::AsyncRunQueryDsl;
use diesel::pg::Pg;
use diesel::prelude::*;
use diesel::query_builder::{QueryFragment, QueryId};
use diesel::query_dsl::methods::LoadQuery;
use diesel::{ExpressionMethods, QueryDsl};
use omicron_common::api::external::Error;
use omicron_common::api::external::IdentityMetadataCreateParams;
use omicron_common::api::external::LookupType;
use omicron_common::api::external::ResourceType;
use omicron_common::backoff::{
BackoffError, retry_notify, retry_policy_internal_service,
};
use omicron_uuid_kinds::{GenericUuid, SledUuid};
use slog::Logger;
use std::net::Ipv6Addr;
use std::num::NonZeroU32;
use std::sync::Arc;
mod address_lot;
mod affinity;
mod allow_list;
mod auth;
mod bfd;
mod bgp;
mod bootstore;
mod certificate;
mod clickhouse_policy;
mod cockroachdb_node_id;
mod cockroachdb_settings;
mod console_session;
mod crucible_dataset;
mod db_metadata;
mod deployment;
mod device_auth;
mod disk;
mod dns;
mod external_ip;
mod identity_provider;
mod image;
pub mod instance;
mod inventory;
mod ip_pool;
mod ipv4_nat_entry;
mod lldp;
mod migration;
mod network_interface;
mod oximeter;
mod physical_disk;
mod probe;
mod project;
mod quota;
mod rack;
mod region;
mod region_replacement;
mod region_snapshot;
pub mod region_snapshot_replacement;
mod rendezvous_debug_dataset;
mod role;
mod saga;
mod silo;
mod silo_group;
mod silo_user;
mod sled;
mod sled_instance;
mod snapshot;
mod ssh_key;
mod support_bundle;
mod switch;
mod switch_interface;
mod switch_port;
mod target_release;
#[cfg(test)]
pub(crate) mod test_utils;
mod update;
mod utilization;
mod v2p_mapping;
mod virtual_provisioning_collection;
mod vmm;
mod volume;
mod volume_repair;
mod vpc;
mod zpool;
pub use address_lot::AddressLotCreateResult;
pub use dns::DataStoreDnsTest;
pub use dns::DnsVersionUpdateBuilder;
pub use instance::{InstanceAndActiveVmm, InstanceGestalt};
pub use inventory::DataStoreInventoryTest;
use nexus_db_model::AllSchemaVersions;
pub use oximeter::CollectorReassignment;
pub use rack::RackInit;
pub use rack::SledUnderlayAllocationResult;
pub use region::RegionAllocationFor;
pub use region::RegionAllocationParameters;
pub use region_snapshot_replacement::NewRegionVolumeId;
pub use region_snapshot_replacement::OldSnapshotVolumeId;
pub use silo::Discoverability;
pub use sled::SledTransition;
pub use sled::TransitionError;
pub use support_bundle::SupportBundleExpungementReport;
pub use switch_port::SwitchPortSettingsCombinedResult;
pub use virtual_provisioning_collection::StorageType;
pub use vmm::VmmStateUpdateResult;
pub use volume::*;
// Number of unique datasets required to back a region.
// TODO: This should likely turn into a configuration option.
pub const REGION_REDUNDANCY_THRESHOLD: usize = 3;
/// The name of the built-in IP pool for Oxide services.
pub const SERVICE_IP_POOL_NAME: &str = "oxide-service-pool";
/// "limit" to be used in SQL queries that paginate through large result sets
///
/// This value is chosen to be small enough to avoid any queries being too
/// expensive.
// unsafe: `new_unchecked` is only unsound if the argument is 0.
pub const SQL_BATCH_SIZE: NonZeroU32 =
unsafe { NonZeroU32::new_unchecked(1000) };
// Represents a query that is ready to be executed.
//
// This helper trait lets the statement either be executed or explained.
//
// U: The output type of executing the statement.
pub trait RunnableQueryNoReturn:
RunQueryDsl<DbConnection> + QueryFragment<Pg> + QueryId
{
}
impl<T> RunnableQueryNoReturn for T where
T: RunQueryDsl<DbConnection> + QueryFragment<Pg> + QueryId
{
}
pub trait RunnableQuery<U>:
RunnableQueryNoReturn + LoadQuery<'static, DbConnection, U>
{
}
impl<U, T> RunnableQuery<U> for T where
T: RunnableQueryNoReturn + LoadQuery<'static, DbConnection, U>
{
}
pub type DataStoreConnection =
qorb::claim::Handle<async_bb8_diesel::Connection<DbConnection>>;
pub struct DataStore {
log: Logger,
pool: Arc<Pool>,
virtual_provisioning_collection_producer: crate::provisioning::Producer,
transaction_retry_producer: crate::transaction_retry::Producer,
}
// The majority of `DataStore`'s methods live in our submodules as a concession
// to compilation times; changing a query only requires incremental
// recompilation of that query's module instead of all queries on `DataStore`.
impl DataStore {
/// Constructs a new Datastore object, without any version validation.
///
/// Ignores the underlying DB version. Should be used with caution, as usage
/// of this method can construct a Datastore which does not understand
/// the underlying CockroachDB schema. Data corruption could result.
pub fn new_unchecked(log: Logger, pool: Arc<Pool>) -> Self {
DataStore {
log,
pool,
virtual_provisioning_collection_producer:
crate::provisioning::Producer::new(),
transaction_retry_producer: crate::transaction_retry::Producer::new(
),
}
}
/// Constructs a new Datastore object.
///
/// Only returns when the database schema is compatible with Nexus's known
/// schema version.
pub async fn new(
log: &Logger,
pool: Arc<Pool>,
config: Option<&AllSchemaVersions>,
) -> Result<Self, String> {
Self::new_with_timeout(log, pool, config, None).await
}
pub async fn new_with_timeout(
log: &Logger,
pool: Arc<Pool>,
config: Option<&AllSchemaVersions>,
try_for: Option<std::time::Duration>,
) -> Result<Self, String> {
use nexus_db_model::SCHEMA_VERSION as EXPECTED_VERSION;
let datastore =
Self::new_unchecked(log.new(o!("component" => "datastore")), pool);
let start = std::time::Instant::now();
// Keep looping until we find that the schema matches our expectation.
retry_notify(
retry_policy_internal_service(),
|| async {
if let Some(try_for) = try_for {
if std::time::Instant::now() > start + try_for {
return Err(BackoffError::permanent(()));
}
}
match datastore
.ensure_schema(&log, EXPECTED_VERSION, config)
.await
{
Ok(()) => return Ok(()),
Err(e) => {
warn!(log, "Failed to ensure schema version"; "error" => #%e);
}
};
return Err(BackoffError::transient(()));
},
|_, _| {},
)
.await
.map_err(|_| "Failed to read valid DB schema".to_string())?;
Ok(datastore)
}
/// Constructs a new Datastore, failing if the schema version does not match
/// this program's expected version
pub async fn new_failfast(
log: &Logger,
pool: Arc<Pool>,
) -> Result<Self, anyhow::Error> {
use nexus_db_model::SCHEMA_VERSION as EXPECTED_VERSION;
let datastore =
Self::new_unchecked(log.new(o!("component" => "datastore")), pool);
let (found_version, found_target) = datastore
.database_schema_version()
.await
.context("loading database schema version")?;
if let Some(found_target) = found_target {
bail!(
"database schema check failed: apparently mid-upgrade \
(found_target = {found_target})"
);
}
if found_version != EXPECTED_VERSION {
bail!(
"database schema check failed: \
expected {EXPECTED_VERSION}, found {found_version}",
);
}
Ok(datastore)
}
/// Terminates the underlying pool, stopping it from connecting to backends.
pub async fn terminate(&self) {
self.pool.terminate().await
}
pub fn register_producers(&self, registry: &ProducerRegistry) {
registry
.register_producer(
self.virtual_provisioning_collection_producer.clone(),
)
.unwrap();
registry
.register_producer(self.transaction_retry_producer.clone())
.unwrap();
}
/// Constructs a transaction retry helper
///
/// Automatically wraps the underlying producer
pub fn transaction_retry_wrapper(
&self,
name: &'static str,
) -> crate::transaction_retry::RetryHelper {
crate::transaction_retry::RetryHelper::new(
&self.log,
&self.transaction_retry_producer,
name,
)
}
/// Constructs a non-retryable transaction helper
pub fn transaction_non_retry_wrapper(
&self,
name: &'static str,
) -> crate::transaction_retry::NonRetryHelper {
crate::transaction_retry::NonRetryHelper::new(&self.log, name)
}
#[cfg(test)]
pub(crate) fn transaction_retry_producer(
&self,
) -> &crate::transaction_retry::Producer {
&self.transaction_retry_producer
}
/// Returns a connection to a connection from the database connection pool.
pub(super) async fn pool_connection_authorized(
&self,
opctx: &OpContext,
) -> Result<DataStoreConnection, Error> {
opctx.authorize(authz::Action::Query, &authz::DATABASE).await?;
let connection = self.pool.claim().await.map_err(|err| {
Error::unavail(&format!("Failed to access DB connection: {err}"))
})?;
Ok(connection)
}
/// Returns an unauthorized connection to a connection from the database
/// connection pool.
///
/// TODO-security: This should be deprecated in favor of
/// "pool_connection_authorized".
pub(super) async fn pool_connection_unauthorized(
&self,
) -> Result<DataStoreConnection, Error> {
let connection = self.pool.claim().await.map_err(|err| {
Error::unavail(&format!("Failed to access DB connection: {err}"))
})?;
Ok(connection)
}
/// For testing only. This isn't cfg(test) because nexus needs access to it.
#[doc(hidden)]
pub async fn pool_connection_for_tests(
&self,
) -> Result<DataStoreConnection, Error> {
self.pool_connection_unauthorized().await
}
/// Return the next available IPv6 address for a propolis instance running
/// on the provided sled.
pub async fn next_ipv6_address(
&self,
opctx: &OpContext,
sled_id: SledUuid,
) -> Result<Ipv6Addr, Error> {
use db::schema::sled::dsl;
let net = diesel::update(
dsl::sled
.find(sled_id.into_untyped_uuid())
.filter(dsl::time_deleted.is_null()),
)
.set(dsl::last_used_address.eq(dsl::last_used_address + 1))
.returning(dsl::last_used_address)
.get_result_async(&*self.pool_connection_authorized(opctx).await?)
.await
.map_err(|e| {
public_error_from_diesel(
e,
ErrorHandler::NotFoundByLookup(
ResourceType::Sled,
LookupType::ById(sled_id.into_untyped_uuid()),
),
)
})?;
// TODO-correctness: We need to ensure that this address is actually
// within the sled's underlay prefix, once that's included in the
// database record.
match net {
ipnetwork::IpNetwork::V6(net) => Ok(net.ip()),
_ => Err(Error::InternalError {
internal_message: String::from("Sled IP address must be IPv6"),
}),
}
}
// Test interfaces
#[cfg(test)]
async fn test_try_table_scan(&self, opctx: &OpContext) -> Error {
use db::schema::project::dsl;
let conn = self.pool_connection_authorized(opctx).await;
if let Err(error) = conn {
return error;
}
let result = dsl::project
.select(diesel::dsl::count_star())
.first_async::<i64>(&*conn.unwrap())
.await;
match result {
Ok(_) => Error::internal_error("table scan unexpectedly succeeded"),
Err(error) => public_error_from_diesel(error, ErrorHandler::Server),
}
}
}
#[derive(Clone, Copy, Debug)]
pub enum UpdatePrecondition<T> {
DontCare,
Null,
Value(T),
}
/// Whether state transitions should be validated. "No" is only accessible in
/// test-only code.
///
/// Intended only for testing around illegal states.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[must_use]
enum ValidateTransition {
Yes,
#[cfg(test)]
No,
}
#[cfg(test)]
mod test {
use super::*;
use crate::authn;
use crate::authn::SiloAuthnPolicy;
use crate::authz;
use crate::db::datastore::test_utils::{
IneligibleSledKind, IneligibleSleds,
};
use crate::db::explain::ExplainableAsync;
use crate::db::identity::Asset;
use crate::db::lookup::LookupPath;
use crate::db::model::{
BlockSize, ConsoleSession, CrucibleDataset, ExternalIp, PhysicalDisk,
PhysicalDiskKind, PhysicalDiskPolicy, PhysicalDiskState, Project, Rack,
Region, SiloUser, SshKey, Zpool,
};
use crate::db::pub_test_utils::TestDatabase;
use crate::db::pub_test_utils::helpers::SledUpdateBuilder;
use crate::db::queries::vpc_subnet::InsertVpcSubnetQuery;
use chrono::{Duration, Utc};
use futures::StreamExt;
use futures::stream;
use nexus_config::RegionAllocationStrategy;
use nexus_db_fixed_data::silo::DEFAULT_SILO;
use nexus_db_model::IpAttachState;
use nexus_db_model::to_db_typed_uuid;
use nexus_types::deployment::Blueprint;
use nexus_types::deployment::BlueprintTarget;
use nexus_types::external_api::params;
use nexus_types::silo::DEFAULT_SILO_ID;
use omicron_common::address::REPO_DEPOT_PORT;
use omicron_common::api::external::{
ByteCount, Error, IdentityMetadataCreateParams, LookupType, Name,
};
use omicron_test_utils::dev;
use omicron_uuid_kinds::CollectionUuid;
use omicron_uuid_kinds::DatasetUuid;
use omicron_uuid_kinds::GenericUuid;
use omicron_uuid_kinds::PhysicalDiskUuid;
use omicron_uuid_kinds::SledUuid;
use omicron_uuid_kinds::VolumeUuid;
use std::collections::HashMap;
use std::collections::HashSet;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddrV6};
use std::sync::Arc;
use strum::EnumCount;
use uuid::Uuid;
/// Inserts a blueprint in the DB and forcibly makes it the target
///
/// WARNING: This makes no attempts to validate the blueprint relative to
/// parents -- this is just a test-only helper to make testing
/// blueprint-specific checks easier.
pub async fn bp_insert_and_make_target(
opctx: &OpContext,
datastore: &DataStore,
bp: &Blueprint,
) {
datastore
.blueprint_insert(opctx, bp)
.await
.expect("inserted blueprint");
datastore
.blueprint_target_set_current(
opctx,
BlueprintTarget {
target_id: bp.id,
enabled: true,
time_made_target: Utc::now(),
},
)
.await
.expect("made blueprint the target");
}
#[tokio::test]
async fn test_project_creation() {
let logctx = dev::test_setup_log("test_project_creation");
let db = TestDatabase::new_with_datastore(&logctx.log).await;
let (opctx, datastore) = (db.opctx(), db.datastore());
let authz_silo = opctx.authn.silo_required().unwrap();
let (.., silo) = LookupPath::new(&opctx, &datastore)
.silo_id(authz_silo.id())
.fetch()
.await
.unwrap();
let project = Project::new(
authz_silo.id(),
params::ProjectCreate {
identity: IdentityMetadataCreateParams {
name: "project".parse().unwrap(),
description: "desc".to_string(),
},
},
);
datastore.project_create(&opctx, project).await.unwrap();
let (.., silo_after_project_create) =
LookupPath::new(&opctx, &datastore)
.silo_id(authz_silo.id())
.fetch()
.await
.unwrap();
assert!(silo_after_project_create.rcgen > silo.rcgen);
db.terminate().await;
logctx.cleanup_successful();
}
#[tokio::test]
async fn test_session_methods() {
let logctx = dev::test_setup_log("test_session_methods");
let db = TestDatabase::new_with_datastore(&logctx.log).await;
let (opctx, datastore) = (db.opctx(), db.datastore());
let authn_opctx = OpContext::for_background(
logctx.log.new(o!("component" => "TestExternalAuthn")),
Arc::new(authz::Authz::new(&logctx.log)),
authn::Context::external_authn(),
Arc::clone(&datastore) as Arc<dyn nexus_auth::storage::Storage>,
);
let token = "a_token".to_string();
let silo_user_id = Uuid::new_v4();
let session = ConsoleSession {
token: token.clone(),
time_created: Utc::now() - Duration::minutes(5),
time_last_used: Utc::now() - Duration::minutes(5),
silo_user_id,
};
let _ = datastore
.session_create(&authn_opctx, session.clone())
.await
.unwrap();
// Associate silo with user
let authz_silo = authz::Silo::new(
authz::FLEET,
DEFAULT_SILO_ID,
LookupType::ById(DEFAULT_SILO_ID),
);
datastore
.silo_user_create(
&authz_silo,
SiloUser::new(
authz_silo.id(),
silo_user_id,
"external_id".into(),
),
)
.await
.unwrap();
let (.., db_silo_user) = LookupPath::new(&opctx, &datastore)
.silo_user_id(session.silo_user_id)
.fetch()
.await
.unwrap();
assert_eq!(DEFAULT_SILO_ID, db_silo_user.silo_id);
// fetch the one we just created
let (.., fetched) = LookupPath::new(&opctx, &datastore)
.console_session_token(&token)
.fetch()
.await
.unwrap();
assert_eq!(session.silo_user_id, fetched.silo_user_id);
// trying to insert the same one again fails
let duplicate =
datastore.session_create(&authn_opctx, session.clone()).await;
assert!(matches!(
duplicate,
Err(Error::InternalError { internal_message: _ })
));
// update last used (i.e., renew token)
let authz_session = authz::ConsoleSession::new(
authz::FLEET,
token.clone(),
LookupType::ByCompositeId(token.clone()),
);
let renewed = datastore
.session_update_last_used(&opctx, &authz_session)
.await
.unwrap();
assert!(
renewed.console_session.time_last_used > session.time_last_used
);
// time_last_used change persists in DB
let (.., fetched) = LookupPath::new(&opctx, &datastore)
.console_session_token(&token)
.fetch()
.await
.unwrap();
assert!(fetched.time_last_used > session.time_last_used);
// deleting it using `opctx` (which represents the test-privileged user)
// should succeed but not do anything -- you can't delete someone else's
// session
let delete =
datastore.session_hard_delete(&opctx, &authz_session).await;
assert_eq!(delete, Ok(()));
let fetched = LookupPath::new(&opctx, &datastore)
.console_session_token(&token)
.fetch()
.await;
assert!(fetched.is_ok());
// delete it and fetch should come back with nothing
let silo_user_opctx = OpContext::for_background(
logctx.log.new(o!()),
Arc::new(authz::Authz::new(&logctx.log)),
authn::Context::for_test_user(
silo_user_id,
DEFAULT_SILO_ID,
SiloAuthnPolicy::try_from(&*DEFAULT_SILO).unwrap(),
),
Arc::clone(&datastore) as Arc<dyn nexus_auth::storage::Storage>,
);
let delete = datastore
.session_hard_delete(&silo_user_opctx, &authz_session)
.await;
assert_eq!(delete, Ok(()));
let fetched = LookupPath::new(&opctx, &datastore)
.console_session_token(&token)
.fetch()
.await;
assert!(matches!(
fetched,
Err(Error::ObjectNotFound { type_name: _, lookup_type: _ })
));
// deleting an already nonexistent is considered a success
let delete_again =
datastore.session_hard_delete(&opctx, &authz_session).await;
assert_eq!(delete_again, Ok(()));
db.terminate().await;
logctx.cleanup_successful();
}
// Creates a test sled, returns its UUID.
async fn create_test_sled(datastore: &DataStore) -> SledUuid {
let sled_id = SledUuid::new_v4();
let sled_update = SledUpdateBuilder::new().sled_id(sled_id).build();
datastore.sled_upsert(sled_update).await.unwrap();
sled_id
}
fn test_zpool_size() -> ByteCount {
ByteCount::from_gibibytes_u32(100)
}
const TEST_VENDOR: &str = "test-vendor";
const TEST_MODEL: &str = "test-model";
/// Creates a disk on a sled of a particular kind.
///
/// The "serial" value of the disk is supplied by the
/// caller, and is arbitrary, but should be unique.
async fn create_test_physical_disk(
datastore: &DataStore,
opctx: &OpContext,
sled_id: SledUuid,
kind: PhysicalDiskKind,
serial: String,
) -> PhysicalDiskUuid {
let physical_disk = PhysicalDisk::new(
PhysicalDiskUuid::new_v4(),
TEST_VENDOR.into(),
serial,
TEST_MODEL.into(),
kind,
sled_id.into_untyped_uuid(),
);
datastore
.physical_disk_insert(opctx, physical_disk.clone())
.await
.expect("Failed to upsert physical disk");
physical_disk.id()
}
// Creates a test zpool, returns its UUID.
async fn create_test_zpool(
datastore: &DataStore,
opctx: &OpContext,
sled_id: SledUuid,
physical_disk_id: PhysicalDiskUuid,
) -> Uuid {
let zpool_id = create_test_zpool_not_in_inventory(
datastore,
opctx,
sled_id,
physical_disk_id,
)
.await;
add_test_zpool_to_inventory(datastore, zpool_id, sled_id).await;
zpool_id
}
// Creates a test zpool, returns its UUID.
//
// However, this helper doesn't add the zpool to the inventory just yet.
async fn create_test_zpool_not_in_inventory(
datastore: &DataStore,
opctx: &OpContext,
sled_id: SledUuid,
physical_disk_id: PhysicalDiskUuid,
) -> Uuid {
let zpool_id = Uuid::new_v4();
let zpool =
Zpool::new(zpool_id, sled_id.into_untyped_uuid(), physical_disk_id);
datastore.zpool_insert(opctx, zpool).await.unwrap();
zpool_id
}
// Adds a test zpool into the inventory, with a randomly generated
// collection UUID.
async fn add_test_zpool_to_inventory(
datastore: &DataStore,
zpool_id: Uuid,
sled_id: SledUuid,
) {
use db::schema::inv_zpool::dsl;
let inv_collection_id = CollectionUuid::new_v4();
let time_collected = Utc::now();
let inv_pool = nexus_db_model::InvZpool {
inv_collection_id: inv_collection_id.into(),
time_collected,
id: zpool_id,
sled_id: to_db_typed_uuid(sled_id),
total_size: test_zpool_size().into(),
};
diesel::insert_into(dsl::inv_zpool)
.values(inv_pool)
.execute_async(
&*datastore.pool_connection_for_tests().await.unwrap(),
)
.await
.unwrap();
}
fn create_test_disk_create_params(
name: &str,
size: ByteCount,
) -> params::DiskCreate {
params::DiskCreate {
identity: IdentityMetadataCreateParams {
name: Name::try_from(name.to_string()).unwrap(),
description: name.to_string(),
},
disk_source: params::DiskSource::Blank {
block_size: params::BlockSize::try_from(4096).unwrap(),
},
size,
}
}
#[derive(Debug)]
pub(crate) struct TestDatasets {
// eligible and ineligible aren't currently used, but are probably handy
// for the future.
#[allow(dead_code)]
eligible: SledToDatasetMap,
#[allow(dead_code)]
ineligible: SledToDatasetMap,
// A map from eligible dataset IDs to their corresponding sled IDs.
eligible_dataset_ids: HashMap<DatasetUuid, SledUuid>,
ineligible_dataset_ids: HashMap<DatasetUuid, IneligibleSledKind>,
}
// Map of sled IDs to dataset IDs.
type SledToDatasetMap = HashMap<SledUuid, Vec<DatasetUuid>>;
impl TestDatasets {
pub(crate) async fn create(
opctx: &OpContext,
datastore: Arc<DataStore>,
num_eligible_sleds: usize,
) -> Self {
let eligible =
Self::create_impl(opctx, datastore.clone(), num_eligible_sleds)
.await;
let eligible_dataset_ids = eligible
.iter()
.flat_map(|(sled_id, dataset_ids)| {
dataset_ids
.iter()
.map(move |dataset_id| (*dataset_id, *sled_id))
})
.collect();
let ineligible = Self::create_impl(
opctx,
datastore.clone(),
IneligibleSledKind::COUNT,
)
.await;
let mut ineligible_sled_ids = ineligible.keys();
// Set up the ineligible sleds. (We're guaranteed that
// IneligibleSledKind::COUNT is the same as the number of next()
// calls below.)
let ineligible_sleds = IneligibleSleds {
non_provisionable: *ineligible_sled_ids.next().unwrap(),
expunged: *ineligible_sled_ids.next().unwrap(),
decommissioned: *ineligible_sled_ids.next().unwrap(),
illegal_decommissioned: *ineligible_sled_ids.next().unwrap(),
};
eprintln!("Setting up ineligible sleds: {:?}", ineligible_sleds);
ineligible_sleds
.setup(opctx, &datastore)
.await
.expect("error setting up ineligible sleds");
// Build a map of dataset IDs to their ineligible kind.
let mut ineligible_dataset_ids = HashMap::new();
for (kind, sled_id) in ineligible_sleds.iter() {
for dataset_id in ineligible.get(&sled_id).unwrap() {
ineligible_dataset_ids.insert(*dataset_id, kind);
}
}
Self {
eligible,
eligible_dataset_ids,
ineligible,
ineligible_dataset_ids,
}
}
// Returns a map of sled ID to dataset IDs.
async fn create_impl(
opctx: &OpContext,
datastore: Arc<DataStore>,
number_of_sleds: usize,
) -> SledToDatasetMap {
// Create sleds...
let sled_ids: Vec<SledUuid> = stream::iter(0..number_of_sleds)
.then(|_| create_test_sled(&datastore))
.collect()
.await;
struct PhysicalDisk {
sled_id: SledUuid,
disk_id: PhysicalDiskUuid,
}
// create 9 disks on each sled
let physical_disks: Vec<PhysicalDisk> = stream::iter(sled_ids)
.map(|sled_id| {
let sled_id_iter: Vec<SledUuid> =
(0..9).map(|_| sled_id).collect();
stream::iter(sled_id_iter).enumerate().then(
|(i, sled_id)| {
let disk_id_future = create_test_physical_disk(
&datastore,
opctx,
sled_id,
PhysicalDiskKind::U2,
format!("{sled_id}, disk index {i}"),
);
async move {
let disk_id = disk_id_future.await;
PhysicalDisk { sled_id, disk_id }
}
},
)
})
.flatten()
.collect()
.await;
#[derive(Copy, Clone)]
struct Zpool {
sled_id: SledUuid,
pool_id: Uuid,
}
// 1 pool per disk
let zpools: Vec<Zpool> = stream::iter(physical_disks)
.then(|disk| {
let pool_id_future = create_test_zpool(
&datastore,
&opctx,
disk.sled_id,
disk.disk_id,
);
async move {
let pool_id = pool_id_future.await;
Zpool { sled_id: disk.sled_id, pool_id }
}
})
.collect()
.await;
let bogus_addr = SocketAddrV6::new(Ipv6Addr::LOCALHOST, 8080, 0, 0);
let datasets = stream::iter(zpools)
.map(|zpool| {
// 3 datasets per zpool, to test that pools are distinct
let zpool_iter: Vec<Zpool> =
(0..3).map(|_| zpool).collect();
stream::iter(zpool_iter).then(|zpool| {
let dataset_id = DatasetUuid::new_v4();
let dataset = CrucibleDataset::new(
dataset_id,
zpool.pool_id,
bogus_addr,
);
let datastore = datastore.clone();
async move {
datastore
.crucible_dataset_upsert(dataset)
.await
.unwrap();
(zpool.sled_id, dataset_id)
}
})
})
.flatten()
.fold(
SledToDatasetMap::new(),
|mut map, (sled_id, dataset_id)| {
// Build a map of sled ID to dataset IDs.
map.entry(sled_id)
.or_insert_with(Vec::new)
.push(dataset_id);
async move { map }
},
)
.await;
datasets
}