blob: 974d1547c030428afb28a42dbb9f14fb25112064 [file] [log] [blame]
Adrian Villin4677d922024-06-14 09:32:39 +02001package hst
Maros Ondrejicka11a03e92022-12-01 09:56:37 +01002
3import (
Adrian Villin25140012024-07-09 15:31:36 +02004 "bytes"
5 "context"
Maros Ondrejicka11a03e92022-12-01 09:56:37 +01006 "fmt"
Matus Fabiane99d2662024-07-19 16:04:09 +02007 "github.com/docker/go-units"
Maros Ondrejickadb823ed2022-12-14 16:30:04 +01008 "os"
Maros Ondrejickaffa3f602023-01-26 10:07:29 +01009 "os/exec"
Matus Fabiand4643382024-07-29 13:30:23 +020010 "regexp"
Adrian Villin25140012024-07-09 15:31:36 +020011 "slices"
12 "strconv"
Maros Ondrejickadb823ed2022-12-14 16:30:04 +010013 "strings"
Maros Ondrejicka85396a52023-02-28 12:49:43 +010014 "text/template"
Filip Tehlar4fa0ba62023-12-06 11:35:11 +010015 "time"
Maros Ondrejicka11a03e92022-12-01 09:56:37 +010016
Adrian Villin4995d0d2024-07-29 17:54:58 +020017 "github.com/cilium/cilium/pkg/sysctl"
Adrian Villin25140012024-07-09 15:31:36 +020018 containerTypes "github.com/docker/docker/api/types/container"
Adrian Villin007be4f2024-07-23 12:14:19 +020019 "github.com/docker/docker/api/types/filters"
Adrian Villin25140012024-07-09 15:31:36 +020020 "github.com/docker/docker/api/types/image"
21 "github.com/docker/docker/pkg/stdcopy"
Maros Ondrejicka11a03e92022-12-01 09:56:37 +010022 "github.com/edwarnicke/exechelper"
Adrian Villincee15aa2024-03-14 11:42:55 -040023 . "github.com/onsi/ginkgo/v2"
Maros Ondrejicka11a03e92022-12-01 09:56:37 +010024)
25
Maros Ondrejickaa2d52622023-02-24 11:26:39 +010026const (
Filip Tehlara1bd50c2024-01-24 11:59:44 +010027 logDir string = "/tmp/hs-test/"
28 volumeDir string = "/volumes"
Maros Ondrejickaa2d52622023-02-24 11:26:39 +010029)
30
Maros Ondrejicka7550dd22023-02-07 20:40:27 +010031var (
32 workDir, _ = os.Getwd()
33)
34
Maros Ondrejicka0e79abb2022-12-06 19:46:24 +010035type Volume struct {
Adrian Villin4677d922024-06-14 09:32:39 +020036 HostDir string
37 ContainerDir string
38 IsDefaultWorkDir bool
Maros Ondrejicka0e79abb2022-12-06 19:46:24 +010039}
40
41type Container struct {
Adrian Villin4677d922024-06-14 09:32:39 +020042 Suite *HstSuite
43 IsOptional bool
44 RunDetached bool
45 Name string
Adrian Villin25140012024-07-09 15:31:36 +020046 ID string
Adrian Villin4677d922024-06-14 09:32:39 +020047 Image string
48 ExtraRunningArgs string
49 Volumes map[string]Volume
50 EnvVars map[string]string
51 VppInstance *VppInstance
52 AllocatedCpus []int
Adrian Villin25140012024-07-09 15:31:36 +020053 ctx context.Context
Maros Ondrejickadb823ed2022-12-14 16:30:04 +010054}
55
Adrian Villincee15aa2024-03-14 11:42:55 -040056func newContainer(suite *HstSuite, yamlInput ContainerConfig) (*Container, error) {
Maros Ondrejickadb823ed2022-12-14 16:30:04 +010057 containerName := yamlInput["name"].(string)
58 if len(containerName) == 0 {
59 err := fmt.Errorf("container name must not be blank")
60 return nil, err
61 }
62
63 var container = new(Container)
Adrian Villin4677d922024-06-14 09:32:39 +020064 container.Volumes = make(map[string]Volume)
65 container.EnvVars = make(map[string]string)
66 container.Name = containerName
67 container.Suite = suite
Adrian Villin25140012024-07-09 15:31:36 +020068 container.ctx = context.Background()
Maros Ondrejickadb823ed2022-12-14 16:30:04 +010069
Adrian Villin4677d922024-06-14 09:32:39 +020070 if Image, ok := yamlInput["image"]; ok {
71 container.Image = Image.(string)
Maros Ondrejickadb823ed2022-12-14 16:30:04 +010072 } else {
Adrian Villin4677d922024-06-14 09:32:39 +020073 container.Image = "hs-test/vpp"
Maros Ondrejickadb823ed2022-12-14 16:30:04 +010074 }
75
Filip Tehlar3f951432023-01-13 21:33:43 +010076 if args, ok := yamlInput["extra-args"]; ok {
Adrian Villin4677d922024-06-14 09:32:39 +020077 container.ExtraRunningArgs = args.(string)
Filip Tehlar3f951432023-01-13 21:33:43 +010078 } else {
Adrian Villin4677d922024-06-14 09:32:39 +020079 container.ExtraRunningArgs = ""
Filip Tehlar3f951432023-01-13 21:33:43 +010080 }
81
Maros Ondrejickadb823ed2022-12-14 16:30:04 +010082 if isOptional, ok := yamlInput["is-optional"]; ok {
Adrian Villin4677d922024-06-14 09:32:39 +020083 container.IsOptional = isOptional.(bool)
Maros Ondrejickadb823ed2022-12-14 16:30:04 +010084 } else {
Adrian Villin4677d922024-06-14 09:32:39 +020085 container.IsOptional = false
Maros Ondrejickadb823ed2022-12-14 16:30:04 +010086 }
87
Filip Tehlarb41b0af2023-03-20 12:39:20 +010088 if runDetached, ok := yamlInput["run-detached"]; ok {
Adrian Villin4677d922024-06-14 09:32:39 +020089 container.RunDetached = runDetached.(bool)
Filip Tehlarb41b0af2023-03-20 12:39:20 +010090 } else {
Adrian Villin4677d922024-06-14 09:32:39 +020091 container.RunDetached = true
Filip Tehlarb41b0af2023-03-20 12:39:20 +010092 }
93
Maros Ondrejickadb823ed2022-12-14 16:30:04 +010094 if _, ok := yamlInput["volumes"]; ok {
Adrian Villin4677d922024-06-14 09:32:39 +020095 workingVolumeDir := logDir + suite.GetCurrentTestName() + volumeDir
Filip Tehlara1bd50c2024-01-24 11:59:44 +010096 workDirReplacer := strings.NewReplacer("$HST_DIR", workDir)
97 volDirReplacer := strings.NewReplacer("$HST_VOLUME_DIR", workingVolumeDir)
Maros Ondrejickadb823ed2022-12-14 16:30:04 +010098 for _, volu := range yamlInput["volumes"].([]interface{}) {
99 volumeMap := volu.(ContainerConfig)
Filip Tehlara1bd50c2024-01-24 11:59:44 +0100100 hostDir := workDirReplacer.Replace(volumeMap["host-dir"].(string))
101 hostDir = volDirReplacer.Replace(hostDir)
Maros Ondrejickadb823ed2022-12-14 16:30:04 +0100102 containerDir := volumeMap["container-dir"].(string)
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100103 isDefaultWorkDir := false
Maros Ondrejickadb823ed2022-12-14 16:30:04 +0100104
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100105 if isDefault, ok := volumeMap["is-default-work-dir"]; ok {
106 isDefaultWorkDir = isDefault.(bool)
Maros Ondrejickadb823ed2022-12-14 16:30:04 +0100107 }
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100108 container.addVolume(hostDir, containerDir, isDefaultWorkDir)
Maros Ondrejickadb823ed2022-12-14 16:30:04 +0100109 }
110 }
111
112 if _, ok := yamlInput["vars"]; ok {
113 for _, envVar := range yamlInput["vars"].([]interface{}) {
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100114 envVarMap := envVar.(ContainerConfig)
115 name := envVarMap["name"].(string)
116 value := envVarMap["value"].(string)
Adrian Villin4677d922024-06-14 09:32:39 +0200117 container.AddEnvVar(name, value)
Maros Ondrejickadb823ed2022-12-14 16:30:04 +0100118 }
119 }
120 return container, nil
Maros Ondrejicka11a03e92022-12-01 09:56:37 +0100121}
122
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100123func (c *Container) getWorkDirVolume() (res Volume, exists bool) {
Adrian Villin4677d922024-06-14 09:32:39 +0200124 for _, v := range c.Volumes {
125 if v.IsDefaultWorkDir {
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100126 res = v
127 exists = true
128 return
129 }
130 }
131 return
132}
133
Adrian Villin4677d922024-06-14 09:32:39 +0200134func (c *Container) GetHostWorkDir() (res string) {
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100135 if v, ok := c.getWorkDirVolume(); ok {
Adrian Villin4677d922024-06-14 09:32:39 +0200136 res = v.HostDir
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100137 }
138 return
139}
140
Adrian Villin4677d922024-06-14 09:32:39 +0200141func (c *Container) GetContainerWorkDir() (res string) {
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100142 if v, ok := c.getWorkDirVolume(); ok {
Adrian Villin4677d922024-06-14 09:32:39 +0200143 res = v.ContainerDir
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100144 }
145 return
146}
147
Maros Ondrejickac2f76f42023-02-27 13:22:45 +0100148func (c *Container) getContainerArguments() string {
Adrian Villineaa7d912024-06-06 04:26:30 -0400149 args := "--ulimit nofile=90000:90000 --cap-add=all --privileged --network host"
Maros Ondrejickac2f76f42023-02-27 13:22:45 +0100150 args += c.getVolumesAsCliOption()
151 args += c.getEnvVarsAsCliOption()
Adrian Villin4677d922024-06-14 09:32:39 +0200152 if *VppSourceFileDir != "" {
153 args += fmt.Sprintf(" -v %s:%s", *VppSourceFileDir, *VppSourceFileDir)
Filip Tehlar109f3ce2023-09-05 15:36:28 +0200154 }
Adrian Villin4677d922024-06-14 09:32:39 +0200155 args += " --name " + c.Name + " " + c.Image
156 args += " " + c.ExtraRunningArgs
Maros Ondrejickac2f76f42023-02-27 13:22:45 +0100157 return args
158}
159
Adrian Villin25140012024-07-09 15:31:36 +0200160func (c *Container) PullDockerImage(name string, ctx context.Context) {
161 // "func (*Client) ImagePull" doesn't work, returns "No such image"
162 c.Suite.Log("Pulling image: " + name)
163 _, err := exechelper.CombinedOutput("docker pull " + name)
164 c.Suite.AssertNil(err)
Filip Tehlar4fa0ba62023-12-06 11:35:11 +0100165}
166
Adrian Villin25140012024-07-09 15:31:36 +0200167// Creates a container
Adrian Villin4677d922024-06-14 09:32:39 +0200168func (c *Container) Create() error {
Adrian Villin25140012024-07-09 15:31:36 +0200169 var sliceOfImageNames []string
170 images, err := c.Suite.Docker.ImageList(c.ctx, image.ListOptions{})
171 c.Suite.AssertNil(err)
172
173 for _, image := range images {
174 sliceOfImageNames = append(sliceOfImageNames, strings.Split(image.RepoTags[0], ":")[0])
175 }
176 if !slices.Contains(sliceOfImageNames, c.Image) {
177 c.PullDockerImage(c.Image, c.ctx)
178 }
179
180 c.allocateCpus()
181 cpuSet := fmt.Sprintf("%d-%d", c.AllocatedCpus[0], c.AllocatedCpus[len(c.AllocatedCpus)-1])
182 resp, err := c.Suite.Docker.ContainerCreate(
183 c.ctx,
184 &containerTypes.Config{
Adrian Villin007be4f2024-07-23 12:14:19 +0200185 Hostname: c.Name,
Matus Fabiand4643382024-07-29 13:30:23 +0200186 Image: c.Image,
187 Env: c.getEnvVars(),
188 Cmd: strings.Split(c.ExtraRunningArgs, " "),
Adrian Villin25140012024-07-09 15:31:36 +0200189 },
190 &containerTypes.HostConfig{
191 Resources: containerTypes.Resources{
192 Ulimits: []*units.Ulimit{
193 {
194 Name: "nofile",
195 Soft: 90000,
196 Hard: 90000,
197 },
198 },
199 CpusetCpus: cpuSet,
200 },
201 CapAdd: []string{"ALL"},
202 Privileged: true,
203 NetworkMode: "host",
204 Binds: c.getVolumesAsSlice(),
205 },
206 nil,
207 nil,
208 c.Name,
209 )
210 c.ID = resp.ID
211 return err
Maros Ondrejickac2f76f42023-02-27 13:22:45 +0100212}
213
Adrian Villinb9464cd2024-05-27 09:52:59 -0400214func (c *Container) allocateCpus() {
Adrian Villin4677d922024-06-14 09:32:39 +0200215 c.Suite.StartedContainers = append(c.Suite.StartedContainers, c)
216 c.AllocatedCpus = c.Suite.AllocateCpus()
217 c.Suite.Log("Allocated CPUs " + fmt.Sprint(c.AllocatedCpus) + " to container " + c.Name)
Adrian Villinb9464cd2024-05-27 09:52:59 -0400218}
219
Adrian Villin25140012024-07-09 15:31:36 +0200220// Starts a container
Adrian Villin4677d922024-06-14 09:32:39 +0200221func (c *Container) Start() error {
Adrian Villin25140012024-07-09 15:31:36 +0200222 var err error
Adrian Villin007be4f2024-07-23 12:14:19 +0200223 var nTries int
224
225 for nTries = 0; nTries < 5; nTries++ {
Adrian Villin25140012024-07-09 15:31:36 +0200226 err = c.Suite.Docker.ContainerStart(c.ctx, c.ID, containerTypes.StartOptions{})
227 if err == nil {
228 continue
229 }
230 c.Suite.Log("Error while starting " + c.Name + ". Retrying...")
231 time.Sleep(1 * time.Second)
232 }
Adrian Villin007be4f2024-07-23 12:14:19 +0200233 if nTries >= 5 {
234 return err
235 }
236
237 // wait for container to start
238 time.Sleep(1 * time.Second)
239
240 // check if container exited right after startup
241 containers, err := c.Suite.Docker.ContainerList(c.ctx, containerTypes.ListOptions{
242 All: true,
243 Filters: filters.NewArgs(filters.Arg("name", c.Name)),
244 })
245 if err != nil {
246 return err
247 }
248 if containers[0].State == "exited" {
249 c.Suite.Log("Container details: " + fmt.Sprint(containers[0]))
250 return fmt.Errorf("Container %s exited: '%s'", c.Name, containers[0].Status)
251 }
Adrian Villin25140012024-07-09 15:31:36 +0200252
253 return err
254}
255
256func (c *Container) GetOutput() (string, string) {
257 // Wait for the container to finish executing
258 statusCh, errCh := c.Suite.Docker.ContainerWait(c.ctx, c.ID, containerTypes.WaitConditionNotRunning)
259 select {
260 case err := <-errCh:
261 c.Suite.AssertNil(err)
262 case <-statusCh:
263 }
264
265 // Get the logs from the container
266 logOptions := containerTypes.LogsOptions{ShowStdout: true, ShowStderr: true}
267 logReader, err := c.Suite.Docker.ContainerLogs(c.ctx, c.ID, logOptions)
268 c.Suite.AssertNil(err)
269 defer logReader.Close()
270
271 var stdoutBuf, stderrBuf bytes.Buffer
272
273 // Use stdcopy.StdCopy to demultiplex the multiplexed stream
274 _, err = stdcopy.StdCopy(&stdoutBuf, &stderrBuf, logReader)
275 c.Suite.AssertNil(err)
276
277 stdout := stdoutBuf.String()
278 stderr := stderrBuf.String()
279 return stdout, stderr
Maros Ondrejicka87531802022-12-19 20:35:27 +0100280}
281
Filip Tehlarb41b0af2023-03-20 12:39:20 +0100282func (c *Container) prepareCommand() (string, error) {
Adrian Villin4677d922024-06-14 09:32:39 +0200283 if c.Name == "" {
Filip Tehlarb41b0af2023-03-20 12:39:20 +0100284 return "", fmt.Errorf("run container failed: name is blank")
Maros Ondrejicka87531802022-12-19 20:35:27 +0100285 }
286
Adrian Villin25140012024-07-09 15:31:36 +0200287 cmd := "docker exec "
Adrian Villin4677d922024-06-14 09:32:39 +0200288 if c.RunDetached {
Adrian Villineaa7d912024-06-06 04:26:30 -0400289 cmd += " -d"
Filip Tehlarb41b0af2023-03-20 12:39:20 +0100290 }
Adrian Villinb9464cd2024-05-27 09:52:59 -0400291
Filip Tehlarb41b0af2023-03-20 12:39:20 +0100292 cmd += " " + c.getContainerArguments()
293
Adrian Villin4677d922024-06-14 09:32:39 +0200294 c.Suite.Log(cmd)
Filip Tehlarb41b0af2023-03-20 12:39:20 +0100295 return cmd, nil
296}
297
Adrian Villin4677d922024-06-14 09:32:39 +0200298func (c *Container) CombinedOutput() (string, error) {
Filip Tehlarb41b0af2023-03-20 12:39:20 +0100299 cmd, err := c.prepareCommand()
Maros Ondrejicka11a03e92022-12-01 09:56:37 +0100300 if err != nil {
Filip Tehlarb41b0af2023-03-20 12:39:20 +0100301 return "", err
Maros Ondrejicka11a03e92022-12-01 09:56:37 +0100302 }
303
Filip Tehlarb41b0af2023-03-20 12:39:20 +0100304 byteOutput, err := exechelper.CombinedOutput(cmd)
305 return string(byteOutput), err
306}
307
Adrian Villin25140012024-07-09 15:31:36 +0200308// Creates and starts a container
309func (c *Container) Run() {
310 c.Suite.AssertNil(c.Create())
311 c.Suite.AssertNil(c.Start())
Maros Ondrejicka11a03e92022-12-01 09:56:37 +0100312}
313
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100314func (c *Container) addVolume(hostDir string, containerDir string, isDefaultWorkDir bool) {
Maros Ondrejickadb823ed2022-12-14 16:30:04 +0100315 var volume Volume
Matus Fabiana647a832024-08-26 18:01:14 +0200316 volume.HostDir = strings.Replace(hostDir, "volumes", c.Suite.GetTestId()+"/"+"volumes", 1)
Adrian Villin4677d922024-06-14 09:32:39 +0200317 volume.ContainerDir = containerDir
318 volume.IsDefaultWorkDir = isDefaultWorkDir
319 c.Volumes[hostDir] = volume
Maros Ondrejicka0e79abb2022-12-06 19:46:24 +0100320}
321
Adrian Villin25140012024-07-09 15:31:36 +0200322func (c *Container) getVolumesAsSlice() []string {
323 var volumeSlice []string
324
325 if *VppSourceFileDir != "" {
326 volumeSlice = append(volumeSlice, fmt.Sprintf("%s:%s", *VppSourceFileDir, *VppSourceFileDir))
327 }
328
Adrian Villin4995d0d2024-07-29 17:54:58 +0200329 core_pattern, err := sysctl.Read("kernel.core_pattern")
330 if err == nil {
331 index := strings.LastIndex(core_pattern, "/")
332 core_pattern = core_pattern[:index]
333 volumeSlice = append(volumeSlice, c.Suite.getLogDirPath()+":"+core_pattern)
334 } else {
335 c.Suite.Log(err)
336 }
337
Adrian Villin25140012024-07-09 15:31:36 +0200338 if len(c.Volumes) > 0 {
339 for _, volume := range c.Volumes {
340 volumeSlice = append(volumeSlice, fmt.Sprintf("%s:%s", volume.HostDir, volume.ContainerDir))
341 }
342 }
Adrian Villin25140012024-07-09 15:31:36 +0200343 return volumeSlice
344}
345
Maros Ondrejickadb823ed2022-12-14 16:30:04 +0100346func (c *Container) getVolumesAsCliOption() string {
347 cliOption := ""
Maros Ondrejicka0e79abb2022-12-06 19:46:24 +0100348
Adrian Villin4677d922024-06-14 09:32:39 +0200349 if len(c.Volumes) > 0 {
350 for _, volume := range c.Volumes {
351 cliOption += fmt.Sprintf(" -v %s:%s", volume.HostDir, volume.ContainerDir)
Maros Ondrejicka0e79abb2022-12-06 19:46:24 +0100352 }
353 }
354
Maros Ondrejickadb823ed2022-12-14 16:30:04 +0100355 return cliOption
356}
357
Adrian Villin4677d922024-06-14 09:32:39 +0200358func (c *Container) AddEnvVar(name string, value string) {
359 c.EnvVars[name] = value
Maros Ondrejickadb823ed2022-12-14 16:30:04 +0100360}
361
362func (c *Container) getEnvVarsAsCliOption() string {
363 cliOption := ""
Adrian Villin4677d922024-06-14 09:32:39 +0200364 if len(c.EnvVars) == 0 {
Maros Ondrejickadb823ed2022-12-14 16:30:04 +0100365 return cliOption
366 }
367
Adrian Villin4677d922024-06-14 09:32:39 +0200368 for name, value := range c.EnvVars {
Maros Ondrejickadb823ed2022-12-14 16:30:04 +0100369 cliOption += fmt.Sprintf(" -e %s=%s", name, value)
370 }
371 return cliOption
372}
373
Adrian Villin25140012024-07-09 15:31:36 +0200374func (c *Container) getEnvVars() []string {
375 var envVars []string
376 if len(c.EnvVars) == 0 {
377 return envVars
378 }
379
380 for name, value := range c.EnvVars {
381 envVars = append(envVars, fmt.Sprintf("%s=%s", name, value))
382 }
383 return envVars
384}
385
Filip Tehlar608d0062023-04-28 10:29:47 +0200386func (c *Container) newVppInstance(cpus []int, additionalConfigs ...Stanza) (*VppInstance, error) {
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100387 vpp := new(VppInstance)
Adrian Villin4677d922024-06-14 09:32:39 +0200388 vpp.Container = c
389 vpp.Cpus = cpus
Hadi Rayan Al-Sandide0e85132024-06-24 10:28:58 +0200390 vpp.setDefaultCpuConfig()
Adrian Villin4677d922024-06-14 09:32:39 +0200391 vpp.AdditionalConfig = append(vpp.AdditionalConfig, additionalConfigs...)
392 c.VppInstance = vpp
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100393 return vpp, nil
394}
395
396func (c *Container) copy(sourceFileName string, targetFileName string) error {
Adrian Villin4677d922024-06-14 09:32:39 +0200397 cmd := exec.Command("docker", "cp", sourceFileName, c.Name+":"+targetFileName)
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100398 return cmd.Run()
399}
400
Adrian Villin4677d922024-06-14 09:32:39 +0200401func (c *Container) CreateFile(destFileName string, content string) error {
402 f, err := os.CreateTemp("/tmp", "hst-config"+c.Suite.Ppid)
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100403 if err != nil {
404 return err
405 }
406 defer os.Remove(f.Name())
407
408 if _, err := f.Write([]byte(content)); err != nil {
409 return err
410 }
411 if err := f.Close(); err != nil {
412 return err
413 }
414 c.copy(f.Name(), destFileName)
415 return nil
416}
417
Matus Fabiane99d2662024-07-19 16:04:09 +0200418func (c *Container) GetFile(sourceFileName, targetFileName string) error {
419 cmd := exec.Command("docker", "cp", c.Name+":"+sourceFileName, targetFileName)
420 return cmd.Run()
421}
422
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100423/*
424 * Executes in detached mode so that the started application can continue to run
425 * without blocking execution of test
426 */
Adrian Villin4677d922024-06-14 09:32:39 +0200427func (c *Container) ExecServer(command string, arguments ...any) {
Maros Ondrejicka2908f8c2023-02-02 08:58:04 +0100428 serverCommand := fmt.Sprintf(command, arguments...)
429 containerExecCommand := "docker exec -d" + c.getEnvVarsAsCliOption() +
Adrian Villin4677d922024-06-14 09:32:39 +0200430 " " + c.Name + " " + serverCommand
Adrian Villincee15aa2024-03-14 11:42:55 -0400431 GinkgoHelper()
Adrian Villin4677d922024-06-14 09:32:39 +0200432 c.Suite.Log(containerExecCommand)
433 c.Suite.AssertNil(exechelper.Run(containerExecCommand))
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100434}
435
Adrian Villin4677d922024-06-14 09:32:39 +0200436func (c *Container) Exec(command string, arguments ...any) string {
Maros Ondrejicka2908f8c2023-02-02 08:58:04 +0100437 cliCommand := fmt.Sprintf(command, arguments...)
438 containerExecCommand := "docker exec" + c.getEnvVarsAsCliOption() +
Adrian Villin4677d922024-06-14 09:32:39 +0200439 " " + c.Name + " " + cliCommand
Adrian Villincee15aa2024-03-14 11:42:55 -0400440 GinkgoHelper()
Adrian Villin4677d922024-06-14 09:32:39 +0200441 c.Suite.Log(containerExecCommand)
Maros Ondrejicka2908f8c2023-02-02 08:58:04 +0100442 byteOutput, err := exechelper.CombinedOutput(containerExecCommand)
Adrian Villin4677d922024-06-14 09:32:39 +0200443 c.Suite.AssertNil(err, fmt.Sprint(err))
Maros Ondrejicka2908f8c2023-02-02 08:58:04 +0100444 return string(byteOutput)
Maros Ondrejickadb823ed2022-12-14 16:30:04 +0100445}
446
Maros Ondrejickaa2d52622023-02-24 11:26:39 +0100447func (c *Container) saveLogs() {
Adrian Villin4995d0d2024-07-29 17:54:58 +0200448 testLogFilePath := c.Suite.getLogDirPath() + "container-" + c.Name + ".log"
Maros Ondrejickaa2d52622023-02-24 11:26:39 +0100449
Adrian Villin25140012024-07-09 15:31:36 +0200450 logs, err := c.log(0)
Maros Ondrejickaa2d52622023-02-24 11:26:39 +0100451 if err != nil {
Adrian Villin4677d922024-06-14 09:32:39 +0200452 c.Suite.Log(err)
Adrian Villin25140012024-07-09 15:31:36 +0200453 return
Maros Ondrejickaa2d52622023-02-24 11:26:39 +0100454 }
455
456 f, err := os.Create(testLogFilePath)
457 if err != nil {
Adrian Villin25140012024-07-09 15:31:36 +0200458 c.Suite.Log(err)
459 return
Maros Ondrejickaa2d52622023-02-24 11:26:39 +0100460 }
Adrian Villin25140012024-07-09 15:31:36 +0200461 defer f.Close()
462 fmt.Fprint(f, logs)
Maros Ondrejickaa2d52622023-02-24 11:26:39 +0100463}
464
Adrian Villin25140012024-07-09 15:31:36 +0200465// Returns logs from docker containers. Set 'maxLines' to 0 to output the full log.
adrianvillin7c675472024-02-12 02:44:53 -0500466func (c *Container) log(maxLines int) (string, error) {
Adrian Villin25140012024-07-09 15:31:36 +0200467 var logOptions containerTypes.LogsOptions
adrianvillin7c675472024-02-12 02:44:53 -0500468 if maxLines == 0 {
Matus Fabiand4643382024-07-29 13:30:23 +0200469 logOptions = containerTypes.LogsOptions{ShowStdout: true, ShowStderr: true, Details: true, Timestamps: true}
adrianvillin7c675472024-02-12 02:44:53 -0500470 } else {
Adrian Villin25140012024-07-09 15:31:36 +0200471 logOptions = containerTypes.LogsOptions{ShowStdout: true, ShowStderr: true, Details: true, Tail: strconv.Itoa(maxLines)}
adrianvillin7c675472024-02-12 02:44:53 -0500472 }
473
Adrian Villin25140012024-07-09 15:31:36 +0200474 out, err := c.Suite.Docker.ContainerLogs(c.ctx, c.ID, logOptions)
475 if err != nil {
476 c.Suite.Log(err)
477 return "", err
478 }
479 defer out.Close()
480
481 var stdoutBuf, stderrBuf bytes.Buffer
482
483 _, err = stdcopy.StdCopy(&stdoutBuf, &stderrBuf, out)
484 if err != nil {
485 c.Suite.Log(err)
486 }
487
488 stdout := stdoutBuf.String()
489 stderr := stderrBuf.String()
490
Matus Fabiand4643382024-07-29 13:30:23 +0200491 re := regexp.MustCompile("(?m)^.*==> /dev/null <==.*$[\r\n]+")
492 stdout = re.ReplaceAllString(stdout, "")
Adrian Villind9da4ee2024-07-24 17:46:53 +0200493
Matus Fabiand4643382024-07-29 13:30:23 +0200494 re = regexp.MustCompile("(?m)^.*tail: cannot open '' for reading: No such file or directory.*$[\r\n]+")
495 stderr = re.ReplaceAllString(stderr, "")
Adrian Villin09b19fe2024-07-18 08:33:59 +0200496
497 return stdout + stderr, err
Maros Ondrejickac2f76f42023-02-27 13:22:45 +0100498}
499
Maros Ondrejicka0e79abb2022-12-06 19:46:24 +0100500func (c *Container) stop() error {
Adrian Villin4677d922024-06-14 09:32:39 +0200501 if c.VppInstance != nil && c.VppInstance.ApiStream != nil {
502 c.VppInstance.saveLogs()
503 c.VppInstance.Disconnect()
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100504 }
Adrian Villin4677d922024-06-14 09:32:39 +0200505 c.VppInstance = nil
Maros Ondrejickaa2d52622023-02-24 11:26:39 +0100506 c.saveLogs()
Adrian Villin25140012024-07-09 15:31:36 +0200507
508 c.Suite.Log("Stopping container " + c.Name)
509 timeout := 0
510 if err := c.Suite.Docker.ContainerStop(c.ctx, c.ID, containerTypes.StopOptions{Timeout: &timeout}); err != nil {
511 return err
512 }
513 return nil
Maros Ondrejicka0e79abb2022-12-06 19:46:24 +0100514}
Maros Ondrejicka85396a52023-02-28 12:49:43 +0100515
Adrian Villin4677d922024-06-14 09:32:39 +0200516func (c *Container) CreateConfig(targetConfigName string, templateName string, values any) {
Maros Ondrejicka85396a52023-02-28 12:49:43 +0100517 template := template.Must(template.ParseFiles(templateName))
518
Filip Tehlara1bd50c2024-01-24 11:59:44 +0100519 f, err := os.CreateTemp(logDir, "hst-config")
Adrian Villin4677d922024-06-14 09:32:39 +0200520 c.Suite.AssertNil(err, err)
Maros Ondrejicka85396a52023-02-28 12:49:43 +0100521 defer os.Remove(f.Name())
522
523 err = template.Execute(f, values)
Adrian Villin4677d922024-06-14 09:32:39 +0200524 c.Suite.AssertNil(err, err)
Maros Ondrejicka85396a52023-02-28 12:49:43 +0100525
526 err = f.Close()
Adrian Villin4677d922024-06-14 09:32:39 +0200527 c.Suite.AssertNil(err, err)
Maros Ondrejicka85396a52023-02-28 12:49:43 +0100528
529 c.copy(f.Name(), targetConfigName)
530}
Maros Ondrejickaf4ddf162023-03-08 16:01:43 +0100531
532func init() {
533 cmd := exec.Command("mkdir", "-p", logDir)
534 if err := cmd.Run(); err != nil {
535 panic(err)
536 }
537}