Skip to content

Commit c60a0f1

Browse files
author
Jonathan Woollett-Light
committed
Update code coverage to grcov
Signed-off-by: Jonathan Woollett-Light <[email protected]>
1 parent 4ae37a4 commit c60a0f1

File tree

6 files changed

+84
-107
lines changed

6 files changed

+84
-107
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

tests/integration_tests/build/test_coverage.py

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

5-
65
import os
7-
import platform
8-
import re
9-
import shutil
106
import pytest
117

128
from framework import utils
13-
import host_tools.cargo_build as host # pylint: disable=import-error
149
from host_tools import proc
1510

1611
# We have different coverages based on the host kernel version. This is
@@ -29,108 +24,92 @@
2924

3025
PROC_MODEL = proc.proc_type()
3126

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."""
27+
# Toolchain target architecture.
28+
if ("Intel" in PROC_MODEL) or ("AMD" in PROC_MODEL):
29+
ARCH = "x86_64"
30+
elif "ARM" in PROC_MODEL:
31+
ARCH = "aarch64"
32+
else:
33+
raise Exception(f"Unsupported processor model ({PROC_MODEL})")
3834

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

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

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

4749

4850
@pytest.mark.timeout(400)
49-
def test_coverage(test_fc_session_root_path, test_session_tmp_path):
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.
51+
def test_coverage():
52+
"""Test code coverage
5453
5554
@type: build
5655
"""
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"
56+
# Get coverage target.
57+
processor_model = [item for item in COVERAGE_DICT if item in PROC_MODEL]
58+
assert len(processor_model) == 1, "Could not get processor model!"
59+
coverage_target = COVERAGE_DICT[processor_model[0]]
60+
61+
# Re-direct to repository root.
62+
os.chdir("..")
63+
64+
# Generate test profiles.
65+
utils.run_cmd(
66+
f'\
67+
env RUSTFLAGS="-Cinstrument-coverage" \
68+
LLVM_PROFILE_FILE="coverage-%p-%m.profraw" \
69+
cargo test --all --target={TARGET} -- --test-threads=1 \
70+
'
7471
)
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-
)
117-
)
118-
119-
assert coverage >= coverage_target_pct - COVERAGE_MAX_DELTA, coverage_low_msg
12072

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-
)
73+
# Generate coverage report.
74+
utils.run_cmd(
75+
f'\
76+
cargo install --version {GRCOV_VERSION} grcov \
77+
&& grcov . \
78+
-s . \
79+
--binary-path ./build/cargo_target/{TARGET}/debug/ \
80+
--excl-start "mod tests" \
81+
--ignore "build/*" \
82+
-t html \
83+
--branch \
84+
--ignore-not-existing \
85+
-o ./build/cargo_target/{TARGET}/debug/coverage \
86+
'
13287
)
13388

134-
assert coverage <= coverage_target_pct + COVERAGE_MAX_DELTA, coverage_high_msg
135-
136-
return (f"{coverage}%", f"{coverage_target_pct}% +/- {COVERAGE_MAX_DELTA * 100}%")
89+
# Extract coverage from html report.
90+
#
91+
# The line looks like `<abbr title="44724 / 49237">90.83 %</abbr></p>` and is the first
92+
# occurrence of the `<abbr>` element in the file.
93+
#
94+
# When we update grcov to 0.8.* we can update this to pull the coverage from a generated .json
95+
# file.
96+
index = open(
97+
f"./build/cargo_target/{TARGET}/debug/coverage/index.html", encoding="utf-8"
98+
)
99+
index_contents = index.read()
100+
end = index_contents.find(" %</abbr></p>")
101+
start = index_contents[:end].rfind(">")
102+
coverage_str = index_contents[start + 1 : end]
103+
coverage = float(coverage_str)
104+
105+
# Compare coverage.
106+
high = coverage_target * (1.0 + COVERAGE_MAX_DELTA)
107+
low = coverage_target * (1.0 - COVERAGE_MAX_DELTA)
108+
assert (
109+
coverage >= low
110+
), f"Current code coverage ({coverage:.2f}%) is more than {COVERAGE_MAX_DELTA:.2f}% below \
111+
the target ({coverage_target:.2f}%)"
112+
assert (
113+
coverage <= high
114+
), f"Current code coverage ({coverage:.2f}%) is more than {COVERAGE_MAX_DELTA:.2f}% above \
115+
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
@@ -100,10 +100,8 @@ RUN cd "$TMP_POETRY_DIR" \
100100
RUN mkdir "$TMP_BUILD_DIR" \
101101
&& curl https://sh.rustup.rs -sSf | sh -s -- -y --profile minimal --default-toolchain "$RUST_TOOLCHAIN" \
102102
&& rustup target add aarch64-unknown-linux-musl \
103-
&& rustup component add clippy \
103+
&& rustup component add clippy llvm-tools-preview \
104104
&& cd "$TMP_BUILD_DIR" \
105-
&& cargo install cargo-kcov \
106-
&& cargo kcov --print-install-kcov-sh | sh \
107105
&& rm -rf "$CARGO_HOME/registry" \
108106
&& ln -s "$CARGO_REGISTRY_DIR" "$CARGO_HOME/registry" \
109107
&& rm -rf "$CARGO_HOME/git" \

tools/devctr/Dockerfile.x86_64

+1-3
Original file line numberDiff line numberDiff line change
@@ -109,14 +109,12 @@ RUN (curl -sL https://deb.nodesource.com/setup_14.x | bash) \
109109
RUN mkdir "$TMP_BUILD_DIR" \
110110
&& curl https://sh.rustup.rs -sSf | sh -s -- -y --profile minimal --default-toolchain "$RUST_TOOLCHAIN" \
111111
&& rustup target add x86_64-unknown-linux-musl \
112-
&& rustup component add rustfmt clippy clippy-preview \
112+
&& rustup component add rustfmt clippy clippy-preview llvm-tools-preview \
113113
&& rustup install --profile minimal "stable" \
114114
&& cd "$TMP_BUILD_DIR" \
115-
&& cargo install cargo-kcov \
116115
&& cargo +"stable" install cargo-audit \
117116
# Fix a version that does not require cargo edition 2021.
118117
&& cargo install --locked cargo-deny --version '^0.9.1' \
119-
&& cargo kcov --print-install-kcov-sh | sh \
120118
&& rm -rf "$CARGO_HOME/registry" \
121119
&& ln -s "$CARGO_REGISTRY_DIR" "$CARGO_HOME/registry" \
122120
&& 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="v45"
75+
DEVCTR_IMAGE_TAG="cpuid-grcov-1.65.0"
7676

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

0 commit comments

Comments
 (0)