blob: 5093398ae56c90248bc7586a1504df33911bc89d [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"
Maros Ondrejickadb823ed2022-12-14 16:30:04 +01007 "os"
Maros Ondrejickaffa3f602023-01-26 10:07:29 +01008 "os/exec"
Adrian Villin25140012024-07-09 15:31:36 +02009 "slices"
10 "strconv"
Maros Ondrejickadb823ed2022-12-14 16:30:04 +010011 "strings"
Maros Ondrejicka85396a52023-02-28 12:49:43 +010012 "text/template"
Filip Tehlar4fa0ba62023-12-06 11:35:11 +010013 "time"
Maros Ondrejicka11a03e92022-12-01 09:56:37 +010014
Adrian Villin25140012024-07-09 15:31:36 +020015 containerTypes "github.com/docker/docker/api/types/container"
16 "github.com/docker/docker/api/types/image"
17 "github.com/docker/docker/pkg/stdcopy"
18 "github.com/docker/go-units"
Maros Ondrejicka11a03e92022-12-01 09:56:37 +010019 "github.com/edwarnicke/exechelper"
Adrian Villincee15aa2024-03-14 11:42:55 -040020 . "github.com/onsi/ginkgo/v2"
Maros Ondrejicka11a03e92022-12-01 09:56:37 +010021)
22
Maros Ondrejickaa2d52622023-02-24 11:26:39 +010023const (
Filip Tehlara1bd50c2024-01-24 11:59:44 +010024 logDir string = "/tmp/hs-test/"
25 volumeDir string = "/volumes"
Maros Ondrejickaa2d52622023-02-24 11:26:39 +010026)
27
Maros Ondrejicka7550dd22023-02-07 20:40:27 +010028var (
29 workDir, _ = os.Getwd()
30)
31
Maros Ondrejicka0e79abb2022-12-06 19:46:24 +010032type Volume struct {
Adrian Villin4677d922024-06-14 09:32:39 +020033 HostDir string
34 ContainerDir string
35 IsDefaultWorkDir bool
Maros Ondrejicka0e79abb2022-12-06 19:46:24 +010036}
37
38type Container struct {
Adrian Villin4677d922024-06-14 09:32:39 +020039 Suite *HstSuite
40 IsOptional bool
41 RunDetached bool
42 Name string
Adrian Villin25140012024-07-09 15:31:36 +020043 ID string
Adrian Villin4677d922024-06-14 09:32:39 +020044 Image string
45 ExtraRunningArgs string
46 Volumes map[string]Volume
47 EnvVars map[string]string
48 VppInstance *VppInstance
49 AllocatedCpus []int
Adrian Villin25140012024-07-09 15:31:36 +020050 ctx context.Context
Maros Ondrejickadb823ed2022-12-14 16:30:04 +010051}
52
Adrian Villincee15aa2024-03-14 11:42:55 -040053func newContainer(suite *HstSuite, yamlInput ContainerConfig) (*Container, error) {
Maros Ondrejickadb823ed2022-12-14 16:30:04 +010054 containerName := yamlInput["name"].(string)
55 if len(containerName) == 0 {
56 err := fmt.Errorf("container name must not be blank")
57 return nil, err
58 }
59
60 var container = new(Container)
Adrian Villin4677d922024-06-14 09:32:39 +020061 container.Volumes = make(map[string]Volume)
62 container.EnvVars = make(map[string]string)
63 container.Name = containerName
64 container.Suite = suite
Adrian Villin25140012024-07-09 15:31:36 +020065 container.ctx = context.Background()
Maros Ondrejickadb823ed2022-12-14 16:30:04 +010066
Adrian Villin4677d922024-06-14 09:32:39 +020067 if Image, ok := yamlInput["image"]; ok {
68 container.Image = Image.(string)
Maros Ondrejickadb823ed2022-12-14 16:30:04 +010069 } else {
Adrian Villin4677d922024-06-14 09:32:39 +020070 container.Image = "hs-test/vpp"
Maros Ondrejickadb823ed2022-12-14 16:30:04 +010071 }
72
Filip Tehlar3f951432023-01-13 21:33:43 +010073 if args, ok := yamlInput["extra-args"]; ok {
Adrian Villin4677d922024-06-14 09:32:39 +020074 container.ExtraRunningArgs = args.(string)
Filip Tehlar3f951432023-01-13 21:33:43 +010075 } else {
Adrian Villin4677d922024-06-14 09:32:39 +020076 container.ExtraRunningArgs = ""
Filip Tehlar3f951432023-01-13 21:33:43 +010077 }
78
Maros Ondrejickadb823ed2022-12-14 16:30:04 +010079 if isOptional, ok := yamlInput["is-optional"]; ok {
Adrian Villin4677d922024-06-14 09:32:39 +020080 container.IsOptional = isOptional.(bool)
Maros Ondrejickadb823ed2022-12-14 16:30:04 +010081 } else {
Adrian Villin4677d922024-06-14 09:32:39 +020082 container.IsOptional = false
Maros Ondrejickadb823ed2022-12-14 16:30:04 +010083 }
84
Filip Tehlarb41b0af2023-03-20 12:39:20 +010085 if runDetached, ok := yamlInput["run-detached"]; ok {
Adrian Villin4677d922024-06-14 09:32:39 +020086 container.RunDetached = runDetached.(bool)
Filip Tehlarb41b0af2023-03-20 12:39:20 +010087 } else {
Adrian Villin4677d922024-06-14 09:32:39 +020088 container.RunDetached = true
Filip Tehlarb41b0af2023-03-20 12:39:20 +010089 }
90
Maros Ondrejickadb823ed2022-12-14 16:30:04 +010091 if _, ok := yamlInput["volumes"]; ok {
Adrian Villin4677d922024-06-14 09:32:39 +020092 workingVolumeDir := logDir + suite.GetCurrentTestName() + volumeDir
Filip Tehlara1bd50c2024-01-24 11:59:44 +010093 workDirReplacer := strings.NewReplacer("$HST_DIR", workDir)
94 volDirReplacer := strings.NewReplacer("$HST_VOLUME_DIR", workingVolumeDir)
Maros Ondrejickadb823ed2022-12-14 16:30:04 +010095 for _, volu := range yamlInput["volumes"].([]interface{}) {
96 volumeMap := volu.(ContainerConfig)
Filip Tehlara1bd50c2024-01-24 11:59:44 +010097 hostDir := workDirReplacer.Replace(volumeMap["host-dir"].(string))
98 hostDir = volDirReplacer.Replace(hostDir)
Maros Ondrejickadb823ed2022-12-14 16:30:04 +010099 containerDir := volumeMap["container-dir"].(string)
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100100 isDefaultWorkDir := false
Maros Ondrejickadb823ed2022-12-14 16:30:04 +0100101
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100102 if isDefault, ok := volumeMap["is-default-work-dir"]; ok {
103 isDefaultWorkDir = isDefault.(bool)
Maros Ondrejickadb823ed2022-12-14 16:30:04 +0100104 }
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100105 container.addVolume(hostDir, containerDir, isDefaultWorkDir)
Maros Ondrejickadb823ed2022-12-14 16:30:04 +0100106 }
107 }
108
109 if _, ok := yamlInput["vars"]; ok {
110 for _, envVar := range yamlInput["vars"].([]interface{}) {
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100111 envVarMap := envVar.(ContainerConfig)
112 name := envVarMap["name"].(string)
113 value := envVarMap["value"].(string)
Adrian Villin4677d922024-06-14 09:32:39 +0200114 container.AddEnvVar(name, value)
Maros Ondrejickadb823ed2022-12-14 16:30:04 +0100115 }
116 }
117 return container, nil
Maros Ondrejicka11a03e92022-12-01 09:56:37 +0100118}
119
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100120func (c *Container) getWorkDirVolume() (res Volume, exists bool) {
Adrian Villin4677d922024-06-14 09:32:39 +0200121 for _, v := range c.Volumes {
122 if v.IsDefaultWorkDir {
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100123 res = v
124 exists = true
125 return
126 }
127 }
128 return
129}
130
Adrian Villin4677d922024-06-14 09:32:39 +0200131func (c *Container) GetHostWorkDir() (res string) {
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100132 if v, ok := c.getWorkDirVolume(); ok {
Adrian Villin4677d922024-06-14 09:32:39 +0200133 res = v.HostDir
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100134 }
135 return
136}
137
Adrian Villin4677d922024-06-14 09:32:39 +0200138func (c *Container) GetContainerWorkDir() (res string) {
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100139 if v, ok := c.getWorkDirVolume(); ok {
Adrian Villin4677d922024-06-14 09:32:39 +0200140 res = v.ContainerDir
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100141 }
142 return
143}
144
Maros Ondrejickac2f76f42023-02-27 13:22:45 +0100145func (c *Container) getContainerArguments() string {
Adrian Villineaa7d912024-06-06 04:26:30 -0400146 args := "--ulimit nofile=90000:90000 --cap-add=all --privileged --network host"
Maros Ondrejickac2f76f42023-02-27 13:22:45 +0100147 args += c.getVolumesAsCliOption()
148 args += c.getEnvVarsAsCliOption()
Adrian Villin4677d922024-06-14 09:32:39 +0200149 if *VppSourceFileDir != "" {
150 args += fmt.Sprintf(" -v %s:%s", *VppSourceFileDir, *VppSourceFileDir)
Filip Tehlar109f3ce2023-09-05 15:36:28 +0200151 }
Adrian Villin4677d922024-06-14 09:32:39 +0200152 args += " --name " + c.Name + " " + c.Image
153 args += " " + c.ExtraRunningArgs
Maros Ondrejickac2f76f42023-02-27 13:22:45 +0100154 return args
155}
156
Adrian Villin25140012024-07-09 15:31:36 +0200157func (c *Container) PullDockerImage(name string, ctx context.Context) {
158 // "func (*Client) ImagePull" doesn't work, returns "No such image"
159 c.Suite.Log("Pulling image: " + name)
160 _, err := exechelper.CombinedOutput("docker pull " + name)
161 c.Suite.AssertNil(err)
Filip Tehlar4fa0ba62023-12-06 11:35:11 +0100162}
163
Adrian Villin25140012024-07-09 15:31:36 +0200164// Creates a container
Adrian Villin4677d922024-06-14 09:32:39 +0200165func (c *Container) Create() error {
Adrian Villin25140012024-07-09 15:31:36 +0200166 var sliceOfImageNames []string
167 images, err := c.Suite.Docker.ImageList(c.ctx, image.ListOptions{})
168 c.Suite.AssertNil(err)
169
170 for _, image := range images {
171 sliceOfImageNames = append(sliceOfImageNames, strings.Split(image.RepoTags[0], ":")[0])
172 }
173 if !slices.Contains(sliceOfImageNames, c.Image) {
174 c.PullDockerImage(c.Image, c.ctx)
175 }
176
177 c.allocateCpus()
178 cpuSet := fmt.Sprintf("%d-%d", c.AllocatedCpus[0], c.AllocatedCpus[len(c.AllocatedCpus)-1])
179 resp, err := c.Suite.Docker.ContainerCreate(
180 c.ctx,
181 &containerTypes.Config{
182 Image: c.Image,
183 Env: c.getEnvVars(),
184 Cmd: strings.Split(c.ExtraRunningArgs, " "),
185 },
186 &containerTypes.HostConfig{
187 Resources: containerTypes.Resources{
188 Ulimits: []*units.Ulimit{
189 {
190 Name: "nofile",
191 Soft: 90000,
192 Hard: 90000,
193 },
194 },
195 CpusetCpus: cpuSet,
196 },
197 CapAdd: []string{"ALL"},
198 Privileged: true,
199 NetworkMode: "host",
200 Binds: c.getVolumesAsSlice(),
201 },
202 nil,
203 nil,
204 c.Name,
205 )
206 c.ID = resp.ID
207 return err
Maros Ondrejickac2f76f42023-02-27 13:22:45 +0100208}
209
Adrian Villinb9464cd2024-05-27 09:52:59 -0400210func (c *Container) allocateCpus() {
Adrian Villin4677d922024-06-14 09:32:39 +0200211 c.Suite.StartedContainers = append(c.Suite.StartedContainers, c)
212 c.AllocatedCpus = c.Suite.AllocateCpus()
213 c.Suite.Log("Allocated CPUs " + fmt.Sprint(c.AllocatedCpus) + " to container " + c.Name)
Adrian Villinb9464cd2024-05-27 09:52:59 -0400214}
215
Adrian Villin25140012024-07-09 15:31:36 +0200216// Starts a container
Adrian Villin4677d922024-06-14 09:32:39 +0200217func (c *Container) Start() error {
Adrian Villin25140012024-07-09 15:31:36 +0200218 var err error
219 for nTries := 0; nTries < 5; nTries++ {
220 err = c.Suite.Docker.ContainerStart(c.ctx, c.ID, containerTypes.StartOptions{})
221 if err == nil {
222 continue
223 }
224 c.Suite.Log("Error while starting " + c.Name + ". Retrying...")
225 time.Sleep(1 * time.Second)
226 }
227
228 return err
229}
230
231func (c *Container) GetOutput() (string, string) {
232 // Wait for the container to finish executing
233 statusCh, errCh := c.Suite.Docker.ContainerWait(c.ctx, c.ID, containerTypes.WaitConditionNotRunning)
234 select {
235 case err := <-errCh:
236 c.Suite.AssertNil(err)
237 case <-statusCh:
238 }
239
240 // Get the logs from the container
241 logOptions := containerTypes.LogsOptions{ShowStdout: true, ShowStderr: true}
242 logReader, err := c.Suite.Docker.ContainerLogs(c.ctx, c.ID, logOptions)
243 c.Suite.AssertNil(err)
244 defer logReader.Close()
245
246 var stdoutBuf, stderrBuf bytes.Buffer
247
248 // Use stdcopy.StdCopy to demultiplex the multiplexed stream
249 _, err = stdcopy.StdCopy(&stdoutBuf, &stderrBuf, logReader)
250 c.Suite.AssertNil(err)
251
252 stdout := stdoutBuf.String()
253 stderr := stderrBuf.String()
254 return stdout, stderr
Maros Ondrejicka87531802022-12-19 20:35:27 +0100255}
256
Filip Tehlarb41b0af2023-03-20 12:39:20 +0100257func (c *Container) prepareCommand() (string, error) {
Adrian Villin4677d922024-06-14 09:32:39 +0200258 if c.Name == "" {
Filip Tehlarb41b0af2023-03-20 12:39:20 +0100259 return "", fmt.Errorf("run container failed: name is blank")
Maros Ondrejicka87531802022-12-19 20:35:27 +0100260 }
261
Adrian Villin25140012024-07-09 15:31:36 +0200262 cmd := "docker exec "
Adrian Villin4677d922024-06-14 09:32:39 +0200263 if c.RunDetached {
Adrian Villineaa7d912024-06-06 04:26:30 -0400264 cmd += " -d"
Filip Tehlarb41b0af2023-03-20 12:39:20 +0100265 }
Adrian Villinb9464cd2024-05-27 09:52:59 -0400266
Filip Tehlarb41b0af2023-03-20 12:39:20 +0100267 cmd += " " + c.getContainerArguments()
268
Adrian Villin4677d922024-06-14 09:32:39 +0200269 c.Suite.Log(cmd)
Filip Tehlarb41b0af2023-03-20 12:39:20 +0100270 return cmd, nil
271}
272
Adrian Villin4677d922024-06-14 09:32:39 +0200273func (c *Container) CombinedOutput() (string, error) {
Filip Tehlarb41b0af2023-03-20 12:39:20 +0100274 cmd, err := c.prepareCommand()
Maros Ondrejicka11a03e92022-12-01 09:56:37 +0100275 if err != nil {
Filip Tehlarb41b0af2023-03-20 12:39:20 +0100276 return "", err
Maros Ondrejicka11a03e92022-12-01 09:56:37 +0100277 }
278
Filip Tehlarb41b0af2023-03-20 12:39:20 +0100279 byteOutput, err := exechelper.CombinedOutput(cmd)
280 return string(byteOutput), err
281}
282
Adrian Villin25140012024-07-09 15:31:36 +0200283// Creates and starts a container
284func (c *Container) Run() {
285 c.Suite.AssertNil(c.Create())
286 c.Suite.AssertNil(c.Start())
Maros Ondrejicka11a03e92022-12-01 09:56:37 +0100287}
288
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100289func (c *Container) addVolume(hostDir string, containerDir string, isDefaultWorkDir bool) {
Maros Ondrejickadb823ed2022-12-14 16:30:04 +0100290 var volume Volume
Adrian Villin4677d922024-06-14 09:32:39 +0200291 volume.HostDir = hostDir
292 volume.ContainerDir = containerDir
293 volume.IsDefaultWorkDir = isDefaultWorkDir
294 c.Volumes[hostDir] = volume
Maros Ondrejicka0e79abb2022-12-06 19:46:24 +0100295}
296
Adrian Villin25140012024-07-09 15:31:36 +0200297func (c *Container) getVolumesAsSlice() []string {
298 var volumeSlice []string
299
300 if *VppSourceFileDir != "" {
301 volumeSlice = append(volumeSlice, fmt.Sprintf("%s:%s", *VppSourceFileDir, *VppSourceFileDir))
302 }
303
304 if len(c.Volumes) > 0 {
305 for _, volume := range c.Volumes {
306 volumeSlice = append(volumeSlice, fmt.Sprintf("%s:%s", volume.HostDir, volume.ContainerDir))
307 }
308 }
309
310 return volumeSlice
311}
312
Maros Ondrejickadb823ed2022-12-14 16:30:04 +0100313func (c *Container) getVolumesAsCliOption() string {
314 cliOption := ""
Maros Ondrejicka0e79abb2022-12-06 19:46:24 +0100315
Adrian Villin4677d922024-06-14 09:32:39 +0200316 if len(c.Volumes) > 0 {
317 for _, volume := range c.Volumes {
318 cliOption += fmt.Sprintf(" -v %s:%s", volume.HostDir, volume.ContainerDir)
Maros Ondrejicka0e79abb2022-12-06 19:46:24 +0100319 }
320 }
321
Maros Ondrejickadb823ed2022-12-14 16:30:04 +0100322 return cliOption
323}
324
Adrian Villin4677d922024-06-14 09:32:39 +0200325func (c *Container) AddEnvVar(name string, value string) {
326 c.EnvVars[name] = value
Maros Ondrejickadb823ed2022-12-14 16:30:04 +0100327}
328
329func (c *Container) getEnvVarsAsCliOption() string {
330 cliOption := ""
Adrian Villin4677d922024-06-14 09:32:39 +0200331 if len(c.EnvVars) == 0 {
Maros Ondrejickadb823ed2022-12-14 16:30:04 +0100332 return cliOption
333 }
334
Adrian Villin4677d922024-06-14 09:32:39 +0200335 for name, value := range c.EnvVars {
Maros Ondrejickadb823ed2022-12-14 16:30:04 +0100336 cliOption += fmt.Sprintf(" -e %s=%s", name, value)
337 }
338 return cliOption
339}
340
Adrian Villin25140012024-07-09 15:31:36 +0200341func (c *Container) getEnvVars() []string {
342 var envVars []string
343 if len(c.EnvVars) == 0 {
344 return envVars
345 }
346
347 for name, value := range c.EnvVars {
348 envVars = append(envVars, fmt.Sprintf("%s=%s", name, value))
349 }
350 return envVars
351}
352
Filip Tehlar608d0062023-04-28 10:29:47 +0200353func (c *Container) newVppInstance(cpus []int, additionalConfigs ...Stanza) (*VppInstance, error) {
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100354 vpp := new(VppInstance)
Adrian Villin4677d922024-06-14 09:32:39 +0200355 vpp.Container = c
356 vpp.Cpus = cpus
Hadi Rayan Al-Sandide0e85132024-06-24 10:28:58 +0200357 vpp.setDefaultCpuConfig()
Adrian Villin4677d922024-06-14 09:32:39 +0200358 vpp.AdditionalConfig = append(vpp.AdditionalConfig, additionalConfigs...)
359 c.VppInstance = vpp
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100360 return vpp, nil
361}
362
363func (c *Container) copy(sourceFileName string, targetFileName string) error {
Adrian Villin4677d922024-06-14 09:32:39 +0200364 cmd := exec.Command("docker", "cp", sourceFileName, c.Name+":"+targetFileName)
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100365 return cmd.Run()
366}
367
Adrian Villin4677d922024-06-14 09:32:39 +0200368func (c *Container) CreateFile(destFileName string, content string) error {
369 f, err := os.CreateTemp("/tmp", "hst-config"+c.Suite.Ppid)
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100370 if err != nil {
371 return err
372 }
373 defer os.Remove(f.Name())
374
375 if _, err := f.Write([]byte(content)); err != nil {
376 return err
377 }
378 if err := f.Close(); err != nil {
379 return err
380 }
381 c.copy(f.Name(), destFileName)
382 return nil
383}
384
385/*
386 * Executes in detached mode so that the started application can continue to run
387 * without blocking execution of test
388 */
Adrian Villin4677d922024-06-14 09:32:39 +0200389func (c *Container) ExecServer(command string, arguments ...any) {
Maros Ondrejicka2908f8c2023-02-02 08:58:04 +0100390 serverCommand := fmt.Sprintf(command, arguments...)
391 containerExecCommand := "docker exec -d" + c.getEnvVarsAsCliOption() +
Adrian Villin4677d922024-06-14 09:32:39 +0200392 " " + c.Name + " " + serverCommand
Adrian Villincee15aa2024-03-14 11:42:55 -0400393 GinkgoHelper()
Adrian Villin4677d922024-06-14 09:32:39 +0200394 c.Suite.Log(containerExecCommand)
395 c.Suite.AssertNil(exechelper.Run(containerExecCommand))
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100396}
397
Adrian Villin4677d922024-06-14 09:32:39 +0200398func (c *Container) Exec(command string, arguments ...any) string {
Maros Ondrejicka2908f8c2023-02-02 08:58:04 +0100399 cliCommand := fmt.Sprintf(command, arguments...)
400 containerExecCommand := "docker exec" + c.getEnvVarsAsCliOption() +
Adrian Villin4677d922024-06-14 09:32:39 +0200401 " " + c.Name + " " + cliCommand
Adrian Villincee15aa2024-03-14 11:42:55 -0400402 GinkgoHelper()
Adrian Villin4677d922024-06-14 09:32:39 +0200403 c.Suite.Log(containerExecCommand)
Maros Ondrejicka2908f8c2023-02-02 08:58:04 +0100404 byteOutput, err := exechelper.CombinedOutput(containerExecCommand)
Adrian Villin4677d922024-06-14 09:32:39 +0200405 c.Suite.AssertNil(err, fmt.Sprint(err))
Maros Ondrejicka2908f8c2023-02-02 08:58:04 +0100406 return string(byteOutput)
Maros Ondrejickadb823ed2022-12-14 16:30:04 +0100407}
408
Maros Ondrejickaa2d52622023-02-24 11:26:39 +0100409func (c *Container) getLogDirPath() string {
Adrian Villin4677d922024-06-14 09:32:39 +0200410 testId := c.Suite.GetTestId()
411 testName := c.Suite.GetCurrentTestName()
Maros Ondrejickaa2d52622023-02-24 11:26:39 +0100412 logDirPath := logDir + testName + "/" + testId + "/"
413
414 cmd := exec.Command("mkdir", "-p", logDirPath)
415 if err := cmd.Run(); err != nil {
Adrian Villincee15aa2024-03-14 11:42:55 -0400416 Fail("mkdir error: " + fmt.Sprint(err))
Maros Ondrejickaa2d52622023-02-24 11:26:39 +0100417 }
418
419 return logDirPath
420}
421
422func (c *Container) saveLogs() {
Adrian Villin4677d922024-06-14 09:32:39 +0200423 testLogFilePath := c.getLogDirPath() + "container-" + c.Name + ".log"
Maros Ondrejickaa2d52622023-02-24 11:26:39 +0100424
Adrian Villin25140012024-07-09 15:31:36 +0200425 logs, err := c.log(0)
Maros Ondrejickaa2d52622023-02-24 11:26:39 +0100426 if err != nil {
Adrian Villin4677d922024-06-14 09:32:39 +0200427 c.Suite.Log(err)
Adrian Villin25140012024-07-09 15:31:36 +0200428 return
Maros Ondrejickaa2d52622023-02-24 11:26:39 +0100429 }
430
431 f, err := os.Create(testLogFilePath)
432 if err != nil {
Adrian Villin25140012024-07-09 15:31:36 +0200433 c.Suite.Log(err)
434 return
Maros Ondrejickaa2d52622023-02-24 11:26:39 +0100435 }
Adrian Villin25140012024-07-09 15:31:36 +0200436 defer f.Close()
437 fmt.Fprint(f, logs)
Maros Ondrejickaa2d52622023-02-24 11:26:39 +0100438}
439
Adrian Villin25140012024-07-09 15:31:36 +0200440// Returns logs from docker containers. Set 'maxLines' to 0 to output the full log.
adrianvillin7c675472024-02-12 02:44:53 -0500441func (c *Container) log(maxLines int) (string, error) {
Adrian Villin25140012024-07-09 15:31:36 +0200442 var logOptions containerTypes.LogsOptions
adrianvillin7c675472024-02-12 02:44:53 -0500443 if maxLines == 0 {
Adrian Villin25140012024-07-09 15:31:36 +0200444 logOptions = containerTypes.LogsOptions{ShowStdout: true, ShowStderr: true, Details: true}
adrianvillin7c675472024-02-12 02:44:53 -0500445 } else {
Adrian Villin25140012024-07-09 15:31:36 +0200446 logOptions = containerTypes.LogsOptions{ShowStdout: true, ShowStderr: true, Details: true, Tail: strconv.Itoa(maxLines)}
adrianvillin7c675472024-02-12 02:44:53 -0500447 }
448
Adrian Villin25140012024-07-09 15:31:36 +0200449 out, err := c.Suite.Docker.ContainerLogs(c.ctx, c.ID, logOptions)
450 if err != nil {
451 c.Suite.Log(err)
452 return "", err
453 }
454 defer out.Close()
455
456 var stdoutBuf, stderrBuf bytes.Buffer
457
458 _, err = stdcopy.StdCopy(&stdoutBuf, &stderrBuf, out)
459 if err != nil {
460 c.Suite.Log(err)
461 }
462
463 stdout := stdoutBuf.String()
464 stderr := stderrBuf.String()
465
Adrian Villin09b19fe2024-07-18 08:33:59 +0200466 if strings.Contains(stdout, "==> /dev/null <==") {
467 stdout = ""
468 }
469 if strings.Contains(stderr, "tail: cannot open") {
470 stderr = ""
471 }
472
473 return stdout + stderr, err
Maros Ondrejickac2f76f42023-02-27 13:22:45 +0100474}
475
Maros Ondrejicka0e79abb2022-12-06 19:46:24 +0100476func (c *Container) stop() error {
Adrian Villin4677d922024-06-14 09:32:39 +0200477 if c.VppInstance != nil && c.VppInstance.ApiStream != nil {
478 c.VppInstance.saveLogs()
479 c.VppInstance.Disconnect()
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100480 }
Adrian Villin4677d922024-06-14 09:32:39 +0200481 c.VppInstance = nil
Maros Ondrejickaa2d52622023-02-24 11:26:39 +0100482 c.saveLogs()
Adrian Villin25140012024-07-09 15:31:36 +0200483
484 c.Suite.Log("Stopping container " + c.Name)
485 timeout := 0
486 if err := c.Suite.Docker.ContainerStop(c.ctx, c.ID, containerTypes.StopOptions{Timeout: &timeout}); err != nil {
487 return err
488 }
489 return nil
Maros Ondrejicka0e79abb2022-12-06 19:46:24 +0100490}
Maros Ondrejicka85396a52023-02-28 12:49:43 +0100491
Adrian Villin4677d922024-06-14 09:32:39 +0200492func (c *Container) CreateConfig(targetConfigName string, templateName string, values any) {
Maros Ondrejicka85396a52023-02-28 12:49:43 +0100493 template := template.Must(template.ParseFiles(templateName))
494
Filip Tehlara1bd50c2024-01-24 11:59:44 +0100495 f, err := os.CreateTemp(logDir, "hst-config")
Adrian Villin4677d922024-06-14 09:32:39 +0200496 c.Suite.AssertNil(err, err)
Maros Ondrejicka85396a52023-02-28 12:49:43 +0100497 defer os.Remove(f.Name())
498
499 err = template.Execute(f, values)
Adrian Villin4677d922024-06-14 09:32:39 +0200500 c.Suite.AssertNil(err, err)
Maros Ondrejicka85396a52023-02-28 12:49:43 +0100501
502 err = f.Close()
Adrian Villin4677d922024-06-14 09:32:39 +0200503 c.Suite.AssertNil(err, err)
Maros Ondrejicka85396a52023-02-28 12:49:43 +0100504
505 c.copy(f.Name(), targetConfigName)
506}
Maros Ondrejickaf4ddf162023-03-08 16:01:43 +0100507
508func init() {
509 cmd := exec.Command("mkdir", "-p", logDir)
510 if err := cmd.Run(); err != nil {
511 panic(err)
512 }
513}