Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
121 changes: 61 additions & 60 deletions nexus/db-queries/src/db/datastore/disk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -445,46 +445,16 @@ impl DataStore {
.await
}

/// List disks associated with a given instance by name.
pub async fn instance_list_disks_on_conn(
&self,
/// Consume a query result listing all parts of the higher level Disk type,
/// and assemble it.
async fn process_tuples_to_disk_list(
conn: &async_bb8_diesel::Connection<DbConnection>,
instance_id: Uuid,
pagparams: &PaginatedBy<'_>,
results: Vec<(
model::Disk,
Option<DiskTypeCrucible>,
Option<DiskTypeLocalStorage>,
)>,
Comment on lines +452 to +456
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

part of me wonders if we might be better off having some kinda

#[derive(Selectable)]
struct RawDiskListEntry {
    disk: model::Disk,
    crucible: Option<DiskTypeCrucible>,
    local: Option<DiskTypeLocalStorage>,
}

so that we can use named fields in the match later, but perhaps that's not worth the effort... i dunno.

) -> ListResultVec<Disk> {
use nexus_db_schema::schema::disk::dsl;
use nexus_db_schema::schema::disk_type_crucible::dsl as disk_type_crucible_dsl;
use nexus_db_schema::schema::disk_type_local_storage::dsl as disk_type_local_storage_dsl;

let results = match pagparams {
PaginatedBy::Id(pagparams) => {
paginated(dsl::disk, dsl::id, &pagparams)
}
PaginatedBy::Name(pagparams) => paginated(
dsl::disk,
dsl::name,
&pagparams.map_name(|n| Name::ref_cast(n)),
),
}
.left_join(
disk_type_crucible_dsl::disk_type_crucible
.on(dsl::id.eq(disk_type_crucible_dsl::disk_id)),
)
.left_join(
disk_type_local_storage_dsl::disk_type_local_storage
.on(dsl::id.eq(disk_type_local_storage_dsl::disk_id)),
)
.filter(dsl::time_deleted.is_null())
.filter(dsl::attach_instance_id.eq(instance_id))
.select((
model::Disk::as_select(),
Option::<DiskTypeCrucible>::as_select(),
Option::<DiskTypeLocalStorage>::as_select(),
))
.get_results_async(conn)
.await
.map_err(|e| public_error_from_diesel(e, ErrorHandler::Server))?;

let mut list = Vec::with_capacity(results.len());

for result in results {
Expand Down Expand Up @@ -555,6 +525,49 @@ impl DataStore {
Ok(list)
}

/// List disks associated with a given instance by name.
pub async fn instance_list_disks_on_conn(
&self,
conn: &async_bb8_diesel::Connection<DbConnection>,
instance_id: Uuid,
pagparams: &PaginatedBy<'_>,
) -> ListResultVec<Disk> {
use nexus_db_schema::schema::disk::dsl;
use nexus_db_schema::schema::disk_type_crucible::dsl as disk_type_crucible_dsl;
use nexus_db_schema::schema::disk_type_local_storage::dsl as disk_type_local_storage_dsl;

let results = match pagparams {
PaginatedBy::Id(pagparams) => {
paginated(dsl::disk, dsl::id, &pagparams)
}
PaginatedBy::Name(pagparams) => paginated(
dsl::disk,
dsl::name,
&pagparams.map_name(|n| Name::ref_cast(n)),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

unimportant turbo-nit: this could be

Suggested change
&pagparams.map_name(|n| Name::ref_cast(n)),
&pagparams.map_name(Name::ref_cast),

),
}
.left_join(
disk_type_crucible_dsl::disk_type_crucible
.on(dsl::id.eq(disk_type_crucible_dsl::disk_id)),
)
.left_join(
disk_type_local_storage_dsl::disk_type_local_storage
.on(dsl::id.eq(disk_type_local_storage_dsl::disk_id)),
)
.filter(dsl::time_deleted.is_null())
.filter(dsl::attach_instance_id.eq(instance_id))
.select((
model::Disk::as_select(),
Option::<DiskTypeCrucible>::as_select(),
Option::<DiskTypeLocalStorage>::as_select(),
))
Comment on lines +539 to +563
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it occurs to me that we might be able to share more code between the two functions by pulling everything here except for the .filter(dsl::attach_instance_id.eq(instance_id)) bit out into a function returning a query, and then have both instance_list_disks_on_conn and disk_list call that function, and just stick slightly different filters (by either the instance ID or the project) on that query fragment.

on one hand, that also would have prevented the original bug, but on the other, well...figuring out the Diesel type of that query is probably gonna hurt, and i think the process_tuples_to_disk_list function taking a Vec of the correct-typed tuple is already a pretty okay way to stop you from forgetting to query one of the tables, and...how many more disk-list-like APIs are we ever gonna add?

so, the current thing is fine and this doesn't matter.

.get_results_async(conn)
.await
.map_err(|e| public_error_from_diesel(e, ErrorHandler::Server))?;

Self::process_tuples_to_disk_list(conn, results).await
}

pub(super) async fn project_create_disk_in_txn(
conn: &async_bb8_diesel::Connection<DbConnection>,
err: OptionalError<Error>,
Expand Down Expand Up @@ -702,6 +715,9 @@ impl DataStore {

use nexus_db_schema::schema::disk::dsl;
use nexus_db_schema::schema::disk_type_crucible::dsl as disk_type_crucible_dsl;
use nexus_db_schema::schema::disk_type_local_storage::dsl as disk_type_local_storage_dsl;

let conn = self.pool_connection_authorized(opctx).await?;

let results = match pagparams {
PaginatedBy::Id(pagparams) => {
Expand All @@ -717,37 +733,22 @@ impl DataStore {
disk_type_crucible_dsl::disk_type_crucible
.on(dsl::id.eq(disk_type_crucible_dsl::disk_id)),
)
.left_join(
disk_type_local_storage_dsl::disk_type_local_storage
.on(dsl::id.eq(disk_type_local_storage_dsl::disk_id)),
)
.filter(dsl::time_deleted.is_null())
.filter(dsl::project_id.eq(authz_project.id()))
.select((
model::Disk::as_select(),
Option::<DiskTypeCrucible>::as_select(),
Option::<DiskTypeLocalStorage>::as_select(),
))
.get_results_async(&*self.pool_connection_authorized(opctx).await?)
.get_results_async(&*conn)
.await
.map_err(|e| public_error_from_diesel(e, ErrorHandler::Server))?;

let mut list = Vec::with_capacity(results.len());

for result in results {
match result {
(disk, Some(disk_type_crucible)) => {
list.push(Disk::Crucible(CrucibleDisk {
disk,
disk_type_crucible,
}));
}

(disk, None) => {
return Err(Error::internal_error(&format!(
"disk {} is invalid!",
disk.id(),
)));
}
}
}

Ok(list)
Self::process_tuples_to_disk_list(&conn, results).await
}

/// Attaches a disk to an instance, if both objects:
Expand Down
75 changes: 75 additions & 0 deletions nexus/tests/integration_tests/disks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2658,6 +2658,81 @@ async fn test_zpool_control_plane_storage_buffer(
.unwrap();
}

#[nexus_test]
async fn test_list_all_types_of_disk(cptestctx: &ControlPlaneTestContext) {
// Create three zpools, each with one dataset
DiskTestBuilder::new(&cptestctx)
.on_all_sleds()
.with_zpool_count(3)
.build()
.await;

// Assert default is still 16 GiB
assert_eq!(16, DiskTest::DEFAULT_ZPOOL_SIZE_GIB);

let client = &cptestctx.external_client;
create_project_and_pool(client).await;

let disks_url = get_disks_url();

// Distributed disk
let new_disk = params::DiskCreate {
identity: IdentityMetadataCreateParams {
name: "disk1".parse().unwrap(),
description: String::from("sells rainsticks"),
},
disk_backend: params::DiskBackend::Distributed {
disk_source: params::DiskSource::Blank {
block_size: params::BlockSize::try_from(512).unwrap(),
},
},
size: ByteCount::from_gibibytes_u32(1),
};

NexusRequest::new(
RequestBuilder::new(client, Method::POST, &disks_url)
.body(Some(&new_disk))
.expect_status(Some(StatusCode::CREATED)),
)
.authn_as(AuthnMode::PrivilegedUser)
.execute()
.await
.unwrap();

// Local disk

let new_disk = params::DiskCreate {
identity: IdentityMetadataCreateParams {
name: "disk2".parse().unwrap(),
description: String::from("sells rainsticks"),
},
disk_backend: params::DiskBackend::Local {},
size: ByteCount::from_gibibytes_u32(1),
};

NexusRequest::new(
RequestBuilder::new(client, Method::POST, &disks_url)
.body(Some(&new_disk))
.expect_status(Some(StatusCode::CREATED)),
)
.authn_as(AuthnMode::PrivilegedUser)
.execute()
.await
.unwrap();

// List them all

NexusRequest::new(
RequestBuilder::new(client, Method::GET, &disks_url)
.body(Some(&new_disk))
.expect_status(Some(StatusCode::OK)),
)
.authn_as(AuthnMode::PrivilegedUser)
.execute()
.await
.unwrap();
}

async fn disk_get(client: &ClientTestContext, disk_url: &str) -> Disk {
NexusRequest::object_get(client, disk_url)
.authn_as(AuthnMode::PrivilegedUser)
Expand Down
Loading