blob: 8785fbf63d4d8495f9a135c91dd1b93b761dd713 [file] [log] [blame]
Adrian Villin4677d922024-06-14 09:32:39 +02001package hst
2
3import (
4 "bufio"
Adrian Villin4677d922024-06-14 09:32:39 +02005 "flag"
6 "fmt"
7 "io"
8 "log"
Matus Fabiand46e6742024-07-31 16:08:40 +02009 "net/http"
10 "net/http/httputil"
Adrian Villin4677d922024-06-14 09:32:39 +020011 "os"
12 "os/exec"
13 "path/filepath"
14 "runtime"
Matus Fabiana647a832024-08-26 18:01:14 +020015 "strconv"
Adrian Villin4677d922024-06-14 09:32:39 +020016 "strings"
17 "time"
18
Adrian Villin5a4c7a92024-09-26 11:24:34 +020019 "github.com/edwarnicke/exechelper"
20
Adrian Villin25140012024-07-09 15:31:36 +020021 containerTypes "github.com/docker/docker/api/types/container"
22 "github.com/docker/docker/client"
Adrian Villin4677d922024-06-14 09:32:39 +020023 "github.com/onsi/gomega/gmeasure"
24 "gopkg.in/yaml.v3"
25
Adrian Villin4677d922024-06-14 09:32:39 +020026 . "github.com/onsi/ginkgo/v2"
27 . "github.com/onsi/gomega"
28)
29
30const (
31 DEFAULT_NETWORK_NUM int = 1
32)
33
34var IsPersistent = flag.Bool("persist", false, "persists topology config")
35var IsVerbose = flag.Bool("verbose", false, "verbose test output")
36var IsUnconfiguring = flag.Bool("unconfigure", false, "remove topology")
37var IsVppDebug = flag.Bool("debug", false, "attach gdb to vpp")
38var NConfiguredCpus = flag.Int("cpus", 1, "number of CPUs assigned to vpp")
39var VppSourceFileDir = flag.String("vppsrc", "", "vpp source file directory")
Adrian Villinb4516bb2024-06-19 06:20:00 -040040var IsDebugBuild = flag.Bool("debug_build", false, "some paths are different with debug build")
Adrian Villin5d171eb2024-06-17 08:51:27 +020041var UseCpu0 = flag.Bool("cpu0", false, "use cpu0")
Matus Fabiane99d2662024-07-19 16:04:09 +020042var IsLeakCheck = flag.Bool("leak_check", false, "run leak-check tests")
Adrian Villin4995d0d2024-07-29 17:54:58 +020043var ParallelTotal = flag.Lookup("ginkgo.parallel.total")
Adrian Villin5d171eb2024-06-17 08:51:27 +020044var NumaAwareCpuAlloc bool
Adrian Villin4677d922024-06-14 09:32:39 +020045var SuiteTimeout time.Duration
46
47type HstSuite struct {
48 Containers map[string]*Container
49 StartedContainers []*Container
50 Volumes []string
51 NetConfigs []NetConfig
52 NetInterfaces map[string]*NetInterface
53 Ip4AddrAllocator *Ip4AddressAllocator
54 TestIds map[string]string
55 CpuAllocator *CpuAllocatorT
56 CpuContexts []*CpuContext
Adrian Villinb69ee002024-07-17 14:38:48 +020057 CpuCount int
Adrian Villin4677d922024-06-14 09:32:39 +020058 Ppid string
59 ProcessIndex string
60 Logger *log.Logger
61 LogFile *os.File
Adrian Villin25140012024-07-09 15:31:36 +020062 Docker *client.Client
Adrian Villin4677d922024-06-14 09:32:39 +020063}
64
Adrian Villin4995d0d2024-07-29 17:54:58 +020065// used for colorful ReportEntry
66type StringerStruct struct {
67 Label string
68}
69
70// ColorableString for ReportEntry to use
71func (s StringerStruct) ColorableString() string {
72 return fmt.Sprintf("{{red}}%s{{/}}", s.Label)
73}
74
75// non-colorable String() is used by go's string formatting support but ignored by ReportEntry
76func (s StringerStruct) String() string {
77 return s.Label
78}
79
Adrian Villin4677d922024-06-14 09:32:39 +020080func getTestFilename() string {
81 _, filename, _, _ := runtime.Caller(2)
82 return filepath.Base(filename)
83}
84
Adrian Villin4995d0d2024-07-29 17:54:58 +020085func (s *HstSuite) getLogDirPath() string {
86 testId := s.GetTestId()
87 testName := s.GetCurrentTestName()
88 logDirPath := logDir + testName + "/" + testId + "/"
89
90 cmd := exec.Command("mkdir", "-p", logDirPath)
91 if err := cmd.Run(); err != nil {
92 Fail("mkdir error: " + fmt.Sprint(err))
93 }
94
95 return logDirPath
96}
97
Adrian Villin25140012024-07-09 15:31:36 +020098func (s *HstSuite) newDockerClient() {
99 var err error
100 s.Docker, err = client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
101 s.AssertNil(err)
102 s.Log("docker client created")
103}
104
Adrian Villin4677d922024-06-14 09:32:39 +0200105func (s *HstSuite) SetupSuite() {
106 s.CreateLogger()
Adrian Villin25140012024-07-09 15:31:36 +0200107 s.newDockerClient()
Adrian Villin4677d922024-06-14 09:32:39 +0200108 s.Log("Suite Setup")
109 RegisterFailHandler(func(message string, callerSkip ...int) {
110 s.HstFail()
111 Fail(message, callerSkip...)
112 })
113 var err error
114 s.Ppid = fmt.Sprint(os.Getppid())
115 // remove last number so we have space to prepend a process index (interfaces have a char limit)
116 s.Ppid = s.Ppid[:len(s.Ppid)-1]
117 s.ProcessIndex = fmt.Sprint(GinkgoParallelProcess())
118 s.CpuAllocator, err = CpuAllocator()
119 if err != nil {
120 Fail("failed to init cpu allocator: " + fmt.Sprint(err))
121 }
Adrian Villinb69ee002024-07-17 14:38:48 +0200122 s.CpuCount = *NConfiguredCpus
Adrian Villin4677d922024-06-14 09:32:39 +0200123}
124
125func (s *HstSuite) AllocateCpus() []int {
Adrian Villinb69ee002024-07-17 14:38:48 +0200126 cpuCtx, err := s.CpuAllocator.Allocate(len(s.StartedContainers), s.CpuCount)
Adrian Villin5d171eb2024-06-17 08:51:27 +0200127 // using Fail instead of AssertNil to make error message more readable
128 if err != nil {
129 Fail(fmt.Sprint(err))
130 }
Adrian Villin4677d922024-06-14 09:32:39 +0200131 s.AddCpuContext(cpuCtx)
132 return cpuCtx.cpus
133}
134
135func (s *HstSuite) AddCpuContext(cpuCtx *CpuContext) {
136 s.CpuContexts = append(s.CpuContexts, cpuCtx)
137}
138
139func (s *HstSuite) TearDownSuite() {
140 defer s.LogFile.Close()
Adrian Villin25140012024-07-09 15:31:36 +0200141 defer s.Docker.Close()
Adrian Villin4677d922024-06-14 09:32:39 +0200142 s.Log("Suite Teardown")
143 s.UnconfigureNetworkTopology()
144}
145
146func (s *HstSuite) TearDownTest() {
147 s.Log("Test Teardown")
148 if *IsPersistent {
149 return
150 }
Adrian Villin4995d0d2024-07-29 17:54:58 +0200151 s.WaitForCoreDump()
Adrian Villin4677d922024-06-14 09:32:39 +0200152 s.ResetContainers()
Adrian Villinb69ee002024-07-17 14:38:48 +0200153
154 if s.Ip4AddrAllocator != nil {
155 s.Ip4AddrAllocator.DeleteIpAddresses()
156 }
Adrian Villin4677d922024-06-14 09:32:39 +0200157}
158
159func (s *HstSuite) SkipIfUnconfiguring() {
160 if *IsUnconfiguring {
161 s.Skip("skipping to unconfigure")
162 }
163}
164
165func (s *HstSuite) SetupTest() {
166 s.Log("Test Setup")
167 s.StartedContainers = s.StartedContainers[:0]
168 s.SkipIfUnconfiguring()
Adrian Villin4677d922024-06-14 09:32:39 +0200169 s.SetupContainers()
170}
171
Adrian Villin4677d922024-06-14 09:32:39 +0200172func (s *HstSuite) SetupContainers() {
173 for _, container := range s.Containers {
174 if !container.IsOptional {
175 container.Run()
176 }
177 }
178}
179
180func (s *HstSuite) LogVppInstance(container *Container, maxLines int) {
181 if container.VppInstance == nil {
182 return
183 }
184
185 logSource := container.GetHostWorkDir() + defaultLogFilePath
186 file, err := os.Open(logSource)
187
188 if err != nil {
189 return
190 }
191 defer file.Close()
192
193 scanner := bufio.NewScanner(file)
194 var lines []string
195 var counter int
196
197 for scanner.Scan() {
198 lines = append(lines, scanner.Text())
199 counter++
200 if counter > maxLines {
201 lines = lines[1:]
202 counter--
203 }
204 }
205
206 s.Log("vvvvvvvvvvvvvvv " + container.Name + " [VPP instance]:")
207 for _, line := range lines {
208 s.Log(line)
209 }
210 s.Log("^^^^^^^^^^^^^^^\n\n")
211}
212
213func (s *HstSuite) HstFail() {
214 for _, container := range s.StartedContainers {
215 out, err := container.log(20)
216 if err != nil {
217 s.Log("An error occured while obtaining '" + container.Name + "' container logs: " + fmt.Sprint(err))
Adrian Villin4995d0d2024-07-29 17:54:58 +0200218 s.Log("The container might not be running - check logs in " + s.getLogDirPath())
Adrian Villin4677d922024-06-14 09:32:39 +0200219 continue
220 }
221 s.Log("\nvvvvvvvvvvvvvvv " +
222 container.Name + ":\n" +
223 out +
224 "^^^^^^^^^^^^^^^\n\n")
225 s.LogVppInstance(container, 20)
226 }
227}
228
229func (s *HstSuite) AssertNil(object interface{}, msgAndArgs ...interface{}) {
Matus Fabian225e6f82024-08-22 15:32:44 +0200230 ExpectWithOffset(2, object).To(BeNil(), msgAndArgs...)
Adrian Villin4677d922024-06-14 09:32:39 +0200231}
232
233func (s *HstSuite) AssertNotNil(object interface{}, msgAndArgs ...interface{}) {
Matus Fabian225e6f82024-08-22 15:32:44 +0200234 ExpectWithOffset(2, object).ToNot(BeNil(), msgAndArgs...)
Adrian Villin4677d922024-06-14 09:32:39 +0200235}
236
237func (s *HstSuite) AssertEqual(expected, actual interface{}, msgAndArgs ...interface{}) {
Matus Fabian225e6f82024-08-22 15:32:44 +0200238 ExpectWithOffset(2, actual).To(Equal(expected), msgAndArgs...)
Adrian Villin4677d922024-06-14 09:32:39 +0200239}
240
241func (s *HstSuite) AssertNotEqual(expected, actual interface{}, msgAndArgs ...interface{}) {
Matus Fabian225e6f82024-08-22 15:32:44 +0200242 ExpectWithOffset(2, actual).ToNot(Equal(expected), msgAndArgs...)
Adrian Villin4677d922024-06-14 09:32:39 +0200243}
244
245func (s *HstSuite) AssertContains(testString, contains interface{}, msgAndArgs ...interface{}) {
Matus Fabian225e6f82024-08-22 15:32:44 +0200246 ExpectWithOffset(2, testString).To(ContainSubstring(fmt.Sprint(contains)), msgAndArgs...)
Adrian Villin4677d922024-06-14 09:32:39 +0200247}
248
249func (s *HstSuite) AssertNotContains(testString, contains interface{}, msgAndArgs ...interface{}) {
Matus Fabian225e6f82024-08-22 15:32:44 +0200250 ExpectWithOffset(2, testString).ToNot(ContainSubstring(fmt.Sprint(contains)), msgAndArgs...)
Adrian Villin4677d922024-06-14 09:32:39 +0200251}
252
Adrian Villin25140012024-07-09 15:31:36 +0200253func (s *HstSuite) AssertEmpty(object interface{}, msgAndArgs ...interface{}) {
Matus Fabian225e6f82024-08-22 15:32:44 +0200254 ExpectWithOffset(2, object).To(BeEmpty(), msgAndArgs...)
Adrian Villin25140012024-07-09 15:31:36 +0200255}
256
Adrian Villin4677d922024-06-14 09:32:39 +0200257func (s *HstSuite) AssertNotEmpty(object interface{}, msgAndArgs ...interface{}) {
Matus Fabian225e6f82024-08-22 15:32:44 +0200258 ExpectWithOffset(2, object).ToNot(BeEmpty(), msgAndArgs...)
Adrian Villin4677d922024-06-14 09:32:39 +0200259}
260
Matus Fabiand086a362024-06-27 13:20:10 +0200261func (s *HstSuite) AssertMatchError(actual, expected error, msgAndArgs ...interface{}) {
Matus Fabiana647a832024-08-26 18:01:14 +0200262 ExpectWithOffset(2, actual).To(MatchError(expected), msgAndArgs...)
263}
264
265func (s *HstSuite) AssertGreaterThan(actual, expected interface{}, msgAndArgs ...interface{}) {
266 ExpectWithOffset(2, actual).Should(BeNumerically(">=", expected), msgAndArgs...)
267}
268
269func (s *HstSuite) AssertTimeEqualWithinThreshold(actual, expected time.Time, threshold time.Duration, msgAndArgs ...interface{}) {
270 ExpectWithOffset(2, actual).Should(BeTemporally("~", expected, threshold), msgAndArgs...)
271}
272
273func (s *HstSuite) AssertHttpStatus(resp *http.Response, expectedStatus int, msgAndArgs ...interface{}) {
274 ExpectWithOffset(2, resp).To(HaveHTTPStatus(expectedStatus), msgAndArgs...)
275}
276
277func (s *HstSuite) AssertHttpHeaderWithValue(resp *http.Response, key string, value interface{}, msgAndArgs ...interface{}) {
278 ExpectWithOffset(2, resp).To(HaveHTTPHeaderWithValue(key, value), msgAndArgs...)
279}
280
281func (s *HstSuite) AssertHttpHeaderNotPresent(resp *http.Response, key string, msgAndArgs ...interface{}) {
282 ExpectWithOffset(2, resp.Header.Get(key)).To(BeEmpty(), msgAndArgs...)
283}
284
285func (s *HstSuite) AssertHttpContentLength(resp *http.Response, expectedContentLen int64, msgAndArgs ...interface{}) {
286 ExpectWithOffset(2, resp).To(HaveHTTPHeaderWithValue("Content-Length", strconv.FormatInt(expectedContentLen, 10)), msgAndArgs...)
287}
288
289func (s *HstSuite) AssertHttpBody(resp *http.Response, expectedBody string, msgAndArgs ...interface{}) {
290 ExpectWithOffset(2, resp).To(HaveHTTPBody(expectedBody), msgAndArgs...)
Matus Fabiand086a362024-06-27 13:20:10 +0200291}
292
Adrian Villin4677d922024-06-14 09:32:39 +0200293func (s *HstSuite) CreateLogger() {
294 suiteName := s.GetCurrentSuiteName()
295 var err error
296 s.LogFile, err = os.Create("summary/" + suiteName + ".log")
297 if err != nil {
298 Fail("Unable to create log file.")
299 }
300 s.Logger = log.New(io.Writer(s.LogFile), "", log.LstdFlags)
301}
302
303// Logs to files by default, logs to stdout when VERBOSE=true with GinkgoWriter
304// to keep console tidy
305func (s *HstSuite) Log(arg any) {
306 logs := strings.Split(fmt.Sprint(arg), "\n")
307 for _, line := range logs {
308 s.Logger.Println(line)
309 }
310 if *IsVerbose {
311 GinkgoWriter.Println(arg)
312 }
313}
314
315func (s *HstSuite) Skip(args string) {
316 Skip(args)
317}
318
319func (s *HstSuite) SkipIfMultiWorker(args ...any) {
320 if *NConfiguredCpus > 1 {
321 s.Skip("test case not supported with multiple vpp workers")
322 }
323}
324
Adrian Villin46ab0b22024-09-19 17:19:39 +0200325func (s *HstSuite) SkipIfNotEnoughAvailableCpus() {
326 var maxRequestedCpu int
327 availableCpus := len(s.CpuAllocator.cpus) - 1
328
329 if *UseCpu0 {
330 availableCpus++
331 }
Adrian Villinb69ee002024-07-17 14:38:48 +0200332
333 if s.CpuAllocator.runningInCi {
Adrian Villin46ab0b22024-09-19 17:19:39 +0200334 maxRequestedCpu = ((s.CpuAllocator.buildNumber + 1) * s.CpuAllocator.maxContainerCount * s.CpuCount)
Adrian Villinb69ee002024-07-17 14:38:48 +0200335 } else {
Adrian Villin46ab0b22024-09-19 17:19:39 +0200336 maxRequestedCpu = (GinkgoParallelProcess() * s.CpuAllocator.maxContainerCount * s.CpuCount)
Adrian Villinb69ee002024-07-17 14:38:48 +0200337 }
Hadi Rayan Al-Sandide0e85132024-06-24 10:28:58 +0200338
Adrian Villin46ab0b22024-09-19 17:19:39 +0200339 if availableCpus < maxRequestedCpu {
340 s.Skip(fmt.Sprintf("Test case cannot allocate requested cpus "+
341 "(%d cpus * %d containers, %d available). Try using 'CPU0=true'",
342 s.CpuCount, s.CpuAllocator.maxContainerCount, availableCpus))
Hadi Rayan Al-Sandide0e85132024-06-24 10:28:58 +0200343 }
Hadi Rayan Al-Sandide0e85132024-06-24 10:28:58 +0200344}
345
Matus Fabiane99d2662024-07-19 16:04:09 +0200346func (s *HstSuite) SkipUnlessLeakCheck() {
347 if !*IsLeakCheck {
348 s.Skip("leak-check tests excluded")
349 }
350}
Adrian Villin4995d0d2024-07-29 17:54:58 +0200351
352func (s *HstSuite) WaitForCoreDump() {
353 var filename string
Adrian Villin4995d0d2024-07-29 17:54:58 +0200354 dir, err := os.Open(s.getLogDirPath())
355 if err != nil {
356 s.Log(err)
357 return
358 }
359 defer dir.Close()
360
361 files, err := dir.Readdirnames(0)
362 if err != nil {
363 s.Log(err)
364 return
365 }
366 for _, file := range files {
367 if strings.Contains(file, "core") {
368 filename = file
369 }
370 }
371 timeout := 60
372 waitTime := 5
373
374 if filename != "" {
Matus Fabian4306a3e2024-08-23 15:52:54 +0200375 corePath := s.getLogDirPath() + filename
376 s.Log(fmt.Sprintf("WAITING FOR CORE DUMP (%s)", corePath))
Adrian Villin4995d0d2024-07-29 17:54:58 +0200377 for i := waitTime; i <= timeout; i += waitTime {
Matus Fabian4306a3e2024-08-23 15:52:54 +0200378 fileInfo, err := os.Stat(corePath)
Adrian Villin4995d0d2024-07-29 17:54:58 +0200379 if err != nil {
380 s.Log("Error while reading file info: " + fmt.Sprint(err))
381 return
382 }
383 currSize := fileInfo.Size()
384 s.Log(fmt.Sprintf("Waiting %ds/%ds...", i, timeout))
385 time.Sleep(time.Duration(waitTime) * time.Second)
Matus Fabian4306a3e2024-08-23 15:52:54 +0200386 fileInfo, _ = os.Stat(corePath)
Adrian Villin4995d0d2024-07-29 17:54:58 +0200387
388 if currSize == fileInfo.Size() {
Matus Fabian4306a3e2024-08-23 15:52:54 +0200389 debug := ""
Adrian Villin4995d0d2024-07-29 17:54:58 +0200390 if *IsDebugBuild {
Matus Fabian4306a3e2024-08-23 15:52:54 +0200391 debug = "_debug"
Adrian Villin4995d0d2024-07-29 17:54:58 +0200392 }
Matus Fabian4306a3e2024-08-23 15:52:54 +0200393 vppBinPath := fmt.Sprintf("../../build-root/build-vpp%s-native/vpp/bin/vpp", debug)
394 pluginsLibPath := fmt.Sprintf("build-root/build-vpp%s-native/vpp/lib/x86_64-linux-gnu/vpp_plugins", debug)
395 cmd := fmt.Sprintf("sudo gdb %s -c %s -ex 'set solib-search-path %s/%s' -ex 'bt full' -batch", vppBinPath, corePath, *VppSourceFileDir, pluginsLibPath)
Adrian Villin4995d0d2024-07-29 17:54:58 +0200396 s.Log(cmd)
Matus Fabian4306a3e2024-08-23 15:52:54 +0200397 output, _ := exechelper.Output(cmd)
Adrian Villin4995d0d2024-07-29 17:54:58 +0200398 AddReportEntry("VPP Backtrace", StringerStruct{Label: string(output)})
399 os.WriteFile(s.getLogDirPath()+"backtrace.log", output, os.FileMode(0644))
400 if s.CpuAllocator.runningInCi {
Matus Fabian4306a3e2024-08-23 15:52:54 +0200401 err = os.Remove(corePath)
Adrian Villin4995d0d2024-07-29 17:54:58 +0200402 if err == nil {
Matus Fabian4306a3e2024-08-23 15:52:54 +0200403 s.Log("removed " + corePath)
Adrian Villin4995d0d2024-07-29 17:54:58 +0200404 } else {
405 s.Log(err)
406 }
407 }
408 return
409 }
410 }
411 }
412}
413
Adrian Villin4677d922024-06-14 09:32:39 +0200414func (s *HstSuite) ResetContainers() {
415 for _, container := range s.StartedContainers {
416 container.stop()
Adrian Villin25140012024-07-09 15:31:36 +0200417 s.Log("Removing container " + container.Name)
418 if err := s.Docker.ContainerRemove(container.ctx, container.ID, containerTypes.RemoveOptions{RemoveVolumes: true}); err != nil {
419 s.Log(err)
420 }
Adrian Villin4677d922024-06-14 09:32:39 +0200421 }
422}
423
424func (s *HstSuite) GetNetNamespaceByName(name string) string {
425 return s.ProcessIndex + name + s.Ppid
426}
427
428func (s *HstSuite) GetInterfaceByName(name string) *NetInterface {
429 return s.NetInterfaces[s.ProcessIndex+name+s.Ppid]
430}
431
432func (s *HstSuite) GetContainerByName(name string) *Container {
433 return s.Containers[s.ProcessIndex+name+s.Ppid]
434}
435
436/*
437 * Create a copy and return its address, so that individial tests which call this
438 * are not able to modify the original container and affect other tests by doing that
439 */
440func (s *HstSuite) GetTransientContainerByName(name string) *Container {
441 containerCopy := *s.Containers[s.ProcessIndex+name+s.Ppid]
442 return &containerCopy
443}
444
445func (s *HstSuite) LoadContainerTopology(topologyName string) {
446 data, err := os.ReadFile(containerTopologyDir + topologyName + ".yaml")
447 if err != nil {
448 Fail("read error: " + fmt.Sprint(err))
449 }
450 var yamlTopo YamlTopology
451 err = yaml.Unmarshal(data, &yamlTopo)
452 if err != nil {
453 Fail("unmarshal error: " + fmt.Sprint(err))
454 }
455
456 for _, elem := range yamlTopo.Volumes {
457 volumeMap := elem["volume"].(VolumeConfig)
458 hostDir := volumeMap["host-dir"].(string)
459 workingVolumeDir := logDir + s.GetCurrentTestName() + volumeDir
460 volDirReplacer := strings.NewReplacer("$HST_VOLUME_DIR", workingVolumeDir)
461 hostDir = volDirReplacer.Replace(hostDir)
462 s.Volumes = append(s.Volumes, hostDir)
463 }
464
465 s.Containers = make(map[string]*Container)
466 for _, elem := range yamlTopo.Containers {
467 newContainer, err := newContainer(s, elem)
468 newContainer.Suite = s
469 newContainer.Name = newContainer.Suite.ProcessIndex + newContainer.Name + newContainer.Suite.Ppid
470 if err != nil {
471 Fail("container config error: " + fmt.Sprint(err))
472 }
473 s.Containers[newContainer.Name] = newContainer
474 }
475}
476
477func (s *HstSuite) LoadNetworkTopology(topologyName string) {
478 data, err := os.ReadFile(networkTopologyDir + topologyName + ".yaml")
479 if err != nil {
480 Fail("read error: " + fmt.Sprint(err))
481 }
482 var yamlTopo YamlTopology
483 err = yaml.Unmarshal(data, &yamlTopo)
484 if err != nil {
485 Fail("unmarshal error: " + fmt.Sprint(err))
486 }
487
488 s.Ip4AddrAllocator = NewIp4AddressAllocator()
489 s.NetInterfaces = make(map[string]*NetInterface)
490
491 for _, elem := range yamlTopo.Devices {
492 if _, ok := elem["name"]; ok {
493 elem["name"] = s.ProcessIndex + elem["name"].(string) + s.Ppid
494 }
495
496 if peer, ok := elem["peer"].(NetDevConfig); ok {
497 if peer["name"].(string) != "" {
498 peer["name"] = s.ProcessIndex + peer["name"].(string) + s.Ppid
499 }
500 if _, ok := peer["netns"]; ok {
501 peer["netns"] = s.ProcessIndex + peer["netns"].(string) + s.Ppid
502 }
503 }
504
505 if _, ok := elem["netns"]; ok {
506 elem["netns"] = s.ProcessIndex + elem["netns"].(string) + s.Ppid
507 }
508
509 if _, ok := elem["interfaces"]; ok {
510 interfaceCount := len(elem["interfaces"].([]interface{}))
511 for i := 0; i < interfaceCount; i++ {
512 elem["interfaces"].([]interface{})[i] = s.ProcessIndex + elem["interfaces"].([]interface{})[i].(string) + s.Ppid
513 }
514 }
515
516 switch elem["type"].(string) {
517 case NetNs:
518 {
519 if namespace, err := newNetNamespace(elem); err == nil {
520 s.NetConfigs = append(s.NetConfigs, &namespace)
521 } else {
522 Fail("network config error: " + fmt.Sprint(err))
523 }
524 }
525 case Veth, Tap:
526 {
527 if netIf, err := newNetworkInterface(elem, s.Ip4AddrAllocator); err == nil {
528 s.NetConfigs = append(s.NetConfigs, netIf)
529 s.NetInterfaces[netIf.Name()] = netIf
530 } else {
531 Fail("network config error: " + fmt.Sprint(err))
532 }
533 }
534 case Bridge:
535 {
536 if bridge, err := newBridge(elem); err == nil {
537 s.NetConfigs = append(s.NetConfigs, &bridge)
538 } else {
539 Fail("network config error: " + fmt.Sprint(err))
540 }
541 }
542 }
543 }
544}
545
546func (s *HstSuite) ConfigureNetworkTopology(topologyName string) {
547 s.LoadNetworkTopology(topologyName)
548
549 if *IsUnconfiguring {
550 return
551 }
552
553 for _, nc := range s.NetConfigs {
554 s.Log(nc.Name())
555 if err := nc.configure(); err != nil {
556 Fail("Network config error: " + fmt.Sprint(err))
557 }
558 }
559}
560
561func (s *HstSuite) UnconfigureNetworkTopology() {
562 if *IsPersistent {
563 return
564 }
565 for _, nc := range s.NetConfigs {
566 nc.unconfigure()
567 }
568}
569
570func (s *HstSuite) GetTestId() string {
571 testName := s.GetCurrentTestName()
572
573 if s.TestIds == nil {
574 s.TestIds = map[string]string{}
575 }
576
577 if _, ok := s.TestIds[testName]; !ok {
578 s.TestIds[testName] = time.Now().Format("2006-01-02_15-04-05")
579 }
580
581 return s.TestIds[testName]
582}
583
584func (s *HstSuite) GetCurrentTestName() string {
585 return strings.Split(CurrentSpecReport().LeafNodeText, "/")[1]
586}
587
588func (s *HstSuite) GetCurrentSuiteName() string {
589 return CurrentSpecReport().ContainerHierarchyTexts[0]
590}
591
592// Returns last 3 digits of PID + Ginkgo process index as the 4th digit
593func (s *HstSuite) GetPortFromPpid() string {
594 port := s.Ppid
595 for len(port) < 3 {
596 port += "0"
597 }
598 return port[len(port)-3:] + s.ProcessIndex
599}
600
Adrian Villin4677d922024-06-14 09:32:39 +0200601/*
Matus Fabiand46e6742024-07-31 16:08:40 +0200602RunBenchmark creates Gomega's experiment with the passed-in name and samples the passed-in callback repeatedly (samplesNum times),
Adrian Villin4677d922024-06-14 09:32:39 +0200603passing in suite context, experiment and your data.
604
605You can also instruct runBenchmark to run with multiple concurrent workers.
Matus Fabian5c4c1b62024-06-28 16:11:04 +0200606Note that if running in parallel Gomega returns from Sample when spins up all samples and does not wait until all finished.
Adrian Villin4677d922024-06-14 09:32:39 +0200607You can record multiple named measurements (float64 or duration) within passed-in callback.
608runBenchmark then produces report to show statistical distribution of measurements.
609*/
610func (s *HstSuite) RunBenchmark(name string, samplesNum, parallelNum int, callback func(s *HstSuite, e *gmeasure.Experiment, data interface{}), data interface{}) {
611 experiment := gmeasure.NewExperiment(name)
612
613 experiment.Sample(func(idx int) {
614 defer GinkgoRecover()
615 callback(s, experiment, data)
616 }, gmeasure.SamplingConfig{N: samplesNum, NumParallel: parallelNum})
617 AddReportEntry(experiment.Name, experiment)
618}
Matus Fabiand46e6742024-07-31 16:08:40 +0200619
620/*
621LogHttpReq is Gomega's ghttp server handler which logs received HTTP request.
622
623You should put it at the first place, so request is logged always.
624*/
625func (s *HstSuite) LogHttpReq(body bool) http.HandlerFunc {
626 return func(w http.ResponseWriter, req *http.Request) {
627 dump, err := httputil.DumpRequest(req, body)
628 if err == nil {
629 s.Log("\n> Received request (" + req.RemoteAddr + "):\n" +
630 string(dump) +
631 "\n------------------------------\n")
632 }
633 }
634}