forked from oxidecomputer/crucible
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdownstairs.rs
10284 lines (9050 loc) · 351 KB
/
downstairs.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
// Copyright 2023 Oxide Computer Company
use std::{
collections::{BTreeMap, BTreeSet, HashMap, VecDeque},
net::SocketAddr,
sync::Arc,
};
use crate::{
cdt,
client::{ClientAction, ClientRequest, ClientStopReason, DownstairsClient},
guest::GuestWork,
live_repair::ExtentInfo,
stats::UpStatOuter,
upstairs::{UpstairsConfig, UpstairsState},
AckStatus, ActiveJobs, AllocRingBuffer, ClientData, ClientIOStateCount,
ClientId, ClientMap, CrucibleError, DownstairsIO, DownstairsMend, DsState,
ExtentFix, ExtentRepairIDs, GuestWorkId, IOState, IOStateCount, IOop,
ImpactedBlocks, JobId, Message, RawMessage, ReadRequest, ReadResponse,
ReconcileIO, ReconciliationId, RegionDefinition, ReplaceResult,
SerializedWrite, SnapshotDetails, WorkSummary,
};
use crucible_common::MAX_ACTIVE_COUNT;
use rand::prelude::*;
use ringbuffer::RingBuffer;
use slog::{debug, error, info, o, warn, Logger};
use uuid::Uuid;
/// Downstairs data
///
/// This data structure is responsible for tracking outstanding jobs from the
/// perspective of the (3x) downstairs. It contains a list of all active jobs,
/// as well as three `DownstairsClient` with per-client data.
#[derive(Debug)]
pub(crate) struct Downstairs {
/// Shared configuration
cfg: Arc<UpstairsConfig>,
/// Per-client data
pub(crate) clients: ClientData<DownstairsClient>,
/// The active list of IO for the downstairs.
pub(crate) ds_active: ActiveJobs,
/// The number of write bytes that haven't finished yet
///
/// This is used to configure backpressure to the host, because writes
/// (uniquely) will return before actually being completed by a Downstairs
/// and can clog up the queues.
///
/// It is stored in the Downstairs because from the perspective of the
/// Upstairs, writes complete immediately; only the Downstairs is actually
/// tracking the pending jobs.
write_bytes_outstanding: u64,
/// The next Job ID this Upstairs should use for downstairs work.
next_id: JobId,
/// Current flush number
///
/// This starts as the highest flush number from all three downstairs on
/// startup, and increments by one each time the guest sends a flush
/// (including automatic flushes).
next_flush: u64,
/// Ringbuf of completed downstairs job IDs.
completed: AllocRingBuffer<JobId>,
/// Ringbuf of a summary of each recently completed downstairs IO.
completed_jobs: AllocRingBuffer<WorkSummary>,
/// Current piece of reconcile work that the downstairs are working on
///
/// It can be New, InProgress, Skipped, or Done.
reconcile_current_work: Option<ReconcileIO>,
/// Remaining reconciliation work
///
/// This queue holds the remaining work required to make all three
/// downstairs in a region set the same.
reconcile_task_list: VecDeque<ReconcileIO>,
/// Number of extents repaired during initial activation
reconcile_repaired: usize,
/// Number of extents needing repair during initial activation
reconcile_repair_needed: usize,
/// The logger for messages sent from downstairs methods.
log: Logger,
/// Data for an in-progress live repair
repair: Option<LiveRepairData>,
/// Jobs that are ready to be acked
///
/// This must be handled after every event
ackable_work: BTreeSet<JobId>,
}
/// State machine for a live-repair operation
///
/// We pass through all states (except `FinalFlush`) in order for each extent,
/// then pass through the `FinalFlush` state before completion. In each state,
/// we're waiting for a particular job to finish, which is indicated by a
/// `BlockReqWaiter`.
///
/// Early states carry around reserved IDs (both `JobId` and guest work IDs), as
/// well as a reserved `BlockReqWaiter` for the final flush.
#[derive(Copy, Clone, Debug)]
pub(crate) enum LiveRepairState {
Closing {
close_id: JobId,
repair_id: JobId,
noop_id: JobId,
reopen_id: JobId,
gw_repair_id: GuestWorkId,
gw_noop_id: GuestWorkId,
},
Repairing {
repair_id: JobId,
noop_id: JobId,
reopen_id: JobId,
gw_noop_id: GuestWorkId,
},
Noop {
noop_id: JobId,
reopen_id: JobId,
},
Reopening {
reopen_id: JobId,
},
FinalFlush {
flush_id: JobId,
},
}
impl LiveRepairState {
/// Returns the job ID that we're waiting on at the moment
fn active_job_id(&self) -> JobId {
match self {
LiveRepairState::Closing { close_id, .. } => *close_id,
LiveRepairState::Repairing { repair_id, .. } => *repair_id,
LiveRepairState::Noop { noop_id, .. } => *noop_id,
LiveRepairState::Reopening { reopen_id, .. } => *reopen_id,
LiveRepairState::FinalFlush { flush_id } => *flush_id,
}
}
}
#[derive(Debug)]
pub(crate) struct LiveRepairData {
/// Total number of extents that need checking
extent_count: u64,
/// Extent being repaired
pub active_extent: u64,
/// Minimum job ID the downstairs under repair needs to consider for deps
min_id: JobId,
/// Reserved live-repair job IDs
///
/// If, while running live repair, we have an IO that spans repaired extents
/// and not yet repaired extents, we will reserve job IDs for the future
/// repair work and store them in this hash map. When it comes time to
/// start a repair and allocate the job IDs we will require, we first check
/// this hash map to see if the IDs were already repaired.
///
/// The key is the extent being repaired; the value is a tuple of reserved
/// IDs and existing dependencies for the first job in the repair.
repair_job_ids: BTreeMap<u64, (ExtentRepairIDs, Vec<JobId>)>,
/// Downstairs providing repair info
source_downstairs: ClientId,
/// Downstairs being repaired
repair_downstairs: Vec<ClientId>,
/// Repair is being aborted
///
/// This means that new operations are replaced with `LiveRepairNoOp`, so
/// that previously submitted operations that depend on them will still
/// happen. We'll stop repairing after the current extent (and all reserved
/// jobs) are handled, then send a final flush.
aborting_repair: bool,
/// Current state
state: LiveRepairState,
}
#[derive(Debug)]
pub(crate) enum DownstairsAction {
/// We received a client action from the given client
Client {
client_id: ClientId,
action: ClientAction,
},
}
impl Downstairs {
pub(crate) fn new(
cfg: Arc<UpstairsConfig>,
ds_target: ClientMap<SocketAddr>,
tls_context: Option<Arc<crucible_common::x509::TLSContext>>,
log: Logger,
) -> Self {
let mut clients = [None, None, None];
for i in ClientId::iter() {
clients[i.get() as usize] = Some(DownstairsClient::new(
i,
cfg.clone(),
ds_target.get(&i).copied(),
log.new(o!("client" => i.get().to_string())),
tls_context.clone(),
));
}
let clients = clients.map(Option::unwrap);
Self {
clients: ClientData(clients),
cfg,
next_flush: 0,
ds_active: ActiveJobs::new(),
write_bytes_outstanding: 0,
completed: AllocRingBuffer::new(2048),
completed_jobs: AllocRingBuffer::new(8),
next_id: JobId(1000),
reconcile_current_work: None,
reconcile_task_list: VecDeque::new(),
reconcile_repaired: 0,
reconcile_repair_needed: 0,
log: log.new(o!("" => "downstairs".to_string())),
ackable_work: BTreeSet::new(),
repair: None,
}
}
/// Build a `Downstairs` for simple tests
///
/// Note that this `Downstairs` does not have valid socket addresses, so the
/// client tasks won't start!
#[cfg(test)]
pub fn test_default() -> Self {
let log = crucible_common::build_logger();
let cfg = Arc::new(UpstairsConfig {
upstairs_id: Uuid::new_v4(),
session_id: Uuid::new_v4(),
generation: std::sync::atomic::AtomicU64::new(1),
read_only: false,
encryption_context: None,
lossy: false,
});
let mut ds = Self::new(cfg, ClientMap::new(), None, log);
// Create a fake repair address so this field is populated.
for cid in ClientId::iter() {
ds.clients[cid].repair_addr =
Some("127.0.0.1:1234".parse().unwrap());
}
ds
}
/// Choose which `DownstairsAction` to apply
///
/// This function is called from within a top-level `select!`, so not only
/// must the select expressions be cancel safe, but the **bodies** must also
/// be cancel-safe. This is why we simply return a single value in the body
/// of each statement.
pub(crate) async fn select(&mut self) -> DownstairsAction {
// Split borrow of the clients
let [ca, cb, cc] = &mut self.clients.0;
tokio::select! {
action = ca.select() => {
DownstairsAction::Client {
client_id: ClientId::new(0),
action
}
}
action = cb.select() => {
DownstairsAction::Client {
client_id: ClientId::new(1),
action
}
}
action = cc.select() => {
DownstairsAction::Client {
client_id: ClientId::new(2),
action
}
}
}
}
/// Checks whether we have ackable work
pub(crate) fn has_ackable_jobs(&self) -> bool {
!self.ackable_work.is_empty()
}
/// Send back acks for all jobs that are `AckReady`
pub(crate) async fn ack_jobs(
&mut self,
gw: &mut GuestWork,
up_stats: &UpStatOuter,
) {
debug!(self.log, "ack_jobs called in Downstairs");
let ack_list = std::mem::take(&mut self.ackable_work);
let jobs_checked = ack_list.len();
for ds_id_done in ack_list.iter() {
self.ack_job(*ds_id_done, gw, up_stats).await;
}
debug!(self.log, "ack_ready handled {jobs_checked} jobs");
}
/// Send the ack for a single job back upstairs through `GuestWork`
///
/// Update stats for the upstairs as well
///
/// This is public for the sake of unit testing, but shouldn't be called
/// outside of this module normally.
async fn ack_job(
&mut self,
ds_id: JobId,
gw: &mut GuestWork,
up_stats: &UpStatOuter,
) {
debug!(self.log, "ack_jobs process {}", ds_id);
let done = self.ds_active.get_mut(&ds_id).unwrap();
assert!(!done.acked);
let gw_id = done.guest_id;
assert_eq!(done.ds_id, ds_id);
let data = done.data.take();
done.acked = true;
let r = done.result();
Self::cdt_gw_work_done(done, up_stats);
debug!(self.log, "[A] ack job {}:{}", ds_id, gw_id);
gw.gw_ds_complete(gw_id, ds_id, data, r, &self.log).await;
self.retire_check(ds_id);
}
/// Match on the `IOop` type, update stats, and fire DTrace probes
fn cdt_gw_work_done(job: &DownstairsIO, stats: &UpStatOuter) {
let gw_id = job.guest_id;
let io_size = job.io_size();
match &job.work {
IOop::Read { .. } => {
cdt::gw__read__done!(|| (gw_id.0));
stats.add_read(io_size as i64);
}
IOop::Write { .. } => {
cdt::gw__write__done!(|| (gw_id.0));
stats.add_write(io_size as i64);
}
IOop::WriteUnwritten { .. } => {
cdt::gw__write__unwritten__done!(|| (gw_id.0));
// We don't include WriteUnwritten operation in the
// metrics for this guest.
}
IOop::Flush { .. } => {
cdt::gw__flush__done!(|| (gw_id.0));
stats.add_flush();
}
IOop::ExtentFlushClose { extent, .. } => {
cdt::gw__close__done!(|| (gw_id.0, extent));
stats.add_flush_close();
}
IOop::ExtentLiveRepair { extent, .. } => {
cdt::gw__repair__done!(|| (gw_id.0, extent));
stats.add_extent_repair();
}
IOop::ExtentLiveNoOp { .. } => {
cdt::gw__noop__done!(|| (gw_id.0));
stats.add_extent_noop();
}
IOop::ExtentLiveReopen { extent, .. } => {
cdt::gw__reopen__done!(|| (gw_id.0, extent));
stats.add_extent_reopen();
}
}
}
pub(crate) async fn io_send(&mut self, client_id: ClientId) -> bool {
// Send as many jobs as possible to the downstairs, limited by
// `MAX_ACTIVE_COUNT`.
//
// This XXX is for coming back here and making a better job of
// flow control; see RFD 445 for details.
let client = &mut self.clients[client_id];
let (new_work, flow_control) = {
let active_count = client.io_state_count.in_progress as usize;
if active_count > MAX_ACTIVE_COUNT {
// Can't do any work
client.stats.flow_control += 1;
return true;
} else {
let n = MAX_ACTIVE_COUNT - active_count;
let (new_work, flow_control) = client.new_work(n);
if flow_control {
client.stats.flow_control += 1;
}
(new_work, flow_control)
}
};
/*
* Now we have a list of all the job IDs that are new for our client id.
* Walk this list and process each job, marking it InProgress as we
* do the work. We do this in two loops because we can't hold the
* lock for the hashmap while we do work, and if we release the lock
* to do work, we would have to start over and look at all jobs in the
* map to see if they are new.
*/
for new_id in new_work {
/*
* Walk the list of work to do, update its status as in progress
* and send the details to our downstairs.
*/
if self.cfg.lossy && random() && random() {
/*
* Requeue this work so it isn't completely lost.
*/
self.clients[client_id].requeue_one(new_id);
continue;
}
/*
* If in_progress returns None, it means that this job on this
* client should be skipped.
*/
let Some(job) = self.in_progress(new_id, client_id) else {
continue;
};
let message = match job {
IOop::Write { dependencies, data } => {
cdt::ds__write__io__start!(|| (new_id.0, client_id.get()));
ClientRequest::RawMessage(
RawMessage::Write {
upstairs_id: self.cfg.upstairs_id,
session_id: self.cfg.session_id,
job_id: new_id,
dependencies,
},
data.data,
)
}
IOop::WriteUnwritten { dependencies, data } => {
cdt::ds__write__unwritten__io__start!(|| (
new_id.0,
client_id.get()
));
ClientRequest::RawMessage(
RawMessage::WriteUnwritten {
upstairs_id: self.cfg.upstairs_id,
session_id: self.cfg.session_id,
job_id: new_id,
dependencies,
},
data.data,
)
}
IOop::Flush {
dependencies,
flush_number,
gen_number,
snapshot_details,
extent_limit,
} => {
cdt::ds__flush__io__start!(|| (new_id.0, client_id.get()));
ClientRequest::Message(Message::Flush {
upstairs_id: self.cfg.upstairs_id,
session_id: self.cfg.session_id,
job_id: new_id,
dependencies,
flush_number,
gen_number,
snapshot_details,
extent_limit,
})
}
IOop::Read {
dependencies,
requests,
} => {
cdt::ds__read__io__start!(|| (new_id.0, client_id.get()));
ClientRequest::Message(Message::ReadRequest {
upstairs_id: self.cfg.upstairs_id,
session_id: self.cfg.session_id,
job_id: new_id,
dependencies,
requests,
})
}
IOop::ExtentFlushClose {
dependencies,
extent,
flush_number,
gen_number,
repair_downstairs,
} => {
cdt::ds__close__start!(|| (
new_id.0,
client_id.get(),
extent
));
if repair_downstairs.contains(&client_id) {
// We are the downstairs being repaired, so just close.
ClientRequest::Message(Message::ExtentLiveClose {
upstairs_id: self.cfg.upstairs_id,
session_id: self.cfg.session_id,
job_id: new_id,
dependencies,
extent_id: extent,
})
} else {
ClientRequest::Message(Message::ExtentLiveFlushClose {
upstairs_id: self.cfg.upstairs_id,
session_id: self.cfg.session_id,
job_id: new_id,
dependencies,
extent_id: extent,
flush_number,
gen_number,
})
}
}
IOop::ExtentLiveRepair {
dependencies,
extent,
source_downstairs,
source_repair_address,
repair_downstairs,
} => {
cdt::ds__repair__start!(|| (
new_id.0,
client_id.get(),
extent
));
if repair_downstairs.contains(&client_id) {
ClientRequest::Message(Message::ExtentLiveRepair {
upstairs_id: self.cfg.upstairs_id,
session_id: self.cfg.session_id,
job_id: new_id,
dependencies,
extent_id: extent,
source_client_id: source_downstairs,
source_repair_address,
})
} else {
ClientRequest::Message(Message::ExtentLiveNoOp {
upstairs_id: self.cfg.upstairs_id,
session_id: self.cfg.session_id,
job_id: new_id,
dependencies,
})
}
}
IOop::ExtentLiveReopen {
dependencies,
extent,
} => {
cdt::ds__reopen__start!(|| (
new_id.0,
client_id.get(),
extent
));
ClientRequest::Message(Message::ExtentLiveReopen {
upstairs_id: self.cfg.upstairs_id,
session_id: self.cfg.session_id,
job_id: new_id,
dependencies,
extent_id: extent,
})
}
IOop::ExtentLiveNoOp { dependencies } => {
cdt::ds__noop__start!(|| (new_id.0, client_id.get()));
ClientRequest::Message(Message::ExtentLiveNoOp {
upstairs_id: self.cfg.upstairs_id,
session_id: self.cfg.session_id,
job_id: new_id,
dependencies,
})
}
};
self.clients[client_id].send(message).await
}
flow_control
}
/// Mark this request as in progress for this client, and return the
/// relevant [`IOOp`] with updated dependencies.
///
/// If the job state is already [`IOState::Skipped`], then this task
/// has no work to do, so return `None`.
///
/// This is normally called only from `io_send`, but is also used for unit
/// test which check how jobs flow through the system.
fn in_progress(
&mut self,
ds_id: JobId,
client_id: ClientId,
) -> Option<IOop> {
let Some(job) = self.ds_active.get_mut(&ds_id) else {
// This job, that we thought was good, is not. As we don't
// keep the lock when gathering job IDs to work on, it is
// possible to have a out of date work list.
warn!(self.log, "[{client_id}] Job {ds_id} not on active list");
return None;
};
// If current state is Skipped, then we have nothing to do here.
if matches!(job.state[client_id], IOState::Skipped) {
return None;
}
Some(
self.clients[client_id]
.in_progress(job, self.repair.as_ref().map(|r| r.min_id)),
)
}
/// Reinitialize the given client
pub(crate) fn reinitialize(
&mut self,
client_id: ClientId,
auto_promote: bool,
up_state: &UpstairsState,
) {
let prev_state = self.clients[client_id].state();
// If the connection goes down here, we need to know what state we were
// in to decide what state to transition to. The on_missing method will
// do that for us!
self.clients[client_id].on_missing();
// If the IO task stops on its own, then under certain circumstances,
// we want to skip all of its jobs. (If we requested that the IO task
// stop, then whoever made that request is responsible for skipping jobs
// if necessary).
//
// Specifically, we want to skip jobs if the only path back online for
// that client goes through live-repair; if that client can come back
// through replay, then the jobs must remain live.
let new_state = self.clients[client_id].state();
if matches!(prev_state, DsState::LiveRepair | DsState::Active)
&& matches!(new_state, DsState::Faulted)
{
self.skip_all_jobs(client_id);
}
// Restart the IO task for that specific client
self.clients[client_id].reinitialize(auto_promote);
for i in ClientId::iter() {
// Clear per-client delay, because we're starting a new session
self.clients[i].set_delay_us(0);
}
// Special-case: if a Downstairs goes away midway through initial
// reconciliation, then we have to manually abort reconciliation.
if self.clients.iter().any(|c| c.state() == DsState::Reconcile) {
self.abort_reconciliation(up_state);
}
// If this client is coming back from being offline, then replay all of
// its jobs.
if self.clients[client_id].state() == DsState::Offline {
self.replay_jobs(client_id);
}
}
/// Returns true if we can deactivate immediately
///
/// This is the case if there are no pending jobs in the queue.
///
/// # Panics
/// If any downstairs is offline
pub(crate) fn can_deactivate_immediately(&self) -> bool {
/*
* If any downstairs are currently offline, then we are going
* to lock the door behind them and not let them back in until
* all non-offline downstairs have deactivated themselves.
*
* However: TODO: This is not done yet.
*/
let offline_ds: Vec<ClientId> = self
.clients
.iter()
.enumerate()
.filter(|(_i, c)| c.state() == DsState::Offline)
.map(|(i, _c)| ClientId::new(i as u8))
.collect();
/*
* TODO: Handle deactivation when a downstairs is offline.
*/
if !offline_ds.is_empty() {
panic!("Can't deactivate with downstairs offline (yet)");
}
// If there are no jobs, then we're immediately done!
self.ds_active.is_empty()
}
/// Tries to deactivate the given client
///
/// If successful, the client state will be set to `Deactivated` and the IO
/// task will be stopped. This will trigger a `ClientAction::TaskStopped`
/// in the main task, which will in turn restart the IO task.
///
/// Returns `true` on success, `false` otherwise
///
/// # Panics
/// If `up_state` is not `UpstairsState::Deactivating`
pub(crate) fn try_deactivate(
&mut self,
client_id: ClientId,
up_state: &UpstairsState,
) -> bool {
assert!(
matches!(up_state, UpstairsState::Deactivating { .. }),
"up_state must be Deactivating, not {up_state:?}"
);
if self.ds_active.is_empty() {
info!(self.log, "[{}] deactivate, no work so YES", client_id);
self.clients[client_id].deactivate(up_state);
return true;
}
// If there are jobs in the queue, then we have to check them!
let last_id = self.ds_active.keys().next_back().unwrap();
/*
* The last job must be a flush. It's possible to get
* here right after deactivating is set, but before the final
* flush happens.
*/
if !self.is_flush(*last_id) {
info!(
self.log,
"[{}] deactivate last job {} not flush, NO", client_id, last_id
);
return false;
}
/*
* Now count our jobs. Any job not done or skipped means
* we are not ready to deactivate.
*/
for (id, job) in &self.ds_active {
let state = &job.state[client_id];
if state == &IOState::New || state == &IOState::InProgress {
info!(
self.log,
"[{}] deactivate job {} not {:?} flush, NO",
client_id,
id,
state
);
return false;
}
}
/*
* To arrive here, we verified our most recent job is a flush, and
* none of the jobs that are on our active job list are New or
* InProgress (either error, skipped, or done)
*/
info!(self.log, "[{}] check deactivate YES", client_id);
self.clients[client_id].deactivate(up_state);
true
}
/// Assign a new downstairs job ID.
fn next_id(&mut self) -> JobId {
let id = self.next_id;
self.next_id.0 += 1;
id
}
/// What would next_id return, if we called it?
#[cfg(test)]
pub(crate) fn peek_next_id(&self) -> JobId {
self.next_id
}
/// Moves all pending jobs back to the `new_jobs` queue
///
/// Jobs are pending if they have not yet been flushed by this client.
fn replay_jobs(&mut self, client_id: ClientId) {
let lf = self.clients[client_id].last_flush();
info!(
self.log,
"[{client_id}] client re-new {} jobs since flush {lf}",
self.ds_active.len(),
);
self.ds_active.for_each(|ds_id, job| {
// We don't need to send anything before our last good flush
if *ds_id <= lf {
assert_eq!(IOState::Done, job.state[client_id]);
return;
}
self.clients[client_id].replay_job(job);
});
}
/// Compare downstairs region metadata and based on the results:
///
/// Determine the global flush number for this region set.
/// Verify the guest given gen number is highest.
/// Decide if we need repair, and if so create the repair list
///
/// Returns `true` if repair is needed, `false` otherwise
pub(crate) fn collate(&mut self) -> Result<bool, CrucibleError> {
let r = self.collate_inner();
if r.is_err() {
// If we failed to begin the repair, then assert that nothing has
// changed and everything is empty.
assert!(self.ds_active.is_empty());
assert!(self.reconcile_task_list.is_empty());
for c in self.clients.iter() {
assert_eq!(c.state(), DsState::WaitQuorum);
}
}
r
}
fn collate_inner(&mut self) -> Result<bool, CrucibleError> {
/*
* Show some (or all if small) of the info from each region.
*
* This loop is load bearing, we use this loop to get the
* max flush number. Eventually the max flush will come after
* we have done any repair we need to do. Since we don't have
* that code yet, we are making use of this loop to find our
* max.
*/
let mut max_flush = 0;
let mut max_gen = 0;
for (cid, rec) in self
.clients
.iter()
.map(|c| c.region_metadata.as_ref().unwrap())
.enumerate()
{
let mf = rec.flush_numbers.iter().max().unwrap() + 1;
if mf > max_flush {
max_flush = mf;
}
let mg = rec.generation.iter().max().unwrap() + 1;
if mg > max_gen {
max_gen = mg;
}
if rec.flush_numbers.len() > 12 {
info!(
self.log,
"[{}]R flush_numbers[0..12]: {:?}",
cid,
rec.flush_numbers[0..12].to_vec()
);
info!(
self.log,
"[{}]R generation[0..12]: {:?}",
cid,
rec.generation[0..12].to_vec()
);
info!(
self.log,
"[{}]R dirty[0..12]: {:?}",
cid,
rec.dirty[0..12].to_vec()
);
} else {
info!(
self.log,
"[{}]R flush_numbers: {:?}", cid, rec.flush_numbers
);
info!(self.log, "[{}]R generation: {:?}", cid, rec.generation);
info!(self.log, "[{}]R dirty: {:?}", cid, rec.dirty);
}
}
info!(self.log, "Max found gen is {}", max_gen);
/*
* Verify that the generation number that the guest has requested
* is higher than what we have from the three downstairs.
*/
let requested_gen = self.cfg.generation();
if requested_gen == 0 {
error!(self.log, "generation number should be at least 1");
return Err(CrucibleError::GenerationNumberTooLow(
"Generation 0 illegal".to_owned(),
));
} else if requested_gen < max_gen {
/*
* We refuse to connect. The provided generation number is not
* high enough to let us connect to these downstairs.
*/
error!(
self.log,
"found generation number {}, larger than requested: {}",
max_gen,
requested_gen,
);
return Err(CrucibleError::GenerationNumberTooLow(format!(
"found generation number {}, larger than requested: {}",
max_gen, requested_gen,
)));
} else {
info!(
self.log,
"Generation requested: {} >= found:{}", requested_gen, max_gen,
);
}
/*
* Set the next flush ID so we have if we need to repair.
*/
self.next_flush = max_flush;
info!(self.log, "Next flush: {}", max_flush);
/*
* Determine what extents don't match and what to do
* about that
*/
if let Some(reconcile_list) = self.mismatch_list() {
for c in self.clients.iter_mut() {
c.begin_reconcile();
}
info!(
self.log,
"Found {:?} extents that need repair",
reconcile_list.mend.len()
);
self.convert_rc_to_messages(
reconcile_list.mend,
max_flush,
max_gen,
);
self.reconcile_repair_needed = self.reconcile_task_list.len();
Ok(true)
} else {
info!(self.log, "All extents match");
Ok(false)
}
}
/// Checks whether a live-repair is in progress
pub(crate) fn live_repair_in_progress(&self) -> bool {
// A live-repair is in progress if any client is in the LiveRepair
// state, _or_ if `self.repair.is_some()`. The latter is necessary
// because if a live-repair encountered an error, that downstairs will
// be marked as Faulted, but we still need to keep going through the
// existing live-repair before retrying.
self.clients
.iter()
.any(|c| c.state() == DsState::LiveRepair)
|| self.repair.is_some()
}
/// Tries to start live-repair
///
/// Returns true on success, false otherwise; the only time it returns
/// `false` is if there are no clients in `DsState::Active` to serve as
/// sources for live-repair.
///
/// # Panics
/// If `self.repair.is_some()` (because that means a repair is already in
/// progress), or if no clients are in `LiveRepairReady`
pub(crate) fn start_live_repair(
&mut self,
up_state: &UpstairsState,
gw: &mut GuestWork,
extent_count: u64,
) -> bool {
assert!(self.repair.is_none());
// Move the upstairs that were LiveRepairReady to LiveRepair
//
// After this point, we must call `abort_repair` if something goes wrong
// to abort the repair on the troublesome clients.
for c in self.clients.iter_mut() {
c.start_live_repair(up_state);
}
// Begin setting up live-repair state
let mut repair_downstairs = vec![];
let mut source_downstairs = None;
for cid in ClientId::iter() {
match self.clients[cid].state() {