-
Notifications
You must be signed in to change notification settings - Fork 24
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add a test framework for monitoring the host system from inside a container #140
Merged
fearful-symmetry
merged 19 commits into
elastic:main
from
fearful-symmetry:test-framework
Apr 18, 2024
Merged
Changes from 17 commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
23d58d4
build out framework
fearful-symmetry f97f8e3
finishing touches on base tests
fearful-symmetry 90fb35f
linter
fearful-symmetry 59ff7fe
linter, still
fearful-symmetry 3c6e37a
fix test setup
fearful-symmetry 500d058
fix buildkite keys
fearful-symmetry 09e778e
check for docker status, try to figure out what our docker config is
fearful-symmetry 129db48
don't install docker, see what happens
fearful-symmetry 1016230
try to diagnose docker issues
fearful-symmetry 9da790d
possible permissions error
fearful-symmetry 7ca1963
use more complex test matrix
fearful-symmetry 25b8614
fix framework runner
fearful-symmetry 99301dd
fix runner, exe check
fearful-symmetry 0ff866c
add extra buildkite stages, see what happens
fearful-symmetry 816285c
Merge remote-tracking branch 'upstream/main' into test-framework
fearful-symmetry 1a6ecec
add filesystem tests, cleanup
fearful-symmetry 975bf1c
remove unneeded tests
fearful-symmetry bbb0416
cleanup comments
fearful-symmetry 33194d8
Merge remote-tracking branch 'upstream/main' into test-framework
fearful-symmetry File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
#!/bin/bash | ||
|
||
set -euo pipefail | ||
|
||
source .buildkite/scripts/common.sh | ||
|
||
install_go_dependencies | ||
|
||
# install docker | ||
|
||
# DOCKER_VERSION="25.0" | ||
|
||
# curl -fsSL https://get.docker.com -o get-docker.sh | ||
# sudo sh ./get-docker.sh --version $DOCKER_VERSION | ||
|
||
go test -v ./tests |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,304 @@ | ||
// Licensed to Elasticsearch B.V. under one or more contributor | ||
// license agreements. See the NOTICE file distributed with | ||
// this work for additional information regarding copyright | ||
// ownership. Elasticsearch B.V. licenses this file to you under | ||
// the Apache License, Version 2.0 (the "License"); you may | ||
// not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, | ||
// software distributed under the License is distributed on an | ||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
// KIND, either express or implied. See the License for the | ||
// specific language governing permissions and limitations | ||
// under the License. | ||
|
||
package systemtests | ||
|
||
import ( | ||
"bytes" | ||
"context" | ||
"fmt" | ||
"io" | ||
"os" | ||
"os/exec" | ||
"runtime" | ||
"strings" | ||
"testing" | ||
|
||
"github.com/docker/docker/api/types/container" | ||
"github.com/docker/docker/api/types/image" | ||
"github.com/docker/docker/client" | ||
"github.com/docker/docker/pkg/stdcopy" | ||
"github.com/stretchr/testify/assert" | ||
"github.com/stretchr/testify/require" | ||
|
||
"github.com/elastic/elastic-agent-libs/logp" | ||
) | ||
|
||
// DockerTestRunner is a simple test framework for running a given go test inside a container. | ||
// In order for this framework to work fully, tests running under this framework must use | ||
// systemtests.DockerTestResolver() to fetch the hostfs, and also set debug-level logging via `logp`. | ||
type DockerTestRunner struct { | ||
Runner *testing.T | ||
// Privileged is equivalent to the `--privileged` flag passed to `docker run`. Sets elevated permissions. | ||
Privileged bool | ||
// Sets the filepath passed to `go test` | ||
Basepath string | ||
// Testname will run a given test if set | ||
Testname string | ||
// Container name passed to `docker run`. | ||
Container string | ||
// RunAsUser will run the container as a non-root user if set to the given username | ||
// equivalent to `--user=USER` | ||
RunAsUser string | ||
// CgroupNSMode sets the cgroup namespace for the container. Newer versions of docker | ||
// will default to a private namespace. Unexpected namespace values have resulted in bugs. | ||
CgroupNSMode container.CgroupnsMode | ||
// Verbose enables debug-level logging | ||
Verbose bool | ||
// FatalLogMessages will fail the test if a given string appears in the log output for the test. | ||
// Useful for turning non-fatal errors into fatal errors. | ||
// These are just passed to strings.Contains(). I.e. []string{"Non-fatal error"} | ||
FatalLogMessages []string | ||
// MonitorPID will tell tests to specifically check the correctness of process-level monitoring for this PID | ||
MonitorPID int | ||
// CreateHostProcess: this will start a process with the following args outside of the container, | ||
// and use the integration tests to monitor it. | ||
// Useful as "monitor random running processes" as a test heuristic tends to be flaky. | ||
CreateHostProcess *exec.Cmd | ||
} | ||
|
||
// RunResult returns the logs and return code from the container | ||
type RunResult struct { | ||
ReturnCode int64 | ||
Stderr string | ||
Stdout string | ||
} | ||
|
||
type testCase struct { | ||
nsmode container.CgroupnsMode | ||
priv bool | ||
user string | ||
} | ||
|
||
func (tc testCase) String() string { | ||
return fmt.Sprintf("%s-priv:%v-user:%s", tc.nsmode, tc.priv, tc.user) | ||
} | ||
|
||
// CreateAndRunPermissionMatrix is a helper that uses the provided settings to run RunTestsOnDocker() across a range of possible | ||
// docker settings. | ||
// If a given array value is supplied, it will be used to override the value in DockerTestRunner, and run the test for as many times | ||
// as there are supplied values. For example, if privilegedValues=[true, false], then RunTestsOnDocker() will be run twice, | ||
// setting the privileged flag differently for each run. | ||
// if an array argument is empty, the default value set in the DockerTestRunner instance will be used | ||
func (tr *DockerTestRunner) CreateAndRunPermissionMatrix(ctx context.Context, | ||
cgroupNSValues []container.CgroupnsMode, privilegedValues []bool, runAsUserValues []string) { | ||
|
||
cases := []testCase{} | ||
|
||
if len(cgroupNSValues) == 0 { | ||
cgroupNSValues = []container.CgroupnsMode{tr.CgroupNSMode} | ||
} | ||
|
||
if len(privilegedValues) == 0 { | ||
privilegedValues = []bool{tr.Privileged} | ||
} | ||
|
||
if len(runAsUserValues) == 0 { | ||
runAsUserValues = []string{tr.RunAsUser} | ||
} | ||
|
||
// Create a test matrix of every possible case. | ||
// This might seem like overkill, but cgroup and container & docker permissions produces some exciting edge cases. Just run all of them. | ||
for _, ns := range cgroupNSValues { | ||
for _, user := range runAsUserValues { | ||
for _, privSetting := range privilegedValues { | ||
cases = append(cases, testCase{nsmode: ns, priv: privSetting, user: user}) | ||
} | ||
} | ||
} | ||
|
||
tr.Runner.Logf("Running %d tests", len(cases)) | ||
|
||
// some odd recursion happens here if we just refer to tr.Runner | ||
baseRunner := tr.Runner | ||
for _, tc := range cases { | ||
baseRunner.Run(tc.String(), func(t *testing.T) { | ||
runner := tr | ||
runner.Runner = t | ||
runner.CgroupNSMode = tc.nsmode | ||
runner.Privileged = tc.priv | ||
runner.RunAsUser = tc.user | ||
runner.RunTestsOnDocker(ctx) | ||
}) | ||
} | ||
|
||
} | ||
|
||
// RunTestsOnDocker runs a provided test, or all the package tests | ||
// (as in `go test ./...`) inside a docker container with the host's root FS mounted as /hostfs. | ||
// This framework relies on the tests using DockerTestResolver(). | ||
// If docker returns !0 or if there's a matching string entry from FatalLogMessages in stdout/stderr, | ||
// this will fail the test | ||
func (tr *DockerTestRunner) RunTestsOnDocker(ctx context.Context) { | ||
// do we want to run on windows? Much of what we're testing, such as host | ||
// cgroup monitoring, is invalid. | ||
if runtime.GOOS != "linux" { | ||
tr.Runner.Skip("Tests only supported on Linux.") | ||
} | ||
|
||
log := logp.L() | ||
if tr.Basepath == "" { | ||
tr.Basepath = "./..." | ||
} | ||
|
||
if tr.Container == "" { | ||
tr.Container = "golang:latest" | ||
} | ||
|
||
// setup and run | ||
|
||
apiClient, err := client.NewClientWithOpts(client.WithAPIVersionNegotiation()) | ||
require.NoError(tr.Runner, err) | ||
defer apiClient.Close() | ||
|
||
_, err = apiClient.ContainerList(ctx, container.ListOptions{}) | ||
if err != nil { | ||
tr.Runner.Skipf("got error in container list, docker isn't installed or not running: %s", err) | ||
} | ||
|
||
// create monitored process, if we need to | ||
tr.createMonitoredProcess(ctx) | ||
|
||
resp := tr.createTestContainer(ctx, apiClient) | ||
|
||
log.Infof("running test...") | ||
result := tr.runContainerTest(ctx, apiClient, resp) | ||
|
||
// check for failures | ||
|
||
require.Equal(tr.Runner, int64(0), result.ReturnCode, "got bad docker return code. stdout: %s \nstderr: %s", result.Stdout, result.Stderr) | ||
|
||
// iterate by lines to make this easier to read | ||
if len(tr.FatalLogMessages) > 0 { | ||
for _, badLine := range tr.FatalLogMessages { | ||
for _, line := range strings.Split(result.Stdout, "\n") { | ||
require.NotContains(tr.Runner, line, badLine) | ||
} | ||
for _, line := range strings.Split(result.Stderr, "\n") { | ||
require.NotContains(tr.Runner, line, badLine) | ||
} | ||
} | ||
|
||
} | ||
|
||
if tr.Verbose { | ||
fmt.Fprintf(os.Stdout, "stderr: %s\n", result.Stderr) | ||
fmt.Fprintf(os.Stdout, "stdout: %s\n", result.Stdout) | ||
} | ||
|
||
} | ||
|
||
// createTestContainer creates a container with the given test path and test name | ||
func (tr *DockerTestRunner) createTestContainer(ctx context.Context, apiClient *client.Client) container.CreateResponse { | ||
reader, err := apiClient.ImagePull(ctx, tr.Container, image.PullOptions{}) | ||
require.NoError(tr.Runner, err, "error pulling image") | ||
defer reader.Close() | ||
|
||
_, err = io.Copy(os.Stdout, reader) | ||
require.NoError(tr.Runner, err, "error copying image") | ||
|
||
wdCmd := exec.Command("git", "rev-parse", "--show-toplevel") | ||
wdPath, err := wdCmd.CombinedOutput() | ||
require.NoError(tr.Runner, err, "error finding root path") | ||
|
||
cwd := strings.TrimSpace(string(wdPath)) | ||
logp.L().Infof("using cwd: %s", cwd) | ||
|
||
testRunCmd := []string{"go", "test", "-v", tr.Basepath} | ||
if tr.Testname != "" { | ||
testRunCmd = append(testRunCmd, "-run", tr.Testname) | ||
} | ||
|
||
mountPath := "/hostfs" | ||
|
||
containerEnv := []string{fmt.Sprintf("HOSTFS=%s", mountPath)} | ||
if tr.Privileged { | ||
containerEnv = append(containerEnv, "PRIVILEGED=1") | ||
} | ||
|
||
if tr.MonitorPID != 0 { | ||
containerEnv = append(containerEnv, fmt.Sprintf("MONITOR_PID=%d", tr.MonitorPID)) | ||
} | ||
|
||
resp, err := apiClient.ContainerCreate(ctx, &container.Config{ | ||
Image: tr.Container, | ||
Cmd: testRunCmd, | ||
Tty: false, | ||
WorkingDir: "/app", | ||
Env: containerEnv, | ||
User: tr.RunAsUser, | ||
}, &container.HostConfig{ | ||
CgroupnsMode: tr.CgroupNSMode, | ||
Privileged: tr.Privileged, | ||
Binds: []string{fmt.Sprintf("/:%s", mountPath), fmt.Sprintf("%s:/app", cwd)}, | ||
}, nil, nil, "") | ||
require.NoError(tr.Runner, err, "error creating container") | ||
|
||
return resp | ||
} | ||
|
||
func (tr *DockerTestRunner) runContainerTest(ctx context.Context, apiClient *client.Client, resp container.CreateResponse) RunResult { | ||
err := apiClient.ContainerStart(ctx, resp.ID, container.StartOptions{}) | ||
require.NoError(tr.Runner, err, "error starting container") | ||
|
||
res := RunResult{} | ||
|
||
statusCh, errCh := apiClient.ContainerWait(ctx, resp.ID, container.WaitConditionNotRunning) | ||
select { | ||
case err := <-errCh: | ||
require.NoError(tr.Runner, err, "error in container") | ||
case status := <-statusCh: | ||
res.ReturnCode = status.StatusCode | ||
} | ||
|
||
out, err := apiClient.ContainerLogs(ctx, resp.ID, container.LogsOptions{ShowStdout: true, ShowStderr: true}) | ||
require.NoError(tr.Runner, err, "error fetching logs") | ||
|
||
stdout := bytes.NewBufferString("") | ||
stderr := bytes.NewBufferString("") | ||
_, err = stdcopy.StdCopy(stdout, stderr, out) | ||
require.NoError(tr.Runner, err, "error copying logs") | ||
res.Stderr = stderr.String() | ||
res.Stdout = stdout.String() | ||
|
||
return res | ||
} | ||
|
||
func (tr *DockerTestRunner) createMonitoredProcess(ctx context.Context) { | ||
log := logp.L() | ||
// if user has specified a process to monitor, start it now | ||
// skip if the process has already been created | ||
if tr.CreateHostProcess != nil && tr.CreateHostProcess.Process == nil { | ||
// We don't need to do this in a channel, but it prevents races between this goroutine | ||
// and the rest of test framework | ||
startPid := make(chan int) | ||
log.Infof("Creating test Process...") | ||
go func() { | ||
err := tr.CreateHostProcess.Start() | ||
// if the process fails to start up, the resulting tests will fail, so just log it | ||
assert.NoError(tr.Runner, err, "error starting monitor process") | ||
startPid <- tr.CreateHostProcess.Process.Pid | ||
|
||
}() | ||
select { | ||
case pid := <-startPid: | ||
tr.MonitorPID = pid | ||
case <-ctx.Done(): | ||
} | ||
log.Infof("Monitoring pid %d", tr.MonitorPID) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
// Licensed to Elasticsearch B.V. under one or more contributor | ||
// license agreements. See the NOTICE file distributed with | ||
// this work for additional information regarding copyright | ||
// ownership. Elasticsearch B.V. licenses this file to you under | ||
// the Apache License, Version 2.0 (the "License"); you may | ||
// not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, | ||
// software distributed under the License is distributed on an | ||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
// KIND, either express or implied. See the License for the | ||
// specific language governing permissions and limitations | ||
// under the License. | ||
|
||
package systemtests | ||
|
||
import ( | ||
"os" | ||
|
||
"github.com/elastic/elastic-agent-libs/logp" | ||
"github.com/elastic/elastic-agent-system-metrics/metric/system/resolve" | ||
) | ||
|
||
// DockerTestResolver is a resolver meant for use with the containerized system tests. | ||
// The logic here is extremely simple: if USE_HOSTFS is set, return that for the resolver | ||
func DockerTestResolver() resolve.Resolver { | ||
if path, set := os.LookupEnv("HOSTFS"); set { | ||
logp.L().Infof("Using /hostfs for container tests") | ||
return resolve.NewTestResolver(path) | ||
} | ||
return resolve.NewTestResolver("/") | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Do we need to keep those here?
Was it left over from development or is it likely to be needed?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Depending on how creative I get with the buildkite images later, I might need it, so I'm leaving it in