11 "github.com/edwarnicke/exechelper"
12 . "github.com/onsi/ginkgo/v2"
16 logDir string = "/tmp/hs-test/"
17 volumeDir string = "/volumes"
21 workDir, _ = os.Getwd()
30 type Container struct {
36 extraRunningArgs string
37 volumes map[string]Volume
38 envVars map[string]string
39 vppInstance *VppInstance
42 func newContainer(suite *HstSuite, yamlInput ContainerConfig) (*Container, error) {
43 containerName := yamlInput["name"].(string)
44 if len(containerName) == 0 {
45 err := fmt.Errorf("container name must not be blank")
49 var container = new(Container)
50 container.volumes = make(map[string]Volume)
51 container.envVars = make(map[string]string)
52 container.name = containerName
53 container.suite = suite
55 if image, ok := yamlInput["image"]; ok {
56 container.image = image.(string)
58 container.image = "hs-test/vpp"
61 if args, ok := yamlInput["extra-args"]; ok {
62 container.extraRunningArgs = args.(string)
64 container.extraRunningArgs = ""
67 if isOptional, ok := yamlInput["is-optional"]; ok {
68 container.isOptional = isOptional.(bool)
70 container.isOptional = false
73 if runDetached, ok := yamlInput["run-detached"]; ok {
74 container.runDetached = runDetached.(bool)
76 container.runDetached = true
79 if _, ok := yamlInput["volumes"]; ok {
80 workingVolumeDir := logDir + CurrentSpecReport().LeafNodeText + container.suite.pid + volumeDir
81 workDirReplacer := strings.NewReplacer("$HST_DIR", workDir)
82 volDirReplacer := strings.NewReplacer("$HST_VOLUME_DIR", workingVolumeDir)
83 for _, volu := range yamlInput["volumes"].([]interface{}) {
84 volumeMap := volu.(ContainerConfig)
85 hostDir := workDirReplacer.Replace(volumeMap["host-dir"].(string))
86 hostDir = volDirReplacer.Replace(hostDir)
87 containerDir := volumeMap["container-dir"].(string)
88 isDefaultWorkDir := false
90 if isDefault, ok := volumeMap["is-default-work-dir"]; ok {
91 isDefaultWorkDir = isDefault.(bool)
93 container.addVolume(hostDir, containerDir, isDefaultWorkDir)
97 if _, ok := yamlInput["vars"]; ok {
98 for _, envVar := range yamlInput["vars"].([]interface{}) {
99 envVarMap := envVar.(ContainerConfig)
100 name := envVarMap["name"].(string)
101 value := envVarMap["value"].(string)
102 container.addEnvVar(name, value)
105 return container, nil
108 func (c *Container) getWorkDirVolume() (res Volume, exists bool) {
109 for _, v := range c.volumes {
110 if v.isDefaultWorkDir {
119 func (c *Container) getHostWorkDir() (res string) {
120 if v, ok := c.getWorkDirVolume(); ok {
126 func (c *Container) getContainerWorkDir() (res string) {
127 if v, ok := c.getWorkDirVolume(); ok {
133 func (c *Container) getContainerArguments() string {
134 args := "--ulimit nofile=90000:90000 --cap-add=all --privileged --network host --rm"
135 args += c.getVolumesAsCliOption()
136 args += c.getEnvVarsAsCliOption()
137 if *vppSourceFileDir != "" {
138 args += fmt.Sprintf(" -v %s:%s", *vppSourceFileDir, *vppSourceFileDir)
140 args += " --name " + c.name + " " + c.image
141 args += " " + c.extraRunningArgs
145 func (c *Container) runWithRetry(cmd string) error {
147 for i := 0; i < nTries; i++ {
148 err := exechelper.Run(cmd)
152 time.Sleep(1 * time.Second)
154 return fmt.Errorf("failed to run container command")
157 func (c *Container) create() error {
158 cmd := "docker create " + c.getContainerArguments()
160 return exechelper.Run(cmd)
163 func (c *Container) start() error {
164 cmd := "docker start " + c.name
166 return c.runWithRetry(cmd)
169 func (c *Container) prepareCommand() (string, error) {
171 return "", fmt.Errorf("run container failed: name is blank")
178 cmd += " " + c.getContainerArguments()
184 func (c *Container) combinedOutput() (string, error) {
185 cmd, err := c.prepareCommand()
190 byteOutput, err := exechelper.CombinedOutput(cmd)
191 return string(byteOutput), err
194 func (c *Container) run() error {
195 cmd, err := c.prepareCommand()
199 return c.runWithRetry(cmd)
202 func (c *Container) addVolume(hostDir string, containerDir string, isDefaultWorkDir bool) {
204 volume.hostDir = hostDir
205 volume.containerDir = containerDir
206 volume.isDefaultWorkDir = isDefaultWorkDir
207 c.volumes[hostDir] = volume
210 func (c *Container) getVolumesAsCliOption() string {
213 if len(c.volumes) > 0 {
214 for _, volume := range c.volumes {
215 cliOption += fmt.Sprintf(" -v %s:%s", volume.hostDir, volume.containerDir)
222 func (c *Container) addEnvVar(name string, value string) {
223 c.envVars[name] = value
226 func (c *Container) getEnvVarsAsCliOption() string {
228 if len(c.envVars) == 0 {
232 for name, value := range c.envVars {
233 cliOption += fmt.Sprintf(" -e %s=%s", name, value)
238 func (c *Container) newVppInstance(cpus []int, additionalConfigs ...Stanza) (*VppInstance, error) {
239 vpp := new(VppInstance)
242 vpp.additionalConfig = append(vpp.additionalConfig, additionalConfigs...)
247 func (c *Container) copy(sourceFileName string, targetFileName string) error {
248 cmd := exec.Command("docker", "cp", sourceFileName, c.name+":"+targetFileName)
252 func (c *Container) createFile(destFileName string, content string) error {
253 f, err := os.CreateTemp("/tmp", "hst-config"+c.suite.pid)
257 defer os.Remove(f.Name())
259 if _, err := f.Write([]byte(content)); err != nil {
262 if err := f.Close(); err != nil {
265 c.copy(f.Name(), destFileName)
270 * Executes in detached mode so that the started application can continue to run
271 * without blocking execution of test
273 func (c *Container) execServer(command string, arguments ...any) {
274 serverCommand := fmt.Sprintf(command, arguments...)
275 containerExecCommand := "docker exec -d" + c.getEnvVarsAsCliOption() +
276 " " + c.name + " " + serverCommand
278 c.suite.log(containerExecCommand)
279 c.suite.assertNil(exechelper.Run(containerExecCommand))
282 func (c *Container) exec(command string, arguments ...any) string {
283 cliCommand := fmt.Sprintf(command, arguments...)
284 containerExecCommand := "docker exec" + c.getEnvVarsAsCliOption() +
285 " " + c.name + " " + cliCommand
287 c.suite.log(containerExecCommand)
288 byteOutput, err := exechelper.CombinedOutput(containerExecCommand)
289 c.suite.assertNil(err, err)
290 return string(byteOutput)
293 func (c *Container) getLogDirPath() string {
294 testId := c.suite.getTestId()
295 testName := CurrentSpecReport().LeafNodeText
296 logDirPath := logDir + testName + "/" + testId + "/"
298 cmd := exec.Command("mkdir", "-p", logDirPath)
299 if err := cmd.Run(); err != nil {
300 Fail("mkdir error: " + fmt.Sprint(err))
306 func (c *Container) saveLogs() {
307 cmd := exec.Command("docker", "inspect", "--format='{{.State.Status}}'", c.name)
308 if output, _ := cmd.CombinedOutput(); !strings.Contains(string(output), "running") {
312 testLogFilePath := c.getLogDirPath() + "container-" + c.name + ".log"
314 cmd = exec.Command("docker", "logs", "--details", "-t", c.name)
315 output, err := cmd.CombinedOutput()
317 Fail("fetching logs error: " + fmt.Sprint(err))
320 f, err := os.Create(testLogFilePath)
322 Fail("file create error: " + fmt.Sprint(err))
324 fmt.Fprint(f, string(output))
328 // Outputs logs from docker containers. Set 'maxLines' to 0 to output the full log.
329 func (c *Container) log(maxLines int) (string, error) {
332 cmd = "docker logs " + c.name
334 cmd = fmt.Sprintf("docker logs --tail %d %s", maxLines, c.name)
338 o, err := exechelper.CombinedOutput(cmd)
339 return string(o), err
342 func (c *Container) stop() error {
343 if c.vppInstance != nil && c.vppInstance.apiChannel != nil {
344 c.vppInstance.saveLogs()
345 c.vppInstance.disconnect()
349 return exechelper.Run("docker stop " + c.name + " -t 0")
352 func (c *Container) createConfig(targetConfigName string, templateName string, values any) {
353 template := template.Must(template.ParseFiles(templateName))
355 f, err := os.CreateTemp(logDir, "hst-config")
356 c.suite.assertNil(err, err)
357 defer os.Remove(f.Name())
359 err = template.Execute(f, values)
360 c.suite.assertNil(err, err)
363 c.suite.assertNil(err, err)
365 c.copy(f.Name(), targetConfigName)
369 cmd := exec.Command("mkdir", "-p", logDir)
370 if err := cmd.Run(); err != nil {