13 "github.com/edwarnicke/exechelper"
14 "github.com/stretchr/testify/assert"
15 "github.com/stretchr/testify/suite"
20 DEFAULT_NETWORK_NUM int = 1
23 var isPersistent = flag.Bool("persist", false, "persists topology config")
24 var isVerbose = flag.Bool("verbose", false, "verbose test output")
25 var isUnconfiguring = flag.Bool("unconfigure", false, "remove topology")
26 var isVppDebug = flag.Bool("debug", false, "attach gdb to vpp")
27 var nConfiguredCpus = flag.Int("cpus", 1, "number of CPUs assigned to vpp")
28 var vppSourceFileDir = flag.String("vppsrc", "", "vpp source file directory")
30 type HstSuite struct {
32 containers map[string]*Container
34 netConfigs []NetConfig
35 netInterfaces map[string]*NetInterface
36 ip4AddrAllocator *Ip4AddressAllocator
37 testIds map[string]string
38 cpuAllocator *CpuAllocatorT
39 cpuContexts []*CpuContext
44 func (s *HstSuite) SetupSuite() {
46 s.pid = fmt.Sprint(os.Getpid())
47 s.cpuAllocator, err = CpuAllocator()
49 s.FailNow("failed to init cpu allocator: %v", err)
51 s.cpuPerVpp = *nConfiguredCpus
54 func (s *HstSuite) AllocateCpus() []int {
55 cpuCtx, err := s.cpuAllocator.Allocate(s.cpuPerVpp)
57 s.AddCpuContext(cpuCtx)
61 func (s *HstSuite) AddCpuContext(cpuCtx *CpuContext) {
62 s.cpuContexts = append(s.cpuContexts, cpuCtx)
65 func (s *HstSuite) TearDownSuite() {
66 s.unconfigureNetworkTopology()
69 func (s *HstSuite) TearDownTest() {
73 for _, c := range s.cpuContexts {
78 s.ip4AddrAllocator.deleteIpAddresses()
81 func (s *HstSuite) skipIfUnconfiguring() {
83 s.skip("skipping to unconfigure")
87 func (s *HstSuite) SetupTest() {
88 s.skipIfUnconfiguring()
93 func (s *HstSuite) setupVolumes() {
94 for _, volume := range s.volumes {
95 cmd := "docker volume create --name=" + volume
101 func (s *HstSuite) setupContainers() {
102 for _, container := range s.containers {
103 if !container.isOptional {
109 func logVppInstance(container *Container, maxLines int){
110 if container.vppInstance == nil{
114 logSource := container.getHostWorkDir() + defaultLogFilePath
115 file, err := os.Open(logSource)
122 scanner := bufio.NewScanner(file)
127 lines = append(lines, scanner.Text())
129 if counter > maxLines {
135 fmt.Println("vvvvvvvvvvvvvvv " + container.name + " [VPP instance]:")
136 for _, line := range lines{
139 fmt.Printf("^^^^^^^^^^^^^^^\n\n")
142 func (s *HstSuite) hstFail() {
143 fmt.Println("Containers: " + fmt.Sprint(s.containers))
144 for _, container := range s.containers{
145 out, err := container.log(20)
147 fmt.Printf("An error occured while obtaining '%s' container logs: %s\n", container.name, fmt.Sprint(err))
150 fmt.Printf("\nvvvvvvvvvvvvvvv " +
151 container.name + ":\n" +
153 "^^^^^^^^^^^^^^^\n\n")
154 logVppInstance(container, 20)
159 func (s *HstSuite) assertNil(object interface{}, msgAndArgs ...interface{}) {
160 if !assert.Nil(s.T(), object, msgAndArgs...) {
165 func (s *HstSuite) assertNotNil(object interface{}, msgAndArgs ...interface{}) {
166 if !assert.NotNil(s.T(), object, msgAndArgs...) {
171 func (s *HstSuite) assertEqual(expected, actual interface{}, msgAndArgs ...interface{}) {
172 if !assert.Equal(s.T(), expected, actual, msgAndArgs...) {
177 func (s *HstSuite) assertNotEqual(expected, actual interface{}, msgAndArgs ...interface{}) {
178 if !assert.NotEqual(s.T(), expected, actual, msgAndArgs...) {
183 func (s *HstSuite) assertContains(testString, contains interface{}, msgAndArgs ...interface{}) {
184 if !assert.Contains(s.T(), testString, contains, msgAndArgs...) {
189 func (s *HstSuite) assertNotContains(testString, contains interface{}, msgAndArgs ...interface{}) {
190 if !assert.NotContains(s.T(), testString, contains, msgAndArgs...) {
195 func (s *HstSuite) assertNotEmpty(object interface{}, msgAndArgs ...interface{}) {
196 if !assert.NotEmpty(s.T(), object, msgAndArgs...) {
201 func (s *HstSuite) log(args ...any) {
208 func (s *HstSuite) skip(args ...any) {
213 func (s *HstSuite) SkipIfMultiWorker(args ...any) {
214 if *nConfiguredCpus > 1 {
215 s.skip("test case not supported with multiple vpp workers")
219 func (s *HstSuite) SkipUnlessExtendedTestsBuilt() {
220 imageName := "hs-test/nginx-http3"
222 cmd := exec.Command("docker", "images", imageName)
223 byteOutput, err := cmd.CombinedOutput()
225 s.log("error while searching for docker image")
228 if !strings.Contains(string(byteOutput), imageName) {
229 s.skip("extended tests not built")
233 func (s *HstSuite) resetContainers() {
234 for _, container := range s.containers {
239 func (s *HstSuite) removeVolumes() {
240 for _, volumeName := range s.volumes {
241 cmd := "docker volume rm " + volumeName
243 os.RemoveAll(volumeName)
247 func (s *HstSuite) getNetNamespaceByName(name string) string {
251 func (s *HstSuite) getInterfaceByName(name string) *NetInterface {
252 return s.netInterfaces[name + s.pid]
255 func (s *HstSuite) getContainerByName(name string) *Container {
256 return s.containers[name + s.pid]
260 * Create a copy and return its address, so that individial tests which call this
261 * are not able to modify the original container and affect other tests by doing that
263 func (s *HstSuite) getTransientContainerByName(name string) *Container {
264 containerCopy := *s.containers[name + s.pid]
265 return &containerCopy
268 func (s *HstSuite) loadContainerTopology(topologyName string) {
269 data, err := os.ReadFile(containerTopologyDir + topologyName + ".yaml")
271 s.T().Fatalf("read error: %v", err)
273 var yamlTopo YamlTopology
274 err = yaml.Unmarshal(data, &yamlTopo)
276 s.T().Fatalf("unmarshal error: %v", err)
279 for _, elem := range yamlTopo.Volumes {
280 volumeMap := elem["volume"].(VolumeConfig)
281 hostDir := volumeMap["host-dir"].(string)
282 workingVolumeDir := logDir + s.T().Name() + s.pid + volumeDir
283 volDirReplacer := strings.NewReplacer("$HST_VOLUME_DIR", workingVolumeDir)
284 hostDir = volDirReplacer.Replace(hostDir)
285 s.volumes = append(s.volumes, hostDir)
288 s.containers = make(map[string]*Container)
289 for _, elem := range yamlTopo.Containers {
290 newContainer, err := newContainer(s, elem, s.pid)
291 newContainer.suite = s
293 s.T().Fatalf("container config error: %v", err)
295 s.containers[newContainer.name] = newContainer
299 func (s *HstSuite) loadNetworkTopology(topologyName string) {
300 data, err := os.ReadFile(networkTopologyDir + topologyName + ".yaml")
302 s.T().Fatalf("read error: %v", err)
304 var yamlTopo YamlTopology
305 err = yaml.Unmarshal(data, &yamlTopo)
307 s.T().Fatalf("unmarshal error: %v", err)
310 s.ip4AddrAllocator = NewIp4AddressAllocator()
311 s.netInterfaces = make(map[string]*NetInterface)
313 for _, elem := range yamlTopo.Devices {
314 if _, ok := elem["name"]; ok {
315 elem["name"] = elem["name"].(string) + s.pid
318 if peer, ok := elem["peer"].(NetDevConfig); ok {
319 if peer["name"].(string) != ""{
320 peer["name"] = peer["name"].(string) + s.pid
322 if _, ok := peer["netns"]; ok{
323 peer["netns"] = peer["netns"].(string) + s.pid
327 if _, ok := elem["netns"]; ok {
328 elem["netns"] = elem["netns"].(string) + s.pid
331 if _, ok := elem["interfaces"]; ok {
332 interfaceCount := len(elem["interfaces"].([]interface{}))
333 for i := 0; i < interfaceCount; i++ {
334 elem["interfaces"].([]interface{})[i] = elem["interfaces"].([]interface{})[i].(string) + s.pid
338 switch elem["type"].(string) {
341 if namespace, err := newNetNamespace(elem); err == nil {
342 s.netConfigs = append(s.netConfigs, &namespace)
344 s.T().Fatalf("network config error: %v", err)
349 if netIf, err := newNetworkInterface(elem, s.ip4AddrAllocator); err == nil {
350 s.netConfigs = append(s.netConfigs, netIf)
351 s.netInterfaces[netIf.Name()] = netIf
353 s.T().Fatalf("network config error: %v", err)
358 if bridge, err := newBridge(elem); err == nil {
359 s.netConfigs = append(s.netConfigs, &bridge)
361 s.T().Fatalf("network config error: %v", err)
368 func (s *HstSuite) configureNetworkTopology(topologyName string) {
369 s.loadNetworkTopology(topologyName)
371 if *isUnconfiguring {
375 for _, nc := range s.netConfigs {
376 if err := nc.configure(); err != nil {
377 s.T().Fatalf("network config error: %v", err)
382 func (s *HstSuite) unconfigureNetworkTopology() {
386 for _, nc := range s.netConfigs {
391 func (s *HstSuite) getTestId() string {
392 testName := s.T().Name()
394 if s.testIds == nil {
395 s.testIds = map[string]string{}
398 if _, ok := s.testIds[testName]; !ok {
399 s.testIds[testName] = time.Now().Format("2006-01-02_15-04-05")
402 return s.testIds[testName]
405 // Returns last 4 digits of PID
406 func (s *HstSuite) getPortFromPid() string {
411 return port[len(port)-4:]
414 func (s *HstSuite) startServerApp(running chan error, done chan struct{}, env []string) {
415 cmd := exec.Command("iperf3", "-4", "-s", "-p", s.getPortFromPid())
422 msg := fmt.Errorf("failed to start iperf server: %v", err)
431 func (s *HstSuite) startClientApp(ipAddress string, env []string, clnCh chan error, clnRes chan string) {
439 cmd := exec.Command("iperf3", "-c", ipAddress, "-u", "-l", "1460", "-b", "10g", "-p", s.getPortFromPid())
444 o, err := cmd.CombinedOutput()
447 clnCh <- fmt.Errorf("failed to start client app '%s'.\n%s", err, o)
450 time.Sleep(1 * time.Second)
454 clnRes <- fmt.Sprintf("Client output: %s", o)
460 func (s *HstSuite) startHttpServer(running chan struct{}, done chan struct{}, addressPort, netNs string) {
461 cmd := newCommand([]string{"./http_server", addressPort, s.pid}, netNs)
465 fmt.Println("Failed to start http server: " + fmt.Sprint(err))
468 running <- struct{}{}
473 func (s *HstSuite) startWget(finished chan error, server_ip, port, query, netNs string) {
475 finished <- errors.New("wget error")
478 cmd := newCommand([]string{"wget", "--timeout=10", "--no-proxy", "--tries=5", "-O", "/dev/null", server_ip + ":" + port + "/" + query},
481 o, err := cmd.CombinedOutput()
483 finished <- fmt.Errorf("wget error: '%v\n\n%s'", err, o)
485 } else if !strings.Contains(string(o), "200 OK") {
486 finished <- fmt.Errorf("wget error: response not 200 OK")