-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathcli.rs
1238 lines (1192 loc) · 42.3 KB
/
cli.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::borrow::Cow;
use std::net::SocketAddr;
use dsc_client::Client;
use futures::{SinkExt, StreamExt};
use reedline::{
FileBackedHistory, Prompt, PromptEditMode, PromptHistorySearch, Reedline,
Signal,
};
use tokio::net::tcp::WriteHalf;
use tokio::net::{TcpListener, TcpSocket, TcpStream};
use tokio_util::codec::{FramedRead, FramedWrite};
use super::*;
use protocol::*;
#[derive(Debug, Parser)]
#[clap(name = "Cli", term_width = 80, no_binary_name = true)]
pub struct CliAction {
#[clap(subcommand)]
cmd: CliCommand,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Debug, Parser, PartialEq)]
pub enum DscCommand {
/// IP:Port for a dsc server
/// #[clap(long, global = true, default_value = "127.0.0.1:9998", action)]
Connect { server: SocketAddr },
/// Disable random stopping of downstairs
DisableRandomStop,
/// Disable auto restart on the given downstairs client ID
DisableRestart {
#[clap(long, short, action)]
cid: u32,
},
/// Disable auto restart on all downstairs
DisableRestartAll,
/// Enable restart on the given client ID
EnableRestart {
#[clap(long, short, action)]
cid: u32,
},
/// Enable random stopping of downstairs
EnableRandomStop,
/// Set the minimum random stop time (in seconds)
EnableRandomMin {
#[clap(long, short, action)]
min: u64,
},
/// Set the maximum random stop time (in seconds)
EnableRandomMax {
#[clap(long, short, action)]
max: u64,
},
/// Enable auto restart on all downstairs
EnableRestartAll,
/// Shutdown all downstairs, then shutdown dsc itself.
Shutdown,
/// Start the downstairs at the given client ID
Start {
#[clap(long, short, action)]
cid: u32,
},
/// Start all downstairs
StartAll,
/// Get the state of the given client ID
State {
#[clap(long, short, action)]
cid: u32,
},
/// Stop the downstairs at the given client ID
Stop {
#[clap(long, short, action)]
cid: u32,
},
/// Stop all the downstairs
StopAll,
/// Stop a random downstairs
StopRand,
}
/*
* Commands supported by the crucible CLI. Most of these translate into
* an actual BlockOpt, but some are processed locally, and some happen
* on the cli_server side.
*/
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Debug, Parser, PartialEq)]
#[clap(name = "", term_width = 80, no_binary_name = true)]
enum CliCommand {
/// Send an activation message and wait for an answer.
Activate {
/// Specify this generation number to use when requesting activation.
#[clap(long, short, default_value = "1", action)]
gen: u64,
},
/// Send an activation message and don't wait for an answer.
///
/// This will spawn a background task that will wait on the result of
/// the request and display a message with the result when it comes.
ActivateRequest {
/// Specify this generation number to use when requesting activation.
#[clap(long, short, default_value = "1", action)]
gen: u64,
},
/// Commit the current write_log data to the minimum expected counts.
Commit,
/// Deactivate the upstairs
Deactivate,
/// DSC
Dsc {
/// Subcommand please
#[clap(subcommand)]
dsc_cmd: DscCommand,
},
/// Report the expected read count for an offset.
Expected {
/// The desired offset to see the expected value for.
#[clap(long, short, action)]
offset: usize,
},
/// Export the current write count to the verify out file
Export,
/// Run the fill then verify test.
Fill {
/// Don't do the verify step after filling the region.
#[clap(long, action)]
skip_verify: bool,
},
/// Run the sparse fill test. Write to a block in each extent.
FillSparse,
/// Flush
Flush,
/// Run Generic workload
Generic {
/// Number of IOs to execute
#[clap(long, short, default_value = "5000", action)]
count: usize,
/// Print out IOs as we send them
#[clap(long, short, default_value = "false", action)]
quiet: bool,
},
/// Request region information
Info,
/// Report if the Upstairs is ready for IO
IsActive,
/// Run the client perf test
Perf {
/// Number of IOs to execute for each test phase
#[clap(long, short, default_value = "5000", action)]
count: usize,
/// Size in blocks of each IO
#[clap(long, default_value = "1", action)]
io_size: usize,
/// Number of outstanding IOs at the same time
#[clap(long, default_value = "1", action)]
io_depth: usize,
/// Number of read test loops to do.
#[clap(long, default_value = "2", action)]
read_loops: usize,
/// Number of write test loops to do.
#[clap(long, default_value = "2", action)]
write_loops: usize,
},
/// Quit the CLI
Quit,
/// Read from a given block offset
Read {
/// The desired offset in blocks to read from.
#[clap(long, short, action)]
offset: usize,
/// The number of blocks to read.
#[clap(long, short, default_value = "1", action)]
len: usize,
},
Replace {
/// Replace a downstairs old (current) SocketAddr.
#[clap(long, short, action)]
old: SocketAddr,
/// Replace a downstairs new SocketAddr.
#[clap(long, short, action)]
new: SocketAddr,
},
/// Issue a random read
Rr,
/// Issue a random write
Rw,
/// Show the work queues
Show,
/// Change the wait state between true and false
Wait,
/// Read and verify the whole volume.
Verify,
/// Write to a given block offset
Write {
/// The desired offset in blocks to write to.
#[clap(short, action)]
offset: usize,
/// The number of blocks to write.
#[clap(long, short, default_value = "1", action)]
len: usize,
},
/// WriteUnwritten to a given block offset.
/// Note that the cli will decide if a block is written to based on
/// the cli's internal write log. This log may not match if the block
/// actually has or has not been written to.
WriteUnwritten {
/// The desired offset in blocks to write to.
#[clap(short, action)]
offset: usize,
},
/// Get the upstairs UUID
Uuid,
}
/*
* Generate a read for the volume with the given offset/length.
* Wait for the IO to return.
* Verify the data is as we expect using the client based validation.
* Note that if you have not written to a block yet and you are not
* importing a verify file, this will default to passing. Only when
* there is non zero data in the ri.write_log will we have something
* to verify against.
*
* After verify, we truncate the data to 10 fields and return that so
* the cli server can send it back to the client for display.
*/
async fn cli_read(
volume: &Volume,
ri: &mut RegionInfo,
block_index: usize,
size: usize,
) -> Result<Bytes, CrucibleError> {
/*
* Convert offset to its byte value.
*/
let offset = BlockIndex(block_index as u64);
let mut data =
crucible::Buffer::repeat(255, size, ri.volume_info.block_size as usize);
println!("Read at block {:5}, len:{:7}", offset.0, data.len());
volume.read(offset, &mut data).await?;
let mut dl = data.into_bytes();
match validate_vec(
dl.clone(),
block_index,
&mut ri.write_log,
ri.volume_info.block_size,
false,
) {
ValidateStatus::Bad => {
println!("Data mismatch error at {}", block_index);
Err(CrucibleError::GenericError("Data mismatch".to_string()))
}
ValidateStatus::InRange => {
println!("Data mismatch range error at {}", block_index);
Err(CrucibleError::GenericError("Data range error".to_string()))
}
ValidateStatus::Good => {
dl.truncate(10);
Ok(dl)
}
}
}
/*
* A wrapper around write that just picks a random offset.
*/
async fn rand_write(
volume: &Volume,
ri: &mut RegionInfo,
) -> Result<(), CrucibleError> {
/*
* TODO: Allow the user to specify a seed here.
*/
let mut rng = rand_chacha::ChaCha8Rng::from_entropy();
/*
* Once we have our IO size, decide where the starting offset should
* be, which is the total possible size minus the randomly chosen
* IO size.
*/
let size = 1;
let block_max = ri.volume_info.total_blocks() - size + 1;
let block_index = rng.gen_range(0..block_max);
cli_write(volume, ri, block_index, size).await
}
/*
* Issue a write to the volume at the given offset/len.
* Data is generated based on the value in the internal write counter.
* Update the internal write counter so we have something to compare to.
*/
async fn cli_write(
volume: &Volume,
ri: &mut RegionInfo,
block_index: usize,
size: usize,
) -> Result<(), CrucibleError> {
/*
* Convert offset and length to their byte values.
*/
let offset = BlockIndex(block_index as u64);
/*
* Update the write count for the block we plan to write to.
* Unless, we are trying to write off the end of the volume.
* If so, then don't update any write counts and just make
* the correct size buffer with all zeros.
*/
let total_blocks = ri.volume_info.total_blocks();
let data = if block_index + size > total_blocks {
println!("Skip write log for invalid size {}", total_blocks);
let mut out = BytesMut::new();
out.resize(size * ri.volume_info.block_size as usize, 0);
out
} else {
for bi in block_index..block_index + size {
ri.write_log.update_wc(bi);
}
fill_vec(block_index, size, &ri.write_log, ri.volume_info.block_size)
};
println!("Write at block {:5}, len:{:7}", offset.0, data.len());
volume.write(offset, data).await?;
Ok(())
}
/*
* Issue a write_unwritten to the volume at the given offset.
* We first check our internal write counter.
* If we believe the block has not been written to, then we update our
* internal counter and we will expect the write to change the block.
* If we do believe the block is written to, then we don't update our
* internal counter and we don't expect our write to change the contents.
*/
async fn cli_write_unwritten(
volume: &Volume,
ri: &mut RegionInfo,
block_index: usize,
) -> Result<(), CrucibleError> {
/*
* Convert offset to its byte value.
*/
let offset = BlockIndex(block_index as u64);
// To determine what we put into our write buffer, look to see if
// we believe we have written to this block or not.
let data = if ri.write_log.get_seed(block_index) == 0 {
// We have not written to this block, so we create our write buffer
// like normal and update our internal counter to reflect that.
ri.write_log.update_wc(block_index);
fill_vec(block_index, 1, &ri.write_log, ri.volume_info.block_size)
} else {
println!("This block has been written");
// Fill the write buffer with random data. We don't expect this
// to actually make it to disk.
let mut data =
BytesMut::with_capacity(ri.volume_info.block_size as usize);
data.extend(
(0..ri.volume_info.block_size)
.map(|_| rand::thread_rng().gen::<u8>()),
);
data
};
println!(
"WriteUnwritten at block {:5}, len:{:7}",
offset.0,
data.len(),
);
volume.write_unwritten(offset, data).await?;
Ok(())
}
// Handle dsc commands
async fn handle_dsc(
dsc_client: &mut Option<dsc_client::Client>,
dsc_cmd: DscCommand,
) {
if let Some(dsc_client) = dsc_client {
match dsc_cmd {
DscCommand::Connect { .. } => {
println!("Already connected");
}
DscCommand::DisableRandomStop => {
let res = dsc_client.dsc_disable_random_stop().await;
println!("Got res: {:?}", res);
}
DscCommand::DisableRestart { cid } => {
let res = dsc_client.dsc_disable_restart(cid).await;
println!("Got res: {:?}", res);
}
DscCommand::DisableRestartAll => {
let res = dsc_client.dsc_disable_restart_all().await;
println!("Got res: {:?}", res);
}
DscCommand::EnableRandomStop => {
let res = dsc_client.dsc_enable_random_stop().await;
println!("Got res: {:?}", res);
}
DscCommand::EnableRandomMin { min } => {
let res = dsc_client.dsc_enable_random_min(min).await;
println!("Got res: {:?}", res);
}
DscCommand::EnableRandomMax { max } => {
let res = dsc_client.dsc_enable_random_max(max).await;
println!("Got res: {:?}", res);
}
DscCommand::EnableRestart { cid } => {
let res = dsc_client.dsc_enable_restart(cid).await;
println!("Got res: {:?}", res);
}
DscCommand::EnableRestartAll => {
let res = dsc_client.dsc_enable_restart_all().await;
println!("Got res: {:?}", res);
}
DscCommand::Shutdown => {
let res = dsc_client.dsc_shutdown().await;
println!("Got res: {:?}", res);
}
DscCommand::Start { cid } => {
let res = dsc_client.dsc_start(cid).await;
println!("Got res: {:?}", res);
}
DscCommand::StartAll => {
let res = dsc_client.dsc_start_all().await;
println!("Got res: {:?}", res);
}
DscCommand::Stop { cid } => {
let res = dsc_client.dsc_stop(cid).await;
println!("Got res: {:?}", res);
}
DscCommand::StopAll => {
let res = dsc_client.dsc_stop_all().await;
println!("Got res: {:?}", res);
}
DscCommand::StopRand => {
let res = dsc_client.dsc_stop_rand().await;
println!("Got res: {:?}", res);
}
DscCommand::State { cid } => {
let res = dsc_client.dsc_get_ds_state(cid).await;
println!("Got res: {:?}", res);
}
}
} else if let DscCommand::Connect { server } = dsc_cmd {
let url = format!("http://{}", server).to_string();
println!("Connecting to {:?}", url);
let rs = Client::new(&url);
*dsc_client = Some(rs);
} else {
println!("dsc: Need to be connected first");
}
}
/*
* Take a CLI cmd coming from our client program and translate it into
* an actual CliMessage to send to the cli server.
*
* At the moment, we ping pong here, where we send a command to the
* cli_server, then we wait for the response.
* Eventually we could make this async, but, yeah, I got things to do.
*
* Also, some commands (dsc for example) don't talk to the cliserver, so
* those and commands like them should return status directly instead of
* falling through the match and then entering the "wait for a response"
* side where they will never get a response.
*/
async fn cmd_to_msg(
cmd: CliCommand,
fr: &mut FramedRead<tokio::net::tcp::ReadHalf<'_>, CliDecoder>,
fw: &mut FramedWrite<WriteHalf<'_>, CliEncoder>,
dsc_client: &mut Option<dsc_client::Client>,
) -> Result<()> {
match cmd {
CliCommand::Activate { gen } => {
fw.send(CliMessage::Activate(gen)).await?;
}
CliCommand::ActivateRequest { gen } => {
fw.send(CliMessage::ActivateRequest(gen)).await?;
}
CliCommand::Commit => {
fw.send(CliMessage::Commit).await?;
}
CliCommand::Deactivate => {
fw.send(CliMessage::Deactivate).await?;
}
CliCommand::Dsc { dsc_cmd } => {
handle_dsc(dsc_client, dsc_cmd).await;
return Ok(());
}
CliCommand::Expected { offset } => {
fw.send(CliMessage::Expected(offset)).await?;
}
CliCommand::Export => {
fw.send(CliMessage::Export).await?;
}
CliCommand::Fill { skip_verify } => {
fw.send(CliMessage::Fill(skip_verify)).await?;
}
CliCommand::FillSparse => {
fw.send(CliMessage::FillSparse).await?;
}
CliCommand::Flush => {
fw.send(CliMessage::Flush).await?;
}
CliCommand::Generic { count, quiet } => {
fw.send(CliMessage::Generic(count, quiet)).await?;
}
CliCommand::IsActive => {
fw.send(CliMessage::IsActive).await?;
}
CliCommand::Info => {
fw.send(CliMessage::InfoPlease).await?;
}
CliCommand::Perf {
count,
io_size,
io_depth,
read_loops,
write_loops,
} => {
fw.send(CliMessage::Perf(
count,
io_size,
io_depth,
read_loops,
write_loops,
))
.await?;
}
CliCommand::Quit => {
println!("The quit command has nothing to send");
return Ok(());
}
CliCommand::Read { offset, len } => {
fw.send(CliMessage::Read(offset, len)).await?;
}
CliCommand::Replace { old, new } => {
fw.send(CliMessage::Replace(old, new)).await?;
}
CliCommand::Rr => {
fw.send(CliMessage::RandRead).await?;
}
CliCommand::Rw => {
fw.send(CliMessage::RandWrite).await?;
}
CliCommand::Show => {
fw.send(CliMessage::ShowWork).await?;
}
CliCommand::Uuid => {
fw.send(CliMessage::Uuid).await?;
}
CliCommand::Verify => {
fw.send(CliMessage::Verify).await?;
}
CliCommand::Wait => {
println!("No support for Wait");
return Ok(());
}
CliCommand::Write { offset, len } => {
fw.send(CliMessage::Write(offset, len)).await?;
}
CliCommand::WriteUnwritten { offset } => {
fw.send(CliMessage::WriteUnwritten(offset)).await?;
}
}
/*
* Now, wait for our response
*/
let new_read = fr.next().await;
match new_read.transpose()? {
Some(CliMessage::MyUuid(uuid)) => {
println!("uuid: {}", uuid);
}
Some(CliMessage::Info(vi)) => {
println!("Got info: {:?}", vi);
}
Some(CliMessage::DoneOk) => {
println!("Ok");
}
Some(CliMessage::ExpectedResponse(offset, data)) => {
println!("[{}] Expt: {:?}", offset, data);
}
Some(CliMessage::ReadResponse(offset, resp)) => match resp {
Ok(data) => {
println!("[{}] Data: {:?}", offset, data);
}
Err(e) => {
println!("ERROR: {:?}", e);
}
},
Some(CliMessage::ReplaceResult(resp)) => match resp {
Ok(msg) => {
println!("Replace returns: {:?}", msg);
}
Err(e) => {
println!("ERROR: {:?}", e);
}
},
Some(CliMessage::Error(e)) => {
println!("ERROR: {:?}", e);
}
Some(CliMessage::ActiveIs(active)) => {
println!("Active is: {}", active);
}
m => {
println!("No code for this response {:?}", m);
}
}
Ok(())
}
// Generic prompt stuff for reedline.
#[derive(Clone)]
pub struct CliPrompt;
impl Prompt for CliPrompt {
fn render_prompt_left(&self) -> Cow<str> {
Cow::Owned(String::from(">> "))
}
fn render_prompt_right(&self) -> Cow<str> {
Cow::Owned(String::from(""))
}
fn render_prompt_indicator(&self, _edit_mode: PromptEditMode) -> Cow<str> {
Cow::Owned(String::from(""))
}
fn render_prompt_multiline_indicator(&self) -> Cow<str> {
Cow::Owned(String::from(""))
}
fn render_prompt_history_search_indicator(
&self,
_history_search: PromptHistorySearch,
) -> Cow<str> {
Cow::Owned(String::from(""))
}
}
impl Default for CliPrompt {
fn default() -> Self {
CliPrompt::new()
}
}
impl CliPrompt {
pub fn new() -> CliPrompt {
CliPrompt {}
}
}
/*
* The CLI just sends commands to the cli_server where all the logic
* lives, including any state about what blocks were written.
*/
pub async fn start_cli_client(attach: SocketAddr) -> Result<()> {
'outer: loop {
let sock = if attach.is_ipv4() {
TcpSocket::new_v4().unwrap()
} else {
TcpSocket::new_v6().unwrap()
};
println!("cli connecting to {0}", attach);
let deadline = tokio::time::sleep_until(deadline_secs(100.0));
tokio::pin!(deadline);
let tcp = sock.connect(attach);
tokio::pin!(tcp);
let mut tcp: TcpStream = tokio::select! {
_ = &mut deadline => {
println!("connect timeout");
continue 'outer;
}
tcp = &mut tcp => {
match tcp {
Ok(tcp) => {
println!("connected to {}", attach);
tcp
}
Err(e) => {
println!("connect to {0} failure: {1:?}",
attach, e);
tokio::time::sleep_until(deadline_secs(10.0)).await;
continue 'outer;
}
}
}
};
/*
* Create the read/write endpoints so this client can send and
* receive messages from the cli_server.
*/
let (r, w) = tcp.split();
let mut fr = FramedRead::new(r, CliDecoder::new());
let mut fw = FramedWrite::new(w, CliEncoder::new());
let history = Box::new(
FileBackedHistory::with_file(50, "history.txt".into())
.expect("Error configuring history with file"),
);
let mut line_editor = Reedline::create().with_history(history);
let prompt = CliPrompt::new();
let mut dsc_client = None;
loop {
let sig = line_editor.read_line(&prompt)?;
match sig {
Signal::Success(buffer) => {
let cmds: Vec<&str> = buffer.trim().split(' ').collect();
// Empty command, just ignore it and loop.
if cmds[0].is_empty() {
continue;
}
match CliCommand::try_parse_from(cmds) {
Ok(CliCommand::Quit) => {
break;
}
Ok(vc) => {
cmd_to_msg(vc, &mut fr, &mut fw, &mut dsc_client)
.await?;
// TODO: Handle this error
}
Err(e) => {
println!("{}", e);
}
}
}
Signal::CtrlD | Signal::CtrlC => {
println!("CTRL-C");
break;
}
}
}
// TODO: Figure out how to handle a disconnect from the crucible
// side and let things continue.
break;
}
Ok(())
}
/**
* Process a CLI command from the client, we are the server side.
*/
async fn process_cli_command(
volume: &Volume,
fw: &mut FramedWrite<tokio::net::tcp::OwnedWriteHalf, CliEncoder>,
cmd: protocol::CliMessage,
ri_option: &mut Option<RegionInfo>,
wc_filled: &mut bool,
verify_input: Option<PathBuf>,
verify_output: Option<PathBuf>,
) -> Result<()> {
match cmd {
CliMessage::Activate(gen) => {
match volume.activate_with_gen(gen).await {
Ok(_) => fw.send(CliMessage::DoneOk).await,
Err(e) => fw.send(CliMessage::Error(e)).await,
}
}
CliMessage::ActivateRequest(gen) => {
let gc = volume.clone();
let _handle = tokio::spawn(async move {
match gc.activate_with_gen(gen).await {
Ok(_) => {
println!("Activate Successful");
}
Err(e) => {
println!("Activate failed: {:?}", e);
}
}
});
// We return OK here as we have sent off the request. It's up to
// the caller to now check is-active to determine if the
// activation has completed.
fw.send(CliMessage::DoneOk).await
}
CliMessage::Deactivate => match volume.deactivate().await {
Ok(_) => fw.send(CliMessage::DoneOk).await,
Err(e) => fw.send(CliMessage::Error(e)).await,
},
CliMessage::Commit => {
if let Some(ri) = ri_option {
if ri.write_log.is_empty() {
fw.send(CliMessage::Error(CrucibleError::GenericError(
"Info not initialized".to_string(),
)))
.await
} else {
ri.write_log.commit();
fw.send(CliMessage::DoneOk).await
}
} else {
fw.send(CliMessage::Error(CrucibleError::GenericError(
"Info not initialized".to_string(),
)))
.await
}
}
CliMessage::Expected(offset) => {
if !*wc_filled {
fw.send(CliMessage::Error(CrucibleError::GenericError(
"Internal write count buffer not filled".to_string(),
)))
.await
} else if let Some(ri) = ri_option {
if ri.write_log.is_empty() {
fw.send(CliMessage::Error(CrucibleError::GenericError(
"Internal write count buffer empty".to_string(),
)))
.await
} else {
let mut vec: Vec<u8> = vec![255; 2];
vec[0] = (offset % 255) as u8;
vec[1] = ri.write_log.get_seed(offset) % 255;
fw.send(CliMessage::ExpectedResponse(offset, vec)).await
}
} else {
fw.send(CliMessage::Error(CrucibleError::GenericError(
"Info not initialized".to_string(),
)))
.await
}
}
CliMessage::Export => {
if let Some(ri) = ri_option {
if ri.write_log.is_empty() {
fw.send(CliMessage::Error(CrucibleError::GenericError(
"Info not initialized".to_string(),
)))
.await
} else if let Some(vo) = verify_output {
println!("Exporting write history to {vo:?}");
match write_json(&vo, &ri.write_log, true) {
Ok(_) => fw.send(CliMessage::DoneOk).await,
Err(e) => {
println!("Failed writing to {vo:?} with {e}");
fw.send(CliMessage::Error(
CrucibleError::GenericError(
"Failed writing to file".to_string(),
),
))
.await
}
}
} else {
fw.send(CliMessage::Error(CrucibleError::GenericError(
"No verify-out file provided".to_string(),
)))
.await
}
} else {
fw.send(CliMessage::Error(CrucibleError::GenericError(
"Info not initialized".to_string(),
)))
.await
}
}
CliMessage::Generic(count, quiet) => {
if let Some(ri) = ri_option {
if ri.write_log.is_empty() {
fw.send(CliMessage::Error(CrucibleError::GenericError(
"Info not initialized".to_string(),
)))
.await
} else {
let mut wtq = WhenToQuit::Count { count };
match generic_workload(volume, &mut wtq, ri, quiet).await {
Ok(_) => fw.send(CliMessage::DoneOk).await,
Err(e) => {
let msg = format!("{}", e);
let e = CrucibleError::GenericError(msg);
fw.send(CliMessage::Error(e)).await
}
}
}
} else {
fw.send(CliMessage::Error(CrucibleError::GenericError(
"Info not initialized".to_string(),
)))
.await
}
}
CliMessage::Fill(skip_verify) => {
if let Some(ri) = ri_option {
if ri.write_log.is_empty() {
fw.send(CliMessage::Error(CrucibleError::GenericError(
"Info not initialized".to_string(),
)))
.await
} else {
match fill_workload(volume, ri, skip_verify).await {
Ok(_) => fw.send(CliMessage::DoneOk).await,
Err(e) => {
let msg = format!("Fill/Verify failed with {}", e);
let e = CrucibleError::GenericError(msg);
fw.send(CliMessage::Error(e)).await
}
}
}
} else {
fw.send(CliMessage::Error(CrucibleError::GenericError(
"Info not initialized".to_string(),
)))
.await
}
}
CliMessage::FillSparse => {
if let Some(ri) = ri_option {
if ri.write_log.is_empty() {
fw.send(CliMessage::Error(CrucibleError::GenericError(
"Info not initialized".to_string(),
)))
.await
} else {
match fill_sparse_workload(volume, ri).await {
Ok(_) => fw.send(CliMessage::DoneOk).await,
Err(e) => {
let msg = format!("FillSparse failed with {}", e);
let e = CrucibleError::GenericError(msg);
fw.send(CliMessage::Error(e)).await
}
}
}
} else {
fw.send(CliMessage::Error(CrucibleError::GenericError(
"Info not initialized".to_string(),
)))
.await
}
}
CliMessage::Flush => {
println!("Flush");
match volume.flush(None).await {
Ok(_) => fw.send(CliMessage::DoneOk).await,
Err(e) => fw.send(CliMessage::Error(e)).await,
}
}
CliMessage::IsActive => match volume.query_is_active().await {
Ok(a) => fw.send(CliMessage::ActiveIs(a)).await,
Err(e) => fw.send(CliMessage::Error(e)).await,
},
CliMessage::InfoPlease => {
match get_region_info(volume).await {
Ok(mut new_ri) => {
/*
* We may only want to read input from the file once.
* Maybe make a command to specifically do it, but it
* seems like once we go active we won't need to run
* it again.
*/
if !*wc_filled {
if let Some(vi) = verify_input {
load_write_log(volume, &mut new_ri, vi, false)
.await?;
*wc_filled = true;
}
}
*ri_option = Some(new_ri.clone());
fw.send(CliMessage::Info(new_ri.volume_info)).await
}
Err(e) => fw.send(CliMessage::Error(e)).await,
}
}
CliMessage::Perf(count, io_size, io_depth, read_loops, write_loops) => {
if let Some(ri) = ri_option {
if ri.write_log.is_empty() {
fw.send(CliMessage::Error(CrucibleError::GenericError(
"Info not initialized".to_string(),
)))
.await
} else {
perf_header();
match perf_workload(
volume,
ri,
None,
count,
io_size,
io_depth,
read_loops,
write_loops,
)
.await
{
Ok(_) => fw.send(CliMessage::DoneOk).await,