This repository was archived by the owner on Jul 17, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathintegration-test.rs
More file actions
3373 lines (2887 loc) · 108 KB
/
integration-test.rs
File metadata and controls
3373 lines (2887 loc) · 108 KB
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 © 2021 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! A set of integration tests to ensure OS functionality is as expected.
//! These tests spawn a QEMU instance and run the OS on it.
//! The output from serial/QEMU is parsed and verified for expected output.
//!
//! The naming scheme of the tests ensures a somewhat useful order of test
//! execution taking into account the dependency chain:
//! * `s00_*`: Core kernel functionality like boot-up and fault handling
//! * `s01_*`: Low level kernel services: SSE, memory allocation etc.
//! * `s02_*`: High level kernel services: ACPI, core booting mechanism, NR, VSpace etc.
//! * `s03_*`: High level kernel functionality: Spawn cores, run user-space programs
//! * `s04_*`: User-space runtimes
//! * `s05_*`: User-space applications
//! * `s06_*`: User-space applications benchmarks
use std::fmt::{self, Display, Formatter};
use std::fs::{File, OpenOptions};
use std::io::ErrorKind;
use std::io::Write;
use std::path::Path;
use std::sync::{Mutex, MutexGuard};
use std::{io, process};
use hwloc2::{ObjectType, Topology};
use lazy_static::lazy_static;
use csv::WriterBuilder;
use rexpect::errors::*;
use rexpect::process::signal::SIGTERM;
use rexpect::process::wait::WaitStatus;
use rexpect::session::{spawn_command, PtyReplSession};
use rexpect::{spawn, spawn_bash};
use serde::Serialize;
/// Port we use for the Redis instances.
const REDIS_PORT: u16 = 6379;
/// Line we use to tell if Redis has started.
const REDIS_START_MATCH: &'static str = "# Server initialized";
/// Line we use in dhcpd to match for giving IP to Qemu VM.
///
/// # Depends on
/// - `tests/dhcpd.conf`: config file contains match of MAC to IP
const DHCP_ACK_MATCH: &'static str = "DHCPACK on 172.31.0.10 to 56:b4:44:e9:62:d0 via tap0";
/// Environment variable that points to machine config (for baremetal booting)
const BAREMETAL_MACHINE: &'static str = "BAREMETAL_MACHINE";
/// Binary of the memcached benchmark program
const MEMASLAP_BINARY: &str = "memaslap";
/// Binary of the redis benchmark program
const REDIS_BENCHMARK: &str = "redis-benchmark";
/// Shmem related default values
const SHMEM_PATH: &str = "ivshmem-file";
const SHMEM_SIZE: u64 = 8;
/// Different ExitStatus codes as returned by NRK.
#[derive(Eq, PartialEq, Debug, Clone, Copy)]
enum ExitStatus {
/// Successful exit.
Success,
/// ReturnFromMain: main() function returned to arch_indepdendent part.
ReturnFromMain,
/// Encountered kernel panic.
KernelPanic,
/// Encountered OOM.
OutOfMemory,
/// Encountered an interrupt that led to an exit.
UnexpectedInterrupt,
/// General Protection Fault.
GeneralProtectionFault,
/// Unexpected Page Fault.
PageFault,
/// Unexpected process exit code when running a user-space test.
UnexpectedUserSpaceExit,
/// Exception happened during kernel initialization.
ExceptionDuringInitialization,
/// An unrecoverable error happened (double-fault etc).
UnrecoverableError,
/// Kernel exited with unknown error status... Update the script.
Unknown(i32),
}
impl From<i32> for ExitStatus {
fn from(exit_code: i32) -> Self {
match exit_code {
0 => ExitStatus::Success,
1 => ExitStatus::ReturnFromMain,
2 => ExitStatus::KernelPanic,
3 => ExitStatus::OutOfMemory,
4 => ExitStatus::UnexpectedInterrupt,
5 => ExitStatus::GeneralProtectionFault,
6 => ExitStatus::PageFault,
7 => ExitStatus::UnexpectedUserSpaceExit,
8 => ExitStatus::ExceptionDuringInitialization,
9 => ExitStatus::UnrecoverableError,
_ => ExitStatus::Unknown(exit_code),
}
}
}
impl Display for ExitStatus {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let desc = match self {
ExitStatus::Success => "Success!",
ExitStatus::ReturnFromMain => {
"ReturnFromMain: main() function returned to arch_indepdendent part"
}
ExitStatus::KernelPanic => "KernelPanic: Encountered kernel panic",
ExitStatus::OutOfMemory => "OutOfMemory: Encountered OOM",
ExitStatus::UnexpectedInterrupt => "Encountered unexpected Interrupt",
ExitStatus::GeneralProtectionFault => {
"Encountered unexpected General Protection Fault: "
}
ExitStatus::PageFault => "Encountered unexpected Page Fault",
ExitStatus::UnexpectedUserSpaceExit => {
"Unexpected process exit code when running a user-space test"
}
ExitStatus::ExceptionDuringInitialization => {
"Got an interrupt/exception during kernel initialization"
}
ExitStatus::UnrecoverableError => "An unrecoverable error happened (double-fault etc).",
ExitStatus::Unknown(_) => {
"Unknown: Kernel exited with unknown error status... Update the code!"
}
};
write!(f, "{}", desc)
}
}
/// Different machine types we can run on.
#[derive(Eq, PartialEq, Debug, Clone)]
enum Machine {
/// A bare-metal machine identified by a string.
/// The name is described in the corresponding TOML file.
///
/// (e.g., Machine::BareMetal("b1542".into()) should have a corresponding b1542.toml file).
Baremetal(String),
/// Run on a virtual machine with QEMU (machine parameters determined by current host)
Qemu,
}
impl Machine {
fn determine() -> Self {
match std::env::var(BAREMETAL_MACHINE) {
Ok(name) => {
if name.is_empty() {
panic!("{} enviroment variable empty.", BAREMETAL_MACHINE);
}
if !Path::new(&name).exists() {
panic!(
"'{}.toml' file not found. Check {} enviroment variable.",
name, BAREMETAL_MACHINE
);
}
Machine::Baremetal(name)
}
_ => Machine::Qemu,
}
}
fn name(&self) -> &str {
match self {
Machine::Qemu => "qemu",
Machine::Baremetal(s) => s.as_str(),
}
}
/// Return a set of cores to run benchmark, run fewer total iterations
/// and instead more with high core counts.
fn thread_defaults_low_mid_high(&self) -> Vec<usize> {
if cfg!(feature = "smoke") {
return vec![1, 4];
}
let uniform_threads = self.thread_defaults_uniform();
let mut threads = Vec::with_capacity(6);
for low in uniform_threads.iter().take(2) {
threads.push(*low);
}
let mid = uniform_threads.len() / 2;
if let Some(e) = uniform_threads.get(mid) {
threads.push(*e);
}
for high in uniform_threads.iter().rev().take(3) {
threads.push(*high);
}
threads.sort_unstable();
threads.dedup();
threads
}
/// Return a set of cores to run benchmark on sampled uniform between
/// 1..self.max_cores().
fn thread_defaults_uniform(&self) -> Vec<usize> {
if cfg!(feature = "smoke") {
return vec![1, 4];
}
let max_cores = self.max_cores();
let nodes = self.max_numa_nodes();
let mut threads = Vec::with_capacity(12);
// On larger machines thread increments are bigger than on smaller
// machines:
let thread_incremements = if max_cores > 96 {
16
} else if max_cores > 24 {
8
} else if max_cores > 16 {
4
} else {
2
};
for t in (0..(max_cores + 1)).step_by(thread_incremements) {
if t == 0 {
// Can't run on 0 threads
threads.push(t + 1);
} else {
threads.push(t);
}
}
threads.push(max_cores / nodes);
threads.push(max_cores);
threads.sort_unstable();
threads.dedup();
threads
}
fn max_cores(&self) -> usize {
if let Machine::Qemu = self {
let topo = Topology::new().expect("Can't retrieve System topology?");
topo.objects_with_type(&ObjectType::Core)
.map_or(1, |cpus| cpus.len())
} else {
match self.name() {
"l0318" => 96,
"b1542" => 28,
_ => unreachable!("unknown machine"),
}
}
}
fn max_numa_nodes(&self) -> usize {
if let Machine::Qemu = self {
let topo = Topology::new().expect("Can't retrieve System topology?");
// TODO: Should be ObjectType::NUMANode but this fails in the C library?
topo.objects_with_type(&ObjectType::Package)
.map_or(1, |nodes| nodes.len())
} else {
match self.name() {
"l0318" => 4,
"b1542" => 2,
_ => unreachable!("unknown machine"),
}
}
}
}
/// A build environement, currently we only have one it has a link to the
/// `target` directory.
///
/// (Ideally we could override this if we ever need to and set the
/// `CARGO_TARGET_DIR`)
///
/// # Note
/// For the tests, all BuildEnvironment's (with different dir) need to be
/// singleton instances, protected for example by a Mutex.
struct BuildEnvironment {
_dir: &'static str,
}
lazy_static! {
static ref TARGET_DIR: Mutex<BuildEnvironment> =
Mutex::new(BuildEnvironment { _dir: "target" });
}
/// A type that exists when the given target enviroment has been successfully
/// built with the given BuildArgs.
///
/// Use `BuildArgs::build` to construct (by providing a BuildEnvironment).
struct Built<'a> {
with_args: BuildArgs<'a>,
}
/// Arguments passed to the run.py script to build a test.
#[derive(Clone)]
struct BuildArgs<'a> {
/// Test name of kernel integration test.
kernel_features: Vec<&'a str>,
/// Features passed to compiled user-space modules.
user_features: Vec<&'a str>,
/// Which user-space modules to include.
mods: Vec<&'a str>,
/// Should we compile in release mode?
release: bool,
}
impl<'a> Default for BuildArgs<'a> {
fn default() -> BuildArgs<'a> {
BuildArgs {
kernel_features: vec!["integration-test"],
user_features: Vec::new(),
mods: Vec::new(),
release: false,
}
}
}
impl<'a> BuildArgs<'a> {
fn build(self) -> Built<'a> {
let env = match TARGET_DIR.lock() {
Ok(env) => env,
// It's fine to get the environment again if another test failed,
// and hence poisoned the lock. That's because the lock doesn't
// contain any state and is just to coordinate access to the build
// directory (no two builds are using target/ at the same time)
Err(pe) => pe.into_inner(),
};
self.compile(env)
}
/// Build the kernel/user-space.
fn compile(self, _env: MutexGuard<'static, BuildEnvironment>) -> Built<'a> {
let mut compile_args = self.as_cmd();
compile_args.push("--norun".to_string());
compile_args.push("net".to_string());
compile_args.push("--no-network-setup".to_string());
let o = process::Command::new("python3")
.args(compile_args.clone())
// TODO(unimplemented): This will place the new `target` directory
// under kernel if tests are executed in the kernel directory
// ideally we just want to customize the name of the directory but
// still have them in the base-directory -- we'd need this if we
// ever need to have two different builds per test.
//
// .env("CARGO_TARGET_DIR", env.dir)
.output()
.expect("failed to build");
if !o.status.success() {
io::stdout().write_all(&o.stdout).unwrap();
io::stderr().write_all(&o.stderr).unwrap();
panic!("Building test failed: {:?}", compile_args.join(" "));
}
Built { with_args: self }
}
/// Converts the RunnerArgs to a run.py command line invocation.
fn as_cmd(&'a self) -> Vec<String> {
// Add features for build
let kernel_features = String::from(self.kernel_features.join(","));
let user_features = String::from(self.user_features.join(","));
let mut cmd = vec![
"run.py".to_string(),
//"--norun".to_string(),
];
if !self.kernel_features.is_empty() {
cmd.push("--kfeatures".to_string());
cmd.push(kernel_features);
}
if !self.user_features.is_empty() {
cmd.push("--ufeatures".to_string());
cmd.push(user_features);
}
if !self.mods.is_empty() {
cmd.push("--mods".to_string());
cmd.push(self.mods.join(" "));
}
if self.release {
cmd.push("--release".to_string());
}
cmd
}
/// Add a cargo feature to the kernel build.
fn kernel_feature(mut self, kernel_feature: &'a str) -> BuildArgs<'a> {
self.kernel_features.push(kernel_feature);
self
}
/// What cargo features should be passed to the user-space modules build.
fn user_features(mut self, user_features: &[&'a str]) -> BuildArgs<'a> {
self.user_features.extend_from_slice(user_features);
self
}
/// Add a cargo feature to the user-space modules build.
fn user_feature(mut self, user_feature: &'a str) -> BuildArgs<'a> {
self.user_features.push(user_feature);
self
}
/// Adds a user-space module to the build and deployment.
fn module(mut self, module: &'a str) -> BuildArgs<'a> {
self.mods.push(module);
self
}
/// Do a release build.
fn release(mut self) -> BuildArgs<'a> {
self.release = true;
self
}
}
/// Arguments passed to the run.py script to configure a test.
#[derive(Clone)]
struct RunnerArgs<'a> {
/// Which machine we should execute on
machine: Machine,
/// Any arguments used during the build of kernel/user-space
build_args: BuildArgs<'a>,
/// Kernel test (aka xmain function) that should be executed.
kernel_test: &'a str,
/// Number of NUMA nodes the VM should have.
nodes: usize,
/// Number of cores the VM should have.
cores: usize,
/// Total memory of the system (in MiB).
memory: usize,
/// Total persistent memory of the system (in MiB).
pmem: usize,
/// Kernel command line argument.
cmd: Option<&'a str>,
/// If true don't run, just compile.
norun: bool,
/// Parameters to add to the QEMU command line
qemu_args: Vec<&'a str>,
/// Timeout in ms
timeout: Option<u64>,
/// Default network interface for QEMU
nic: &'static str,
/// Pin QEMU cpu threads
setaffinity: bool,
/// Pre-alloc host memory for guest
prealloc: bool,
/// Use large-pages for host memory
large_pages: bool,
/// Enable gdb for the kernel
kgdb: bool,
/// shared memory size.
shmem_size: usize,
/// Shared memory file path.
shmem_path: String,
/// Tap interface
tap: Option<String>,
/// Number of workers
workers: Option<usize>,
/// Configure network only
network_only: bool,
/// Do not configure the network
no_network_setup: bool,
}
#[allow(unused)]
impl<'a> RunnerArgs<'a> {
fn new_with_build(kernel_test: &'a str, built: &'a Built<'a>) -> RunnerArgs<'a> {
let mut args = RunnerArgs {
machine: Machine::determine(),
kernel_test,
build_args: built.with_args.clone(),
nodes: 0,
cores: 1,
memory: 1024,
pmem: 0,
cmd: None,
norun: false,
qemu_args: Vec::new(),
timeout: Some(15_000),
nic: "e1000",
setaffinity: false,
prealloc: false,
large_pages: false,
kgdb: false,
shmem_size: 0,
shmem_path: String::new(),
tap: None,
workers: None,
network_only: false,
no_network_setup: false,
};
if cfg!(feature = "prealloc") {
args = args.prealloc().disable_timeout();
}
args
}
fn new(kernel_test: &'a str) -> RunnerArgs {
let mut args = RunnerArgs {
machine: Machine::determine(),
kernel_test,
build_args: Default::default(),
nodes: 0,
cores: 1,
memory: 1024,
pmem: 0,
cmd: None,
norun: false,
qemu_args: Vec::new(),
timeout: Some(15_000),
nic: "e1000",
setaffinity: false,
prealloc: false,
large_pages: false,
kgdb: false,
shmem_size: 0,
shmem_path: String::new(),
tap: None,
workers: None,
network_only: false,
no_network_setup: false,
};
if cfg!(feature = "prealloc") {
args = args.prealloc().disable_timeout();
}
args
}
/// What machine we should run on.
fn machine(mut self, machine: Machine) -> RunnerArgs<'a> {
self.machine = machine;
self
}
/// How many NUMA nodes QEMU should simulate.
fn nodes(mut self, nodes: usize) -> RunnerArgs<'a> {
self.nodes = nodes;
self
}
/// Use virtio NIC.
fn use_virtio(mut self) -> RunnerArgs<'a> {
self.nic = "virtio-net-pci";
self
}
/// Use virtio NIC.
fn use_vmxnet3(mut self) -> RunnerArgs<'a> {
self.nic = "vmxnet3";
self
}
/// Use e1000 NIC.
fn use_e1000(mut self) -> RunnerArgs<'a> {
self.nic = "e1000";
self
}
/// How many cores QEMU should simulate.
fn cores(mut self, cores: usize) -> RunnerArgs<'a> {
self.cores = cores;
self
}
/// How much total system memory (in MiB) that the instance should get.
///
/// The amount is evenly divided among all nodes.
fn memory(mut self, mibs: usize) -> RunnerArgs<'a> {
self.memory = mibs;
self
}
/// How much total system persistent memory (in MiB) that the instance should get.
///
/// The amount is evenly divided among all nodes.
fn pmem(mut self, mibs: usize) -> RunnerArgs<'a> {
self.pmem = mibs;
self
}
/// Command line passed to the kernel.
fn cmd(mut self, cmd: &'a str) -> RunnerArgs<'a> {
self.cmd = Some(cmd);
self
}
/// Don't run, just build.
fn norun(mut self) -> RunnerArgs<'a> {
self.norun = true;
self
}
/// Which arguments we want to add to QEMU.
fn qemu_args(mut self, args: &[&'a str]) -> RunnerArgs<'a> {
self.qemu_args.extend_from_slice(args);
self
}
/// Adds an argument to QEMU.
fn qemu_arg(mut self, arg: &'a str) -> RunnerArgs<'a> {
self.qemu_args.push(arg);
self
}
fn timeout(mut self, timeout: u64) -> RunnerArgs<'a> {
self.timeout = Some(timeout);
self
}
fn disable_timeout(mut self) -> RunnerArgs<'a> {
self.timeout = None;
self
}
fn setaffinity(mut self) -> RunnerArgs<'a> {
self.setaffinity = true;
self
}
fn prealloc(mut self) -> RunnerArgs<'a> {
self.prealloc = true;
self
}
fn large_pages(mut self) -> RunnerArgs<'a> {
self.large_pages = true;
self
}
fn kgdb(mut self) -> RunnerArgs<'a> {
self.kgdb = true;
self
}
fn shmem_size(mut self, mibs: usize) -> RunnerArgs<'a> {
self.shmem_size = mibs;
self
}
fn shmem_path(mut self, path: &str) -> RunnerArgs<'a> {
self.shmem_path = String::from(path);
self
}
fn tap(mut self, tap: &str) -> RunnerArgs<'a> {
self.tap = Some(String::from(tap));
self
}
fn workers(mut self, workers: usize) -> RunnerArgs<'a> {
self.workers = Some(workers);
self
}
fn network_only(mut self) -> RunnerArgs<'a> {
self.network_only = true;
self
}
fn no_network_setup(mut self) -> RunnerArgs<'a> {
self.no_network_setup = true;
self
}
/// Converts the RunnerArgs to a run.py command line invocation.
fn as_cmd(&'a self) -> Vec<String> {
// Figure out log-level
let log_level = match std::env::var("RUST_LOG") {
Ok(lvl) if lvl == "debug" => "debug",
Ok(lvl) if lvl == "trace" => "trace",
Ok(lvl) if lvl == "warn" => "warn",
Ok(lvl) if lvl == "error" => "error",
Ok(lvl) if lvl == "info" => "info",
_ => "info",
};
// Start with cmdline from build
let mut cmd = self.build_args.as_cmd();
// Add net subcommand, will only use if needed
let mut net_cmd = Vec::<String>::new();
net_cmd.push(String::from("net"));
cmd.push(String::from("--cmd"));
cmd.push(format!(
"log={} test={} {}",
log_level,
self.kernel_test,
self.cmd.unwrap_or("")
));
cmd.push(String::from("--nic"));
cmd.push(String::from(self.nic));
match &self.machine {
Machine::Qemu => {
cmd.push(String::from("--qemu-cores"));
cmd.push(format!("{}", self.cores));
cmd.push(String::from("--qemu-nodes"));
cmd.push(format!("{}", self.nodes));
cmd.push(String::from("--qemu-memory"));
cmd.push(format!("{}", self.memory));
if self.pmem > 0 {
cmd.push(String::from("--qemu-pmem"));
cmd.push(format!("{}", self.pmem));
}
if self.shmem_size > 0 {
cmd.push(String::from("--qemu-ivshmem"));
cmd.push(format!("{}", self.shmem_size));
}
if !self.shmem_path.is_empty() {
cmd.push(String::from("--qemu-shmem-path"));
cmd.push(format!("{}", self.shmem_path));
}
if self.tap.is_some() {
cmd.push(String::from("--tap"));
cmd.push(format!("{}", self.tap.as_ref().unwrap()));
}
if self.setaffinity {
cmd.push(String::from("--qemu-affinity"));
}
if self.prealloc {
cmd.push(String::from("--qemu-prealloc"));
}
if self.large_pages {
// TODO: Also register some?
// let pages = (self.memory+2) / 2;
// sudo bash -c "echo $pages > /sys/kernel/mm/hugepages/hugepages-2048kB/nr_hugepages"
// and when done
// sudo bash -c "echo 0 > /sys/kernel/mm/hugepages/hugepages-2048kB/nr_hugepages"
cmd.push(String::from("--qemu-large-pages"));
}
// Form arguments for QEMU
let mut qemu_args: Vec<String> =
self.qemu_args.iter().map(|arg| arg.to_string()).collect();
if !qemu_args.is_empty() {
cmd.push(format!("--qemu-settings={}", qemu_args.join(" ")));
}
// TODO: this is a bit broken, because no regular arguments can come after a
// command to a python argparse subparser. To make sure parsing order doesn't matter,
// create as a separate 'net_cmd' variable, and add it to the end later (even though it is qemu specific)
if self.workers.is_some() {
net_cmd.push(String::from("--workers"));
net_cmd.push(format!("{}", self.workers.unwrap()));
}
if self.network_only {
net_cmd.push(String::from("--network-only"));
}
if self.no_network_setup {
net_cmd.push(String::from("--no-network-setup"));
}
}
Machine::Baremetal(mname) => {
cmd.push(format!("--machine={}", mname));
}
}
if self.kgdb {
cmd.push(String::from("--kgdb"));
}
// Don't run qemu, just build?
if self.norun {
cmd.push(String::from("--norun"));
}
// Considered empty if only subcommand start ('net') is only thing in array
if net_cmd.len() > 1 {
cmd.append(&mut net_cmd);
}
cmd
}
}
fn check_for_successful_exit(args: &RunnerArgs, r: Result<WaitStatus>, output: String) {
check_for_exit(ExitStatus::Success, args, r, output);
}
fn log_qemu_out(args: &RunnerArgs, output: String) {
if !output.is_empty() {
println!("\n===== QEMU LOG =====");
println!("{}", &output);
println!("===== END QEMU LOG =====");
}
let quoted_cmd = args
.as_cmd()
.into_iter()
.map(|mut arg| {
arg.insert(0, '"');
arg.push('"');
arg
})
.collect::<Vec<String>>()
.join(" ");
println!("We invoked: python3 {}", quoted_cmd);
}
fn check_for_exit(expected: ExitStatus, args: &RunnerArgs, r: Result<WaitStatus>, output: String) {
match r {
Ok(WaitStatus::Exited(_, code)) => {
let exit_status: ExitStatus = code.into();
if exit_status != expected {
log_qemu_out(args, output);
if expected != ExitStatus::Success {
println!("We expected to exit with {}, but", expected);
}
panic!("Unexpected exit code from QEMU: {}", exit_status);
}
// else: We're good
}
Err(e) => {
log_qemu_out(args, output);
panic!("Qemu testing failed: {}", e);
}
e => {
log_qemu_out(args, output);
panic!(
"Something weird happened to the Qemu process, please investigate: {:?}",
e
);
}
};
}
fn wait_for_sigterm(args: &RunnerArgs, r: Result<WaitStatus>, output: String) {
match r {
Ok(WaitStatus::Signaled(_, SIGTERM, _)) => { /* This is what we expect */ }
Ok(WaitStatus::Exited(_, code)) => {
let exit_status: ExitStatus = code.into();
log_qemu_out(args, output);
panic!("Unexpected exit code from QEMU: {}", exit_status);
}
Err(e) => {
log_qemu_out(args, output);
panic!("Qemu testing failed: {}", e);
}
e => {
log_qemu_out(args, output);
panic!(
"Something weird happened to the Qemu process, please investigate: {:?}",
e
);
}
};
}
/// Sets up network interfaces and bridge for rackscale mode
///
/// num_nodes includes the controller in the count. Internally this
/// invokes run.py in 'network-only' mode.
fn setup_network(num_nodes: usize) {
// Setup network
let net_build = BuildArgs::default().build();
let network_setup = RunnerArgs::new_with_build("network_only", &net_build)
.workers(num_nodes)
.network_only();
let mut output = String::new();
let mut network_setup = || -> Result<WaitStatus> {
let mut p = spawn_nrk(&network_setup)?;
output += p.exp_eof()?.as_str();
p.process.exit()
};
network_setup().unwrap();
}
fn setup_shmem(filename: &str, filelen: u64) {
use memfile::{CreateOptions, MemFile};
use std::fs::remove_file;
let _ignore = remove_file(&filename);
let file = MemFile::create(filename, CreateOptions::new()).expect("Unable to create memfile");
file.set_len(filelen * 1024 * 1024)
.expect("Unable to set file length");
}
/// Builds the kernel and spawns a qemu instance of it.
///
/// For kernel-code it gets compiled with kernel features `integration-test`
/// and whatever feature is supplied in `test`. For user-space modules
/// we pass everything in `user_features` to the build.
///
/// It will make sure the code is compiled and ready to launch.
/// Otherwise the 15s timeout we set on the PtySession may not be enough
/// to build from scratch and run the test.
fn spawn_nrk(args: &RunnerArgs) -> Result<rexpect::session::PtySession> {
let mut o = process::Command::new("python3");
o.args(args.as_cmd());
eprintln!("Invoke QEMU: {:?}", o);
let timeout = if cfg!(feature = "baremetal") {
// Machine might take very long to boot, so currently
// we don't use timeouts for baremetal
Some(8 * 60 * 1000) // 8 Minutes
} else {
args.timeout
};
let ret = spawn_command(o, timeout);
ret
}
/// Spawns a DCM solver
///
/// Uses target/dcm-scheduler.jar that is set up by run.py
/// -r => number of requests per solve
fn spawn_dcm(r: usize, timeout: u64) -> Result<rexpect::session::PtyReplSession> {
use std::fs::remove_file;
// Remove existing DCM log file
let file_name = "dcm.log";
let _ignore = remove_file(file_name);
let mut dcm_args = Vec::new();
dcm_args.push("-r".to_string());
dcm_args.push(format!("{}", r));
// Start DCM
let cmd = format!(
"java -jar ../target/dcm-scheduler.jar {} > {}",
dcm_args.join(" "),
file_name
);
eprintln!("Invoke DCM: {}", cmd);
let mut b = spawn_bash(Some(timeout))?;
b.send_line(&cmd)?;
Ok(b)
}
/// Spawns a DHCP server on our host
///
/// It uses our dhcpd config and listens on the tap0 interface
/// (that we set up in our run.py script).
fn spawn_dhcpd() -> Result<rexpect::session::PtyReplSession> {
// apparmor prevents reading of ./tests/dhcpd.conf for dhcpd
// on Ubuntu, so we make sure it is disabled:
let o = process::Command::new("sudo")
.args(&["aa-teardown"])
.output();
if o.is_err() {
match o.unwrap_err().kind() {
ErrorKind::NotFound => println!("AppArmor not found"),
_ => panic!("failed to disable apparmor"),
}
}
let _o = process::Command::new("sudo")
.args(&["killall", "dhcpd"])
.output()
.expect("failed to shut down dhcpd");
// Spawn a bash session for dhcpd, otherwise it seems we
// can't kill the process since we do not run as root
let mut b = spawn_bash(Some(45_000))?;
b.send_line("sudo dhcpd -f -d tap0 --no-pid -cf ./tests/dhcpd.conf")?;
Ok(b)
}
/// Helper function that spawns a UDP receiver socket on the host.
fn spawn_receiver() -> Result<rexpect::session::PtySession> {
spawn("socat UDP-LISTEN:8889,fork stdout", Some(20_000))
}
/// Helper function that tries to ping the QEMU guest.
fn spawn_ping() -> Result<rexpect::session::PtySession> {
spawn("ping 172.31.0.10", Some(20_000))
}
#[allow(unused)]