-
Notifications
You must be signed in to change notification settings - Fork 40
/
nexus.rs
2527 lines (2343 loc) · 84.5 KB
/
nexus.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/.
/*!
* Nexus, the service that operates much of the control plane in an Oxide fleet
*/
use crate::authn;
use crate::authz;
use crate::config;
use crate::context::OpContext;
use crate::db;
use crate::db::identity::{Asset, Resource};
use crate::db::model::DatasetKind;
use crate::db::model::Name;
use crate::external_api::params;
use crate::internal_api::params::{OximeterInfo, ZpoolPutRequest};
use crate::populate::populate_start;
use crate::populate::PopulateStatus;
use crate::saga_interface::SagaContext;
use crate::sagas;
use anyhow::anyhow;
use anyhow::Context;
use async_trait::async_trait;
use futures::future::ready;
use futures::StreamExt;
use hex;
use ipnetwork::Ipv4Network;
use ipnetwork::Ipv6Network;
use lazy_static::lazy_static;
use omicron_common::api::external;
use omicron_common::api::external::CreateResult;
use omicron_common::api::external::DataPageParams;
use omicron_common::api::external::DeleteResult;
use omicron_common::api::external::Disk;
use omicron_common::api::external::DiskState;
use omicron_common::api::external::Error;
use omicron_common::api::external::IdentityMetadataCreateParams;
use omicron_common::api::external::InstanceState;
use omicron_common::api::external::Ipv4Net;
use omicron_common::api::external::Ipv6Net;
use omicron_common::api::external::ListResult;
use omicron_common::api::external::ListResultVec;
use omicron_common::api::external::LookupResult;
use omicron_common::api::external::LookupType;
use omicron_common::api::external::PaginationOrder;
use omicron_common::api::external::ResourceType;
use omicron_common::api::external::RouteDestination;
use omicron_common::api::external::RouteTarget;
use omicron_common::api::external::RouterRouteCreateParams;
use omicron_common::api::external::RouterRouteKind;
use omicron_common::api::external::RouterRouteUpdateParams;
use omicron_common::api::external::UpdateResult;
use omicron_common::api::external::VpcFirewallRuleUpdateParams;
use omicron_common::api::external::VpcFirewallRuleUpdateResult;
use omicron_common::api::external::VpcRouterKind;
use omicron_common::api::internal::nexus;
use omicron_common::api::internal::nexus::DiskRuntimeState;
use omicron_common::api::internal::sled_agent::InstanceRuntimeStateRequested;
use omicron_common::api::internal::sled_agent::InstanceStateRequested;
use omicron_common::backoff;
use omicron_common::bail_unless;
use oximeter_client::Client as OximeterClient;
use oximeter_db::TimeseriesSchema;
use oximeter_db::TimeseriesSchemaPaginationParams;
use oximeter_producer::register;
use rand::{rngs::StdRng, RngCore, SeedableRng};
use sled_agent_client::Client as SledAgentClient;
use slog::Logger;
use std::convert::TryInto;
use std::net::SocketAddr;
use std::num::NonZeroU32;
use std::sync::Arc;
use std::time::Duration;
use steno::SagaId;
use steno::SagaResultOk;
use steno::SagaTemplate;
use steno::SagaType;
use uuid::Uuid;
// TODO: When referring to API types, we should try to include
// the prefix unless it is unambiguous.
/**
* Exposes additional [`Nexus`] interfaces for use by the test suite
*/
#[async_trait]
pub trait TestInterfaces {
/**
* Returns the SledAgentClient for an Instance from its id. We may also
* want to split this up into instance_lookup_by_id() and instance_sled(),
* but after all it's a test suite special to begin with.
*/
async fn instance_sled_by_id(
&self,
id: &Uuid,
) -> Result<Arc<SledAgentClient>, Error>;
/**
* Returns the SledAgentClient for a Disk from its id.
*/
async fn disk_sled_by_id(
&self,
id: &Uuid,
) -> Result<Arc<SledAgentClient>, Error>;
async fn session_create_with(
&self,
session: db::model::ConsoleSession,
) -> CreateResult<db::model::ConsoleSession>;
}
/**
* Manages an Oxide fleet -- the heart of the control plane
*/
pub struct Nexus {
/** uuid for this nexus instance. */
id: Uuid,
/** uuid for this rack (TODO should also be in persistent storage) */
rack_id: Uuid,
/** general server log */
log: Logger,
/** cached rack identity metadata */
api_rack_identity: db::model::RackIdentity,
/** persistent storage for resources in the control plane */
db_datastore: Arc<db::DataStore>,
/** saga execution coordinator */
sec_client: Arc<steno::SecClient>,
/** Task representing completion of recovered Sagas */
recovery_task: std::sync::Mutex<Option<db::RecoveryTask>>,
/** Status of background task to populate database */
populate_status: tokio::sync::watch::Receiver<PopulateStatus>,
/** Client to the timeseries database. */
timeseries_client: oximeter_db::Client,
}
/*
* TODO Is it possible to make some of these operations more generic? A
* particularly good example is probably list() (or even lookup()), where
* with the right type parameters, generic code can be written to work on all
* types.
* TODO update and delete need to accommodate both with-etag and don't-care
* TODO audit logging ought to be part of this structure and its functions
*/
impl Nexus {
/**
* Create a new Nexus instance for the given rack id `rack_id`
*/
/* TODO-polish revisit rack metadata */
pub fn new_with_id(
rack_id: &Uuid,
log: Logger,
pool: db::Pool,
config: &config::Config,
authz: Arc<authz::Authz>,
) -> Arc<Nexus> {
let pool = Arc::new(pool);
let my_sec_id = db::SecId::from(config.id);
let db_datastore = Arc::new(db::DataStore::new(Arc::clone(&pool)));
let sec_store = Arc::new(db::CockroachDbSecStore::new(
my_sec_id,
Arc::clone(&db_datastore),
log.new(o!("component" => "SecStore")),
)) as Arc<dyn steno::SecStore>;
let sec_client = Arc::new(steno::sec(
log.new(o!(
"component" => "SEC",
"sec_id" => my_sec_id.to_string()
)),
sec_store,
));
let timeseries_client =
oximeter_db::Client::new(config.timeseries_db.address, &log);
/*
* TODO-cleanup We may want a first-class subsystem for managing startup
* background tasks. It could use a Future for each one, a status enum
* for each one, status communication via channels, and a single task to
* run them all.
*/
let populate_ctx = OpContext::for_background(
log.new(o!("component" => "DataLoader")),
Arc::clone(&authz),
authn::Context::internal_db_init(),
Arc::clone(&db_datastore),
);
let populate_status =
populate_start(populate_ctx, Arc::clone(&db_datastore));
let nexus = Nexus {
id: config.id,
rack_id: *rack_id,
log: log.new(o!()),
api_rack_identity: db::model::RackIdentity::new(*rack_id),
db_datastore: Arc::clone(&db_datastore),
sec_client: Arc::clone(&sec_client),
recovery_task: std::sync::Mutex::new(None),
populate_status,
timeseries_client,
};
/* TODO-cleanup all the extra Arcs here seems wrong */
let nexus_arc = Arc::new(nexus);
let opctx = OpContext::for_background(
log.new(o!("component" => "SagaRecoverer")),
authz,
authn::Context::internal_saga_recovery(),
Arc::clone(&db_datastore),
);
let recovery_task = db::recover(
opctx,
my_sec_id,
Arc::new(Arc::new(SagaContext::new(Arc::clone(&nexus_arc)))),
db_datastore,
Arc::clone(&sec_client),
&sagas::ALL_TEMPLATES,
);
*nexus_arc.recovery_task.lock().unwrap() = Some(recovery_task);
nexus_arc
}
pub async fn wait_for_populate(&self) -> Result<(), anyhow::Error> {
let mut my_rx = self.populate_status.clone();
loop {
my_rx
.changed()
.await
.map_err(|error| anyhow!(error.to_string()))?;
match &*my_rx.borrow() {
PopulateStatus::NotDone => (),
PopulateStatus::Done => return Ok(()),
PopulateStatus::Failed(error) => {
return Err(anyhow!(error.clone()))
}
};
}
}
/*
* TODO-robustness we should have a limit on how many sled agents there can
* be (for graceful degradation at large scale).
*/
pub async fn upsert_sled(
&self,
id: Uuid,
address: SocketAddr,
) -> Result<(), Error> {
info!(self.log, "registered sled agent"; "sled_uuid" => id.to_string());
let sled = db::model::Sled::new(id, address);
self.db_datastore.sled_upsert(sled).await?;
Ok(())
}
/// Upserts a Zpool into the database, updating it if it already exists.
pub async fn upsert_zpool(
&self,
id: Uuid,
sled_id: Uuid,
info: ZpoolPutRequest,
) -> Result<(), Error> {
info!(self.log, "upserting zpool"; "sled_id" => sled_id.to_string(), "zpool_id" => id.to_string());
let zpool = db::model::Zpool::new(id, sled_id, &info);
self.db_datastore.zpool_upsert(zpool).await?;
Ok(())
}
/// Upserts a dataset into the database, updating it if it already exists.
pub async fn upsert_dataset(
&self,
id: Uuid,
zpool_id: Uuid,
address: SocketAddr,
kind: DatasetKind,
) -> Result<(), Error> {
info!(self.log, "upserting dataset"; "zpool_id" => zpool_id.to_string(), "dataset_id" => id.to_string());
let dataset = db::model::Dataset::new(id, zpool_id, address, kind);
self.db_datastore.dataset_upsert(dataset).await?;
Ok(())
}
/**
* Insert a new record of an Oximeter collector server.
*/
pub async fn upsert_oximeter_collector(
&self,
oximeter_info: &OximeterInfo,
) -> Result<(), Error> {
// Insert the Oximeter instance into the DB. Note that this _updates_ the record,
// specifically, the time_modified, ip, and port columns, if the instance has already been
// registered.
let db_info = db::model::OximeterInfo::new(&oximeter_info);
self.db_datastore.oximeter_create(&db_info).await?;
info!(
self.log,
"registered new oximeter metric collection server";
"collector_id" => ?oximeter_info.collector_id,
"address" => oximeter_info.address,
);
// Regardless, notify the collector of any assigned metric producers. This should be empty
// if this Oximeter collector is registering for the first time, but may not be if the
// service is re-registering after failure.
let pagparams = DataPageParams {
marker: None,
direction: PaginationOrder::Ascending,
limit: std::num::NonZeroU32::new(100).unwrap(),
};
let producers = self
.db_datastore
.producers_list_by_oximeter_id(
oximeter_info.collector_id,
&pagparams,
)
.await?;
if !producers.is_empty() {
debug!(
self.log,
"registered oximeter collector that is already assigned producers, re-assigning them to the collector";
"n_producers" => producers.len(),
"collector_id" => ?oximeter_info.collector_id,
);
let client = self.build_oximeter_client(
&oximeter_info.collector_id,
oximeter_info.address,
);
for producer in producers.into_iter() {
let producer_info = oximeter_client::types::ProducerEndpoint {
id: producer.id(),
address: SocketAddr::new(
producer.ip.ip(),
producer.port.try_into().unwrap(),
)
.to_string(),
base_route: producer.base_route,
interval: oximeter_client::types::Duration::from(
Duration::from_secs_f64(producer.interval),
),
};
client
.producers_post(&producer_info)
.await
.map_err(Error::from)?;
}
}
Ok(())
}
/// Register as a metric producer with the oximeter metric collection server.
pub async fn register_as_producer(&self, address: SocketAddr) {
let producer_endpoint = nexus::ProducerEndpoint {
id: self.id,
address,
base_route: String::from("/metrics/collect"),
interval: Duration::from_secs(10),
};
let register = || async {
debug!(self.log, "registering nexus as metric producer");
register(address, &self.log, &producer_endpoint)
.await
.map_err(backoff::BackoffError::Transient)
};
let log_registration_failure = |error, delay| {
warn!(
self.log,
"failed to register nexus as a metric producer, will retry in {:?}", delay;
"error_message" => ?error,
);
};
backoff::retry_notify(
backoff::internal_service_policy(),
register,
log_registration_failure,
).await
.expect("expected an infinite retry loop registering nexus as a metric producer");
}
// Internal helper to build an Oximeter client from its ID and address (common data between
// model type and the API type).
fn build_oximeter_client(
&self,
id: &Uuid,
address: SocketAddr,
) -> OximeterClient {
let client_log =
self.log.new(o!("oximeter-collector" => id.to_string()));
let client =
OximeterClient::new(&format!("http://{}", address), client_log);
info!(
self.log,
"registered oximeter collector client";
"id" => id.to_string(),
);
client
}
/**
* List all registered Oximeter collector instances.
*/
pub async fn oximeter_list(
&self,
page_params: &DataPageParams<'_, Uuid>,
) -> ListResultVec<db::model::OximeterInfo> {
self.db_datastore.oximeter_list(page_params).await
}
pub fn datastore(&self) -> &Arc<db::DataStore> {
&self.db_datastore
}
/**
* Given a saga template and parameters, create a new saga and execute it.
*/
async fn execute_saga<P, S>(
self: &Arc<Self>,
saga_template: Arc<SagaTemplate<S>>,
template_name: &str,
saga_params: Arc<P>,
) -> Result<SagaResultOk, Error>
where
S: SagaType<
ExecContextType = Arc<SagaContext>,
SagaParamsType = Arc<P>,
>,
/*
* TODO-cleanup The bound `P: Serialize` should not be necessary because
* SagaParamsType must already impl Serialize.
*/
P: serde::Serialize,
{
let saga_id = SagaId(Uuid::new_v4());
let saga_context =
Arc::new(Arc::new(SagaContext::new(Arc::clone(self))));
let future = self
.sec_client
.saga_create(
saga_id,
saga_context,
saga_template,
template_name.to_owned(),
saga_params,
)
.await
.context("creating saga")
.map_err(|error| {
/*
* TODO-error This could be a service unavailable error,
* depending on the failure mode. We need more information from
* Steno.
*/
Error::internal_error(&format!("{:#}", error))
})?;
self.sec_client
.saga_start(saga_id)
.await
.context("starting saga")
.map_err(|error| Error::internal_error(&format!("{:#}", error)))?;
let result = future.await;
result.kind.map_err(|saga_error| {
saga_error.error_source.convert::<Error>().unwrap_or_else(|e| {
/* TODO-error more context would be useful */
Error::InternalError { internal_message: e.to_string() }
})
})
}
/*
* Organizations
*/
pub async fn organization_create(
&self,
opctx: &OpContext,
new_organization: ¶ms::OrganizationCreate,
) -> CreateResult<db::model::Organization> {
let db_org = db::model::Organization::new(new_organization.clone());
self.db_datastore.organization_create(opctx, db_org).await
}
pub async fn organization_fetch(
&self,
opctx: &OpContext,
name: &Name,
) -> LookupResult<db::model::Organization> {
Ok(self.db_datastore.organization_fetch(opctx, name).await?.1)
}
pub async fn organizations_list_by_name(
&self,
opctx: &OpContext,
pagparams: &DataPageParams<'_, Name>,
) -> ListResultVec<db::model::Organization> {
self.db_datastore.organizations_list_by_name(opctx, pagparams).await
}
pub async fn organizations_list_by_id(
&self,
opctx: &OpContext,
pagparams: &DataPageParams<'_, Uuid>,
) -> ListResultVec<db::model::Organization> {
self.db_datastore.organizations_list_by_id(opctx, pagparams).await
}
pub async fn organization_delete(
&self,
opctx: &OpContext,
name: &Name,
) -> DeleteResult {
self.db_datastore.organization_delete(opctx, name).await
}
pub async fn organization_update(
&self,
opctx: &OpContext,
name: &Name,
new_params: ¶ms::OrganizationUpdate,
) -> UpdateResult<db::model::Organization> {
self.db_datastore
.organization_update(opctx, name, new_params.clone().into())
.await
}
/*
* Projects
*/
pub async fn project_create(
&self,
opctx: &OpContext,
organization_name: &Name,
new_project: ¶ms::ProjectCreate,
) -> CreateResult<db::model::Project> {
let org =
self.db_datastore.organization_lookup_id(organization_name).await?;
// Create a project.
let db_project = db::model::Project::new(org.id(), new_project.clone());
let db_project =
self.db_datastore.project_create(opctx, &org, db_project).await?;
// TODO: We probably want to have "project creation" and "default VPC
// creation" co-located within a saga for atomicity.
//
// Until then, we just perform the operations sequentially.
// Create a default VPC associated with the project.
let _ = self
.project_create_vpc(
&organization_name,
&new_project.identity.name.clone().into(),
¶ms::VpcCreate {
identity: IdentityMetadataCreateParams {
name: "default".parse().unwrap(),
description: "Default VPC".to_string(),
},
// TODO-robustness this will need to be None if we decide to
// handle the logic around name and dns_name by making
// dns_name optional
dns_name: "default".parse().unwrap(),
},
)
.await?;
Ok(db_project)
}
pub async fn project_fetch(
&self,
organization_name: &Name,
project_name: &Name,
) -> LookupResult<db::model::Project> {
let organization_id = self
.db_datastore
.organization_lookup_id(organization_name)
.await?
.id();
self.db_datastore.project_fetch(&organization_id, project_name).await
}
pub async fn projects_list_by_name(
&self,
organization_name: &Name,
pagparams: &DataPageParams<'_, Name>,
) -> ListResultVec<db::model::Project> {
let organization_id = self
.db_datastore
.organization_lookup_id(organization_name)
.await?
.id();
self.db_datastore
.projects_list_by_name(&organization_id, pagparams)
.await
}
pub async fn projects_list_by_id(
&self,
organization_name: &Name,
pagparams: &DataPageParams<'_, Uuid>,
) -> ListResultVec<db::model::Project> {
let organization_id = self
.db_datastore
.organization_lookup_id(organization_name)
.await?
.id();
self.db_datastore.projects_list_by_id(&organization_id, pagparams).await
}
pub async fn project_delete(
&self,
organization_name: &Name,
project_name: &Name,
) -> DeleteResult {
let organization_id = self
.db_datastore
.organization_lookup_id(organization_name)
.await?
.id();
self.db_datastore.project_delete(&organization_id, project_name).await
}
pub async fn project_update(
&self,
organization_name: &Name,
project_name: &Name,
new_params: ¶ms::ProjectUpdate,
) -> UpdateResult<db::model::Project> {
let organization_id = self
.db_datastore
.organization_lookup_id(organization_name)
.await?
.id();
self.db_datastore
.project_update(
&organization_id,
project_name,
new_params.clone().into(),
)
.await
}
/*
* Disks
*/
pub async fn project_list_disks(
&self,
organization_name: &Name,
project_name: &Name,
pagparams: &DataPageParams<'_, Name>,
) -> ListResultVec<db::model::Disk> {
let organization_id = self
.db_datastore
.organization_lookup_id(organization_name)
.await?
.id();
let project_id = self
.db_datastore
.project_lookup_id_by_name(&organization_id, project_name)
.await?;
self.db_datastore.project_list_disks(&project_id, pagparams).await
}
pub async fn project_create_disk(
&self,
organization_name: &Name,
project_name: &Name,
params: ¶ms::DiskCreate,
) -> CreateResult<db::model::Disk> {
let project =
self.project_fetch(organization_name, project_name).await?;
/*
* Until we implement snapshots, do not allow disks to be created with a
* snapshot id.
*/
if params.snapshot_id.is_some() {
return Err(Error::InvalidValue {
label: String::from("snapshot_id"),
message: String::from("snapshots are not yet supported"),
});
}
let disk_id = Uuid::new_v4();
let disk = db::model::Disk::new(
disk_id,
project.id(),
params.clone(),
db::model::DiskRuntimeState::new(),
);
let disk_created = self.db_datastore.project_create_disk(disk).await?;
// TODO: Here, we should ensure the disk is backed by appropriate
// regions. This is blocked behind actually having Crucible agents
// running in zones for dedicated zpools.
//
// TODO: Performing this operation, alongside "create" and "update
// state from create to detach", should be executed in a Saga.
/*
* This is a little hokey. We'd like to simulate an asynchronous
* transition from "Creating" to "Detached". For instances, the
* simulation lives in a simulated sled agent. Here, the analog might
* be a simulated storage control plane. But that doesn't exist yet,
* and we don't even know what APIs it would provide yet. So we just
* carry out the simplest possible "simulation" here: we'll return to
* the client a structure describing a disk in state "Creating", but by
* the time we do so, we've already updated the internal representation
* to "Created".
*/
self.db_datastore
.disk_update_runtime(&disk_id, &disk_created.runtime().detach())
.await?;
Ok(disk_created)
}
pub async fn project_lookup_disk(
&self,
organization_name: &Name,
project_name: &Name,
disk_name: &Name,
) -> LookupResult<(db::model::Disk, authz::ProjectChild)> {
let organization_id = self
.db_datastore
.organization_lookup_id(organization_name)
.await?
.id();
let project_id = self
.db_datastore
.project_lookup_id_by_name(&organization_id, project_name)
.await?;
let disk = self
.db_datastore
.disk_fetch_by_name(&project_id, disk_name)
.await?;
let disk_id = disk.id();
Ok((
disk,
authz::FLEET
.organization(
organization_id,
LookupType::from(&organization_name.0),
)
.project(project_id, LookupType::from(&project_name.0))
.child_generic(
ResourceType::Disk,
disk_id,
LookupType::from(&disk_name.0),
),
))
}
pub async fn project_delete_disk(
&self,
opctx: &OpContext,
organization_name: &Name,
project_name: &Name,
disk_name: &Name,
) -> DeleteResult {
let (disk, authz_disk) = self
.project_lookup_disk(organization_name, project_name, disk_name)
.await?;
let runtime = disk.runtime();
bail_unless!(runtime.state().state() != &DiskState::Destroyed);
if runtime.state().is_attached() {
return Err(Error::InvalidRequest {
message: String::from("disk is attached"),
});
}
/*
* TODO-correctness It's not clear how this handles the case where we
* begin this delete operation while some other request is ongoing to
* attach the disk. We won't be able to see that in the state here. We
* might be able to detect this when we go update the disk's state to
* Attaching (because a SQL UPDATE will update 0 rows), but we'd sort of
* already be in a bad state because the destroyed disk will be
* attaching (and eventually attached) on some sled, and if the wrong
* combination of components crash at this point, we could wind up not
* fixing that state.
*
* This is a consequence of the choice _not_ to record the Attaching
* state in the database before beginning the attach process. If we did
* that, we wouldn't have this problem, but we'd have a similar problem
* of dealing with the case of a crash after recording this state and
* before actually beginning the attach process. Sagas can maybe
* address that.
*/
self.db_datastore.project_delete_disk(opctx, &authz_disk).await
}
/*
* Instances
*/
/*
* TODO-design This interface should not exist. See
* SagaContext::alloc_server().
*/
pub async fn sled_allocate(&self) -> Result<Uuid, Error> {
// TODO: replace this with a real allocation policy.
//
// This implementation always assigns the first sled (by ID order).
let pagparams = DataPageParams {
marker: None,
direction: dropshot::PaginationOrder::Ascending,
limit: std::num::NonZeroU32::new(1).unwrap(),
};
let sleds = self.db_datastore.sled_list(&pagparams).await?;
sleds
.first()
.ok_or_else(|| Error::ServiceUnavailable {
internal_message: String::from(
"no sleds available for new Instance",
),
})
.map(|s| s.id())
}
pub async fn project_list_instances(
&self,
organization_name: &Name,
project_name: &Name,
pagparams: &DataPageParams<'_, Name>,
) -> ListResultVec<db::model::Instance> {
let organization_id = self
.db_datastore
.organization_lookup_id(organization_name)
.await?
.id();
let project_id = self
.db_datastore
.project_lookup_id_by_name(&organization_id, project_name)
.await?;
self.db_datastore.project_list_instances(&project_id, pagparams).await
}
pub async fn project_create_instance(
self: &Arc<Self>,
organization_name: &Name,
project_name: &Name,
params: ¶ms::InstanceCreate,
) -> CreateResult<db::model::Instance> {
let organization_id = self
.db_datastore
.organization_lookup_id(organization_name)
.await?
.id();
let project_id = self
.db_datastore
.project_lookup_id_by_name(&organization_id, project_name)
.await?;
let saga_params = Arc::new(sagas::ParamsInstanceCreate {
project_id,
create_params: params.clone(),
});
let saga_outputs = self
.execute_saga(
Arc::clone(&sagas::SAGA_INSTANCE_CREATE_TEMPLATE),
sagas::SAGA_INSTANCE_CREATE_NAME,
saga_params,
)
.await?;
/* TODO-error more context would be useful */
let instance_id =
saga_outputs.lookup_output::<Uuid>("instance_id").map_err(|e| {
Error::InternalError { internal_message: e.to_string() }
})?;
/*
* TODO-correctness TODO-robustness TODO-design It's not quite correct
* to take this instance id and look it up again. It's possible that
* it's been modified or even deleted since the saga executed. In that
* case, we might return a different state of the Instance than the one
* that the user created or even fail with a 404! Both of those are
* wrong behavior -- we should be returning the very instance that the
* user created.
*
* How can we fix this? Right now we have internal representations like
* Instance and analaogous end-user-facing representations like
* Instance. The former is not even serializable. The saga
* _could_ emit the View version, but that's not great for two (related)
* reasons: (1) other sagas might want to provision instances and get
* back the internal representation to do other things with the
* newly-created instance, and (2) even within a saga, it would be
* useful to pass a single Instance representation along the saga,
* but they probably would want the internal representation, not the
* view.
*
* The saga could emit an Instance directly. Today, Instance
* etc. aren't supposed to even be serializable -- we wanted to be able
* to have other datastore state there if needed. We could have a third
* InstanceInternalView...but that's starting to feel pedantic. We
* could just make Instance serializable, store that, and call it a
* day. Does it matter that we might have many copies of the same
* objects in memory?
*
* If we make these serializable, it would be nice if we could leverage
* the type system to ensure that we never accidentally send them out a
* dropshot endpoint. (On the other hand, maybe we _do_ want to do
* that, for internal interfaces! Can we do this on a
* per-dropshot-server-basis?)
*/
let instance = self.db_datastore.instance_fetch(&instance_id).await?;
Ok(instance)
}
/*
* TODO-correctness It's not totally clear what the semantics and behavior
* should be here. It might be nice to say that you can only do this
* operation if the Instance is already stopped, in which case we can
* execute this immediately by just removing it from the database, with the
* same race we have with disk delete (i.e., if someone else is requesting
* an instance boot, we may wind up in an inconsistent state). On the other
* hand, we could always allow this operation, issue the request to the SA
* to destroy the instance (not just stop it), and proceed with deletion
* when that finishes. But in that case, although the HTTP DELETE request
* completed, the object will still appear for a little while, which kind of
* sucks.
*/
pub async fn project_destroy_instance(
&self,
organization_name: &Name,
project_name: &Name,
instance_name: &Name,
) -> DeleteResult {
/*
* TODO-robustness We need to figure out what to do with Destroyed
* instances? Presumably we need to clean them up at some point, but
* not right away so that callers can see that they've been destroyed.
*/
let organization_id = self
.db_datastore
.organization_lookup_id(organization_name)
.await?
.id();
let project_id = self
.db_datastore
.project_lookup_id_by_name(&organization_id, project_name)
.await?;
let instance = self
.db_datastore
.instance_fetch_by_name(&project_id, instance_name)
.await?;
self.db_datastore.project_delete_instance(&instance.id()).await
}
pub async fn project_lookup_instance(
&self,
organization_name: &Name,
project_name: &Name,
instance_name: &Name,
) -> LookupResult<db::model::Instance> {
let organization_id = self
.db_datastore
.organization_lookup_id(organization_name)
.await?
.id();
let project_id = self
.db_datastore
.project_lookup_id_by_name(&organization_id, project_name)
.await?;
self.db_datastore
.instance_fetch_by_name(&project_id, instance_name)
.await
}
fn check_runtime_change_allowed(
&self,
runtime: &nexus::InstanceRuntimeState,
) -> Result<(), Error> {
/*
* Users are allowed to request a start or stop even if the instance is
* already in the desired state (or moving to it), and we will issue a
* request to the SA to make the state change in these cases in case the
* runtime state we saw here was stale. However, users are not allowed
* to change the state of an instance that's failed or destroyed.
*/
let allowed = match runtime.run_state {
InstanceState::Creating => true,
InstanceState::Starting => true,
InstanceState::Running => true,
InstanceState::Stopping => true,
InstanceState::Stopped => true,
InstanceState::Rebooting => true,