-
Notifications
You must be signed in to change notification settings - Fork 40
/
datastore.rs
4601 lines (4196 loc) · 172 KB
/
datastore.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::collection_insert::{
AsyncInsertError, DatastoreCollection, SyncInsertError,
};
use super::error::diesel_pool_result_optional;
use super::identity::{Asset, Resource};
use super::pool::DbConnection;
use super::Pool;
use crate::authn;
use crate::authz::{self, ApiResource};
use crate::context::OpContext;
use crate::db::collection_attach::{AttachError, DatastoreAttachTarget};
use crate::db::collection_detach::{DatastoreDetachTarget, DetachError};
use crate::db::collection_detach_many::{
DatastoreDetachManyTarget, DetachManyError,
};
use crate::db::fixed_data::role_assignment::BUILTIN_ROLE_ASSIGNMENTS;
use crate::db::fixed_data::role_builtin::BUILTIN_ROLES;
use crate::db::fixed_data::silo::DEFAULT_SILO;
use crate::db::lookup::LookupPath;
use crate::db::model::DatabaseString;
use crate::db::model::IncompleteVpc;
use crate::db::model::NetworkInterfaceUpdate;
use crate::db::model::Vpc;
use crate::db::queries::network_interface;
use crate::db::queries::vpc::InsertVpcQuery;
use crate::db::queries::vpc_subnet::FilterConflictingVpcSubnetRangesQuery;
use crate::db::queries::vpc_subnet::SubnetError;
use crate::db::{
self,
error::{
public_error_from_diesel_create, public_error_from_diesel_lookup,
public_error_from_diesel_pool, ErrorHandler, TransactionError,
},
model::{
ConsoleSession, Dataset, DatasetKind, Disk, DiskRuntimeState,
Generation, GlobalImage, IdentityProvider, IncompleteNetworkInterface,
Instance, InstanceRuntimeState, Name, NetworkInterface, Organization,
OrganizationUpdate, OximeterInfo, ProducerEndpoint, Project,
ProjectUpdate, Rack, Region, RoleAssignment, RoleBuiltin, RouterRoute,
RouterRouteUpdate, Service, Silo, SiloUser, Sled, SshKey,
UpdateAvailableArtifact, UserBuiltin, Volume, VpcFirewallRule,
VpcRouter, VpcRouterUpdate, VpcSubnet, VpcSubnetUpdate, VpcUpdate,
Zpool,
},
pagination::paginated,
pagination::paginated_multicolumn,
update_and_check::{UpdateAndCheck, UpdateStatus},
};
use crate::external_api::{params, shared};
use async_bb8_diesel::{AsyncConnection, AsyncRunQueryDsl, ConnectionManager};
use chrono::Utc;
use db::model::IdentityType;
use diesel::pg::Pg;
use diesel::prelude::*;
use diesel::query_builder::{QueryFragment, QueryId};
use diesel::query_dsl::methods::LoadQuery;
use diesel::upsert::excluded;
use diesel::{ExpressionMethods, QueryDsl, SelectableHelper};
use omicron_common::api;
use omicron_common::api::external;
use omicron_common::api::external::DataPageParams;
use omicron_common::api::external::DeleteResult;
use omicron_common::api::external::Error;
use omicron_common::api::external::ListResultVec;
use omicron_common::api::external::LookupResult;
use omicron_common::api::external::LookupType;
use omicron_common::api::external::ResourceType;
use omicron_common::api::external::UpdateResult;
use omicron_common::api::external::{
CreateResult, IdentityMetadataCreateParams,
};
use omicron_common::bail_unless;
use sled_agent_client::types as sled_client_types;
use std::convert::{TryFrom, TryInto};
use std::net::Ipv6Addr;
use std::sync::Arc;
use uuid::Uuid;
// Number of unique datasets required to back a region.
// TODO: This should likely turn into a configuration option.
const REGION_REDUNDANCY_THRESHOLD: usize = 3;
// 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.
trait RunnableQuery<U>:
RunQueryDsl<DbConnection>
+ QueryFragment<Pg>
+ LoadQuery<'static, DbConnection, U>
+ QueryId
{
}
impl<U, T> RunnableQuery<U> for T where
T: RunQueryDsl<DbConnection>
+ QueryFragment<Pg>
+ LoadQuery<'static, DbConnection, U>
+ QueryId
{
}
pub struct DataStore {
pool: Arc<Pool>,
}
impl DataStore {
pub fn new(pool: Arc<Pool>) -> Self {
DataStore { pool }
}
// TODO-security This should be deprecated in favor of pool_authorized(),
// which gives us the chance to do a minimal security check before hitting
// the database. Eventually, this function should only be used for doing
// authentication in the first place (since we can't do an authz check in
// that case).
fn pool(&self) -> &bb8::Pool<ConnectionManager<DbConnection>> {
self.pool.pool()
}
pub(super) async fn pool_authorized(
&self,
opctx: &OpContext,
) -> Result<&bb8::Pool<ConnectionManager<DbConnection>>, Error> {
opctx.authorize(authz::Action::Query, &authz::DATABASE).await?;
Ok(self.pool.pool())
}
/// Stores a new rack in the database.
///
/// This function is a no-op if the rack already exists.
pub async fn rack_insert(
&self,
opctx: &OpContext,
rack: &Rack,
) -> Result<Rack, Error> {
use db::schema::rack::dsl;
diesel::insert_into(dsl::rack)
.values(rack.clone())
.on_conflict(dsl::id)
.do_update()
// This is a no-op, since we conflicted on the ID.
.set(dsl::id.eq(excluded(dsl::id)))
.returning(Rack::as_returning())
.get_result_async(self.pool_authorized(opctx).await?)
.await
.map_err(|e| {
public_error_from_diesel_pool(
e,
ErrorHandler::Conflict(
ResourceType::Rack,
&rack.id().to_string(),
),
)
})
}
/// Update a rack to mark that it has been initialized
pub async fn rack_set_initialized(
&self,
opctx: &OpContext,
rack_id: Uuid,
services: Vec<Service>,
) -> UpdateResult<Rack> {
use db::schema::rack::dsl as rack_dsl;
use db::schema::service::dsl as service_dsl;
#[derive(Debug)]
enum RackInitError {
ServiceInsert { err: SyncInsertError, sled_id: Uuid, svc_id: Uuid },
RackUpdate(diesel::result::Error),
}
type TxnError = TransactionError<RackInitError>;
// NOTE: This operation could likely be optimized with a CTE, but given
// the low-frequency of calls, this optimization has been deferred.
self.pool_authorized(opctx)
.await?
.transaction(move |conn| {
// Early exit if the rack has already been initialized.
let rack = rack_dsl::rack
.filter(rack_dsl::id.eq(rack_id))
.select(Rack::as_select())
.get_result(conn)
.map_err(|e| {
TxnError::CustomError(RackInitError::RackUpdate(e))
})?;
if rack.initialized {
return Ok(rack);
}
// Otherwise, insert services and set rack.initialized = true.
for svc in services {
let sled_id = svc.sled_id;
<Sled as DatastoreCollection<Service>>::insert_resource(
sled_id,
diesel::insert_into(service_dsl::service)
.values(svc.clone())
.on_conflict(service_dsl::id)
.do_update()
.set((
service_dsl::time_modified.eq(Utc::now()),
service_dsl::sled_id
.eq(excluded(service_dsl::sled_id)),
service_dsl::ip.eq(excluded(service_dsl::ip)),
service_dsl::kind
.eq(excluded(service_dsl::kind)),
)),
)
.insert_and_get_result(conn)
.map_err(|err| {
TxnError::CustomError(RackInitError::ServiceInsert {
err,
sled_id,
svc_id: svc.id(),
})
})?;
}
diesel::update(rack_dsl::rack)
.filter(rack_dsl::id.eq(rack_id))
.set((
rack_dsl::initialized.eq(true),
rack_dsl::time_modified.eq(Utc::now()),
))
.returning(Rack::as_returning())
.get_result::<Rack>(conn)
.map_err(|e| {
TxnError::CustomError(RackInitError::RackUpdate(e))
})
})
.await
.map_err(|e| match e {
TxnError::CustomError(RackInitError::ServiceInsert {
err,
sled_id,
svc_id,
}) => match err {
SyncInsertError::CollectionNotFound => {
Error::ObjectNotFound {
type_name: ResourceType::Sled,
lookup_type: LookupType::ById(sled_id),
}
}
SyncInsertError::DatabaseError(e) => {
public_error_from_diesel_create(
e,
ResourceType::Service,
&svc_id.to_string(),
)
}
},
TxnError::CustomError(RackInitError::RackUpdate(err)) => {
public_error_from_diesel_lookup(
err,
ResourceType::Rack,
&LookupType::ById(rack_id),
)
}
TxnError::Pool(e) => {
Error::internal_error(&format!("Transaction error: {}", e))
}
})
}
/// Stores a new sled in the database.
pub async fn sled_upsert(&self, sled: Sled) -> CreateResult<Sled> {
use db::schema::sled::dsl;
diesel::insert_into(dsl::sled)
.values(sled.clone())
.on_conflict(dsl::id)
.do_update()
.set((
dsl::time_modified.eq(Utc::now()),
dsl::ip.eq(sled.ip),
dsl::port.eq(sled.port),
))
.returning(Sled::as_returning())
.get_result_async(self.pool())
.await
.map_err(|e| {
public_error_from_diesel_pool(
e,
ErrorHandler::Conflict(
ResourceType::Sled,
&sled.id().to_string(),
),
)
})
}
pub async fn sled_list(
&self,
opctx: &OpContext,
pagparams: &DataPageParams<'_, Uuid>,
) -> ListResultVec<Sled> {
opctx.authorize(authz::Action::Read, &authz::FLEET).await?;
use db::schema::sled::dsl;
paginated(dsl::sled, dsl::id, pagparams)
.select(Sled::as_select())
.load_async(self.pool_authorized(opctx).await?)
.await
.map_err(|e| public_error_from_diesel_pool(e, ErrorHandler::Server))
}
/// Stores a new zpool in the database.
pub async fn zpool_upsert(&self, zpool: Zpool) -> CreateResult<Zpool> {
use db::schema::zpool::dsl;
let sled_id = zpool.sled_id;
Sled::insert_resource(
sled_id,
diesel::insert_into(dsl::zpool)
.values(zpool.clone())
.on_conflict(dsl::id)
.do_update()
.set((
dsl::time_modified.eq(Utc::now()),
dsl::sled_id.eq(excluded(dsl::sled_id)),
dsl::total_size.eq(excluded(dsl::total_size)),
)),
)
.insert_and_get_result_async(self.pool())
.await
.map_err(|e| match e {
AsyncInsertError::CollectionNotFound => Error::ObjectNotFound {
type_name: ResourceType::Sled,
lookup_type: LookupType::ById(sled_id),
},
AsyncInsertError::DatabaseError(e) => {
public_error_from_diesel_pool(
e,
ErrorHandler::Conflict(
ResourceType::Zpool,
&zpool.id().to_string(),
),
)
}
})
}
/// Stores a new dataset in the database.
pub async fn dataset_upsert(
&self,
dataset: Dataset,
) -> CreateResult<Dataset> {
use db::schema::dataset::dsl;
let zpool_id = dataset.pool_id;
Zpool::insert_resource(
zpool_id,
diesel::insert_into(dsl::dataset)
.values(dataset.clone())
.on_conflict(dsl::id)
.do_update()
.set((
dsl::time_modified.eq(Utc::now()),
dsl::pool_id.eq(excluded(dsl::pool_id)),
dsl::ip.eq(excluded(dsl::ip)),
dsl::port.eq(excluded(dsl::port)),
dsl::kind.eq(excluded(dsl::kind)),
)),
)
.insert_and_get_result_async(self.pool())
.await
.map_err(|e| match e {
AsyncInsertError::CollectionNotFound => Error::ObjectNotFound {
type_name: ResourceType::Zpool,
lookup_type: LookupType::ById(zpool_id),
},
AsyncInsertError::DatabaseError(e) => {
public_error_from_diesel_pool(
e,
ErrorHandler::Conflict(
ResourceType::Dataset,
&dataset.id().to_string(),
),
)
}
})
}
/// Stores a new service in the database.
pub async fn service_upsert(
&self,
opctx: &OpContext,
service: Service,
) -> CreateResult<Service> {
use db::schema::service::dsl;
let sled_id = service.sled_id;
Sled::insert_resource(
sled_id,
diesel::insert_into(dsl::service)
.values(service.clone())
.on_conflict(dsl::id)
.do_update()
.set((
dsl::time_modified.eq(Utc::now()),
dsl::sled_id.eq(excluded(dsl::sled_id)),
dsl::ip.eq(excluded(dsl::ip)),
dsl::kind.eq(excluded(dsl::kind)),
)),
)
.insert_and_get_result_async(self.pool_authorized(opctx).await?)
.await
.map_err(|e| match e {
AsyncInsertError::CollectionNotFound => Error::ObjectNotFound {
type_name: ResourceType::Sled,
lookup_type: LookupType::ById(sled_id),
},
AsyncInsertError::DatabaseError(e) => {
public_error_from_diesel_pool(
e,
ErrorHandler::Conflict(
ResourceType::Service,
&service.id().to_string(),
),
)
}
})
}
fn get_allocated_regions_query(
volume_id: Uuid,
) -> impl RunnableQuery<(Dataset, Region)> {
use db::schema::dataset::dsl as dataset_dsl;
use db::schema::region::dsl as region_dsl;
region_dsl::region
.filter(region_dsl::volume_id.eq(volume_id))
.inner_join(
dataset_dsl::dataset
.on(region_dsl::dataset_id.eq(dataset_dsl::id)),
)
.select((Dataset::as_select(), Region::as_select()))
}
/// Gets allocated regions for a disk, and the datasets to which those
/// regions belong.
///
/// Note that this function does not validate liveness of the Disk, so it
/// may be used in a context where the disk is being deleted.
pub async fn get_allocated_regions(
&self,
volume_id: Uuid,
) -> Result<Vec<(Dataset, Region)>, Error> {
Self::get_allocated_regions_query(volume_id)
.get_results_async::<(Dataset, Region)>(self.pool())
.await
.map_err(|e| public_error_from_diesel_pool(e, ErrorHandler::Server))
}
fn get_allocatable_datasets_query() -> impl RunnableQuery<Dataset> {
use db::schema::dataset::dsl;
dsl::dataset
// We look for valid datasets (non-deleted crucible datasets).
.filter(dsl::size_used.is_not_null())
.filter(dsl::time_deleted.is_null())
.filter(dsl::kind.eq(DatasetKind::Crucible))
.order(dsl::size_used.asc())
// TODO: We admittedly don't actually *fail* any request for
// running out of space - we try to send the request down to
// crucible agents, and expect them to fail on our behalf in
// out-of-storage conditions. This should undoubtedly be
// handled more explicitly.
.select(Dataset::as_select())
.limit(REGION_REDUNDANCY_THRESHOLD.try_into().unwrap())
}
async fn get_block_size_from_disk_create(
&self,
opctx: &OpContext,
disk_create: ¶ms::DiskCreate,
) -> Result<db::model::BlockSize, Error> {
match &disk_create.disk_source {
params::DiskSource::Blank { block_size } => {
Ok(db::model::BlockSize::try_from(*block_size)
.map_err(|e| Error::invalid_request(&e.to_string()))?)
}
params::DiskSource::Snapshot { snapshot_id: _ } => {
// Until we implement snapshots, do not allow disks to be
// created from a snapshot.
return Err(Error::InvalidValue {
label: String::from("snapshot"),
message: String::from("snapshots are not yet supported"),
});
}
params::DiskSource::Image { image_id: _ } => {
// Until we implement project images, do not allow disks to be
// created from a project image.
return Err(Error::InvalidValue {
label: String::from("image"),
message: String::from(
"project image are not yet supported",
),
});
}
params::DiskSource::GlobalImage { image_id } => {
let (.., db_global_image) = LookupPath::new(opctx, &self)
.global_image_id(*image_id)
.fetch()
.await?;
Ok(db_global_image.block_size)
}
}
}
/// Idempotently allocates enough regions to back a disk.
///
/// Returns the allocated regions, as well as the datasets to which they
/// belong.
pub async fn region_allocate(
&self,
opctx: &OpContext,
volume_id: Uuid,
params: ¶ms::DiskCreate,
) -> Result<Vec<(Dataset, Region)>, Error> {
use db::schema::dataset::dsl as dataset_dsl;
use db::schema::region::dsl as region_dsl;
// ALLOCATION POLICY
//
// NOTE: This policy can - and should! - be changed.
//
// See https://rfd.shared.oxide.computer/rfd/0205 for a more
// complete discussion.
//
// It is currently acting as a placeholder, showing a feasible
// interaction between datasets and regions.
//
// This policy allocates regions to distinct Crucible datasets,
// favoring datasets with the smallest existing (summed) region
// sizes. Basically, "pick the datasets with the smallest load first".
//
// Longer-term, we should consider:
// - Storage size + remaining free space
// - Sled placement of datasets
// - What sort of loads we'd like to create (even split across all disks
// may not be preferable, especially if maintenance is expected)
#[derive(Debug, thiserror::Error)]
enum RegionAllocateError {
#[error("Not enough datasets for replicated allocation: {0}")]
NotEnoughDatasets(usize),
}
type TxnError = TransactionError<RegionAllocateError>;
let params: params::DiskCreate = params.clone();
let block_size =
self.get_block_size_from_disk_create(opctx, ¶ms).await?;
let blocks_per_extent =
params.extent_size() / block_size.to_bytes() as i64;
self.pool()
.transaction(move |conn| {
// First, for idempotency, check if regions are already
// allocated to this disk.
//
// If they are, return those regions and the associated
// datasets.
let datasets_and_regions =
Self::get_allocated_regions_query(volume_id)
.get_results::<(Dataset, Region)>(conn)?;
if !datasets_and_regions.is_empty() {
return Ok(datasets_and_regions);
}
let mut datasets: Vec<Dataset> =
Self::get_allocatable_datasets_query()
.get_results::<Dataset>(conn)?;
if datasets.len() < REGION_REDUNDANCY_THRESHOLD {
return Err(TxnError::CustomError(
RegionAllocateError::NotEnoughDatasets(datasets.len()),
));
}
// Create identical regions on each of the following datasets.
let source_datasets =
&mut datasets[0..REGION_REDUNDANCY_THRESHOLD];
let regions: Vec<Region> = source_datasets
.iter()
.map(|dataset| {
Region::new(
dataset.id(),
volume_id,
block_size.into(),
blocks_per_extent,
params.extent_count(),
)
})
.collect();
let regions = diesel::insert_into(region_dsl::region)
.values(regions)
.returning(Region::as_returning())
.get_results(conn)?;
// Update the tallied sizes in the source datasets containing
// those regions.
let region_size = i64::from(block_size.to_bytes())
* blocks_per_extent
* params.extent_count();
for dataset in source_datasets.iter_mut() {
dataset.size_used =
dataset.size_used.map(|v| v + region_size);
}
let dataset_ids: Vec<Uuid> =
source_datasets.iter().map(|ds| ds.id()).collect();
diesel::update(dataset_dsl::dataset)
.filter(dataset_dsl::id.eq_any(dataset_ids))
.set(
dataset_dsl::size_used
.eq(dataset_dsl::size_used + region_size),
)
.execute(conn)?;
// Return the regions with the datasets to which they were allocated.
Ok(source_datasets
.into_iter()
.map(|d| d.clone())
.zip(regions)
.collect())
})
.await
.map_err(|e| match e {
TxnError::CustomError(
RegionAllocateError::NotEnoughDatasets(_),
) => Error::unavail("Not enough datasets to allocate disks"),
_ => {
Error::internal_error(&format!("Transaction error: {}", e))
}
})
}
/// Deletes all regions backing a disk.
///
/// Also updates the storage usage on their corresponding datasets.
pub async fn regions_hard_delete(&self, volume_id: Uuid) -> DeleteResult {
use db::schema::dataset::dsl as dataset_dsl;
use db::schema::region::dsl as region_dsl;
// Remove the regions, collecting datasets they're from.
let (dataset_id, size) = diesel::delete(region_dsl::region)
.filter(region_dsl::volume_id.eq(volume_id))
.returning((
region_dsl::dataset_id,
region_dsl::block_size
* region_dsl::blocks_per_extent
* region_dsl::extent_count,
))
.get_result_async::<(Uuid, i64)>(self.pool())
.await
.map_err(|e| {
Error::internal_error(&format!(
"error deleting regions: {:?}",
e
))
})?;
// Update those datasets to which the regions belonged.
diesel::update(dataset_dsl::dataset)
.filter(dataset_dsl::id.eq(dataset_id))
.set(dataset_dsl::size_used.eq(dataset_dsl::size_used - size))
.execute_async(self.pool())
.await
.map_err(|e| {
Error::internal_error(&format!(
"error updating dataset space: {:?}",
e
))
})?;
Ok(())
}
pub async fn volume_create(&self, volume: Volume) -> CreateResult<Volume> {
use db::schema::volume::dsl;
diesel::insert_into(dsl::volume)
.values(volume.clone())
.on_conflict(dsl::id)
.do_nothing()
.returning(Volume::as_returning())
.get_result_async(self.pool())
.await
.map_err(|e| {
public_error_from_diesel_pool(
e,
ErrorHandler::Conflict(
ResourceType::Volume,
volume.id().to_string().as_str(),
),
)
})
}
pub async fn volume_delete(&self, volume_id: Uuid) -> DeleteResult {
use db::schema::volume::dsl;
let now = Utc::now();
diesel::update(dsl::volume)
.filter(dsl::id.eq(volume_id))
.set(dsl::time_deleted.eq(now))
.check_if_exists::<Volume>(volume_id)
.execute_and_check(self.pool())
.await
.map_err(|e| {
public_error_from_diesel_pool(
e,
ErrorHandler::NotFoundByLookup(
ResourceType::Volume,
LookupType::ById(volume_id),
),
)
})?;
Ok(())
}
pub async fn volume_get(&self, volume_id: Uuid) -> LookupResult<Volume> {
use db::schema::volume::dsl;
dsl::volume
.filter(dsl::id.eq(volume_id))
.select(Volume::as_select())
.get_result_async(self.pool())
.await
.map_err(|e| public_error_from_diesel_pool(e, ErrorHandler::Server))
}
/// Create a organization
pub async fn organization_create(
&self,
opctx: &OpContext,
organization: ¶ms::OrganizationCreate,
) -> CreateResult<Organization> {
let authz_silo = opctx.authn.silo_required()?;
opctx.authorize(authz::Action::CreateChild, &authz_silo).await?;
use db::schema::organization::dsl;
let silo_id = authz_silo.id();
let organization = Organization::new(organization.clone(), silo_id);
let name = organization.name().as_str().to_string();
Silo::insert_resource(
silo_id,
diesel::insert_into(dsl::organization).values(organization),
)
.insert_and_get_result_async(self.pool_authorized(opctx).await?)
.await
.map_err(|e| match e {
AsyncInsertError::CollectionNotFound => Error::InternalError {
internal_message: format!(
"attempting to create an \
organization under non-existent silo {}",
silo_id
),
},
AsyncInsertError::DatabaseError(e) => {
public_error_from_diesel_pool(
e,
ErrorHandler::Conflict(ResourceType::Organization, &name),
)
}
})
}
/// Delete a organization
pub async fn organization_delete(
&self,
opctx: &OpContext,
authz_org: &authz::Organization,
db_org: &db::model::Organization,
) -> DeleteResult {
opctx.authorize(authz::Action::Delete, authz_org).await?;
use db::schema::organization::dsl;
use db::schema::project;
// Make sure there are no projects present within this organization.
let project_found = diesel_pool_result_optional(
project::dsl::project
.filter(project::dsl::organization_id.eq(authz_org.id()))
.filter(project::dsl::time_deleted.is_null())
.select(project::dsl::id)
.limit(1)
.first_async::<Uuid>(self.pool_authorized(opctx).await?)
.await,
)
.map_err(|e| public_error_from_diesel_pool(e, ErrorHandler::Server))?;
if project_found.is_some() {
return Err(Error::InvalidRequest {
message: "organization to be deleted contains a project"
.to_string(),
});
}
let now = Utc::now();
let updated_rows = diesel::update(dsl::organization)
.filter(dsl::time_deleted.is_null())
.filter(dsl::id.eq(authz_org.id()))
.filter(dsl::rcgen.eq(db_org.rcgen))
.set(dsl::time_deleted.eq(now))
.execute_async(self.pool_authorized(opctx).await?)
.await
.map_err(|e| {
public_error_from_diesel_pool(
e,
ErrorHandler::NotFoundByResource(authz_org),
)
})?;
if updated_rows == 0 {
return Err(Error::InvalidRequest {
message: "deletion failed due to concurrent modification"
.to_string(),
});
}
Ok(())
}
pub async fn organizations_list_by_id(
&self,
opctx: &OpContext,
pagparams: &DataPageParams<'_, Uuid>,
) -> ListResultVec<Organization> {
let authz_silo = opctx.authn.silo_required()?;
opctx.authorize(authz::Action::ListChildren, &authz_silo).await?;
use db::schema::organization::dsl;
paginated(dsl::organization, dsl::id, pagparams)
.filter(dsl::time_deleted.is_null())
.filter(dsl::silo_id.eq(authz_silo.id()))
.select(Organization::as_select())
.load_async::<Organization>(self.pool_authorized(opctx).await?)
.await
.map_err(|e| public_error_from_diesel_pool(e, ErrorHandler::Server))
}
pub async fn organizations_list_by_name(
&self,
opctx: &OpContext,
pagparams: &DataPageParams<'_, Name>,
) -> ListResultVec<Organization> {
let authz_silo = opctx.authn.silo_required()?;
opctx.authorize(authz::Action::ListChildren, &authz_silo).await?;
use db::schema::organization::dsl;
paginated(dsl::organization, dsl::name, pagparams)
.filter(dsl::time_deleted.is_null())
.filter(dsl::silo_id.eq(authz_silo.id()))
.select(Organization::as_select())
.load_async::<Organization>(self.pool_authorized(opctx).await?)
.await
.map_err(|e| public_error_from_diesel_pool(e, ErrorHandler::Server))
}
/// Updates a organization by name (clobbering update -- no etag)
pub async fn organization_update(
&self,
opctx: &OpContext,
authz_org: &authz::Organization,
updates: OrganizationUpdate,
) -> UpdateResult<Organization> {
use db::schema::organization::dsl;
opctx.authorize(authz::Action::Modify, authz_org).await?;
diesel::update(dsl::organization)
.filter(dsl::time_deleted.is_null())
.filter(dsl::id.eq(authz_org.id()))
.set(updates)
.returning(Organization::as_returning())
.get_result_async(self.pool_authorized(opctx).await?)
.await
.map_err(|e| {
public_error_from_diesel_pool(
e,
ErrorHandler::NotFoundByResource(authz_org),
)
})
}
/// Create a project
pub async fn project_create(
&self,
opctx: &OpContext,
org: &authz::Organization,
project: Project,
) -> CreateResult<Project> {
use db::schema::project::dsl;
opctx.authorize(authz::Action::CreateChild, org).await?;
let name = project.name().as_str().to_string();
let organization_id = project.organization_id;
Organization::insert_resource(
organization_id,
diesel::insert_into(dsl::project).values(project),
)
.insert_and_get_result_async(self.pool_authorized(opctx).await?)
.await
.map_err(|e| match e {
AsyncInsertError::CollectionNotFound => Error::ObjectNotFound {
type_name: ResourceType::Organization,
lookup_type: LookupType::ById(organization_id),
},
AsyncInsertError::DatabaseError(e) => {
public_error_from_diesel_pool(
e,
ErrorHandler::Conflict(ResourceType::Project, &name),
)
}
})
}
/// Delete a project
// TODO-correctness This needs to check whether there are any resources that
// depend on the Project (Disks, Instances). We can do this with a
// generation counter that gets bumped when these resources are created.
pub async fn project_delete(
&self,
opctx: &OpContext,
authz_project: &authz::Project,
) -> DeleteResult {
opctx.authorize(authz::Action::Delete, authz_project).await?;
use db::schema::project::dsl;
let now = Utc::now();
diesel::update(dsl::project)
.filter(dsl::time_deleted.is_null())
.filter(dsl::id.eq(authz_project.id()))
.set(dsl::time_deleted.eq(now))
.returning(Project::as_returning())
.get_result_async(self.pool_authorized(opctx).await?)
.await
.map_err(|e| {
public_error_from_diesel_pool(
e,
ErrorHandler::NotFoundByResource(authz_project),
)
})?;
Ok(())
}
pub async fn projects_list_by_id(
&self,
opctx: &OpContext,
authz_org: &authz::Organization,
pagparams: &DataPageParams<'_, Uuid>,
) -> ListResultVec<Project> {
use db::schema::project::dsl;
opctx.authorize(authz::Action::ListChildren, authz_org).await?;
paginated(dsl::project, dsl::id, pagparams)
.filter(dsl::organization_id.eq(authz_org.id()))
.filter(dsl::time_deleted.is_null())
.select(Project::as_select())
.load_async(self.pool_authorized(opctx).await?)
.await
.map_err(|e| public_error_from_diesel_pool(e, ErrorHandler::Server))
}
pub async fn projects_list_by_name(
&self,
opctx: &OpContext,
authz_org: &authz::Organization,
pagparams: &DataPageParams<'_, Name>,
) -> ListResultVec<Project> {
use db::schema::project::dsl;
opctx.authorize(authz::Action::ListChildren, authz_org).await?;
paginated(dsl::project, dsl::name, &pagparams)
.filter(dsl::organization_id.eq(authz_org.id()))
.filter(dsl::time_deleted.is_null())
.select(Project::as_select())