Skip to content

Commit 11ebc1c

Browse files
Jonathan Woollett-Lightpb8o
Jonathan Woollett-Light
andcommitted
test: Update code coverage to grcov
Moved code coverage from kcov to grcov. Updated `verify_dependencies.rs` as no longer proxying through `cargo kcov` and the environment variable `CARGO_MANIFEST_DIR` is now always set. Signed-off-by: Jonathan Woollett-Light <[email protected]> Co-authored-by: Pablo Barbáchano <[email protected]>
1 parent 87f49b4 commit 11ebc1c

File tree

7 files changed

+84
-114
lines changed

7 files changed

+84
-114
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,4 @@ __pycache__
99
.vscode
1010
test_results/*
1111
*.core
12+
*.profraw

src/firecracker/tests/verify_dependencies.rs

+1-6
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,7 @@ fn test_no_comparison_requirements() {
1212
// HashMap mapping crate -> [(violating dependency, specified version)]
1313
let mut violating_dependencies = HashMap::new();
1414

15-
let src_firecracker_path = match std::env::var("CARGO_MANIFEST_DIR") {
16-
Ok(path) => path,
17-
Err(_) => return, /* when running under kcov, this variable is not set. As we do not
18-
* actually run any firecracker code, we can just skip this test
19-
* without affecting coverage */
20-
};
15+
let src_firecracker_path = std::env::var("CARGO_MANIFEST_DIR").unwrap();
2116
let src_path = format!("{}/..", src_firecracker_path);
2217

