-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathinstance.rs
2432 lines (2266 loc) · 95.3 KB
/
instance.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/.
//! Virtual Machine Instances
use super::MAX_DISKS_PER_INSTANCE;
use super::MAX_EPHEMERAL_IPS_PER_INSTANCE;
use super::MAX_EXTERNAL_IPS_PER_INSTANCE;
use super::MAX_MEMORY_BYTES_PER_INSTANCE;
use super::MAX_NICS_PER_INSTANCE;
use super::MAX_SSH_KEYS_PER_INSTANCE;
use super::MAX_VCPU_PER_INSTANCE;
use super::MIN_MEMORY_BYTES_PER_INSTANCE;
use crate::app::sagas;
use crate::app::sagas::NexusSaga;
use crate::cidata::InstanceCiData;
use crate::external_api::params;
use cancel_safe_futures::prelude::*;
use futures::future::Fuse;
use futures::{FutureExt, SinkExt, StreamExt};
use nexus_db_model::IpAttachState;
use nexus_db_model::IpKind;
use nexus_db_model::Vmm as DbVmm;
use nexus_db_model::VmmRuntimeState;
use nexus_db_model::VmmState as DbVmmState;
use nexus_db_queries::authn;
use nexus_db_queries::authz;
use nexus_db_queries::context::OpContext;
use nexus_db_queries::db;
use nexus_db_queries::db::datastore::InstanceAndActiveVmm;
use nexus_db_queries::db::identity::Resource;
use nexus_db_queries::db::lookup;
use nexus_db_queries::db::lookup::LookupPath;
use nexus_db_queries::db::DataStore;
use nexus_types::external_api::views;
use omicron_common::api::external::http_pagination::PaginatedBy;
use omicron_common::api::external::ByteCount;
use omicron_common::api::external::CreateResult;
use omicron_common::api::external::DataPageParams;
use omicron_common::api::external::DeleteResult;
use omicron_common::api::external::Error;
use omicron_common::api::external::InstanceState;
use omicron_common::api::external::InternalContext;
use omicron_common::api::external::ListResultVec;
use omicron_common::api::external::LookupResult;
use omicron_common::api::external::NameOrId;
use omicron_common::api::external::UpdateResult;
use omicron_common::api::internal::nexus;
use omicron_common::api::internal::shared::SourceNatConfig;
use omicron_uuid_kinds::GenericUuid;
use omicron_uuid_kinds::InstanceUuid;
use omicron_uuid_kinds::PropolisUuid;
use omicron_uuid_kinds::SledUuid;
use propolis_client::support::tungstenite::protocol::frame::coding::CloseCode;
use propolis_client::support::tungstenite::protocol::CloseFrame;
use propolis_client::support::tungstenite::Message as WebSocketMessage;
use propolis_client::support::InstanceSerialConsoleHelper;
use propolis_client::support::WSClientOffset;
use propolis_client::support::WebSocketStream;
use sagas::instance_common::ExternalIpAttach;
use sagas::instance_start;
use sagas::instance_update;
use sled_agent_client::types::InstanceMigrationTargetParams;
use sled_agent_client::types::InstanceProperties;
use sled_agent_client::types::VmmPutStateBody;
use std::matches;
use std::net::SocketAddr;
use std::sync::Arc;
use tokio::io::{AsyncRead, AsyncWrite};
use uuid::Uuid;
type SledAgentClientError =
sled_agent_client::Error<sled_agent_client::types::Error>;
// Newtype wrapper to avoid the orphan type rule.
#[derive(Debug, thiserror::Error)]
pub struct SledAgentInstanceError(pub SledAgentClientError);
impl std::fmt::Display for SledAgentInstanceError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl From<SledAgentClientError> for SledAgentInstanceError {
fn from(value: SledAgentClientError) -> Self {
Self(value)
}
}
impl From<SledAgentInstanceError> for omicron_common::api::external::Error {
fn from(value: SledAgentInstanceError) -> Self {
value.0.into()
}
}
impl From<SledAgentInstanceError> for dropshot::HttpError {
fn from(value: SledAgentInstanceError) -> Self {
use dropshot::HttpError;
use progenitor_client::Error as ClientError;
// See RFD 486 §6.3:
// https://rfd.shared.oxide.computer/rfd/486#_stopping_or_rebooting_a_running_instance
match value {
// Errors communicating with the sled-agent should return 502 Bad
// Gateway to the caller.
SledAgentInstanceError(ClientError::CommunicationError(e)) => {
// N.B.: it sure *seems* like we should be using the
// `HttpError::for_status` constructor here, but that
// constructor secretly calls the `for_client_error`
// constructor, which panics if we pass a status code that isn't
// a 4xx error. So, instead, we construct an internal error and
// then munge its status code.
// See https://github.com/oxidecomputer/dropshot/issues/693
let mut error = HttpError::for_internal_error(e.to_string());
error.status_code = if e.is_timeout() {
http::StatusCode::GATEWAY_TIMEOUT
} else {
http::StatusCode::BAD_GATEWAY
};
error
}
// Invalid request errors from the sled-agent should return 500
// Internal Server Errors.
SledAgentInstanceError(ClientError::InvalidRequest(s)) => {
HttpError::for_internal_error(s)
}
// Error responses from sled-agent that indicate the instance is
// unhealthy should be mapped to a 503 error.
e if e.vmm_gone() => {
let mut error = HttpError::for_unavail(None, e.to_string());
error.external_message = "The instance was running but is no \
longer reachable. It is being moved to the Failed state."
.to_string();
error
}
// Other client errors can be handled by the normal
// `external::Error` to `HttpError` conversions.
SledAgentInstanceError(e) => HttpError::from(Error::from(e)),
}
}
}
impl SledAgentInstanceError {
/// Returns `true` if this error is of a class that indicates that the
/// VMM is no longer known to the sled-agent.
pub fn vmm_gone(&self) -> bool {
match &self.0 {
// See RFD 486 §6.3:
// https://rfd.shared.oxide.computer/rfd/486#_stopping_or_rebooting_a_running_instance
//
// > If a sled agent call returns 404 Not Found with a
// > NO_SUCH_INSTANCE error string, the VMM of interest is missing.
// > In this case, sled agent has disowned the VMM, so Nexus can
// > take control of its state machine and drive the VMM to the
// > Failed state and trigger an instance update saga that will
// > remove the dangling VMM ID from the instance and clean up the
// > VMM’s resources.
progenitor_client::Error::ErrorResponse(rv) => {
rv.status() == http::StatusCode::NOT_FOUND
&& rv.error_code.as_deref() == Some("NO_SUCH_INSTANCE")
}
_ => false,
}
}
}
/// An error that can be returned from an operation that changes the state of an
/// instance on a specific sled.
#[derive(Debug, thiserror::Error)]
pub enum InstanceStateChangeError {
/// Sled agent returned an error from one of its instance endpoints.
#[error("sled agent client error")]
SledAgent(#[source] SledAgentInstanceError),
/// Some other error occurred outside of the attempt to communicate with
/// sled agent.
#[error(transparent)]
Other(#[from] omicron_common::api::external::Error),
}
// Allow direct conversion of instance state change errors into API errors for
// callers who don't care about the specific reason the update failed and just
// need to return an API error.
impl From<InstanceStateChangeError> for omicron_common::api::external::Error {
fn from(value: InstanceStateChangeError) -> Self {
match value {
InstanceStateChangeError::SledAgent(e) => e.into(),
InstanceStateChangeError::Other(e) => e,
}
}
}
impl From<InstanceStateChangeError> for dropshot::HttpError {
fn from(value: InstanceStateChangeError) -> Self {
match value {
InstanceStateChangeError::SledAgent(e) => e.into(),
InstanceStateChangeError::Other(e) => e.into(),
}
}
}
/// The kinds of state changes that can be requested of an instance's current
/// VMM (i.e. the VMM pointed to be the instance's `propolis_id` field).
pub(crate) enum InstanceStateChangeRequest {
Run,
Reboot,
Stop,
Migrate(InstanceMigrationTargetParams),
}
impl From<InstanceStateChangeRequest>
for sled_agent_client::types::VmmStateRequested
{
fn from(value: InstanceStateChangeRequest) -> Self {
match value {
InstanceStateChangeRequest::Run => Self::Running,
InstanceStateChangeRequest::Reboot => Self::Reboot,
InstanceStateChangeRequest::Stop => Self::Stopped,
InstanceStateChangeRequest::Migrate(params) => {
Self::MigrationTarget(params)
}
}
}
}
/// The actions that can be taken in response to an
/// [`InstanceStateChangeRequest`].
enum InstanceStateChangeRequestAction {
/// The instance is already in the correct state, so no action is needed.
AlreadyDone,
/// Request the appropriate state change from the sled with the specified
/// UUID.
SendToSled { sled_id: SledUuid, propolis_id: PropolisUuid },
/// The instance is not currently incarnated on a sled, so just update its
/// runtime state in the database without communicating with a sled-agent.
UpdateRuntime(db::model::InstanceRuntimeState),
}
/// What is the higher level operation that is calling
/// `instance_ensure_registered`?
pub(crate) enum InstanceRegisterReason {
Start { vmm_id: PropolisUuid },
Migrate { vmm_id: PropolisUuid, target_vmm_id: PropolisUuid },
}
enum InstanceStartDisposition {
Start,
AlreadyStarted,
}
/// The set of API resources needed when ensuring that an instance is registered
/// on a sled.
pub(crate) struct InstanceEnsureRegisteredApiResources {
pub(crate) authz_silo: nexus_auth::authz::Silo,
pub(crate) authz_project: nexus_auth::authz::Project,
pub(crate) authz_instance: nexus_auth::authz::Instance,
}
impl super::Nexus {
pub fn instance_lookup<'a>(
&'a self,
opctx: &'a OpContext,
instance_selector: params::InstanceSelector,
) -> LookupResult<lookup::Instance<'a>> {
match instance_selector {
params::InstanceSelector {
instance: NameOrId::Id(id),
project: None
} => {
let instance =
LookupPath::new(opctx, &self.db_datastore).instance_id(id);
Ok(instance)
}
params::InstanceSelector {
instance: NameOrId::Name(name),
project: Some(project)
} => {
let instance = self
.project_lookup(opctx, params::ProjectSelector { project })?
.instance_name_owned(name.into());
Ok(instance)
}
params::InstanceSelector {
instance: NameOrId::Id(_),
..
} => {
Err(Error::invalid_request(
"when providing instance as an ID project should not be specified",
))
}
_ => {
Err(Error::invalid_request(
"instance should either be UUID or project should be specified",
))
}
}
}
pub(crate) async fn project_create_instance(
self: &Arc<Self>,
opctx: &OpContext,
project_lookup: &lookup::Project<'_>,
params: ¶ms::InstanceCreate,
) -> CreateResult<InstanceAndActiveVmm> {
let (.., authz_project) =
project_lookup.lookup_for(authz::Action::CreateChild).await?;
// Validate parameters
if params.disks.len() > MAX_DISKS_PER_INSTANCE as usize {
return Err(Error::invalid_request(&format!(
"cannot attach more than {} disks to instance",
MAX_DISKS_PER_INSTANCE
)));
}
for disk in ¶ms.disks {
if let params::InstanceDiskAttachment::Create(create) = disk {
self.validate_disk_create_params(opctx, &authz_project, create)
.await?;
}
}
if params.ncpus.0 > MAX_VCPU_PER_INSTANCE {
return Err(Error::invalid_request(&format!(
"cannot have more than {} vCPUs per instance",
MAX_VCPU_PER_INSTANCE
)));
}
if params.external_ips.len() > MAX_EXTERNAL_IPS_PER_INSTANCE {
return Err(Error::invalid_request(&format!(
"An instance may not have more than {} external IP addresses",
MAX_EXTERNAL_IPS_PER_INSTANCE,
)));
}
if params
.external_ips
.iter()
.filter(|v| matches!(v, params::ExternalIpCreate::Ephemeral { .. }))
.count()
> MAX_EPHEMERAL_IPS_PER_INSTANCE
{
return Err(Error::invalid_request(&format!(
"An instance may not have more than {} ephemeral IP address",
MAX_EPHEMERAL_IPS_PER_INSTANCE,
)));
}
if let params::InstanceNetworkInterfaceAttachment::Create(ref ifaces) =
params.network_interfaces
{
if ifaces.len() > MAX_NICS_PER_INSTANCE {
return Err(Error::invalid_request(&format!(
"An instance may not have more than {} network interfaces",
MAX_NICS_PER_INSTANCE,
)));
}
// Check that all VPC names are the same.
//
// This isn't strictly necessary, as the queries to create these
// interfaces would fail in the saga, but it's easier to handle here.
if ifaces
.iter()
.map(|iface| &iface.vpc_name)
.collect::<std::collections::BTreeSet<_>>()
.len()
!= 1
{
return Err(Error::invalid_request(
"All interfaces must be in the same VPC",
));
}
}
// Reject instances where the memory is not at least
// MIN_MEMORY_BYTES_PER_INSTANCE
if params.memory.to_bytes() < u64::from(MIN_MEMORY_BYTES_PER_INSTANCE) {
return Err(Error::invalid_value(
"size",
format!(
"memory must be at least {}",
ByteCount::from(MIN_MEMORY_BYTES_PER_INSTANCE)
),
));
}
// Reject instances where the memory is not divisible by
// MIN_MEMORY_BYTES_PER_INSTANCE
if (params.memory.to_bytes() % u64::from(MIN_MEMORY_BYTES_PER_INSTANCE))
!= 0
{
return Err(Error::invalid_value(
"size",
format!(
"memory must be divisible by {}",
ByteCount::from(MIN_MEMORY_BYTES_PER_INSTANCE)
),
));
}
// Reject instances where the memory is greater than the limit
if params.memory.to_bytes() > MAX_MEMORY_BYTES_PER_INSTANCE {
return Err(Error::invalid_value(
"size",
format!(
"memory must be less than or equal to {}",
ByteCount::try_from(MAX_MEMORY_BYTES_PER_INSTANCE).unwrap()
),
));
}
let actor = opctx.authn.actor_required().internal_context(
"loading current user's ssh keys for new Instance",
)?;
let (.., authz_user) = LookupPath::new(opctx, &self.db_datastore)
.silo_user_id(actor.actor_id())
.lookup_for(authz::Action::ListChildren)
.await?;
let ssh_keys = match ¶ms.ssh_public_keys {
Some(keys) => Some(
self.db_datastore
.ssh_keys_batch_lookup(opctx, &authz_user, keys)
.await?
.iter()
.map(|id| NameOrId::Id(*id))
.collect::<Vec<NameOrId>>(),
),
None => None,
};
if let Some(ssh_keys) = &ssh_keys {
if ssh_keys.len() > MAX_SSH_KEYS_PER_INSTANCE.try_into().unwrap() {
return Err(Error::invalid_request(format!(
"cannot attach more than {} ssh keys to the instance",
MAX_SSH_KEYS_PER_INSTANCE
)));
}
}
let saga_params = sagas::instance_create::Params {
serialized_authn: authn::saga::Serialized::for_opctx(opctx),
project_id: authz_project.id(),
create_params: params::InstanceCreate {
ssh_public_keys: ssh_keys,
..params.clone()
},
boundary_switches: self
.boundary_switches(&self.opctx_alloc)
.await?,
};
let saga_outputs = self
.sagas
.saga_execute::<sagas::instance_create::SagaInstanceCreate>(
saga_params,
)
.await?;
let instance_id = saga_outputs
.lookup_node_output::<Uuid>("instance_id")
.map_err(|e| Error::internal_error(&format!("{:#}", &e)))
.internal_context("looking up output from instance create saga")?;
// If the caller asked to start the instance, kick off that saga.
// There's a window in which the instance is stopped and can be deleted,
// so this is not guaranteed to succeed, and its result should not
// affect the result of the attempt to create the instance.
if params.start {
let lookup = LookupPath::new(opctx, &self.db_datastore)
.instance_id(instance_id);
let start_result = self
.instance_start(
opctx,
&lookup,
instance_start::Reason::AutoStart,
)
.await;
if let Err(e) = start_result {
info!(self.log, "failed to start newly-created instance";
"instance_id" => %instance_id,
"error" => ?e);
}
}
// TODO: This operation should return the instance as it was created.
// Refetching the instance state here won't return that version of the
// instance if its state changed between the time the saga finished and
// the time this lookup was performed.
//
// Because the create saga has to synthesize an instance record (and
// possibly a VMM record), and these are serializable, it should be
// possible to yank the outputs out of the appropriate saga steps and
// return them here.
let (.., authz_instance) = LookupPath::new(opctx, &self.db_datastore)
.instance_id(instance_id)
.lookup_for(authz::Action::Read)
.await?;
self.db_datastore.instance_fetch_with_vmm(opctx, &authz_instance).await
}
pub(crate) async fn instance_list(
&self,
opctx: &OpContext,
project_lookup: &lookup::Project<'_>,
pagparams: &PaginatedBy<'_>,
) -> ListResultVec<InstanceAndActiveVmm> {
let (.., authz_project) =
project_lookup.lookup_for(authz::Action::ListChildren).await?;
self.db_datastore.instance_list(opctx, &authz_project, pagparams).await
}
// This operation may only occur on stopped instances, which implies that
// the attached disks do not have any running "upstairs" process running
// within the sled.
pub(crate) async fn project_destroy_instance(
self: &Arc<Self>,
opctx: &OpContext,
instance_lookup: &lookup::Instance<'_>,
) -> 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 (.., authz_instance, instance) =
instance_lookup.fetch_for(authz::Action::Delete).await?;
// TODO: #3593 Correctness
// When the set of boundary switches changes, there is no cleanup /
// reconciliation logic performed to ensure that the NAT entries are
// propogated to new boundary switches / removed from former boundary
// switches, meaning we could end up with stale or missing entries.
let boundary_switches =
self.boundary_switches(&self.opctx_alloc).await?;
let saga_params = sagas::instance_delete::Params {
serialized_authn: authn::saga::Serialized::for_opctx(opctx),
authz_instance,
instance,
boundary_switches,
};
self.sagas
.saga_execute::<sagas::instance_delete::SagaInstanceDelete>(
saga_params,
)
.await?;
Ok(())
}
pub(crate) async fn instance_migrate(
self: &Arc<Self>,
opctx: &OpContext,
id: InstanceUuid,
params: nexus_types::internal_api::params::InstanceMigrateRequest,
) -> UpdateResult<InstanceAndActiveVmm> {
let (.., authz_instance) = LookupPath::new(&opctx, &self.db_datastore)
.instance_id(id.into_untyped_uuid())
.lookup_for(authz::Action::Modify)
.await?;
let state = self
.db_datastore
.instance_fetch_with_vmm(opctx, &authz_instance)
.await?;
let (instance, vmm) = (state.instance(), state.vmm());
if vmm.is_none()
|| vmm.as_ref().unwrap().runtime.state != DbVmmState::Running
{
return Err(Error::invalid_request(
"instance must be running before it can migrate",
));
}
let vmm = vmm.as_ref().unwrap();
if vmm.sled_id == params.dst_sled_id {
return Err(Error::invalid_request(
"instance is already running on destination sled",
));
}
if instance.runtime().migration_id.is_some() {
return Err(Error::conflict("instance is already migrating"));
}
// Kick off the migration saga
let saga_params = sagas::instance_migrate::Params {
serialized_authn: authn::saga::Serialized::for_opctx(opctx),
instance: instance.clone(),
src_vmm: vmm.clone(),
migrate_params: params,
};
self.sagas
.saga_execute::<sagas::instance_migrate::SagaInstanceMigrate>(
saga_params,
)
.await?;
// TODO correctness TODO robustness TODO design
// Should we lookup the instance again here?
// See comment in project_create_instance.
self.db_datastore.instance_fetch_with_vmm(opctx, &authz_instance).await
}
/// Reboot the specified instance.
pub(crate) async fn instance_reboot(
&self,
opctx: &OpContext,
instance_lookup: &lookup::Instance<'_>,
) -> Result<InstanceAndActiveVmm, InstanceStateChangeError> {
let (.., authz_instance) =
instance_lookup.lookup_for(authz::Action::Modify).await?;
let state = self
.db_datastore
.instance_fetch_with_vmm(opctx, &authz_instance)
.await?;
if let Err(e) = self
.instance_request_state(
opctx,
state.instance(),
state.vmm(),
InstanceStateChangeRequest::Reboot,
)
.await
{
if let (InstanceStateChangeError::SledAgent(inner), Some(vmm)) =
(&e, state.vmm())
{
if inner.vmm_gone() {
let _ = self
.mark_vmm_failed(opctx, authz_instance, vmm, inner)
.await;
}
}
return Err(e);
}
self.db_datastore
.instance_fetch_with_vmm(opctx, &authz_instance)
.await
.map_err(Into::into)
}
/// Attempts to start an instance if it is currently stopped.
pub(crate) async fn instance_start(
self: &Arc<Self>,
opctx: &OpContext,
instance_lookup: &lookup::Instance<'_>,
reason: instance_start::Reason,
) -> Result<InstanceAndActiveVmm, InstanceStateChangeError> {
let (.., authz_instance) =
instance_lookup.lookup_for(authz::Action::Modify).await?;
let state = self
.db_datastore
.instance_fetch_with_vmm(opctx, &authz_instance)
.await?;
match instance_start_allowed(&self.log, &state, reason)? {
InstanceStartDisposition::AlreadyStarted => Ok(state),
InstanceStartDisposition::Start => {
let saga_params = sagas::instance_start::Params {
serialized_authn: authn::saga::Serialized::for_opctx(opctx),
db_instance: state.instance().clone(),
reason,
};
self.sagas
.saga_execute::<sagas::instance_start::SagaInstanceStart>(
saga_params,
)
.await?;
self.db_datastore
.instance_fetch_with_vmm(opctx, &authz_instance)
.await
.map_err(Into::into)
}
}
}
/// Make sure the given Instance is stopped.
pub(crate) async fn instance_stop(
&self,
opctx: &OpContext,
instance_lookup: &lookup::Instance<'_>,
) -> Result<InstanceAndActiveVmm, InstanceStateChangeError> {
let (.., authz_instance) =
instance_lookup.lookup_for(authz::Action::Modify).await?;
let state = self
.db_datastore
.instance_fetch_with_vmm(opctx, &authz_instance)
.await?;
if let Err(e) = self
.instance_request_state(
opctx,
state.instance(),
state.vmm(),
InstanceStateChangeRequest::Stop,
)
.await
{
if let (InstanceStateChangeError::SledAgent(inner), Some(vmm)) =
(&e, state.vmm())
{
if inner.vmm_gone() {
let _ = self
.mark_vmm_failed(opctx, authz_instance, vmm, inner)
.await;
}
}
return Err(e);
}
self.db_datastore
.instance_fetch_with_vmm(opctx, &authz_instance)
.await
.map_err(Into::into)
}
/// Idempotently ensures that the sled specified in `db_instance` does not
/// have a record of the instance. If the instance is currently running on
/// this sled, this operation rudely terminates it.
pub(crate) async fn instance_ensure_unregistered(
&self,
propolis_id: &PropolisUuid,
sled_id: &SledUuid,
) -> Result<Option<nexus::SledVmmState>, InstanceStateChangeError> {
let sa = self.sled_client(&sled_id).await?;
sa.vmm_unregister(propolis_id)
.await
.map(|res| res.into_inner().updated_runtime.map(Into::into))
.map_err(|e| {
InstanceStateChangeError::SledAgent(SledAgentInstanceError(e))
})
}
/// Determines the action to take on an instance's active VMM given a
/// request to change its state.
///
/// # Arguments
///
/// - instance_state: The prior state of the instance as recorded in CRDB
/// and obtained by the caller.
/// - vmm_state: The prior state of the instance's active VMM as recorded in
/// CRDB and obtained by the caller. `None` if the instance has no active
/// VMM.
/// - requested: The state change being requested.
///
/// # Return value
///
/// - `Ok(action)` if the request is allowed to proceed. The result payload
/// specifies how to handle the request.
/// - `Err` if the request should be denied.
fn select_runtime_change_action(
&self,
instance_state: &db::model::Instance,
vmm_state: &Option<db::model::Vmm>,
requested: &InstanceStateChangeRequest,
) -> Result<InstanceStateChangeRequestAction, Error> {
let effective_state = InstanceAndActiveVmm::determine_effective_state(
instance_state,
vmm_state.as_ref(),
);
// Requests that operate on active instances have to be directed to the
// instance's current sled agent. If there is none, the request needs to
// be handled specially based on its type.
let (sled_id, propolis_id) = if let Some(vmm) = vmm_state {
(
SledUuid::from_untyped_uuid(vmm.sled_id),
PropolisUuid::from_untyped_uuid(vmm.id),
)
} else {
match effective_state {
// If there's no active sled because the instance is stopped,
// allow requests to stop to succeed silently for idempotency,
// but reject requests to do anything else.
InstanceState::Stopped => match requested {
InstanceStateChangeRequest::Run => {
return Err(Error::invalid_request(&format!(
"cannot run an instance in state {} with no VMM",
effective_state
)))
}
InstanceStateChangeRequest::Stop => {
return Ok(InstanceStateChangeRequestAction::AlreadyDone);
}
InstanceStateChangeRequest::Reboot => {
return Err(Error::invalid_request(&format!(
"cannot reboot an instance in state {} with no VMM",
effective_state
)))
}
InstanceStateChangeRequest::Migrate(_) => {
return Err(Error::invalid_request(&format!(
"cannot migrate an instance in state {} with no VMM",
effective_state
)))
}
},
// If the instance is still being created (such that it hasn't
// even begun to start yet), no runtime state change is valid.
// Return a specific error message explaining the problem.
InstanceState::Creating => {
return Err(Error::invalid_request(
"cannot change instance state while it is \
still being created"
))
}
// Failed instances may transition to Stopped by just changing
// the Nexus state in the database to NoVmm.
//
// An instance's effective state will never be Failed while it
// is linked with a VMM. If the instance has an active VMM which
// is Failed, the instance's effective state will be Stopping,
// rather than Failed, until an instance-update saga has
// unlinked the Failed VMM. We can guarantee this is the case,
// as a database CHECK constraint will not permit an instance
// with an active Propolis ID to be Failed. Therefore, we know
// that a Failed instance is definitely not incarnated on a
// sled, so all we need to do to "stop" it is to update its
// state in the database.
InstanceState::Failed if matches!(requested, InstanceStateChangeRequest::Stop) => {
// As discussed above, this shouldn't happen, so return an
// internal error and complain about it in the logs.
if vmm_state.is_some() {
return Err(Error::internal_error(
"an instance should not be in the Failed \
effective state if it has an active VMM"
));
}
let prev_runtime = instance_state.runtime();
return Ok(InstanceStateChangeRequestAction::UpdateRuntime(db::model::InstanceRuntimeState {
time_updated: chrono::Utc::now(),
r#gen: prev_runtime.r#gen.0.next().into(),
nexus_state: db::model::InstanceState::NoVmm,
..prev_runtime.clone()
}));
}
// If the instance has no sled beacuse it's been destroyed or
// has fallen over, reject the state change.
InstanceState::Failed | InstanceState::Destroyed => {
return Err(Error::invalid_request(&format!(
"instance state cannot be changed from {}",
effective_state
)))
}
// In other states, the instance should have a sled, and an
// internal invariant has been violated if it doesn't have one.
_ => {
error!(self.log, "instance has no sled but isn't halted";
"instance_id" => %instance_state.id(),
"state" => ?effective_state);
return Err(Error::internal_error(
"instance is active but not resident on a sled"
));
}
}
};
// The instance has an active sled. Allow the sled agent to decide how
// to handle the request unless the instance is being recovered or the
// underlying VMM has been destroyed.
//
// TODO(#2825): Failed instances should be allowed to stop. See above.
let allowed = match requested {
InstanceStateChangeRequest::Run
| InstanceStateChangeRequest::Reboot
| InstanceStateChangeRequest::Stop => match effective_state {
InstanceState::Creating
| InstanceState::Starting
| InstanceState::Running
| InstanceState::Stopping
| InstanceState::Stopped
| InstanceState::Rebooting
| InstanceState::Migrating => true,
InstanceState::Repairing | InstanceState::Failed => false,
InstanceState::Destroyed => false,
},
InstanceStateChangeRequest::Migrate(_) => match effective_state {
InstanceState::Running
| InstanceState::Rebooting
| InstanceState::Migrating => true,
InstanceState::Creating
| InstanceState::Starting
| InstanceState::Stopping
| InstanceState::Stopped
| InstanceState::Repairing
| InstanceState::Failed
| InstanceState::Destroyed => false,
},
};
if allowed {
Ok(InstanceStateChangeRequestAction::SendToSled {
sled_id,
propolis_id,
})
} else {
Err(Error::invalid_request(format!(
"instance state cannot be changed from state \"{}\"",
effective_state
)))
}
}
pub(crate) async fn instance_request_state(
&self,
opctx: &OpContext,
prev_instance_state: &db::model::Instance,
prev_vmm_state: &Option<db::model::Vmm>,
requested: InstanceStateChangeRequest,
) -> Result<(), InstanceStateChangeError> {
match self.select_runtime_change_action(
prev_instance_state,
prev_vmm_state,
&requested,
)? {
InstanceStateChangeRequestAction::AlreadyDone => Ok(()),
InstanceStateChangeRequestAction::UpdateRuntime(new_runtime) => {
let instance_id =
InstanceUuid::from_untyped_uuid(prev_instance_state.id());
let changed = self
.datastore()
.instance_update_runtime(&instance_id, &new_runtime)
.await
.map_err(InstanceStateChangeError::Other)?;
if !changed {
// TODO(eliza): perhaps we should refetch the instance here
// and return Ok if it was in the desired state...
Err(InstanceStateChangeError::Other(Error::conflict(
"The instance was previously in a state that allowed \
the requested state change, but the instance's state \
changed before the request could be completed",
)))
} else {
Ok(())
}
}
InstanceStateChangeRequestAction::SendToSled {
sled_id,
propolis_id,
} => {
let sa = self.sled_client(&sled_id).await?;
let instance_put_result = sa
.vmm_put_state(
&propolis_id,
&VmmPutStateBody { state: requested.into() },
)
.await
.map(|res| res.into_inner().updated_runtime.map(Into::into))
.map_err(|e| SledAgentInstanceError(e));
// If the operation succeeded, write the instance state back,
// returning any subsequent errors that occurred during that
// write.
//
// If the operation failed, kick the sled agent error back up to
// the caller to let it decide how to handle it.
//
// When creating the zone for the first time, we just get
// Ok(None) here, in which case, there's nothing to write back.
match instance_put_result {
Ok(Some(ref state)) => self
.notify_vmm_updated(opctx, propolis_id, state)
.await
.map_err(Into::into),
Ok(None) => Ok(()),
Err(e) => Err(InstanceStateChangeError::SledAgent(e)),
}
}
}
}
/// Modifies the runtime state of the Instance as requested. This generally
/// means booting or halting the Instance.
pub(crate) async fn instance_ensure_registered(
&self,
opctx: &OpContext,
InstanceEnsureRegisteredApiResources {
authz_silo,
authz_project,
authz_instance,
}: &InstanceEnsureRegisteredApiResources,
db_instance: &db::model::Instance,
propolis_id: &PropolisUuid,
initial_vmm: &db::model::Vmm,
operation: InstanceRegisterReason,
) -> Result<db::model::Vmm, InstanceStateChangeError> {