-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathsnapshot_create.rs
2369 lines (2065 loc) · 81.3 KB
/
snapshot_create.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 taking a snapshot is a perfect application for a saga. There are
//! several services that requests must be sent to, and the snapshot can only be
//! considered completed when all have returned OK and the appropriate database
//! records have been created.
//!
//! # Taking a snapshot of a disk currently attached to an instance
//!
//! A running instance has a corresponding zone that is running a propolis
//! server. That propolis server emulates a disk for the guest OS, and the
//! backend for that virtual disk is a crucible volume that is constructed out
//! of downstairs regions and optionally some sort of read only source (an
//! image, another snapshot, etc). The downstairs regions are concatenated
//! together under a "sub-volume" array over the span of the whole virtual disk
//! (this allows for one 1TB virtual disk to be composed of several smaller
//! downstairs regions for example). Below is an example of a volume where there
//! are two regions (where each region is backed by three downstairs) and a read
//! only parent that points to a URL:
//!
//! ```text
//! Volume {
//! sub-volumes [
//! region A {
//! downstairs @ [fd00:1122:3344:0101::0500]:19000,
//! downstairs @ [fd00:1122:3344:0101::0501]:19000,
//! downstairs @ [fd00:1122:3344:0101::0502]:19000,
//! },
//! region B {
//! downstairs @ [fd00:1122:3344:0101::0503]:19000,
//! downstairs @ [fd00:1122:3344:0101::0504]:19000,
//! downstairs @ [fd00:1122:3344:0101::0505]:19000,
//! },
//! ]
//!
//! read only parent {
//! image {
//! url: "some.url/debian-11.img"
//! }
//! }
//! ```
//!
//! When the guest OS writes to their disk, those blocks will be written to the
//! sub-volume regions only - no writes or flushes are sent to the read only
//! parent by the volume, only reads. A block read is served from the read only
//! parent if there hasn't been a write to that block in the sub volume,
//! otherwise the block is served from the sub volume. This means all modified
//! blocks for a volume will be written to sub-volume regions, and it's those
//! modifications we want to capture in a snapshot.
//!
//! First, this saga will send a snapshot request to the instance's propolis
//! server. Currently a snapshot request is implemented as a flush with an extra
//! parameter, and this is sent to the volume through the standard IO channels.
//! This flush will be processed by each downstairs in the same job order so
//! that each snapshot will contain the same information. A crucible snapshot is
//! created by taking a ZFS snapshot in each downstairs, so after this operation
//! there will be six new ZFS snapshots, one in each downstair's zfs dataset,
//! each with the same name.
//!
//! Next, this saga will validate with the crucible agent that the snapshot was
//! created ok, and start a new read-only downstairs process for each snapshot.
//! The validation step isn't strictly required as the flush (with the extra
//! snapshot parameter) wouldn't have returned successfully if there was a
//! problem creating the snapshot, but it never hurts to check :) Once each
//! snapshot has a corresponding read-only downstairs process started for it,
//! the saga will record the addresses that those processes are listening on.
//!
//! The next step is to copy and modify the volume construction request for the
//! running volume in order to create the snapshot's volume construction
//! request. The read-only parent will stay the same, and the sub-volume's
//! region addresses will change to point to the new read-only downstairs
//! process' addresses. This is done by creating a map of old -> new addresses,
//! and passing that into a `create_snapshot_from_disk` function. This new
//! volume construction request will be used as a read only parent when creating
//! other disks using this snapshot as a disk source.
//!
//! # Taking a snapshot of a detached disk
//!
//! This process is mostly the same as the process of taking a snapshot of a
//! disk that's attached to an instance, but if a disk is not currently attached
//! to an instance, there's no Upstairs to send the snapshot request to. The
//! Crucible Pantry is a service that will be launched on each Sled and will be
//! used for these types of maintenance tasks. In this case this saga will
//! attach the volume "to" a random Pantry by sending a volume construction
//! request, then send a snapshot request, then detach "from" that random
//! Pantry. Most of the rest of the saga is unchanged.
//!
use super::{
common_storage::{
call_pantry_attach_for_disk, call_pantry_detach_for_disk,
delete_crucible_regions, delete_crucible_running_snapshot,
delete_crucible_snapshot, ensure_all_datasets_and_regions,
get_pantry_address,
},
ActionRegistry, NexusActionContext, NexusSaga, SagaInitError,
ACTION_GENERATE_ID,
};
use crate::app::sagas::declare_saga_actions;
use crate::app::sagas::retry_until_known_result;
use crate::app::{authn, authz, db};
use crate::external_api::params;
use anyhow::anyhow;
use crucible_agent_client::{types::RegionId, Client as CrucibleAgentClient};
use nexus_db_model::Generation;
use nexus_db_queries::db::identity::{Asset, Resource};
use nexus_db_queries::db::lookup::LookupPath;
use omicron_common::api::external;
use omicron_common::api::external::Error;
use rand::{rngs::StdRng, RngCore, SeedableRng};
use serde::Deserialize;
use serde::Serialize;
use sled_agent_client::types::CrucibleOpts;
use sled_agent_client::types::InstanceIssueDiskSnapshotRequestBody;
use sled_agent_client::types::VolumeConstructionRequest;
use slog::info;
use std::collections::BTreeMap;
use std::net::SocketAddrV6;
use steno::ActionError;
use steno::Node;
use uuid::Uuid;
// snapshot create saga: input parameters
#[derive(Debug, Deserialize, Serialize)]
pub(crate) struct Params {
pub serialized_authn: authn::saga::Serialized,
pub silo_id: Uuid,
pub project_id: Uuid,
pub disk_id: Uuid,
pub attached_instance_and_sled: Option<(Uuid, Uuid)>,
pub create_params: params::SnapshotCreate,
}
// snapshot create saga: actions
declare_saga_actions! {
snapshot_create;
REGIONS_ALLOC -> "datasets_and_regions" {
+ ssc_alloc_regions
- ssc_alloc_regions_undo
}
REGIONS_ENSURE_UNDO -> "regions_ensure_undo" {
+ ssc_noop
- ssc_regions_ensure_undo
}
REGIONS_ENSURE -> "regions_ensure" {
+ ssc_regions_ensure
}
CREATE_DESTINATION_VOLUME_RECORD -> "created_destination_volume" {
+ ssc_create_destination_volume_record
- ssc_create_destination_volume_record_undo
}
CREATE_SNAPSHOT_RECORD -> "created_snapshot" {
+ ssc_create_snapshot_record
- ssc_create_snapshot_record_undo
}
SPACE_ACCOUNT -> "no_result" {
+ ssc_account_space
- ssc_account_space_undo
}
SEND_SNAPSHOT_REQUEST_TO_SLED_AGENT -> "snapshot_request_to_sled_agent" {
+ ssc_send_snapshot_request_to_sled_agent
- ssc_send_snapshot_request_to_sled_agent_undo
}
GET_PANTRY_ADDRESS -> "pantry_address" {
+ ssc_get_pantry_address
}
ATTACH_DISK_TO_PANTRY -> "disk_generation_number" {
+ ssc_attach_disk_to_pantry
- ssc_attach_disk_to_pantry_undo
}
CALL_PANTRY_ATTACH_FOR_DISK -> "call_pantry_attach_for_disk" {
+ ssc_call_pantry_attach_for_disk
- ssc_call_pantry_attach_for_disk_undo
}
CALL_PANTRY_SNAPSHOT_FOR_DISK -> "call_pantry_snapshot_for_disk" {
+ ssc_call_pantry_snapshot_for_disk
- ssc_call_pantry_snapshot_for_disk_undo
}
CALL_PANTRY_DETACH_FOR_DISK -> "call_pantry_detach_for_disk" {
+ ssc_call_pantry_detach_for_disk
}
DETACH_DISK_FROM_PANTRY -> "detach_disk_from_pantry" {
+ ssc_detach_disk_from_pantry
}
START_RUNNING_SNAPSHOT_UNDO -> "ssc_not_used" {
+ ssc_noop
- ssc_start_running_snapshot_undo
}
START_RUNNING_SNAPSHOT -> "replace_sockets_map" {
+ ssc_start_running_snapshot
}
CREATE_VOLUME_RECORD -> "created_volume" {
+ ssc_create_volume_record
- ssc_create_volume_record_undo
}
FINALIZE_SNAPSHOT_RECORD -> "finalized_snapshot" {
+ ssc_finalize_snapshot_record
}
}
// snapshot create saga: definition
#[derive(Debug)]
pub(crate) struct SagaSnapshotCreate;
impl NexusSaga for SagaSnapshotCreate {
const NAME: &'static str = "snapshot-create";
type Params = Params;
fn register_actions(registry: &mut ActionRegistry) {
snapshot_create_register_actions(registry);
}
fn make_saga_dag(
params: &Self::Params,
mut builder: steno::DagBuilder,
) -> Result<steno::Dag, SagaInitError> {
// Generate IDs
builder.append(Node::action(
"snapshot_id",
"GenerateSnapshotId",
ACTION_GENERATE_ID.as_ref(),
));
builder.append(Node::action(
"volume_id",
"GenerateVolumeId",
ACTION_GENERATE_ID.as_ref(),
));
builder.append(Node::action(
"destination_volume_id",
"GenerateDestinationVolumeId",
ACTION_GENERATE_ID.as_ref(),
));
// (DB) Allocate region space for snapshot to store blocks post-scrub
builder.append(regions_alloc_action());
// (Sleds) Reaches out to each dataset, and ensures the regions exist
// for the destination volume
builder.append(regions_ensure_undo_action());
builder.append(regions_ensure_action());
// (DB) Creates a record of the destination volume in the DB
builder.append(create_destination_volume_record_action());
// (DB) Creates a record of the snapshot, referencing both the
// original disk ID and the destination volume
builder.append(create_snapshot_record_action());
// (DB) Tracks virtual resource provisioning.
builder.append(space_account_action());
let use_the_pantry = params.attached_instance_and_sled.is_none();
if !use_the_pantry {
// (Sleds) If the disk is attached to an instance, send a
// snapshot request to sled-agent to create a ZFS snapshot.
builder.append(send_snapshot_request_to_sled_agent_action());
} else {
// (Pantry) Record the address of a Pantry service
builder.append(get_pantry_address_action());
// (Pantry) If the disk is _not_ attached to an instance:
// "attach" the disk to the pantry
builder.append(attach_disk_to_pantry_action());
// (Pantry) Call the Pantry's /attach
builder.append(call_pantry_attach_for_disk_action());
// (Pantry) Call the Pantry's /snapshot
builder.append(call_pantry_snapshot_for_disk_action());
// (Pantry) Call the Pantry's /detach
builder.append(call_pantry_detach_for_disk_action());
}
// (Sleds + DB) Start snapshot downstairs, add an entry in the DB for
// the dataset's snapshot.
builder.append(start_running_snapshot_undo_action());
builder.append(start_running_snapshot_action());
// (DB) Copy and modify the disk volume construction request to point
// to the new running snapshot
builder.append(create_volume_record_action());
// (DB) Mark snapshot as "ready"
builder.append(finalize_snapshot_record_action());
if use_the_pantry {
// (Pantry) Set the state back to Detached
//
// This has to be the last saga node! Otherwise, concurrent
// operation on this disk is possible.
builder.append(detach_disk_from_pantry_action());
}
Ok(builder.build()?)
}
}
// snapshot create saga: action implementations
async fn ssc_noop(_sagactx: NexusActionContext) -> Result<(), ActionError> {
Ok(())
}
async fn ssc_alloc_regions(
sagactx: NexusActionContext,
) -> Result<Vec<(db::model::Dataset, db::model::Region)>, ActionError> {
let osagactx = sagactx.user_data();
let params = sagactx.saga_params::<Params>()?;
let destination_volume_id =
sagactx.lookup::<Uuid>("destination_volume_id")?;
// Ensure the destination volume is backed by appropriate regions.
//
// This allocates regions in the database, but the disk state is still
// "creating" - the respective Crucible Agents must be instructed to
// allocate the necessary regions before we can mark the disk as "ready to
// be used".
//
// TODO: Depending on the result of
// https://github.com/oxidecomputer/omicron/issues/613 , we
// should consider using a paginated API to access regions, rather than
// returning all of them at once.
let opctx = crate::context::op_context_for_saga_action(
&sagactx,
¶ms.serialized_authn,
);
let (.., disk) = LookupPath::new(&opctx, &osagactx.datastore())
.disk_id(params.disk_id)
.fetch()
.await
.map_err(ActionError::action_failed)?;
let strategy = &osagactx.nexus().default_region_allocation_strategy;
let datasets_and_regions = osagactx
.datastore()
.region_allocate(
&opctx,
destination_volume_id,
¶ms::DiskSource::Blank {
block_size: params::BlockSize::try_from(
disk.block_size.to_bytes(),
)
.map_err(|e| ActionError::action_failed(e.to_string()))?,
},
external::ByteCount::from(disk.size),
&strategy,
)
.await
.map_err(ActionError::action_failed)?;
Ok(datasets_and_regions)
}
async fn ssc_alloc_regions_undo(
sagactx: NexusActionContext,
) -> Result<(), anyhow::Error> {
let osagactx = sagactx.user_data();
let log = osagactx.log();
let region_ids = sagactx
.lookup::<Vec<(db::model::Dataset, db::model::Region)>>(
"datasets_and_regions",
)?
.into_iter()
.map(|(_, region)| region.id())
.collect::<Vec<Uuid>>();
osagactx.datastore().regions_hard_delete(log, region_ids).await?;
Ok(())
}
async fn ssc_regions_ensure(
sagactx: NexusActionContext,
) -> Result<String, ActionError> {
let osagactx = sagactx.user_data();
let log = osagactx.log();
let destination_volume_id =
sagactx.lookup::<Uuid>("destination_volume_id")?;
let datasets_and_regions = ensure_all_datasets_and_regions(
&log,
sagactx.lookup::<Vec<(db::model::Dataset, db::model::Region)>>(
"datasets_and_regions",
)?,
)
.await?;
let block_size = datasets_and_regions[0].1.block_size;
let blocks_per_extent = datasets_and_regions[0].1.extent_size;
let extent_count = datasets_and_regions[0].1.extent_count;
// Create volume construction request
let mut rng = StdRng::from_entropy();
let volume_construction_request = VolumeConstructionRequest::Volume {
id: destination_volume_id,
block_size,
sub_volumes: vec![VolumeConstructionRequest::Region {
block_size,
blocks_per_extent,
extent_count: extent_count.try_into().unwrap(),
gen: 1,
opts: CrucibleOpts {
id: destination_volume_id,
target: datasets_and_regions
.iter()
.map(|(dataset, region)| {
dataset
.address_with_port(region.port_number)
.to_string()
})
.collect(),
lossy: false,
flush_timeout: None,
// all downstairs will expect encrypted blocks
key: Some(base64::Engine::encode(
&base64::engine::general_purpose::STANDARD,
{
// TODO the current encryption key
// requirement is 32 bytes, what if that
// changes?
let mut random_bytes: [u8; 32] = [0; 32];
rng.fill_bytes(&mut random_bytes);
random_bytes
},
)),
// TODO TLS, which requires sending X509 stuff during
// downstairs region allocation too.
cert_pem: None,
key_pem: None,
root_cert_pem: None,
control: None,
// TODO while the transfer of blocks is occurring to the
// destination volume, the opt here should be read-write. When
// the transfer has completed, update the volume to make it
// read-only.
read_only: false,
},
}],
read_only_parent: None,
};
let volume_data = serde_json::to_string(&volume_construction_request)
.map_err(|e| {
ActionError::action_failed(Error::internal_error(&e.to_string()))
})?;
Ok(volume_data)
}
async fn ssc_regions_ensure_undo(
sagactx: NexusActionContext,
) -> Result<(), anyhow::Error> {
let log = sagactx.user_data().log();
warn!(log, "ssc_regions_ensure_undo: Deleting crucible regions");
delete_crucible_regions(
log,
sagactx.lookup::<Vec<(db::model::Dataset, db::model::Region)>>(
"datasets_and_regions",
)?,
)
.await?;
info!(log, "ssc_regions_ensure_undo: Deleted crucible regions");
Ok(())
}
async fn ssc_create_destination_volume_record(
sagactx: NexusActionContext,
) -> Result<(), ActionError> {
let osagactx = sagactx.user_data();
let destination_volume_id =
sagactx.lookup::<Uuid>("destination_volume_id")?;
let destination_volume_data = sagactx.lookup::<String>("regions_ensure")?;
let volume =
db::model::Volume::new(destination_volume_id, destination_volume_data);
osagactx
.datastore()
.volume_create(volume)
.await
.map_err(ActionError::action_failed)?;
Ok(())
}
async fn ssc_create_destination_volume_record_undo(
sagactx: NexusActionContext,
) -> Result<(), anyhow::Error> {
let log = sagactx.user_data().log();
let osagactx = sagactx.user_data();
let destination_volume_id =
sagactx.lookup::<Uuid>("destination_volume_id")?;
// This saga contains what is necessary to clean up the destination volume
// resources. It's safe here to perform a volume hard delete without
// decreasing the crucible resource count because the destination volume is
// guaranteed to never have read only resources that require that
// accounting.
info!(log, "hard deleting volume {}", destination_volume_id,);
osagactx.datastore().volume_hard_delete(destination_volume_id).await?;
Ok(())
}
async fn ssc_create_snapshot_record(
sagactx: NexusActionContext,
) -> Result<db::model::Snapshot, ActionError> {
let log = sagactx.user_data().log();
let osagactx = sagactx.user_data();
let params = sagactx.saga_params::<Params>()?;
let opctx = crate::context::op_context_for_saga_action(
&sagactx,
¶ms.serialized_authn,
);
let snapshot_id = sagactx.lookup::<Uuid>("snapshot_id")?;
// We admittedly reference the volume(s) before they have been allocated,
// but this should be acceptable because the snapshot remains in a
// "Creating" state until the saga has completed.
let volume_id = sagactx.lookup::<Uuid>("volume_id")?;
let destination_volume_id =
sagactx.lookup::<Uuid>("destination_volume_id")?;
info!(log, "grabbing disk by name {}", params.create_params.disk);
let (.., disk) = LookupPath::new(&opctx, &osagactx.datastore())
.disk_id(params.disk_id)
.fetch()
.await
.map_err(ActionError::action_failed)?;
info!(log, "creating snapshot {} from disk {}", snapshot_id, disk.id());
let snapshot = db::model::Snapshot {
identity: db::model::SnapshotIdentity::new(
snapshot_id,
params.create_params.identity.clone(),
),
project_id: params.project_id,
disk_id: disk.id(),
volume_id,
destination_volume_id,
gen: db::model::Generation::new(),
state: db::model::SnapshotState::Creating,
block_size: disk.block_size,
size: disk.size,
};
let (.., authz_project) = LookupPath::new(&opctx, &osagactx.datastore())
.project_id(params.project_id)
.lookup_for(authz::Action::CreateChild)
.await
.map_err(ActionError::action_failed)?;
let snapshot_created = osagactx
.datastore()
.project_ensure_snapshot(&opctx, &authz_project, snapshot)
.await
.map_err(ActionError::action_failed)?;
info!(log, "created snapshot {} ok", snapshot_id);
Ok(snapshot_created)
}
async fn ssc_create_snapshot_record_undo(
sagactx: NexusActionContext,
) -> Result<(), anyhow::Error> {
let log = sagactx.user_data().log();
let osagactx = sagactx.user_data();
let params = sagactx.saga_params::<Params>()?;
let opctx = crate::context::op_context_for_saga_action(
&sagactx,
¶ms.serialized_authn,
);
let snapshot_id = sagactx.lookup::<Uuid>("snapshot_id")?;
info!(log, "deleting snapshot {}", snapshot_id);
let (.., authz_snapshot, db_snapshot) =
LookupPath::new(&opctx, &osagactx.datastore())
.snapshot_id(snapshot_id)
.fetch_for(authz::Action::Delete)
.await
.map_err(ActionError::action_failed)?;
osagactx
.datastore()
.project_delete_snapshot(
&opctx,
&authz_snapshot,
&db_snapshot,
vec![
db::model::SnapshotState::Creating,
db::model::SnapshotState::Ready,
db::model::SnapshotState::Faulted,
],
)
.await?;
Ok(())
}
async fn ssc_account_space(
sagactx: NexusActionContext,
) -> Result<(), ActionError> {
let osagactx = sagactx.user_data();
let params = sagactx.saga_params::<Params>()?;
let snapshot_created =
sagactx.lookup::<db::model::Snapshot>("created_snapshot")?;
let opctx = crate::context::op_context_for_saga_action(
&sagactx,
¶ms.serialized_authn,
);
osagactx
.datastore()
.virtual_provisioning_collection_insert_snapshot(
&opctx,
snapshot_created.id(),
params.project_id,
snapshot_created.size,
)
.await
.map_err(ActionError::action_failed)?;
Ok(())
}
async fn ssc_account_space_undo(
sagactx: NexusActionContext,
) -> Result<(), anyhow::Error> {
let osagactx = sagactx.user_data();
let params = sagactx.saga_params::<Params>()?;
let snapshot_created =
sagactx.lookup::<db::model::Snapshot>("created_snapshot")?;
let opctx = crate::context::op_context_for_saga_action(
&sagactx,
¶ms.serialized_authn,
);
osagactx
.datastore()
.virtual_provisioning_collection_delete_snapshot(
&opctx,
snapshot_created.id(),
params.project_id,
snapshot_created.size,
)
.await?;
Ok(())
}
async fn ssc_send_snapshot_request_to_sled_agent(
sagactx: NexusActionContext,
) -> Result<(), ActionError> {
let log = sagactx.user_data().log();
let osagactx = sagactx.user_data();
let params = sagactx.saga_params::<Params>()?;
let snapshot_id = sagactx.lookup::<Uuid>("snapshot_id")?;
// If this node was reached, the saga initiator thought the disk was
// attached to an instance that was running on a specific sled. Contact that
// sled and ask it to initiate a snapshot. Note that this is best-effort:
// the instance may have stopped (or may be have stopped, had the disk
// detached, and resumed running on the same sled) while the saga was
// executing.
let (instance_id, sled_id) =
params.attached_instance_and_sled.ok_or_else(|| {
ActionError::action_failed(Error::internal_error(
"snapshot saga in send_snapshot_request_to_sled_agent but no \
instance/sled pair was provided",
))
})?;
info!(log, "asking for disk snapshot from Propolis via sled agent";
"disk_id" => %params.disk_id,
"instance_id" => %instance_id,
"sled_id" => %sled_id);
let sled_agent_client = osagactx
.nexus()
.sled_client(&sled_id)
.await
.map_err(ActionError::action_failed)?;
retry_until_known_result(log, || async {
sled_agent_client
.instance_issue_disk_snapshot_request(
&instance_id,
¶ms.disk_id,
&InstanceIssueDiskSnapshotRequestBody { snapshot_id },
)
.await
})
.await
.map_err(|e| e.to_string())
.map_err(ActionError::action_failed)?;
Ok(())
}
async fn ssc_send_snapshot_request_to_sled_agent_undo(
sagactx: NexusActionContext,
) -> Result<(), anyhow::Error> {
let log = sagactx.user_data().log();
let osagactx = sagactx.user_data();
let params = sagactx.saga_params::<Params>()?;
let opctx = crate::context::op_context_for_saga_action(
&sagactx,
¶ms.serialized_authn,
);
let snapshot_id = sagactx.lookup::<Uuid>("snapshot_id")?;
info!(log, "Undoing snapshot request for {snapshot_id}");
// Lookup the regions used by the source disk...
let (.., disk) = LookupPath::new(&opctx, &osagactx.datastore())
.disk_id(params.disk_id)
.fetch()
.await?;
let datasets_and_regions =
osagactx.datastore().get_allocated_regions(disk.volume_id).await?;
// ... and instruct each of those regions to delete the snapshot.
for (dataset, region) in datasets_and_regions {
let url = format!("http://{}", dataset.address());
let client = CrucibleAgentClient::new(&url);
delete_crucible_snapshot(log, &client, region.id(), snapshot_id)
.await?;
}
Ok(())
}
async fn ssc_get_pantry_address(
sagactx: NexusActionContext,
) -> Result<(SocketAddrV6, bool), ActionError> {
let log = sagactx.user_data().log();
let osagactx = sagactx.user_data();
let params = sagactx.saga_params::<Params>()?;
let opctx = crate::context::op_context_for_saga_action(
&sagactx,
¶ms.serialized_authn,
);
// If the disk is already attached to a Pantry, use that, otherwise get a
// random one. Return boolean indicating if additional saga nodes need to
// attach this disk to that random pantry.
let (.., disk) = LookupPath::new(&opctx, &osagactx.datastore())
.disk_id(params.disk_id)
.fetch()
.await
.map_err(ActionError::action_failed)?;
let pantry_address = if let Some(pantry_address) = disk.pantry_address() {
pantry_address
} else {
get_pantry_address(osagactx.nexus()).await?
};
let disk_already_attached_to_pantry = disk.pantry_address().is_some();
info!(
log,
"using pantry at {}{}",
pantry_address,
if disk_already_attached_to_pantry {
" (already attached)"
} else {
""
}
);
Ok((pantry_address, disk_already_attached_to_pantry))
}
async fn ssc_attach_disk_to_pantry(
sagactx: NexusActionContext,
) -> Result<Generation, ActionError> {
let log = sagactx.user_data().log();
let osagactx = sagactx.user_data();
let params = sagactx.saga_params::<Params>()?;
let opctx = crate::context::op_context_for_saga_action(
&sagactx,
¶ms.serialized_authn,
);
let (.., authz_disk, db_disk) =
LookupPath::new(&opctx, &osagactx.datastore())
.disk_id(params.disk_id)
.fetch_for(authz::Action::Modify)
.await
.map_err(ActionError::action_failed)?;
// Query the fetched disk's runtime to see if changed after the saga
// execution started. This can happen if it's attached to an instance, or if
// it's undergoing other maintenance. If it was, then bail out. If it
// wasn't, then try to update the runtime and attach it to the Pantry. In
// the case where the disk is attached to an instance after this lookup, the
// "runtime().maintenance(...)" call below should fail because the
// generation number is too low.
match db_disk.state().into() {
external::DiskState::Detached => {
info!(log, "setting state of {} to maintenance", params.disk_id);
osagactx
.datastore()
.disk_update_runtime(
&opctx,
&authz_disk,
&db_disk.runtime().maintenance(),
)
.await
.map_err(ActionError::action_failed)?;
}
external::DiskState::Finalizing => {
// This saga is a sub-saga of the finalize saga if the user has
// specified an optional snapshot should be taken. No state change
// is required.
info!(log, "disk {} in state finalizing", params.disk_id);
}
_ => {
// Return a 503 indicating that the user should retry
return Err(ActionError::action_failed(
Error::ServiceUnavailable {
internal_message: format!(
"disk is in state {:?}",
db_disk.state(),
),
},
));
}
}
// Record the disk's new generation number as this saga node's output. It
// will be important later to *only* transition this disk out of maintenance
// if the generation number matches what *this* saga is doing.
let (.., db_disk) = LookupPath::new(&opctx, &osagactx.datastore())
.disk_id(params.disk_id)
.fetch_for(authz::Action::Read)
.await
.map_err(ActionError::action_failed)?;
Ok(db_disk.runtime().gen)
}
async fn ssc_attach_disk_to_pantry_undo(
sagactx: NexusActionContext,
) -> Result<(), anyhow::Error> {
let log = sagactx.user_data().log();
let osagactx = sagactx.user_data();
let params = sagactx.saga_params::<Params>()?;
let opctx = crate::context::op_context_for_saga_action(
&sagactx,
¶ms.serialized_authn,
);
let (.., authz_disk, db_disk) =
LookupPath::new(&opctx, &osagactx.datastore())
.disk_id(params.disk_id)
.fetch_for(authz::Action::Modify)
.await
.map_err(ActionError::action_failed)?;
match db_disk.state().into() {
external::DiskState::Maintenance => {
info!(
log,
"undo: setting disk {} state from maintenance to detached",
params.disk_id
);
osagactx
.datastore()
.disk_update_runtime(
&opctx,
&authz_disk,
&db_disk.runtime().detach(),
)
.await
.map_err(ActionError::action_failed)?;
}
external::DiskState::Detached => {
info!(
log,
"undo: disk {} already in state detached", params.disk_id
);
}
external::DiskState::Finalizing => {
info!(
log,
"undo: disk {} already in state finalizing", params.disk_id
);
}
_ => {
warn!(log, "undo: disk is in state {:?}", db_disk.state());
}
}
Ok(())
}
async fn ssc_call_pantry_attach_for_disk(
sagactx: NexusActionContext,
) -> Result<(), ActionError> {
let log = sagactx.user_data().log();
let osagactx = sagactx.user_data();
let params = sagactx.saga_params::<Params>()?;
let opctx = crate::context::op_context_for_saga_action(
&sagactx,
¶ms.serialized_authn,
);
let (pantry_address, disk_already_attached_to_pantry) =
sagactx.lookup::<(SocketAddrV6, bool)>("pantry_address")?;
if !disk_already_attached_to_pantry {
info!(
log,
"attaching disk {:?} to pantry at {:?}",
params.disk_id,
pantry_address
);
call_pantry_attach_for_disk(
&log,
&opctx,
&osagactx.nexus(),
params.disk_id,
pantry_address,
)
.await?;
} else {
info!(log, "disk {} already attached to a pantry", params.disk_id);
}
Ok(())
}
async fn ssc_call_pantry_attach_for_disk_undo(
sagactx: NexusActionContext,
) -> Result<(), anyhow::Error> {
let log = sagactx.user_data().log();
let params = sagactx.saga_params::<Params>()?;
let (pantry_address, disk_already_attached_to_pantry) =
sagactx.lookup::<(SocketAddrV6, bool)>("pantry_address")?;
// If the disk came into this saga attached to a pantry, don't detach it
if !disk_already_attached_to_pantry {
info!(
log,
"undo: detaching disk {:?} from pantry at {:?}",
params.disk_id,
pantry_address
);
call_pantry_detach_for_disk(&log, params.disk_id, pantry_address)
.await?;
} else {
info!(
log,
"undo: not detaching disk {}, was already attached to a pantry",
params.disk_id
);
}
Ok(())
}
async fn ssc_call_pantry_snapshot_for_disk(
sagactx: NexusActionContext,
) -> Result<(), ActionError> {
let log = sagactx.user_data().log();
let params = sagactx.saga_params::<Params>()?;
let (pantry_address, _) =
sagactx.lookup::<(SocketAddrV6, bool)>("pantry_address")?;