blob: d8bddab211e7f5006c8d3dcaa2ceb8b738ddc3ad [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 Villin25140012024-07-09 15:31:36 +020017 containerTypes "github.com/docker/docker/api/types/container"
Adrian Villin007be4f2024-07-23 12:14:19 +020018 "github.com/docker/docker/api/types/filters"
Adrian Villin25140012024-07-09 15:31:36 +020019 "github.com/docker/docker/api/types/image"
20 "github.com/docker/docker/pkg/stdcopy"
Maros Ondrejicka11a03e92022-12-01 09:56:37 +010021 "github.com/edwarnicke/exechelper"
Adrian Villincee15aa2024-03-14 11:42:55 -040022 . "github.com/onsi/ginkgo/v2"
Maros Ondrejicka11a03e92022-12-01 09:56:37 +010023)
24
Maros Ondrejickaa2d52622023-02-24 11:26:39 +010025const (
Filip Tehlara1bd50c2024-01-24 11:59:44 +010026 logDir string = "/tmp/hs-test/"
27 volumeDir string = "/volumes"
Maros Ondrejickaa2d52622023-02-24 11:26:39 +010028)
29
Maros Ondrejicka7550dd22023-02-07 20:40:27 +010030var (
31 workDir, _ = os.Getwd()
32)
33
Maros Ondrejicka0e79abb2022-12-06 19:46:24 +010034type Volume struct {
Adrian Villin4677d922024-06-14 09:32:39 +020035 HostDir string
36 ContainerDir string
37 IsDefaultWorkDir bool
Maros Ondrejicka0e79abb2022-12-06 19:46:24 +010038}
39
40type Container struct {
Adrian Villin4677d922024-06-14 09:32:39 +020041 Suite *HstSuite
42 IsOptional bool
43 RunDetached bool
44 Name string
Adrian Villin25140012024-07-09 15:31:36 +020045 ID string
Adrian Villin4677d922024-06-14 09:32:39 +020046 Image string
47 ExtraRunningArgs string
48 Volumes map[string]Volume
49 EnvVars map[string]string
50 VppInstance *VppInstance
51 AllocatedCpus []int
Adrian Villin25140012024-07-09 15:31:36 +020052 ctx context.Context
Maros Ondrejickadb823ed2022-12-14 16:30:04 +010053}
54
Adrian Villincee15aa2024-03-14 11:42:55 -040055func newContainer(suite *HstSuite, yamlInput ContainerConfig) (*Container, error) {
Maros Ondrejickadb823ed2022-12-14 16:30:04 +010056 containerName := yamlInput["name"].(string)
57 if len(containerName) == 0 {
58 err := fmt.Errorf("container name must not be blank")
59 return nil, err
60 }
61
62 var container = new(Container)
Adrian Villin4677d922024-06-14 09:32:39 +020063 container.Volumes = make(map[string]Volume)
64 container.EnvVars = make(map[string]string)
65 container.Name = containerName
66 container.Suite = suite
Adrian Villin25140012024-07-09 15:31:36 +020067 container.ctx = context.Background()
Maros Ondrejickadb823ed2022-12-14 16:30:04 +010068
Adrian Villin4677d922024-06-14 09:32:39 +020069 if Image, ok := yamlInput["image"]; ok {
70 container.Image = Image.(string)
Maros Ondrejickadb823ed2022-12-14 16:30:04 +010071 } else {
Adrian Villin4677d922024-06-14 09:32:39 +020072 container.Image = "hs-test/vpp"
Maros Ondrejickadb823ed2022-12-14 16:30:04 +010073 }
74
Filip Tehlar3f951432023-01-13 21:33:43 +010075 if args, ok := yamlInput["extra-args"]; ok {
Adrian Villin4677d922024-06-14 09:32:39 +020076 container.ExtraRunningArgs = args.(string)
Filip Tehlar3f951432023-01-13 21:33:43 +010077 } else {
Adrian Villin4677d922024-06-14 09:32:39 +020078 container.ExtraRunningArgs = ""
Filip Tehlar3f951432023-01-13 21:33:43 +010079 }
80
Maros Ondrejickadb823ed2022-12-14 16:30:04 +010081 if isOptional, ok := yamlInput["is-optional"]; ok {
Adrian Villin4677d922024-06-14 09:32:39 +020082 container.IsOptional = isOptional.(bool)
Maros Ondrejickadb823ed2022-12-14 16:30:04 +010083 } else {
Adrian Villin4677d922024-06-14 09:32:39 +020084 container.IsOptional = false
Maros Ondrejickadb823ed2022-12-14 16:30:04 +010085 }
86
Filip Tehlarb41b0af2023-03-20 12:39:20 +010087 if runDetached, ok := yamlInput["run-detached"]; ok {
Adrian Villin4677d922024-06-14 09:32:39 +020088 container.RunDetached = runDetached.(bool)
Filip Tehlarb41b0af2023-03-20 12:39:20 +010089 } else {
Adrian Villin4677d922024-06-14 09:32:39 +020090 container.RunDetached = true
Filip Tehlarb41b0af2023-03-20 12:39:20 +010091 }
92
Maros Ondrejickadb823ed2022-12-14 16:30:04 +010093 if _, ok := yamlInput["volumes"]; ok {
Adrian Villin4677d922024-06-14 09:32:39 +020094 workingVolumeDir := logDir + suite.GetCurrentTestName() + volumeDir
Filip Tehlara1bd50c2024-01-24 11:59:44 +010095 workDirReplacer := strings.NewReplacer("$HST_DIR", workDir)
96 volDirReplacer := strings.NewReplacer("$HST_VOLUME_DIR", workingVolumeDir)
Maros Ondrejickadb823ed2022-12-14 16:30:04 +010097 for _, volu := range yamlInput["volumes"].([]interface{}) {
98 volumeMap := volu.(ContainerConfig)
Filip Tehlara1bd50c2024-01-24 11:59:44 +010099 hostDir := workDirReplacer.Replace(volumeMap["host-dir"].(string))
100 hostDir = volDirReplacer.Replace(hostDir)
Maros Ondrejickadb823ed2022-12-14 16:30:04 +0100101 containerDir := volumeMap["container-dir"].(string)
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100102 isDefaultWorkDir := false
Maros Ondrejickadb823ed2022-12-14 16:30:04 +0100103
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100104 if isDefault, ok := volumeMap["is-default-work-dir"]; ok {
105 isDefaultWorkDir = isDefault.(bool)
Maros Ondrejickadb823ed2022-12-14 16:30:04 +0100106 }
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100107 container.addVolume(hostDir, containerDir, isDefaultWorkDir)
Maros Ondrejickadb823ed2022-12-14 16:30:04 +0100108 }
109 }
110
111 if _, ok := yamlInput["vars"]; ok {
112 for _, envVar := range yamlInput["vars"].([]interface{}) {
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100113 envVarMap := envVar.(ContainerConfig)
114 name := envVarMap["name"].(string)
115 value := envVarMap["value"].(string)
Adrian Villin4677d922024-06-14 09:32:39 +0200116 container.AddEnvVar(name, value)
Maros Ondrejickadb823ed2022-12-14 16:30:04 +0100117 }
118 }
119 return container, nil
Maros Ondrejicka11a03e92022-12-01 09:56:37 +0100120}
121
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100122func (c *Container) getWorkDirVolume() (res Volume, exists bool) {
Adrian Villin4677d922024-06-14 09:32:39 +0200123 for _, v := range c.Volumes {
124 if v.IsDefaultWorkDir {
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100125 res = v
126 exists = true
127 return
128 }
129 }
130 return
131}
132
Adrian Villin4677d922024-06-14 09:32:39 +0200133func (c *Container) GetHostWorkDir() (res string) {
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100134 if v, ok := c.getWorkDirVolume(); ok {
Adrian Villin4677d922024-06-14 09:32:39 +0200135 res = v.HostDir
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100136 }
137 return
138}
139
Adrian Villin4677d922024-06-14 09:32:39 +0200140func (c *Container) GetContainerWorkDir() (res string) {
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100141 if v, ok := c.getWorkDirVolume(); ok {
Adrian Villin4677d922024-06-14 09:32:39 +0200142 res = v.ContainerDir
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100143 }
144 return
145}
146
Maros Ondrejickac2f76f42023-02-27 13:22:45 +0100147func (c *Container) getContainerArguments() string {
Adrian Villineaa7d912024-06-06 04:26:30 -0400148 args := "--ulimit nofile=90000:90000 --cap-add=all --privileged --network host"
Maros Ondrejickac2f76f42023-02-27 13:22:45 +0100149 args += c.getVolumesAsCliOption()
150 args += c.getEnvVarsAsCliOption()
Adrian Villin4677d922024-06-14 09:32:39 +0200151 if *VppSourceFileDir != "" {
152 args += fmt.Sprintf(" -v %s:%s", *VppSourceFileDir, *VppSourceFileDir)
Filip Tehlar109f3ce2023-09-05 15:36:28 +0200153 }
Adrian Villin4677d922024-06-14 09:32:39 +0200154 args += " --name " + c.Name + " " + c.Image
155 args += " " + c.ExtraRunningArgs
Maros Ondrejickac2f76f42023-02-27 13:22:45 +0100156 return args
157}
158
Adrian Villin25140012024-07-09 15:31:36 +0200159func (c *Container) PullDockerImage(name string, ctx context.Context) {
160 // "func (*Client) ImagePull" doesn't work, returns "No such image"
161 c.Suite.Log("Pulling image: " + name)
162 _, err := exechelper.CombinedOutput("docker pull " + name)
163 c.Suite.AssertNil(err)
Filip Tehlar4fa0ba62023-12-06 11:35:11 +0100164}
165
Adrian Villin25140012024-07-09 15:31:36 +0200166// Creates a container
Adrian Villin4677d922024-06-14 09:32:39 +0200167func (c *Container) Create() error {
Adrian Villin25140012024-07-09 15:31:36 +0200168 var sliceOfImageNames []string
169 images, err := c.Suite.Docker.ImageList(c.ctx, image.ListOptions{})
170 c.Suite.AssertNil(err)
171
172 for _, image := range images {
173 sliceOfImageNames = append(sliceOfImageNames, strings.Split(image.RepoTags[0], ":")[0])
174 }
175 if !slices.Contains(sliceOfImageNames, c.Image) {
176 c.PullDockerImage(c.Image, c.ctx)
177 }
178
179 c.allocateCpus()
180 cpuSet := fmt.Sprintf("%d-%d", c.AllocatedCpus[0], c.AllocatedCpus[len(c.AllocatedCpus)-1])
181 resp, err := c.Suite.Docker.ContainerCreate(
182 c.ctx,
183 &containerTypes.Config{
Adrian Villin007be4f2024-07-23 12:14:19 +0200184 Hostname: c.Name,
Matus Fabiand4643382024-07-29 13:30:23 +0200185 Image: c.Image,
186 Env: c.getEnvVars(),
187 Cmd: strings.Split(c.ExtraRunningArgs, " "),
Adrian Villin25140012024-07-09 15:31:36 +0200188 },
189 &containerTypes.HostConfig{
190 Resources: containerTypes.Resources{
191 Ulimits: []*units.Ulimit{
192 {
193 Name: "nofile",
194 Soft: 90000,
195 Hard: 90000,
196 },
197 },
198 CpusetCpus: cpuSet,
199 },
200 CapAdd: []string{"ALL"},
201 Privileged: true,
202 NetworkMode: "host",
203 Binds: c.getVolumesAsSlice(),
204 },
205 nil,
206 nil,
207 c.Name,
208 )
209 c.ID = resp.ID
210 return err
Maros Ondrejickac2f76f42023-02-27 13:22:45 +0100211}
212
Adrian Villinb9464cd2024-05-27 09:52:59 -0400213func (c *Container) allocateCpus() {
Adrian Villin4677d922024-06-14 09:32:39 +0200214 c.Suite.StartedContainers = append(c.Suite.StartedContainers, c)
215 c.AllocatedCpus = c.Suite.AllocateCpus()
216 c.Suite.Log("Allocated CPUs " + fmt.Sprint(c.AllocatedCpus) + " to container " + c.Name)
Adrian Villinb9464cd2024-05-27 09:52:59 -0400217}
218
Adrian Villin25140012024-07-09 15:31:36 +0200219// Starts a container
Adrian Villin4677d922024-06-14 09:32:39 +0200220func (c *Container) Start() error {
Adrian Villin25140012024-07-09 15:31:36 +0200221 var err error
Adrian Villin007be4f2024-07-23 12:14:19 +0200222 var nTries int
223
224 for nTries = 0; nTries < 5; nTries++ {
Adrian Villin25140012024-07-09 15:31:36 +0200225 err = c.Suite.Docker.ContainerStart(c.ctx, c.ID, containerTypes.StartOptions{})
226 if err == nil {
227 continue
228 }
229 c.Suite.Log("Error while starting " + c.Name + ". Retrying...")
230 time.Sleep(1 * time.Second)
231 }
Adrian Villin007be4f2024-07-23 12:14:19 +0200232 if nTries >= 5 {
233 return err
234 }
235
236 // wait for container to start
237 time.Sleep(1 * time.Second)
238
239 // check if container exited right after startup
240 containers, err := c.Suite.Docker.ContainerList(c.ctx, containerTypes.ListOptions{
241 All: true,
242 Filters: filters.NewArgs(filters.Arg("name", c.Name)),
243 })
244 if err != nil {
245 return err
246 }
247 if containers[0].State == "exited" {
248 c.Suite.Log("Container details: " + fmt.Sprint(containers[0]))
249 return fmt.Errorf("Container %s exited: '%s'", c.Name, containers[0].Status)
250 }
Adrian Villin25140012024-07-09 15:31:36 +0200251
252 return err
253}
254
255func (c *Container) GetOutput() (string, string) {
256 // Wait for the container to finish executing
257 statusCh, errCh := c.Suite.Docker.ContainerWait(c.ctx, c.ID, containerTypes.WaitConditionNotRunning)
258 select {
259 case err := <-errCh:
260 c.Suite.AssertNil(err)
261 case <-statusCh:
262 }
263
264 // Get the logs from the container
265 logOptions := containerTypes.LogsOptions{ShowStdout: true, ShowStderr: true}
266 logReader, err := c.Suite.Docker.ContainerLogs(c.ctx, c.ID, logOptions)
267 c.Suite.AssertNil(err)
268 defer logReader.Close()
269
270 var stdoutBuf, stderrBuf bytes.Buffer
271
272 // Use stdcopy.StdCopy to demultiplex the multiplexed stream
273 _, err = stdcopy.StdCopy(&stdoutBuf, &stderrBuf, logReader)
274 c.Suite.AssertNil(err)
275
276 stdout := stdoutBuf.String()
277 stderr := stderrBuf.String()
278 return stdout, stderr
Maros Ondrejicka87531802022-12-19 20:35:27 +0100279}
280
Filip Tehlarb41b0af2023-03-20 12:39:20 +0100281func (c *Container) prepareCommand() (string, error) {
Adrian Villin4677d922024-06-14 09:32:39 +0200282 if c.Name == "" {
Filip Tehlarb41b0af2023-03-20 12:39:20 +0100283 return "", fmt.Errorf("run container failed: name is blank")
Maros Ondrejicka87531802022-12-19 20:35:27 +0100284 }
285
Adrian Villin25140012024-07-09 15:31:36 +0200286 cmd := "docker exec "
Adrian Villin4677d922024-06-14 09:32:39 +0200287 if c.RunDetached {
Adrian Villineaa7d912024-06-06 04:26:30 -0400288 cmd += " -d"
Filip Tehlarb41b0af2023-03-20 12:39:20 +0100289 }
Adrian Villinb9464cd2024-05-27 09:52:59 -0400290
Filip Tehlarb41b0af2023-03-20 12:39:20 +0100291 cmd += " " + c.getContainerArguments()
292
Adrian Villin4677d922024-06-14 09:32:39 +0200293 c.Suite.Log(cmd)
Filip Tehlarb41b0af2023-03-20 12:39:20 +0100294 return cmd, nil
295}
296
Adrian Villin4677d922024-06-14 09:32:39 +0200297func (c *Container) CombinedOutput() (string, error) {
Filip Tehlarb41b0af2023-03-20 12:39:20 +0100298 cmd, err := c.prepareCommand()
Maros Ondrejicka11a03e92022-12-01 09:56:37 +0100299 if err != nil {
Filip Tehlarb41b0af2023-03-20 12:39:20 +0100300 return "", err
Maros Ondrejicka11a03e92022-12-01 09:56:37 +0100301 }
302
Filip Tehlarb41b0af2023-03-20 12:39:20 +0100303 byteOutput, err := exechelper.CombinedOutput(cmd)
304 return string(byteOutput), err
305}
306
Adrian Villin25140012024-07-09 15:31:36 +0200307// Creates and starts a container
308func (c *Container) Run() {
309 c.Suite.AssertNil(c.Create())
310 c.Suite.AssertNil(c.Start())
Maros Ondrejicka11a03e92022-12-01 09:56:37 +0100311}
312
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100313func (c *Container) addVolume(hostDir string, containerDir string, isDefaultWorkDir bool) {
Maros Ondrejickadb823ed2022-12-14 16:30:04 +0100314 var volume Volume
Adrian Villin4677d922024-06-14 09:32:39 +0200315 volume.HostDir = hostDir
316 volume.ContainerDir = containerDir
317 volume.IsDefaultWorkDir = isDefaultWorkDir
318 c.Volumes[hostDir] = volume
Maros Ondrejicka0e79abb2022-12-06 19:46:24 +0100319}
320
Adrian Villin25140012024-07-09 15:31:36 +0200321func (c *Container) getVolumesAsSlice() []string {
322 var volumeSlice []string
323
324 if *VppSourceFileDir != "" {
325 volumeSlice = append(volumeSlice, fmt.Sprintf("%s:%s", *VppSourceFileDir, *VppSourceFileDir))
326 }
327
328 if len(c.Volumes) > 0 {
329 for _, volume := range c.Volumes {
330 volumeSlice = append(volumeSlice, fmt.Sprintf("%s:%s", volume.HostDir, volume.ContainerDir))
331 }
332 }
333
334 return volumeSlice
335}
336
Maros Ondrejickadb823ed2022-12-14 16:30:04 +0100337func (c *Container) getVolumesAsCliOption() string {
338 cliOption := ""
Maros Ondrejicka0e79abb2022-12-06 19:46:24 +0100339
Adrian Villin4677d922024-06-14 09:32:39 +0200340 if len(c.Volumes) > 0 {
341 for _, volume := range c.Volumes {
342 cliOption += fmt.Sprintf(" -v %s:%s", volume.HostDir, volume.ContainerDir)
Maros Ondrejicka0e79abb2022-12-06 19:46:24 +0100343 }
344 }
345
Maros Ondrejickadb823ed2022-12-14 16:30:04 +0100346 return cliOption
347}
348
Adrian Villin4677d922024-06-14 09:32:39 +0200349func (c *Container) AddEnvVar(name string, value string) {
350 c.EnvVars[name] = value
Maros Ondrejickadb823ed2022-12-14 16:30:04 +0100351}
352
353func (c *Container) getEnvVarsAsCliOption() string {
354 cliOption := ""
Adrian Villin4677d922024-06-14 09:32:39 +0200355 if len(c.EnvVars) == 0 {
Maros Ondrejickadb823ed2022-12-14 16:30:04 +0100356 return cliOption
357 }
358
Adrian Villin4677d922024-06-14 09:32:39 +0200359 for name, value := range c.EnvVars {
Maros Ondrejickadb823ed2022-12-14 16:30:04 +0100360 cliOption += fmt.Sprintf(" -e %s=%s", name, value)
361 }
362 return cliOption
363}
364
Adrian Villin25140012024-07-09 15:31:36 +0200365func (c *Container) getEnvVars() []string {
366 var envVars []string
367 if len(c.EnvVars) == 0 {
368 return envVars
369 }
370
371 for name, value := range c.EnvVars {
372 envVars = append(envVars, fmt.Sprintf("%s=%s", name, value))
373 }
374 return envVars
375}
376
Filip Tehlar608d0062023-04-28 10:29:47 +0200377func (c *Container) newVppInstance(cpus []int, additionalConfigs ...Stanza) (*VppInstance, error) {
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100378 vpp := new(VppInstance)
Adrian Villin4677d922024-06-14 09:32:39 +0200379 vpp.Container = c
380 vpp.Cpus = cpus
Hadi Rayan Al-Sandide0e85132024-06-24 10:28:58 +0200381 vpp.setDefaultCpuConfig()
Adrian Villin4677d922024-06-14 09:32:39 +0200382 vpp.AdditionalConfig = append(vpp.AdditionalConfig, additionalConfigs...)
383 c.VppInstance = vpp
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100384 return vpp, nil
385}
386
387func (c *Container) copy(sourceFileName string, targetFileName string) error {
Adrian Villin4677d922024-06-14 09:32:39 +0200388 cmd := exec.Command("docker", "cp", sourceFileName, c.Name+":"+targetFileName)
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100389 return cmd.Run()
390}
391
Adrian Villin4677d922024-06-14 09:32:39 +0200392func (c *Container) CreateFile(destFileName string, content string) error {
393 f, err := os.CreateTemp("/tmp", "hst-config"+c.Suite.Ppid)
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100394 if err != nil {
395 return err
396 }
397 defer os.Remove(f.Name())
398
399 if _, err := f.Write([]byte(content)); err != nil {
400 return err
401 }
402 if err := f.Close(); err != nil {
403 return err
404 }
405 c.copy(f.Name(), destFileName)
406 return nil
407}
408
Matus Fabiane99d2662024-07-19 16:04:09 +0200409func (c *Container) GetFile(sourceFileName, targetFileName string) error {
410 cmd := exec.Command("docker", "cp", c.Name+":"+sourceFileName, targetFileName)
411 return cmd.Run()
412}
413
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100414/*
415 * Executes in detached mode so that the started application can continue to run
416 * without blocking execution of test
417 */
Adrian Villin4677d922024-06-14 09:32:39 +0200418func (c *Container) ExecServer(command string, arguments ...any) {
Maros Ondrejicka2908f8c2023-02-02 08:58:04 +0100419 serverCommand := fmt.Sprintf(command, arguments...)
420 containerExecCommand := "docker exec -d" + c.getEnvVarsAsCliOption() +
Adrian Villin4677d922024-06-14 09:32:39 +0200421 " " + c.Name + " " + serverCommand
Adrian Villincee15aa2024-03-14 11:42:55 -0400422 GinkgoHelper()
Adrian Villin4677d922024-06-14 09:32:39 +0200423 c.Suite.Log(containerExecCommand)
424 c.Suite.AssertNil(exechelper.Run(containerExecCommand))
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100425}
426
Adrian Villin4677d922024-06-14 09:32:39 +0200427func (c *Container) Exec(command string, arguments ...any) string {
Maros Ondrejicka2908f8c2023-02-02 08:58:04 +0100428 cliCommand := fmt.Sprintf(command, arguments...)
429 containerExecCommand := "docker exec" + c.getEnvVarsAsCliOption() +
Adrian Villin4677d922024-06-14 09:32:39 +0200430 " " + c.Name + " " + cliCommand
Adrian Villincee15aa2024-03-14 11:42:55 -0400431 GinkgoHelper()
Adrian Villin4677d922024-06-14 09:32:39 +0200432 c.Suite.Log(containerExecCommand)
Maros Ondrejicka2908f8c2023-02-02 08:58:04 +0100433 byteOutput, err := exechelper.CombinedOutput(containerExecCommand)
Adrian Villin4677d922024-06-14 09:32:39 +0200434 c.Suite.AssertNil(err, fmt.Sprint(err))
Maros Ondrejicka2908f8c2023-02-02 08:58:04 +0100435 return string(byteOutput)
Maros Ondrejickadb823ed2022-12-14 16:30:04 +0100436}
437
Maros Ondrejickaa2d52622023-02-24 11:26:39 +0100438func (c *Container) getLogDirPath() string {
Adrian Villin4677d922024-06-14 09:32:39 +0200439 testId := c.Suite.GetTestId()
440 testName := c.Suite.GetCurrentTestName()
Maros Ondrejickaa2d52622023-02-24 11:26:39 +0100441 logDirPath := logDir + testName + "/" + testId + "/"
442
443 cmd := exec.Command("mkdir", "-p", logDirPath)
444 if err := cmd.Run(); err != nil {
Adrian Villincee15aa2024-03-14 11:42:55 -0400445 Fail("mkdir error: " + fmt.Sprint(err))
Maros Ondrejickaa2d52622023-02-24 11:26:39 +0100446 }
447
448 return logDirPath
449}
450
451func (c *Container) saveLogs() {
Adrian Villin4677d922024-06-14 09:32:39 +0200452 testLogFilePath := c.getLogDirPath() + "container-" + c.Name + ".log"
Maros Ondrejickaa2d52622023-02-24 11:26:39 +0100453
Adrian Villin25140012024-07-09 15:31:36 +0200454 logs, err := c.log(0)
Maros Ondrejickaa2d52622023-02-24 11:26:39 +0100455 if err != nil {
Adrian Villin4677d922024-06-14 09:32:39 +0200456 c.Suite.Log(err)
Adrian Villin25140012024-07-09 15:31:36 +0200457 return
Maros Ondrejickaa2d52622023-02-24 11:26:39 +0100458 }
459
460 f, err := os.Create(testLogFilePath)
461 if err != nil {
Adrian Villin25140012024-07-09 15:31:36 +0200462 c.Suite.Log(err)
463 return
Maros Ondrejickaa2d52622023-02-24 11:26:39 +0100464 }
Adrian Villin25140012024-07-09 15:31:36 +0200465 defer f.Close()
466 fmt.Fprint(f, logs)
Maros Ondrejickaa2d52622023-02-24 11:26:39 +0100467}
468
Adrian Villin25140012024-07-09 15:31:36 +0200469// Returns logs from docker containers. Set 'maxLines' to 0 to output the full log.
adrianvillin7c675472024-02-12 02:44:53 -0500470func (c *Container) log(maxLines int) (string, error) {
Adrian Villin25140012024-07-09 15:31:36 +0200471 var logOptions containerTypes.LogsOptions
adrianvillin7c675472024-02-12 02:44:53 -0500472 if maxLines == 0 {
Matus Fabiand4643382024-07-29 13:30:23 +0200473 logOptions = containerTypes.LogsOptions{ShowStdout: true, ShowStderr: true, Details: true, Timestamps: true}
adrianvillin7c675472024-02-12 02:44:53 -0500474 } else {
Adrian Villin25140012024-07-09 15:31:36 +0200475 logOptions = containerTypes.LogsOptions{ShowStdout: true, ShowStderr: true, Details: true, Tail: strconv.Itoa(maxLines)}
adrianvillin7c675472024-02-12 02:44:53 -0500476 }
477
Adrian Villin25140012024-07-09 15:31:36 +0200478 out, err := c.Suite.Docker.ContainerLogs(c.ctx, c.ID, logOptions)
479 if err != nil {
480 c.Suite.Log(err)
481 return "", err
482 }
483 defer out.Close()
484
485 var stdoutBuf, stderrBuf bytes.Buffer
486
487 _, err = stdcopy.StdCopy(&stdoutBuf, &stderrBuf, out)
488 if err != nil {
489 c.Suite.Log(err)
490 }
491
492 stdout := stdoutBuf.String()
493 stderr := stderrBuf.String()
494
Matus Fabiand4643382024-07-29 13:30:23 +0200495 re := regexp.MustCompile("(?m)^.*==> /dev/null <==.*$[\r\n]+")
496 stdout = re.ReplaceAllString(stdout, "")
Adrian Villind9da4ee2024-07-24 17:46:53 +0200497
Matus Fabiand4643382024-07-29 13:30:23 +0200498 re = regexp.MustCompile("(?m)^.*tail: cannot open '' for reading: No such file or directory.*$[\r\n]+")
499 stderr = re.ReplaceAllString(stderr, "")
Adrian Villin09b19fe2024-07-18 08:33:59 +0200500
501 return stdout + stderr, err
Maros Ondrejickac2f76f42023-02-27 13:22:45 +0100502}
503
Maros Ondrejicka0e79abb2022-12-06 19:46:24 +0100504func (c *Container) stop() error {
Adrian Villin4677d922024-06-14 09:32:39 +0200505 if c.VppInstance != nil && c.VppInstance.ApiStream != nil {
506 c.VppInstance.saveLogs()
507 c.VppInstance.Disconnect()
Maros Ondrejickaffa3f602023-01-26 10:07:29 +0100508 }
Adrian Villin4677d922024-06-14 09:32:39 +0200509 c.VppInstance = nil
Maros Ondrejickaa2d52622023-02-24 11:26:39 +0100510 c.saveLogs()
Adrian Villin25140012024-07-09 15:31:36 +0200511
512 c.Suite.Log("Stopping container " + c.Name)
513 timeout := 0
514 if err := c.Suite.Docker.ContainerStop(c.ctx, c.ID, containerTypes.StopOptions{Timeout: &timeout}); err != nil {
515 return err
516 }
517 return nil
Maros Ondrejicka0e79abb2022-12-06 19:46:24 +0100518}
Maros Ondrejicka85396a52023-02-28 12:49:43 +0100519
Adrian Villin4677d922024-06-14 09:32:39 +0200520func (c *Container) CreateConfig(targetConfigName string, templateName string, values any) {
Maros Ondrejicka85396a52023-02-28 12:49:43 +0100521 template := template.Must(template.ParseFiles(templateName))
522
Filip Tehlara1bd50c2024-01-24 11:59:44 +0100523 f, err := os.CreateTemp(logDir, "hst-config")
Adrian Villin4677d922024-06-14 09:32:39 +0200524 c.Suite.AssertNil(err, err)
Maros Ondrejicka85396a52023-02-28 12:49:43 +0100525 defer os.Remove(f.Name())
526
527 err = template.Execute(f, values)
Adrian Villin4677d922024-06-14 09:32:39 +0200528 c.Suite.AssertNil(err, err)
Maros Ondrejicka85396a52023-02-28 12:49:43 +0100529
530 err = f.Close()
Adrian Villin4677d922024-06-14 09:32:39 +0200531 c.Suite.AssertNil(err, err)
Maros Ondrejicka85396a52023-02-28 12:49:43 +0100532
533 c.copy(f.Name(), targetConfigName)
534}
Maros Ondrejickaf4ddf162023-03-08 16:01:43 +0100535
536func init() {
537 cmd := exec.Command("mkdir", "-p", logDir)
538 if err := cmd.Run(); err != nil {
539 panic(err)
540 }
541}