11 "github.com/edwarnicke/exechelper"
15 logDir string = "/tmp/hs-test/"
19 workDir, _ = os.Getwd()
28 type Container struct {
34 extraRunningArgs string
35 volumes map[string]Volume
36 envVars map[string]string
37 vppInstance *VppInstance
40 func newContainer(yamlInput ContainerConfig) (*Container, error) {
41 containerName := yamlInput["name"].(string)
42 if len(containerName) == 0 {
43 err := fmt.Errorf("container name must not be blank")
47 var container = new(Container)
48 container.volumes = make(map[string]Volume)
49 container.envVars = make(map[string]string)
50 container.name = containerName
52 if image, ok := yamlInput["image"]; ok {
53 container.image = image.(string)
55 container.image = "hs-test/vpp"
58 if args, ok := yamlInput["extra-args"]; ok {
59 container.extraRunningArgs = args.(string)
61 container.extraRunningArgs = ""
64 if isOptional, ok := yamlInput["is-optional"]; ok {
65 container.isOptional = isOptional.(bool)
67 container.isOptional = false
70 if runDetached, ok := yamlInput["run-detached"]; ok {
71 container.runDetached = runDetached.(bool)
73 container.runDetached = true
76 if _, ok := yamlInput["volumes"]; ok {
77 r := strings.NewReplacer("$HST_DIR", workDir)
78 for _, volu := range yamlInput["volumes"].([]interface{}) {
79 volumeMap := volu.(ContainerConfig)
80 hostDir := r.Replace(volumeMap["host-dir"].(string))
81 containerDir := volumeMap["container-dir"].(string)
82 isDefaultWorkDir := false
84 if isDefault, ok := volumeMap["is-default-work-dir"]; ok {
85 isDefaultWorkDir = isDefault.(bool)
88 container.addVolume(hostDir, containerDir, isDefaultWorkDir)
93 if _, ok := yamlInput["vars"]; ok {
94 for _, envVar := range yamlInput["vars"].([]interface{}) {
95 envVarMap := envVar.(ContainerConfig)
96 name := envVarMap["name"].(string)
97 value := envVarMap["value"].(string)
98 container.addEnvVar(name, value)
101 return container, nil
104 func (c *Container) getWorkDirVolume() (res Volume, exists bool) {
105 for _, v := range c.volumes {
106 if v.isDefaultWorkDir {
115 func (c *Container) getHostWorkDir() (res string) {
116 if v, ok := c.getWorkDirVolume(); ok {
122 func (c *Container) getContainerWorkDir() (res string) {
123 if v, ok := c.getWorkDirVolume(); ok {
129 func (c *Container) getContainerArguments() string {
130 args := "--ulimit nofile=90000:90000 --cap-add=all --privileged --network host --rm"
131 args += c.getVolumesAsCliOption()
132 args += c.getEnvVarsAsCliOption()
133 if *vppSourceFileDir != "" {
134 args += fmt.Sprintf(" -v %s:%s", *vppSourceFileDir, *vppSourceFileDir)
136 args += " --name " + c.name + " " + c.image
137 args += " " + c.extraRunningArgs
141 func (c *Container) runWithRetry(cmd string) error {
143 for i := 0; i < nTries; i++ {
144 err := exechelper.Run(cmd)
148 time.Sleep(1 * time.Second)
150 return fmt.Errorf("failed to run container command")
153 func (c *Container) create() error {
154 cmd := "docker create " + c.getContainerArguments()
156 return exechelper.Run(cmd)
159 func (c *Container) start() error {
160 cmd := "docker start " + c.name
162 return c.runWithRetry(cmd)
165 func (c *Container) prepareCommand() (string, error) {
167 return "", fmt.Errorf("run container failed: name is blank")
174 cmd += " " + c.getContainerArguments()
180 func (c *Container) combinedOutput() (string, error) {
181 cmd, err := c.prepareCommand()
186 byteOutput, err := exechelper.CombinedOutput(cmd)
187 return string(byteOutput), err
190 func (c *Container) run() error {
191 cmd, err := c.prepareCommand()
195 return c.runWithRetry(cmd)
198 func (c *Container) addVolume(hostDir string, containerDir string, isDefaultWorkDir bool) {
200 volume.hostDir = hostDir
201 volume.containerDir = containerDir
202 volume.isDefaultWorkDir = isDefaultWorkDir
203 c.volumes[hostDir] = volume
206 func (c *Container) getVolumesAsCliOption() string {
209 if len(c.volumes) > 0 {
210 for _, volume := range c.volumes {
211 cliOption += fmt.Sprintf(" -v %s:%s", volume.hostDir, volume.containerDir)
218 func (c *Container) addEnvVar(name string, value string) {
219 c.envVars[name] = value
222 func (c *Container) getEnvVarsAsCliOption() string {
224 if len(c.envVars) == 0 {
228 for name, value := range c.envVars {
229 cliOption += fmt.Sprintf(" -e %s=%s", name, value)
234 func (c *Container) newVppInstance(cpus []int, additionalConfigs ...Stanza) (*VppInstance, error) {
235 vpp := new(VppInstance)
238 vpp.additionalConfig = append(vpp.additionalConfig, additionalConfigs...)
243 func (c *Container) copy(sourceFileName string, targetFileName string) error {
244 cmd := exec.Command("docker", "cp", sourceFileName, c.name+":"+targetFileName)
248 func (c *Container) createFile(destFileName string, content string) error {
249 f, err := os.CreateTemp("/tmp", "hst-config")
253 defer os.Remove(f.Name())
255 if _, err := f.Write([]byte(content)); err != nil {
258 if err := f.Close(); err != nil {
261 c.copy(f.Name(), destFileName)
266 * Executes in detached mode so that the started application can continue to run
267 * without blocking execution of test
269 func (c *Container) execServer(command string, arguments ...any) {
270 serverCommand := fmt.Sprintf(command, arguments...)
271 containerExecCommand := "docker exec -d" + c.getEnvVarsAsCliOption() +
272 " " + c.name + " " + serverCommand
274 c.suite.log(containerExecCommand)
275 c.suite.assertNil(exechelper.Run(containerExecCommand))
278 func (c *Container) exec(command string, arguments ...any) string {
279 cliCommand := fmt.Sprintf(command, arguments...)
280 containerExecCommand := "docker exec" + c.getEnvVarsAsCliOption() +
281 " " + c.name + " " + cliCommand
283 c.suite.log(containerExecCommand)
284 byteOutput, err := exechelper.CombinedOutput(containerExecCommand)
285 c.suite.assertNil(err)
286 return string(byteOutput)
289 func (c *Container) getLogDirPath() string {
290 testId := c.suite.getTestId()
291 testName := c.suite.T().Name()
292 logDirPath := logDir + testName + "/" + testId + "/"
294 cmd := exec.Command("mkdir", "-p", logDirPath)
295 if err := cmd.Run(); err != nil {
296 c.suite.T().Fatalf("mkdir error: %v", err)
302 func (c *Container) saveLogs() {
303 cmd := exec.Command("docker", "inspect", "--format='{{.State.Status}}'", c.name)
304 if output, _ := cmd.CombinedOutput(); !strings.Contains(string(output), "running") {
308 testLogFilePath := c.getLogDirPath() + "container-" + c.name + ".log"
310 cmd = exec.Command("docker", "logs", "--details", "-t", c.name)
311 output, err := cmd.CombinedOutput()
313 c.suite.T().Fatalf("fetching logs error: %v", err)
316 f, err := os.Create(testLogFilePath)
318 c.suite.T().Fatalf("file create error: %v", err)
320 fmt.Fprint(f, string(output))
324 func (c *Container) log() string {
325 cmd := "docker logs " + c.name
327 o, err := exechelper.CombinedOutput(cmd)
328 c.suite.assertNil(err)
332 func (c *Container) stop() error {
333 if c.vppInstance != nil && c.vppInstance.apiChannel != nil {
334 c.vppInstance.saveLogs()
335 c.vppInstance.disconnect()
339 return exechelper.Run("docker stop " + c.name + " -t 0")
342 func (c *Container) createConfig(targetConfigName string, templateName string, values any) {
343 template := template.Must(template.ParseFiles(templateName))
345 f, err := os.CreateTemp("/tmp/hs-test/", "hst-config")
346 c.suite.assertNil(err)
347 defer os.Remove(f.Name())
349 err = template.Execute(f, values)
350 c.suite.assertNil(err)
353 c.suite.assertNil(err)
355 c.copy(f.Name(), targetConfigName)
359 cmd := exec.Command("mkdir", "-p", logDir)
360 if err := cmd.Run(); err != nil {