2318
for fc_crate in std::fs::read_dir(src_path).unwrap() {

tests/integration_tests/build/test_coverage.py

+75-98
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,9 @@
22
# SPDX-License-Identifier: Apache-2.0
33
"""Tests enforcing code coverage for production code."""
44

5-
6-
import os
7-
import platform
8-
import re
9-
import shutil
105
import pytest
116

127
from framework import utils
13-
import host_tools.cargo_build as host # pylint: disable=import-error
148
from host_tools import proc
159

1610
# We have different coverages based on the host kernel version. This is
@@ -29,109 +23,92 @@
2923

3024
PROC_MODEL = proc.proc_type()
3125

32-
COVERAGE_MAX_DELTA = 0.05
33-
34-
CARGO_KCOV_REL_PATH = os.path.join(host.CARGO_BUILD_REL_PATH, "kcov")
35-
36-
KCOV_COVERAGE_FILE = "index.js"
37-
"""kcov will aggregate coverage data in this file."""
26+
# Toolchain target architecture.
27+
if ("Intel" in PROC_MODEL) or ("AMD" in PROC_MODEL):
28+
ARCH = "x86_64"
29+
elif "ARM" in PROC_MODEL:
30+
ARCH = "aarch64"
31+
else:
32+
raise Exception(f"Unsupported processor model ({PROC_MODEL})")
3833

39-
KCOV_COVERED_LINES_REGEX = r'"covered_lines":"(\d+)"'
40-
"""Regex for extracting number of total covered lines found by kcov."""
34+
# Toolchain target.
35+
# Currently profiling with `aarch64-unknown-linux-musl` is unsupported (see
36+
# https://github.com/rust-lang/rustup/issues/3095#issuecomment-1280705619) therefore we profile and
37+
# run coverage with the `gnu` toolchains and run unit tests with the `musl` toolchains.
38+
TARGET = f"{ARCH}-unknown-linux-gnu"
4139

42-
KCOV_TOTAL_LINES_REGEX = r'"total_lines" : "(\d+)"'
43-
"""Regex for extracting number of total executable lines found by kcov."""
40+
# We allow coverage to have a max difference of `COVERAGE_MAX_DELTA` as percentage before failing
41+
# the test.
42+
COVERAGE_MAX_DELTA = 0.05
4443

45-
SECCOMPILER_BUILD_DIR = "../build/seccompiler"
44+
# grcov 0.8.* requires GLIBC >2.27, this is not present in ubuntu 18.04, when we update the docker
45+
# container with a newer version of ubuntu we can also update this.
46+
GRCOV_VERSION = "0.7.1"
4647

4748

4849
@pytest.mark.timeout(400)
49-
def test_coverage(test_fc_session_root_path, test_session_tmp_path, record_property):
50-
"""Test line coverage for rust tests is within bounds.
51-
52-
The result is extracted from the $KCOV_COVERAGE_FILE file created by kcov
53-
after a coverage run.
50+
def test_coverage(monkeypatch):
51+
"""Test code coverage
5452
5553
@type: build
5654
"""
57-
proc_model = [item for item in COVERAGE_DICT if item in PROC_MODEL]
58-
assert len(proc_model) == 1, "Could not get processor model!"
59-
coverage_target_pct = COVERAGE_DICT[proc_model[0]]
60-
exclude_pattern = (
61-
"${CARGO_HOME:-$HOME/.cargo/},"
62-
"build/,"
63-
"tests/,"
64-
"usr/lib/gcc,"
65-
"lib/x86_64-linux-gnu/,"
66-
"test_utils.rs,"
67-
# The following files/directories are auto-generated
68-
"bootparam.rs,"
69-
"elf.rs,"
70-
"mpspec.rs,"
71-
"msr_index.rs,"
72-
"bindings.rs,"
73-
"_gen"
74-
)
75-
exclude_region = "'mod tests {'"
76-
target = "{}-unknown-linux-musl".format(platform.machine())
77-
78-
cmd = (
79-
'CARGO_WRAPPER="kcov" RUSTFLAGS="{}" CARGO_TARGET_DIR={} '
80-
"cargo kcov --all "
81-
"--target {} --output {} -- "
82-
"--exclude-pattern={} "
83-
"--exclude-region={} --verify"
84-
).format(
85-
host.get_rustflags(),
86-
os.path.join(test_fc_session_root_path, CARGO_KCOV_REL_PATH),
87-
target,
88-
test_session_tmp_path,
89-
exclude_pattern,
90-
exclude_region,
91-
)
92-
# We remove the seccompiler custom build directory, created by the
93-
# vmm-level `build.rs`.
94-
# If we don't delete it before and after running the kcov command, we will
95-
# run into linker errors.
96-
shutil.rmtree(SECCOMPILER_BUILD_DIR, ignore_errors=True)
97-
# By default, `cargo kcov` passes `--exclude-pattern=$CARGO_HOME --verify`
98-
# to kcov. To pass others arguments, we need to include the defaults.
99-
utils.run_cmd(cmd)
100-
101-
shutil.rmtree(SECCOMPILER_BUILD_DIR)
102-
103-
coverage_file = os.path.join(test_session_tmp_path, KCOV_COVERAGE_FILE)
104-
with open(coverage_file, encoding="utf-8") as cov_output:
105-
contents = cov_output.read()
106-
covered_lines = int(re.findall(KCOV_COVERED_LINES_REGEX, contents)[0])
107-
total_lines = int(re.findall(KCOV_TOTAL_LINES_REGEX, contents)[0])
108-
coverage = covered_lines / total_lines * 100
109-
print("Number of executable lines: {}".format(total_lines))
110-
print("Number of covered lines: {}".format(covered_lines))
111-
print("Thus, coverage is: {:.2f}%".format(coverage))
112-
113-
coverage_low_msg = (
114-
"Current code coverage ({:.2f}%) is >{:.2f}% below the target ({}%).".format(
115-
coverage, COVERAGE_MAX_DELTA, coverage_target_pct
116-
)
55+
# Get coverage target.
56+
processor_model = [item for item in COVERAGE_DICT if item in PROC_MODEL]
57+
assert len(processor_model) == 1, "Could not get processor model!"
58+
coverage_target = COVERAGE_DICT[processor_model[0]]
59+
60+
# Re-direct to repository root.
61+
monkeypatch.chdir("..")
62+
63+
# Generate test profiles.
64+
utils.run_cmd(
65+
f'\
66+
env RUSTFLAGS="-Cinstrument-coverage" \
67+
LLVM_PROFILE_FILE="coverage-%p-%m.profraw" \
68+
cargo test --all --target={TARGET} -- --test-threads=1 \
69+
'
11770
)
11871

119-
assert coverage >= coverage_target_pct - COVERAGE_MAX_DELTA, coverage_low_msg
120-
121-
# Get the name of the variable that needs updating.
122-
namespace = globals()
123-
cov_target_name = [name for name in namespace if namespace[name] is COVERAGE_DICT][
124-
0
125-
]
126-
127-
coverage_high_msg = (
128-
"Current code coverage ({:.2f}%) is >{:.2f}% above the target ({}%).\n"
129-
"Please update the value of {}.".format(
130-
coverage, COVERAGE_MAX_DELTA, coverage_target_pct, cov_target_name
131-
)
72+
# Generate coverage report.
73+
utils.run_cmd(
74+
f'\
75+
cargo install --version {GRCOV_VERSION} grcov \
76+
&& grcov . \
77+
-s . \
78+
--binary-path ./build/cargo_target/{TARGET}/debug/ \
79+
--excl-start "mod tests" \
80+
--ignore "build/*" \
81+
-t html \
82+
--branch \
83+
--ignore-not-existing \
84+
-o ./build/cargo_target/{TARGET}/debug/coverage \
85+
'
13286
)
13387

134-
record_property(
135-
"coverage", f"{coverage}% {coverage_target_pct}% ±{COVERAGE_MAX_DELTA:.2}%"
88+
# Extract coverage from html report.
89+
#
90+
# The line looks like `<abbr title="44724 / 49237">90.83 %</abbr></p>` and is the first
91+
# occurrence of the `<abbr>` element in the file.
92+
#
93+
# When we update grcov to 0.8.* we can update this to pull the coverage from a generated .json
94+
# file.
95+
index = open(
96+
f"./build/cargo_target/{TARGET}/debug/coverage/index.html", encoding="utf-8"
13697
)
137-
assert coverage <= coverage_target_pct + COVERAGE_MAX_DELTA, coverage_high_msg
98+
index_contents = index.read()
99+
end = index_contents.find(" %</abbr></p>")
100+
start = index_contents[:end].rfind(">")
101+
coverage_str = index_contents[start + 1 : end]
102+
coverage = float(coverage_str)
103+
104+
# Compare coverage.
105+
high = coverage_target * (1.0 + COVERAGE_MAX_DELTA)
106+
low = coverage_target * (1.0 - COVERAGE_MAX_DELTA)
107+
assert (
108+
coverage >= low
109+
), f"Current code coverage ({coverage:.2f}%) is more than {COVERAGE_MAX_DELTA:.2f}% below \
110+
the target ({coverage_target:.2f}%)"
111+
assert (
112+
coverage <= high
113+
), f"Current code coverage ({coverage:.2f}%) is more than {COVERAGE_MAX_DELTA:.2f}% above \
114+
the target ({coverage_target:.2f}%)"

tests/integration_tests/build/test_unittests.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,10 @@
77
import host_tools.cargo_build as host # pylint:disable=import-error
88

99
MACHINE = platform.machine()
10-
# No need to run unittests for musl since
11-
# we run coverage with musl for all platforms.
12-
TARGET = "{}-unknown-linux-gnu".format(MACHINE)
10+
# Currently profiling with `aarch64-unknown-linux-musl` is unsupported (see
11+
# https://github.com/rust-lang/rustup/issues/3095#issuecomment-1280705619) therefore we profile and
12+
# run coverage with the `gnu` toolchains and run unit tests with the `musl` toolchains.
13+
TARGET = "{}-unknown-linux-musl".format(MACHINE)
1314

1415

1516
def test_unittests(test_fc_session_root_path):

tools/devctr/Dockerfile.aarch64

+1-3
Original file line numberDiff line numberDiff line change
@@ -105,10 +105,8 @@ RUN cd "$TMP_POETRY_DIR" \
105105
RUN mkdir "$TMP_BUILD_DIR" \
106106
&& curl https://sh.rustup.rs -sSf | sh -s -- -y --profile minimal --default-toolchain "$RUST_TOOLCHAIN" \
107107
&& rustup target add aarch64-unknown-linux-musl \
108-
&& rustup component add clippy \
108+
&& rustup component add clippy llvm-tools-preview \
109109
&& cd "$TMP_BUILD_DIR" \
110-
&& cargo install cargo-kcov \
111-
&& cargo kcov --print-install-kcov-sh | sh \
112110
&& rm -rf "$CARGO_HOME/registry" \
113111
&& ln -s "$CARGO_REGISTRY_DIR" "$CARGO_HOME/registry" \
114112
&& rm -rf "$CARGO_HOME/git" \

tools/devctr/Dockerfile.x86_64

+1-3
Original file line numberDiff line numberDiff line change
@@ -110,14 +110,12 @@ RUN (curl -sL https://deb.nodesource.com/setup_14.x | bash) \
110110
RUN mkdir "$TMP_BUILD_DIR" \
111111
&& curl https://sh.rustup.rs -sSf | sh -s -- -y --profile minimal --default-toolchain "$RUST_TOOLCHAIN" \
112112
&& rustup target add x86_64-unknown-linux-musl \
113-
&& rustup component add rustfmt clippy clippy-preview \
113+
&& rustup component add rustfmt clippy clippy-preview llvm-tools-preview \
114114
&& rustup install --profile minimal "stable" \
115115
&& cd "$TMP_BUILD_DIR" \
116-
&& cargo install cargo-kcov \
117116
&& cargo +"stable" install cargo-audit \
118117
# Fix a version that does not require cargo edition 2021.
119118
&& cargo install --locked cargo-deny --version '^0.9.1' \
120-
&& cargo kcov --print-install-kcov-sh | sh \
121119
&& rm -rf "$CARGO_HOME/registry" \
122120
&& ln -s "$CARGO_REGISTRY_DIR" "$CARGO_HOME/registry" \
123121
&& rm -rf "$CARGO_HOME/git" \

tools/devtool

+1-1
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@
7272
DEVCTR_IMAGE_NO_TAG="public.ecr.aws/firecracker/fcuvm"
7373

7474
# Development container tag
75-
DEVCTR_IMAGE_TAG="v48"
75+
DEVCTR_IMAGE_TAG="v49"
7676

7777
# Development container image (name:tag)
7878
# This should be updated whenever we upgrade the development container.

0 commit comments

Comments
 (0)