11 "github.com/edwarnicke/exechelper"
15 logDir string = "/tmp/hs-test/"
16 volumeDir string = "/volumes"
20 workDir, _ = os.Getwd()
29 type Container struct {
35 extraRunningArgs string
36 volumes map[string]Volume
37 envVars map[string]string
38 vppInstance *VppInstance
41 func newContainer(suite *HstSuite, yamlInput ContainerConfig) (*Container, error) {
42 containerName := yamlInput["name"].(string)
43 if len(containerName) == 0 {
44 err := fmt.Errorf("container name must not be blank")
48 var container = new(Container)
49 container.volumes = make(map[string]Volume)
50 container.envVars = make(map[string]string)
51 container.name = containerName
52 container.suite = suite
54 if image, ok := yamlInput["image"]; ok {
55 container.image = image.(string)
57 container.image = "hs-test/vpp"
60 if args, ok := yamlInput["extra-args"]; ok {
61 container.extraRunningArgs = args.(string)
63 container.extraRunningArgs = ""
66 if isOptional, ok := yamlInput["is-optional"]; ok {
67 container.isOptional = isOptional.(bool)
69 container.isOptional = false
72 if runDetached, ok := yamlInput["run-detached"]; ok {
73 container.runDetached = runDetached.(bool)
75 container.runDetached = true
78 if _, ok := yamlInput["volumes"]; ok {
79 workingVolumeDir := logDir + container.suite.T().Name() + volumeDir
80 workDirReplacer := strings.NewReplacer("$HST_DIR", workDir)
81 volDirReplacer := strings.NewReplacer("$HST_VOLUME_DIR", workingVolumeDir)
82 for _, volu := range yamlInput["volumes"].([]interface{}) {
83 volumeMap := volu.(ContainerConfig)
84 hostDir := workDirReplacer.Replace(volumeMap["host-dir"].(string))
85 hostDir = volDirReplacer.Replace(hostDir)
86 containerDir := volumeMap["container-dir"].(string)
87 isDefaultWorkDir := false
89 if isDefault, ok := volumeMap["is-default-work-dir"]; ok {
90 isDefaultWorkDir = isDefault.(bool)
92 container.addVolume(hostDir, containerDir, isDefaultWorkDir)
96 if _, ok := yamlInput["vars"]; ok {
97 for _, envVar := range yamlInput["vars"].([]interface{}) {
98 envVarMap := envVar.(ContainerConfig)
99 name := envVarMap["name"].(string)
100 value := envVarMap["value"].(string)
101 container.addEnvVar(name, value)
104 return container, nil
107 func (c *Container) getWorkDirVolume() (res Volume, exists bool) {
108 for _, v := range c.volumes {
109 if v.isDefaultWorkDir {
118 func (c *Container) getHostWorkDir() (res string) {
119 if v, ok := c.getWorkDirVolume(); ok {
125 func (c *Container) getContainerWorkDir() (res string) {
126 if v, ok := c.getWorkDirVolume(); ok {
132 func (c *Container) getContainerArguments() string {
133 args := "--ulimit nofile=90000:90000 --cap-add=all --privileged --network host --rm"
134 args += c.getVolumesAsCliOption()
135 args += c.getEnvVarsAsCliOption()
136 if *vppSourceFileDir != "" {
137 args += fmt.Sprintf(" -v %s:%s", *vppSourceFileDir, *vppSourceFileDir)
139 args += " --name " + c.name + " " + c.image
140 args += " " + c.extraRunningArgs
144 func (c *Container) runWithRetry(cmd string) error {
146 for i := 0; i < nTries; i++ {
147 err := exechelper.Run(cmd)
151 time.Sleep(1 * time.Second)
153 return fmt.Errorf("failed to run container command")
156 func (c *Container) create() error {
157 cmd := "docker create " + c.getContainerArguments()
159 return exechelper.Run(cmd)
162 func (c *Container) start() error {
163 cmd := "docker start " + c.name
165 return c.runWithRetry(cmd)
168 func (c *Container) prepareCommand() (string, error) {
170 return "", fmt.Errorf("run container failed: name is blank")
177 cmd += " " + c.getContainerArguments()
183 func (c *Container) combinedOutput() (string, error) {
184 cmd, err := c.prepareCommand()
189 byteOutput, err := exechelper.CombinedOutput(cmd)
190 return string(byteOutput), err
193 func (c *Container) run() error {
194 cmd, err := c.prepareCommand()
198 return c.runWithRetry(cmd)
201 func (c *Container) addVolume(hostDir string, containerDir string, isDefaultWorkDir bool) {
203 volume.hostDir = hostDir
204 volume.containerDir = containerDir
205 volume.isDefaultWorkDir = isDefaultWorkDir
206 c.volumes[hostDir] = volume
209 func (c *Container) getVolumesAsCliOption() string {
212 if len(c.volumes) > 0 {
213 for _, volume := range c.volumes {
214 cliOption += fmt.Sprintf(" -v %s:%s", volume.hostDir, volume.containerDir)
221 func (c *Container) addEnvVar(name string, value string) {
222 c.envVars[name] = value
225 func (c *Container) getEnvVarsAsCliOption() string {
227 if len(c.envVars) == 0 {
231 for name, value := range c.envVars {
232 cliOption += fmt.Sprintf(" -e %s=%s", name, value)
237 func (c *Container) newVppInstance(cpus []int, additionalConfigs ...Stanza) (*VppInstance, error) {
238 vpp := new(VppInstance)
241 vpp.additionalConfig = append(vpp.additionalConfig, additionalConfigs...)
246 func (c *Container) copy(sourceFileName string, targetFileName string) error {
247 cmd := exec.Command("docker", "cp", sourceFileName, c.name+":"+targetFileName)
251 func (c *Container) createFile(destFileName string, content string) error {
252 f, err := os.CreateTemp("/tmp", "hst-config")
256 defer os.Remove(f.Name())
258 if _, err := f.Write([]byte(content)); err != nil {
261 if err := f.Close(); err != nil {
264 c.copy(f.Name(), destFileName)
269 * Executes in detached mode so that the started application can continue to run
270 * without blocking execution of test
272 func (c *Container) execServer(command string, arguments ...any) {
273 serverCommand := fmt.Sprintf(command, arguments...)
274 containerExecCommand := "docker exec -d" + c.getEnvVarsAsCliOption() +
275 " " + c.name + " " + serverCommand
277 c.suite.log(containerExecCommand)
278 c.suite.assertNil(exechelper.Run(containerExecCommand))
281 func (c *Container) exec(command string, arguments ...any) string {
282 cliCommand := fmt.Sprintf(command, arguments...)
283 containerExecCommand := "docker exec" + c.getEnvVarsAsCliOption() +
284 " " + c.name + " " + cliCommand
286 c.suite.log(containerExecCommand)
287 byteOutput, err := exechelper.CombinedOutput(containerExecCommand)
288 c.suite.assertNil(err)
289 return string(byteOutput)
292 func (c *Container) getLogDirPath() string {
293 testId := c.suite.getTestId()
294 testName := c.suite.T().Name()
295 logDirPath := logDir + testName + "/" + testId + "/"
297 cmd := exec.Command("mkdir", "-p", logDirPath)
298 if err := cmd.Run(); err != nil {
299 c.suite.T().Fatalf("mkdir error: %v", err)
305 func (c *Container) saveLogs() {
306 cmd := exec.Command("docker", "inspect", "--format='{{.State.Status}}'", c.name)
307 if output, _ := cmd.CombinedOutput(); !strings.Contains(string(output), "running") {
311 testLogFilePath := c.getLogDirPath() + "container-" + c.name + ".log"
313 cmd = exec.Command("docker", "logs", "--details", "-t", c.name)
314 output, err := cmd.CombinedOutput()
316 c.suite.T().Fatalf("fetching logs error: %v", err)
319 f, err := os.Create(testLogFilePath)
321 c.suite.T().Fatalf("file create error: %v", err)
323 fmt.Fprint(f, string(output))
327 func (c *Container) log() string {
328 cmd := "docker logs " + c.name
330 o, err := exechelper.CombinedOutput(cmd)
331 c.suite.assertNil(err)
335 func (c *Container) stop() error {
336 if c.vppInstance != nil && c.vppInstance.apiChannel != nil {
337 c.vppInstance.saveLogs()
338 c.vppInstance.disconnect()
342 return exechelper.Run("docker stop " + c.name + " -t 0")
345 func (c *Container) createConfig(targetConfigName string, templateName string, values any) {
346 template := template.Must(template.ParseFiles(templateName))
348 f, err := os.CreateTemp(logDir, "hst-config")
349 c.suite.assertNil(err)
350 defer os.Remove(f.Name())
352 err = template.Execute(f, values)
353 c.suite.assertNil(err)
356 c.suite.assertNil(err)
358 c.copy(f.Name(), targetConfigName)
362 cmd := exec.Command("mkdir", "-p", logDir)
363 if err := cmd.Run(); err != nil {