/
handler.rs
2609 lines (2202 loc) 路 86.9 KB
/
handler.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
use crate::{
constants::{MAX_PIPE_CHUNK_SIZE, READ_PAUSE_MILLIS},
data::{
self, DirEntry, FileType, Request, RequestData, Response, ResponseData, RunningProcess,
},
server::distant::state::{Process, State},
};
use derive_more::{Display, Error, From};
use futures::future;
use log::*;
use std::{
env,
path::{Path, PathBuf},
process::Stdio,
sync::Arc,
time::SystemTime,
};
use tokio::{
io::{self, AsyncReadExt, AsyncWriteExt},
process::Command,
sync::{mpsc, oneshot, Mutex, MutexGuard},
};
use walkdir::WalkDir;
pub type Reply = mpsc::Sender<Response>;
type HState = Arc<Mutex<State>>;
#[derive(Debug, Display, Error, From)]
pub enum ServerError {
IoError(io::Error),
WalkDirError(walkdir::Error),
}
impl From<ServerError> for ResponseData {
fn from(x: ServerError) -> Self {
match x {
ServerError::IoError(x) => Self::from(x),
ServerError::WalkDirError(x) => Self::from(x),
}
}
}
type PostHook = Box<dyn FnOnce(MutexGuard<'_, State>) + Send>;
struct Outgoing {
data: ResponseData,
post_hook: Option<PostHook>,
}
impl From<ResponseData> for Outgoing {
fn from(data: ResponseData) -> Self {
Self {
data,
post_hook: None,
}
}
}
/// Processes the provided request, sending replies using the given sender
pub(super) async fn process(
conn_id: usize,
state: HState,
req: Request,
tx: Reply,
) -> Result<(), mpsc::error::SendError<Response>> {
async fn inner(
tenant: Arc<String>,
conn_id: usize,
state: HState,
data: RequestData,
tx: Reply,
) -> Result<Outgoing, ServerError> {
match data {
RequestData::FileRead { path } => file_read(path).await,
RequestData::FileReadText { path } => file_read_text(path).await,
RequestData::FileWrite { path, data } => file_write(path, data).await,
RequestData::FileWriteText { path, text } => file_write(path, text).await,
RequestData::FileAppend { path, data } => file_append(path, data).await,
RequestData::FileAppendText { path, text } => file_append(path, text).await,
RequestData::DirRead {
path,
depth,
absolute,
canonicalize,
include_root,
} => dir_read(path, depth, absolute, canonicalize, include_root).await,
RequestData::DirCreate { path, all } => dir_create(path, all).await,
RequestData::Remove { path, force } => remove(path, force).await,
RequestData::Copy { src, dst } => copy(src, dst).await,
RequestData::Rename { src, dst } => rename(src, dst).await,
RequestData::Exists { path } => exists(path).await,
RequestData::Metadata {
path,
canonicalize,
resolve_file_type,
} => metadata(path, canonicalize, resolve_file_type).await,
RequestData::ProcRun { cmd, args } => {
proc_run(tenant.to_string(), conn_id, state, tx, cmd, args).await
}
RequestData::ProcKill { id } => proc_kill(state, id).await,
RequestData::ProcStdin { id, data } => proc_stdin(state, id, data).await,
RequestData::ProcList {} => proc_list(state).await,
RequestData::SystemInfo {} => system_info().await,
}
}
let tenant = Arc::new(req.tenant.clone());
// Build up a collection of tasks to run independently
let mut payload_tasks = Vec::new();
for data in req.payload {
let tenant_2 = Arc::clone(&tenant);
let state_2 = Arc::clone(&state);
let tx_2 = tx.clone();
payload_tasks.push(tokio::spawn(async move {
match inner(tenant_2, conn_id, state_2, data, tx_2).await {
Ok(outgoing) => outgoing,
Err(x) => Outgoing::from(ResponseData::from(x)),
}
}));
}
// Collect the results of our tasks into the payload entries
let mut outgoing: Vec<Outgoing> = future::join_all(payload_tasks)
.await
.into_iter()
.map(|x| match x {
Ok(outgoing) => outgoing,
Err(x) => Outgoing::from(ResponseData::from(x)),
})
.collect();
let post_hooks: Vec<PostHook> = outgoing
.iter_mut()
.filter_map(|x| x.post_hook.take())
.collect();
let payload = outgoing.into_iter().map(|x| x.data).collect();
let res = Response::new(req.tenant, Some(req.id), payload);
// Send out our primary response from processing the request
let result = tx.send(res).await;
// Invoke all post hooks
for hook in post_hooks {
hook(state.lock().await);
}
result
}
async fn file_read(path: PathBuf) -> Result<Outgoing, ServerError> {
Ok(Outgoing::from(ResponseData::Blob {
data: tokio::fs::read(path).await?,
}))
}
async fn file_read_text(path: PathBuf) -> Result<Outgoing, ServerError> {
Ok(Outgoing::from(ResponseData::Text {
data: tokio::fs::read_to_string(path).await?,
}))
}
async fn file_write(path: PathBuf, data: impl AsRef<[u8]>) -> Result<Outgoing, ServerError> {
tokio::fs::write(path, data).await?;
Ok(Outgoing::from(ResponseData::Ok))
}
async fn file_append(path: PathBuf, data: impl AsRef<[u8]>) -> Result<Outgoing, ServerError> {
let mut file = tokio::fs::OpenOptions::new()
.append(true)
.open(path)
.await?;
file.write_all(data.as_ref()).await?;
Ok(Outgoing::from(ResponseData::Ok))
}
async fn dir_read(
path: PathBuf,
depth: usize,
absolute: bool,
canonicalize: bool,
include_root: bool,
) -> Result<Outgoing, ServerError> {
// Canonicalize our provided path to ensure that it is exists, not a loop, and absolute
let root_path = tokio::fs::canonicalize(path).await?;
// Traverse, but don't include root directory in entries (hence min depth 1), unless indicated
// to do so (min depth 0)
let dir = WalkDir::new(root_path.as_path())
.min_depth(if include_root { 0 } else { 1 })
.sort_by_file_name();
// If depth > 0, will recursively traverse to specified max depth, otherwise
// performs infinite traversal
let dir = if depth > 0 { dir.max_depth(depth) } else { dir };
// Determine our entries and errors
let mut entries = Vec::new();
let mut errors = Vec::new();
#[inline]
fn map_file_type(ft: std::fs::FileType) -> FileType {
if ft.is_dir() {
FileType::Dir
} else if ft.is_file() {
FileType::File
} else {
FileType::Symlink
}
}
for entry in dir {
match entry.map_err(data::Error::from) {
// For entries within the root, we want to transform the path based on flags
Ok(e) if e.depth() > 0 => {
// Canonicalize the path if specified, otherwise just return
// the path as is
let mut path = if canonicalize {
match tokio::fs::canonicalize(e.path()).await {
Ok(path) => path,
Err(x) => {
errors.push(data::Error::from(x));
continue;
}
}
} else {
e.path().to_path_buf()
};
// Strip the path of its prefix based if not flagged as absolute
if !absolute {
// NOTE: In the situation where we canonicalized the path earlier,
// there is no guarantee that our root path is still the
// parent of the symlink's destination; so, in that case we MUST just
// return the path if the strip_prefix fails
path = path
.strip_prefix(root_path.as_path())
.map(Path::to_path_buf)
.unwrap_or(path);
};
entries.push(DirEntry {
path,
file_type: map_file_type(e.file_type()),
depth: e.depth(),
});
}
// For the root, we just want to echo back the entry as is
Ok(e) => {
entries.push(DirEntry {
path: e.path().to_path_buf(),
file_type: map_file_type(e.file_type()),
depth: e.depth(),
});
}
Err(x) => errors.push(x),
}
}
Ok(Outgoing::from(ResponseData::DirEntries { entries, errors }))
}
async fn dir_create(path: PathBuf, all: bool) -> Result<Outgoing, ServerError> {
if all {
tokio::fs::create_dir_all(path).await?;
} else {
tokio::fs::create_dir(path).await?;
}
Ok(Outgoing::from(ResponseData::Ok))
}
async fn remove(path: PathBuf, force: bool) -> Result<Outgoing, ServerError> {
let path_metadata = tokio::fs::metadata(path.as_path()).await?;
if path_metadata.is_dir() {
if force {
tokio::fs::remove_dir_all(path).await?;
} else {
tokio::fs::remove_dir(path).await?;
}
} else {
tokio::fs::remove_file(path).await?;
}
Ok(Outgoing::from(ResponseData::Ok))
}
async fn copy(src: PathBuf, dst: PathBuf) -> Result<Outgoing, ServerError> {
let src_metadata = tokio::fs::metadata(src.as_path()).await?;
if src_metadata.is_dir() {
// Create the destination directory first, regardless of if anything
// is in the source directory
tokio::fs::create_dir_all(dst.as_path()).await?;
for entry in WalkDir::new(src.as_path())
.min_depth(1)
.follow_links(false)
.into_iter()
.filter_entry(|e| {
e.file_type().is_file() || e.file_type().is_dir() || e.path_is_symlink()
})
{
let entry = entry?;
// Get unique portion of path relative to src
// NOTE: Because we are traversing files that are all within src, this
// should always succeed
let local_src = entry.path().strip_prefix(src.as_path()).unwrap();
// Get the file without any directories
let local_src_file_name = local_src.file_name().unwrap();
// Get the directory housing the file
// NOTE: Because we enforce files/symlinks, there will always be a parent
let local_src_dir = local_src.parent().unwrap();
// Map out the path to the destination
let dst_parent_dir = dst.join(local_src_dir);
// Create the destination directory for the file when copying
tokio::fs::create_dir_all(dst_parent_dir.as_path()).await?;
let dst_path = dst_parent_dir.join(local_src_file_name);
// Perform copying from entry to destination (if a file/symlink)
if !entry.file_type().is_dir() {
tokio::fs::copy(entry.path(), dst_path).await?;
// Otherwise, if a directory, create it
} else {
tokio::fs::create_dir(dst_path).await?;
}
}
} else {
tokio::fs::copy(src, dst).await?;
}
Ok(Outgoing::from(ResponseData::Ok))
}
async fn rename(src: PathBuf, dst: PathBuf) -> Result<Outgoing, ServerError> {
tokio::fs::rename(src, dst).await?;
Ok(Outgoing::from(ResponseData::Ok))
}
async fn exists(path: PathBuf) -> Result<Outgoing, ServerError> {
// Following experimental `std::fs::try_exists`, which checks the error kind of the
// metadata lookup to see if it is not found and filters accordingly
Ok(match tokio::fs::metadata(path.as_path()).await {
Ok(_) => Outgoing::from(ResponseData::Exists(true)),
Err(x) if x.kind() == io::ErrorKind::NotFound => {
Outgoing::from(ResponseData::Exists(false))
}
Err(x) => return Err(ServerError::from(x)),
})
}
async fn metadata(
path: PathBuf,
canonicalize: bool,
resolve_file_type: bool,
) -> Result<Outgoing, ServerError> {
let metadata = tokio::fs::symlink_metadata(path.as_path()).await?;
let canonicalized_path = if canonicalize {
Some(tokio::fs::canonicalize(path.as_path()).await?)
} else {
None
};
// If asking for resolved file type and current type is symlink, then we want to refresh
// our metadata to get the filetype for the resolved link
let file_type = if resolve_file_type && metadata.file_type().is_symlink() {
tokio::fs::metadata(path).await?.file_type()
} else {
metadata.file_type()
};
Ok(Outgoing::from(ResponseData::Metadata {
canonicalized_path,
accessed: metadata
.accessed()
.ok()
.and_then(|t| t.duration_since(SystemTime::UNIX_EPOCH).ok())
.map(|d| d.as_millis()),
created: metadata
.created()
.ok()
.and_then(|t| t.duration_since(SystemTime::UNIX_EPOCH).ok())
.map(|d| d.as_millis()),
modified: metadata
.modified()
.ok()
.and_then(|t| t.duration_since(SystemTime::UNIX_EPOCH).ok())
.map(|d| d.as_millis()),
len: metadata.len(),
readonly: metadata.permissions().readonly(),
file_type: if file_type.is_dir() {
FileType::Dir
} else if file_type.is_file() {
FileType::File
} else {
FileType::Symlink
},
}))
}
async fn proc_run(
tenant: String,
conn_id: usize,
state: HState,
tx: Reply,
cmd: String,
args: Vec<String>,
) -> Result<Outgoing, ServerError> {
let id = rand::random();
let mut child = Command::new(cmd.to_string())
.args(args.clone())
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()?;
state
.lock()
.await
.push_process(conn_id, Process::new(id, cmd, args));
let post_hook = Box::new(move |mut state_lock: MutexGuard<'_, State>| {
// Spawn a task that sends stdout as a response
let tx_2 = tx.clone();
let tenant_2 = tenant.clone();
let mut stdout = child.stdout.take().unwrap();
let stdout_task = tokio::spawn(async move {
let mut buf: [u8; MAX_PIPE_CHUNK_SIZE] = [0; MAX_PIPE_CHUNK_SIZE];
loop {
match stdout.read(&mut buf).await {
Ok(n) if n > 0 => match String::from_utf8(buf[..n].to_vec()) {
Ok(data) => {
let res = Response::new(
tenant_2.as_str(),
None,
vec![ResponseData::ProcStdout { id, data }],
);
if tx_2.send(res).await.is_err() {
error!("<Conn @ {}> Stdout channel closed", conn_id);
break;
}
// Pause to allow buffer to fill up a little bit, avoiding
// spamming with a lot of smaller responses
tokio::time::sleep(tokio::time::Duration::from_millis(
READ_PAUSE_MILLIS,
))
.await;
}
Err(x) => {
error!("Invalid data read from stdout pipe: {}", x);
break;
}
},
Ok(_) => break,
Err(_) => break,
}
}
});
// Spawn a task that sends stderr as a response
let tx_2 = tx.clone();
let tenant_2 = tenant.clone();
let mut stderr = child.stderr.take().unwrap();
let stderr_task = tokio::spawn(async move {
let mut buf: [u8; MAX_PIPE_CHUNK_SIZE] = [0; MAX_PIPE_CHUNK_SIZE];
loop {
match stderr.read(&mut buf).await {
Ok(n) if n > 0 => match String::from_utf8(buf[..n].to_vec()) {
Ok(data) => {
let res = Response::new(
tenant_2.as_str(),
None,
vec![ResponseData::ProcStderr { id, data }],
);
if tx_2.send(res).await.is_err() {
error!("<Conn @ {}> Stderr channel closed", conn_id);
break;
}
// Pause to allow buffer to fill up a little bit, avoiding
// spamming with a lot of smaller responses
tokio::time::sleep(tokio::time::Duration::from_millis(
READ_PAUSE_MILLIS,
))
.await;
}
Err(x) => {
error!("Invalid data read from stdout pipe: {}", x);
break;
}
},
Ok(_) => break,
Err(_) => break,
}
}
});
// Spawn a task that sends stdin to the process
let mut stdin = child.stdin.take().unwrap();
let (stdin_tx, mut stdin_rx) = mpsc::channel::<String>(1);
let stdin_task = tokio::spawn(async move {
while let Some(line) = stdin_rx.recv().await {
if let Err(x) = stdin.write_all(line.as_bytes()).await {
error!(
"<Conn @ {}> Failed to send stdin to process {}: {}",
conn_id, id, x
);
break;
}
}
});
// Spawn a task that waits on the process to exit but can also
// kill the process when triggered
let state_2 = Arc::clone(&state);
let (kill_tx, kill_rx) = oneshot::channel();
let wait_task = tokio::spawn(async move {
tokio::select! {
status = child.wait() => {
debug!("<Conn @ {}> Process {} done", conn_id, id);
// Force stdin task to abort if it hasn't exited as there is no
// point to sending any more stdin
stdin_task.abort();
if let Err(x) = stderr_task.await {
error!("<Conn @ {}> Join on stderr task failed: {}", conn_id, x);
}
if let Err(x) = stdout_task.await {
error!("<Conn @ {}> Join on stdout task failed: {}", conn_id, x);
}
state_2.lock().await.remove_process(conn_id, id);
match status {
Ok(status) => {
let success = status.success();
let code = status.code();
let res = Response::new(
tenant.as_str(),
None,
vec![ResponseData::ProcDone { id, success, code }]
);
if tx.send(res).await.is_err() {
error!(
"<Conn @ {}> Failed to send done for process {}!",
conn_id,
id,
);
}
}
Err(x) => {
let res = Response::new(tenant.as_str(), None, vec![ResponseData::from(x)]);
if tx.send(res).await.is_err() {
error!(
"<Conn @ {}> Failed to send error for waiting on process {}!",
conn_id,
id,
);
}
}
}
},
_ = kill_rx => {
debug!("<Conn @ {}> Process {} killed", conn_id, id);
if let Err(x) = child.kill().await {
error!("<Conn @ {}> Unable to kill process {}: {}", conn_id, id, x);
}
// Force stdin task to abort if it hasn't exited as there is no
// point to sending any more stdin
stdin_task.abort();
if let Err(x) = stderr_task.await {
error!("<Conn @ {}> Join on stderr task failed: {}", conn_id, x);
}
if let Err(x) = stdout_task.await {
error!("<Conn @ {}> Join on stdout task failed: {}", conn_id, x);
}
state_2.lock().await.remove_process(conn_id, id);
let res = Response::new(tenant.as_str(), None, vec![ResponseData::ProcDone {
id, success: false, code: None
}]);
if tx.send(res).await.is_err() {
error!("<Conn @ {}> Failed to send done for process {}!", conn_id, id);
}
}
}
});
// Update our state with the new process
if let Some(proc) = state_lock.mut_process(id) {
proc.initialize(stdin_tx, kill_tx, wait_task);
}
});
Ok(Outgoing {
data: ResponseData::ProcStart { id },
post_hook: Some(post_hook),
})
}
async fn proc_kill(state: HState, id: usize) -> Result<Outgoing, ServerError> {
if let Some(process) = state.lock().await.processes.remove(&id) {
if process.kill() {
return Ok(Outgoing::from(ResponseData::Ok));
}
}
Err(ServerError::IoError(io::Error::new(
io::ErrorKind::BrokenPipe,
"Unable to send kill signal to process",
)))
}
async fn proc_stdin(state: HState, id: usize, data: String) -> Result<Outgoing, ServerError> {
if let Some(process) = state.lock().await.processes.get(&id) {
if process.send_stdin(data).await {
return Ok(Outgoing::from(ResponseData::Ok));
}
}
Err(ServerError::IoError(io::Error::new(
io::ErrorKind::BrokenPipe,
"Unable to send stdin to process",
)))
}
async fn proc_list(state: HState) -> Result<Outgoing, ServerError> {
Ok(Outgoing::from(ResponseData::ProcEntries {
entries: state
.lock()
.await
.processes
.values()
.map(|p| RunningProcess {
cmd: p.cmd.to_string(),
args: p.args.clone(),
id: p.id,
})
.collect(),
}))
}
async fn system_info() -> Result<Outgoing, ServerError> {
Ok(Outgoing::from(ResponseData::SystemInfo {
family: env::consts::FAMILY.to_string(),
os: env::consts::OS.to_string(),
arch: env::consts::ARCH.to_string(),
current_dir: env::current_dir().unwrap_or_default(),
main_separator: std::path::MAIN_SEPARATOR,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use assert_fs::prelude::*;
use predicates::prelude::*;
use std::time::Duration;
lazy_static::lazy_static! {
static ref TEMP_SCRIPT_DIR: assert_fs::TempDir = assert_fs::TempDir::new().unwrap();
static ref SCRIPT_RUNNER: String = String::from("bash");
static ref ECHO_ARGS_TO_STDOUT_SH: assert_fs::fixture::ChildPath = {
let script = TEMP_SCRIPT_DIR.child("echo_args_to_stdout.sh");
script.write_str(indoc::indoc!(r#"
#/usr/bin/env bash
printf "%s" "$@"
"#)).unwrap();
script
};
static ref ECHO_ARGS_TO_STDERR_SH: assert_fs::fixture::ChildPath = {
let script = TEMP_SCRIPT_DIR.child("echo_args_to_stderr.sh");
script.write_str(indoc::indoc!(r#"
#/usr/bin/env bash
printf "%s" "$@" 1>&2
"#)).unwrap();
script
};
static ref ECHO_STDIN_TO_STDOUT_SH: assert_fs::fixture::ChildPath = {
let script = TEMP_SCRIPT_DIR.child("echo_stdin_to_stdout.sh");
script.write_str(indoc::indoc!(r#"
#/usr/bin/env bash
while IFS= read; do echo "$REPLY"; done
"#)).unwrap();
script
};
static ref EXIT_CODE_SH: assert_fs::fixture::ChildPath = {
let script = TEMP_SCRIPT_DIR.child("exit_code.sh");
script.write_str(indoc::indoc!(r#"
#!/usr/bin/env bash
exit "$1"
"#)).unwrap();
script
};
static ref SLEEP_SH: assert_fs::fixture::ChildPath = {
let script = TEMP_SCRIPT_DIR.child("sleep.sh");
script.write_str(indoc::indoc!(r#"
#!/usr/bin/env bash
sleep "$1"
"#)).unwrap();
script
};
static ref DOES_NOT_EXIST_BIN: assert_fs::fixture::ChildPath =
TEMP_SCRIPT_DIR.child("does_not_exist_bin");
}
fn setup(
buffer: usize,
) -> (
usize,
Arc<Mutex<State>>,
mpsc::Sender<Response>,
mpsc::Receiver<Response>,
) {
let (tx, rx) = mpsc::channel(buffer);
(
rand::random(),
Arc::new(Mutex::new(State::default())),
tx,
rx,
)
}
#[tokio::test]
async fn file_read_should_send_error_if_fails_to_read_file() {
let (conn_id, state, tx, mut rx) = setup(1);
let temp = assert_fs::TempDir::new().unwrap();
let path = temp.child("missing-file").path().to_path_buf();
let req = Request::new("test-tenant", vec![RequestData::FileRead { path }]);
process(conn_id, state, req, tx).await.unwrap();
let res = rx.recv().await.unwrap();
assert_eq!(res.payload.len(), 1, "Wrong payload size");
assert!(
matches!(res.payload[0], ResponseData::Error(_)),
"Unexpected response: {:?}",
res.payload[0]
);
}
#[tokio::test]
async fn file_read_should_send_blob_with_file_contents() {
let (conn_id, state, tx, mut rx) = setup(1);
let temp = assert_fs::TempDir::new().unwrap();
let file = temp.child("test-file");
file.write_str("some file contents").unwrap();
let req = Request::new(
"test-tenant",
vec![RequestData::FileRead {
path: file.path().to_path_buf(),
}],
);
process(conn_id, state, req, tx).await.unwrap();
let res = rx.recv().await.unwrap();
assert_eq!(res.payload.len(), 1, "Wrong payload size");
match &res.payload[0] {
ResponseData::Blob { data } => assert_eq!(data, b"some file contents"),
x => panic!("Unexpected response: {:?}", x),
}
}
#[tokio::test]
async fn file_read_text_should_send_error_if_fails_to_read_file() {
let (conn_id, state, tx, mut rx) = setup(1);
let temp = assert_fs::TempDir::new().unwrap();
let path = temp.child("missing-file").path().to_path_buf();
let req = Request::new("test-tenant", vec![RequestData::FileReadText { path }]);
process(conn_id, state, req, tx).await.unwrap();
let res = rx.recv().await.unwrap();
assert_eq!(res.payload.len(), 1, "Wrong payload size");
assert!(
matches!(res.payload[0], ResponseData::Error(_)),
"Unexpected response: {:?}",
res.payload[0]
);
}
#[tokio::test]
async fn file_read_text_should_send_text_with_file_contents() {
let (conn_id, state, tx, mut rx) = setup(1);
let temp = assert_fs::TempDir::new().unwrap();
let file = temp.child("test-file");
file.write_str("some file contents").unwrap();
let req = Request::new(
"test-tenant",
vec![RequestData::FileReadText {
path: file.path().to_path_buf(),
}],
);
process(conn_id, state, req, tx).await.unwrap();
let res = rx.recv().await.unwrap();
assert_eq!(res.payload.len(), 1, "Wrong payload size");
match &res.payload[0] {
ResponseData::Text { data } => assert_eq!(data, "some file contents"),
x => panic!("Unexpected response: {:?}", x),
}
}
#[tokio::test]
async fn file_write_should_send_error_if_fails_to_write_file() {
let (conn_id, state, tx, mut rx) = setup(1);
// Create a temporary path and add to it to ensure that there are
// extra components that don't exist to cause writing to fail
let temp = assert_fs::TempDir::new().unwrap();
let file = temp.child("dir").child("test-file");
let req = Request::new(
"test-tenant",
vec![RequestData::FileWrite {
path: file.path().to_path_buf(),
data: b"some text".to_vec(),
}],
);
process(conn_id, state, req, tx).await.unwrap();
let res = rx.recv().await.unwrap();
assert_eq!(res.payload.len(), 1, "Wrong payload size");
assert!(
matches!(res.payload[0], ResponseData::Error(_)),
"Unexpected response: {:?}",
res.payload[0]
);
// Also verify that we didn't actually create the file
file.assert(predicate::path::missing());
}
#[tokio::test]
async fn file_write_should_send_ok_when_successful() {
let (conn_id, state, tx, mut rx) = setup(1);
// Path should point to a file that does not exist, but all
// other components leading up to it do
let temp = assert_fs::TempDir::new().unwrap();
let file = temp.child("test-file");
let req = Request::new(
"test-tenant",
vec![RequestData::FileWrite {
path: file.path().to_path_buf(),
data: b"some text".to_vec(),
}],
);
process(conn_id, state, req, tx).await.unwrap();
let res = rx.recv().await.unwrap();
assert_eq!(res.payload.len(), 1, "Wrong payload size");
assert!(
matches!(res.payload[0], ResponseData::Ok),
"Unexpected response: {:?}",
res.payload[0]
);
// Also verify that we actually did create the file
// with the associated contents
file.assert("some text");
}
#[tokio::test]
async fn file_write_text_should_send_error_if_fails_to_write_file() {
let (conn_id, state, tx, mut rx) = setup(1);
// Create a temporary path and add to it to ensure that there are
// extra components that don't exist to cause writing to fail
let temp = assert_fs::TempDir::new().unwrap();
let file = temp.child("dir").child("test-file");
let req = Request::new(
"test-tenant",
vec![RequestData::FileWriteText {
path: file.path().to_path_buf(),
text: String::from("some text"),
}],
);
process(conn_id, state, req, tx).await.unwrap();
let res = rx.recv().await.unwrap();
assert_eq!(res.payload.len(), 1, "Wrong payload size");
assert!(
matches!(res.payload[0], ResponseData::Error(_)),
"Unexpected response: {:?}",
res.payload[0]
);
// Also verify that we didn't actually create the file
file.assert(predicate::path::missing());
}
#[tokio::test]
async fn file_write_text_should_send_ok_when_successful() {
let (conn_id, state, tx, mut rx) = setup(1);
// Path should point to a file that does not exist, but all
// other components leading up to it do
let temp = assert_fs::TempDir::new().unwrap();
let file = temp.child("test-file");
let req = Request::new(
"test-tenant",
vec![RequestData::FileWriteText {
path: file.path().to_path_buf(),
text: String::from("some text"),
}],
);
process(conn_id, state, req, tx).await.unwrap();
let res = rx.recv().await.unwrap();
assert_eq!(res.payload.len(), 1, "Wrong payload size");
assert!(
matches!(res.payload[0], ResponseData::Ok),
"Unexpected response: {:?}",
res.payload[0]
);
// Also verify that we actually did create the file
// with the associated contents
file.assert("some text");
}
#[tokio::test]
async fn file_append_should_send_error_if_fails_to_create_file() {
let (conn_id, state, tx, mut rx) = setup(1);
// Create a temporary path and add to it to ensure that there are
// extra components that don't exist to cause writing to fail
let temp = assert_fs::TempDir::new().unwrap();
let file = temp.child("dir").child("test-file");
let req = Request::new(
"test-tenant",
vec![RequestData::FileAppend {
path: file.path().to_path_buf(),
data: b"some extra contents".to_vec(),
}],
);
process(conn_id, state, req, tx).await.unwrap();
let res = rx.recv().await.unwrap();
assert_eq!(res.payload.len(), 1, "Wrong payload size");
assert!(
matches!(res.payload[0], ResponseData::Error(_)),
"Unexpected response: {:?}",
res.payload[0]
);
// Also verify that we didn't actually create the file
file.assert(predicate::path::missing());
}
#[tokio::test]
async fn file_append_should_send_ok_when_successful() {
let (conn_id, state, tx, mut rx) = setup(1);
// Create a temporary file and fill it with some contents
let temp = assert_fs::TempDir::new().unwrap();