tetragon

Форк
0
140 строк · 3.6 Кб
1
// SPDX-License-Identifier: Apache-2.0
2
// Copyright Authors of Tetragon
3

4
package sensors
5

6
import (
7
	"flag"
8
	"fmt"
9
	"log"
10
	"os"
11
	"path/filepath"
12
	"runtime"
13
	"testing"
14
	"time"
15

16
	"github.com/cilium/tetragon/pkg/bpf"
17
	"github.com/cilium/tetragon/pkg/btf"
18
	"github.com/cilium/tetragon/pkg/logger"
19
	"github.com/cilium/tetragon/pkg/option"
20
	"github.com/cilium/tetragon/pkg/sensors/program"
21
	"github.com/sirupsen/logrus"
22
)
23

24
var config *Config
25

26
// Conf is configuration for testing sensors.
27
// It is intialized in TestSensorsRun() so all sensors test should call this
28
// function in their TestMain
29
type Config struct {
30
	TetragonLib         string
31
	SelfBinary          string
32
	CmdWaitTime         time.Duration
33
	DisableTetragonLogs bool
34
	Debug               bool
35
	Trace               bool
36
}
37

38
var ConfigDefaults = Config{
39
	TetragonLib: filepath.Join(TetragonBpfPath(), "objs"),
40
	SelfBinary:  filepath.Base(os.Args[0]),
41
	// NB: for sensor tests, CmdWaitTime is initialized by TestSensorsRun to 5min
42
	CmdWaitTime:         60000 * time.Millisecond,
43
	DisableTetragonLogs: false,
44
	Debug:               false,
45
	Trace:               false,
46
}
47

48
func Conf() *Config {
49
	if config == nil {
50
		panic("please call TestSensorsRun() to initialize GetTestSensorsConf")
51
	}
52
	return config
53
}
54

55
// TetragonBpfPath retrieves bpf code path
56
func TetragonBpfPath() string {
57
	_, testFname, _, _ := runtime.Caller(0)
58
	return filepath.Join(filepath.Dir(testFname), "..", "..", "..", "bpf")
59
}
60

61
func TestSensorsRun(m *testing.M, sensorName string) int {
62
	c := ConfigDefaults
63
	config = &c
64

65
	// instruct loader to keep the loaded collection for TestLoad* tests
66
	program.KeepCollection = true
67

68
	// some tests require the name of the current binary.
69
	config.SelfBinary = filepath.Base(os.Args[0])
70

71
	flag.StringVar(&config.TetragonLib,
72
		"bpf-lib", ConfigDefaults.TetragonLib,
73
		"tetragon lib directory (location of btf file and bpf objs). Will be overridden by an TETRAGON_LIB env variable.")
74
	flag.DurationVar(&config.CmdWaitTime,
75
		"command-wait",
76
		5*time.Minute,
77
		"duration to wait for tetragon to gather logs from commands")
78
	flag.BoolVar(
79
		&config.DisableTetragonLogs,
80
		"disable-tetragon-logs",
81
		ConfigDefaults.DisableTetragonLogs,
82
		"do not output teragon log")
83
	flag.BoolVar(
84
		&config.Debug,
85
		"debug",
86
		ConfigDefaults.Debug,
87
		"enable debug log output")
88
	flag.BoolVar(
89
		&config.Trace,
90
		"trace",
91
		ConfigDefaults.Trace,
92
		"enable trace log output. Implies debug. Note that due to a naming conflict this must be passed after -args")
93
	flag.Parse()
94

95
	if config.Debug {
96
		if err := logger.SetupLogging(option.Config.LogOpts, true); err != nil {
97
			log.Fatal(err)
98
		}
99
	}
100
	if config.Trace {
101
		logger.DefaultLogger.SetLevel(logrus.TraceLevel)
102
	}
103

104
	// use a sensor-specific name for the bpffs directory for the maps.
105
	// Also, we currently seem to fail to remove the /sys/fs/bpf/<testMapDir>
106
	// Do so here, until we figure out a way to do it properly. Also, issue
107
	// a message.
108
	testMapDir := fmt.Sprintf("test%s", sensorName)
109

110
	bpf.CheckOrMountFS("")
111
	bpf.CheckOrMountDebugFS()
112
	bpf.ConfigureResourceLimits()
113

114
	if config.TetragonLib != "" {
115
		option.Config.HubbleLib = config.TetragonLib
116
	}
117

118
	bpf.SetMapPrefix(testMapDir)
119
	defer func() {
120
		log := logger.GetLogger()
121
		path := bpf.MapPrefixPath()
122
		_, err := os.Stat(path)
123
		if os.IsNotExist(err) {
124
			return
125
		}
126

127
		if entries, err := os.ReadDir(path); err == nil {
128
			for _, entry := range entries {
129
				log.Printf("`%s` still exists after test", entry.Name())
130
			}
131
		}
132

133
		log.Printf("map dir `%s` still exists after test. Removing it.", path)
134
		os.RemoveAll(path)
135
	}()
136
	if err := btf.InitCachedBTF(config.TetragonLib, ""); err != nil {
137
		fmt.Printf("InitCachedBTF failed: %v", err)
138
	}
139
	return m.Run()
140
}
141

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.