10 "github.com/edwarnicke/exechelper"
14 logDir string = "/tmp/hs-test/"
18 workDir, _ = os.Getwd()
27 type Container struct {
33 extraRunningArgs string
34 volumes map[string]Volume
35 envVars map[string]string
36 vppInstance *VppInstance
39 func newContainer(yamlInput ContainerConfig) (*Container, error) {
40 containerName := yamlInput["name"].(string)
41 if len(containerName) == 0 {
42 err := fmt.Errorf("container name must not be blank")
46 var container = new(Container)
47 container.volumes = make(map[string]Volume)
48 container.envVars = make(map[string]string)
49 container.name = containerName
51 if image, ok := yamlInput["image"]; ok {
52 container.image = image.(string)
54 container.image = "hs-test/vpp"
57 if args, ok := yamlInput["extra-args"]; ok {
58 container.extraRunningArgs = args.(string)
60 container.extraRunningArgs = ""
63 if isOptional, ok := yamlInput["is-optional"]; ok {
64 container.isOptional = isOptional.(bool)
66 container.isOptional = false
69 if runDetached, ok := yamlInput["run-detached"]; ok {
70 container.runDetached = runDetached.(bool)
72 container.runDetached = true
75 if _, ok := yamlInput["volumes"]; ok {
76 r := strings.NewReplacer("$HST_DIR", workDir)
77 for _, volu := range yamlInput["volumes"].([]interface{}) {
78 volumeMap := volu.(ContainerConfig)
79 hostDir := r.Replace(volumeMap["host-dir"].(string))
80 containerDir := volumeMap["container-dir"].(string)
81 isDefaultWorkDir := false
83 if isDefault, ok := volumeMap["is-default-work-dir"]; ok {
84 isDefaultWorkDir = isDefault.(bool)
87 container.addVolume(hostDir, containerDir, isDefaultWorkDir)
92 if _, ok := yamlInput["vars"]; ok {
93 for _, envVar := range yamlInput["vars"].([]interface{}) {
94 envVarMap := envVar.(ContainerConfig)
95 name := envVarMap["name"].(string)
96 value := envVarMap["value"].(string)
97 container.addEnvVar(name, value)
100 return container, nil
103 func (c *Container) getWorkDirVolume() (res Volume, exists bool) {
104 for _, v := range c.volumes {
105 if v.isDefaultWorkDir {
114 func (c *Container) getHostWorkDir() (res string) {
115 if v, ok := c.getWorkDirVolume(); ok {
121 func (c *Container) getContainerWorkDir() (res string) {
122 if v, ok := c.getWorkDirVolume(); ok {
128 func (c *Container) getContainerArguments() string {
129 args := "--ulimit nofile=90000:90000 --cap-add=all --privileged --network host --rm"
130 args += c.getVolumesAsCliOption()
131 args += c.getEnvVarsAsCliOption()
132 if *vppSourceFileDir != "" {
133 args += fmt.Sprintf(" -v %s:%s", *vppSourceFileDir, *vppSourceFileDir)
135 args += " --name " + c.name + " " + c.image
136 args += " " + c.extraRunningArgs
140 func (c *Container) create() error {
141 cmd := "docker create " + c.getContainerArguments()
143 return exechelper.Run(cmd)
146 func (c *Container) start() error {
147 cmd := "docker start " + c.name
149 return exechelper.Run(cmd)
152 func (c *Container) prepareCommand() (string, error) {
154 return "", fmt.Errorf("run container failed: name is blank")
161 cmd += " " + c.getContainerArguments()
167 func (c *Container) combinedOutput() (string, error) {
168 cmd, err := c.prepareCommand()
173 byteOutput, err := exechelper.CombinedOutput(cmd)
174 return string(byteOutput), err
177 func (c *Container) run() error {
178 cmd, err := c.prepareCommand()
183 return exechelper.Run(cmd)
186 func (c *Container) addVolume(hostDir string, containerDir string, isDefaultWorkDir bool) {
188 volume.hostDir = hostDir
189 volume.containerDir = containerDir
190 volume.isDefaultWorkDir = isDefaultWorkDir
191 c.volumes[hostDir] = volume
194 func (c *Container) getVolumesAsCliOption() string {
197 if len(c.volumes) > 0 {
198 for _, volume := range c.volumes {
199 cliOption += fmt.Sprintf(" -v %s:%s", volume.hostDir, volume.containerDir)
206 func (c *Container) addEnvVar(name string, value string) {
207 c.envVars[name] = value
210 func (c *Container) getEnvVarsAsCliOption() string {
212 if len(c.envVars) == 0 {
216 for name, value := range c.envVars {
217 cliOption += fmt.Sprintf(" -e %s=%s", name, value)
222 func (c *Container) newVppInstance(cpus []int, additionalConfigs ...Stanza) (*VppInstance, error) {
223 vpp := new(VppInstance)
226 vpp.additionalConfig = append(vpp.additionalConfig, additionalConfigs...)
231 func (c *Container) copy(sourceFileName string, targetFileName string) error {
232 cmd := exec.Command("docker", "cp", sourceFileName, c.name+":"+targetFileName)
236 func (c *Container) createFile(destFileName string, content string) error {
237 f, err := os.CreateTemp("/tmp", "hst-config")
241 defer os.Remove(f.Name())
243 if _, err := f.Write([]byte(content)); err != nil {
246 if err := f.Close(); err != nil {
249 c.copy(f.Name(), destFileName)
254 * Executes in detached mode so that the started application can continue to run
255 * without blocking execution of test
257 func (c *Container) execServer(command string, arguments ...any) {
258 serverCommand := fmt.Sprintf(command, arguments...)
259 containerExecCommand := "docker exec -d" + c.getEnvVarsAsCliOption() +
260 " " + c.name + " " + serverCommand
262 c.suite.log(containerExecCommand)
263 c.suite.assertNil(exechelper.Run(containerExecCommand))
266 func (c *Container) exec(command string, arguments ...any) string {
267 cliCommand := fmt.Sprintf(command, arguments...)
268 containerExecCommand := "docker exec" + c.getEnvVarsAsCliOption() +
269 " " + c.name + " " + cliCommand
271 c.suite.log(containerExecCommand)
272 byteOutput, err := exechelper.CombinedOutput(containerExecCommand)
273 c.suite.assertNil(err)
274 return string(byteOutput)
277 func (c *Container) getLogDirPath() string {
278 testId := c.suite.getTestId()
279 testName := c.suite.T().Name()
280 logDirPath := logDir + testName + "/" + testId + "/"
282 cmd := exec.Command("mkdir", "-p", logDirPath)
283 if err := cmd.Run(); err != nil {
284 c.suite.T().Fatalf("mkdir error: %v", err)
290 func (c *Container) saveLogs() {
291 cmd := exec.Command("docker", "inspect", "--format='{{.State.Status}}'", c.name)
292 if output, _ := cmd.CombinedOutput(); !strings.Contains(string(output), "running") {
296 testLogFilePath := c.getLogDirPath() + "container-" + c.name + ".log"
298 cmd = exec.Command("docker", "logs", "--details", "-t", c.name)
299 output, err := cmd.CombinedOutput()
301 c.suite.T().Fatalf("fetching logs error: %v", err)
304 f, err := os.Create(testLogFilePath)
306 c.suite.T().Fatalf("file create error: %v", err)
308 fmt.Fprint(f, string(output))
312 func (c *Container) log() string {
313 cmd := "docker logs " + c.name
315 o, err := exechelper.CombinedOutput(cmd)
316 c.suite.assertNil(err)
320 func (c *Container) stop() error {
321 if c.vppInstance != nil && c.vppInstance.apiChannel != nil {
322 c.vppInstance.saveLogs()
323 c.vppInstance.disconnect()
327 return exechelper.Run("docker stop " + c.name + " -t 0")
330 func (c *Container) createConfig(targetConfigName string, templateName string, values any) {
331 template := template.Must(template.ParseFiles(templateName))
333 f, err := os.CreateTemp("/tmp/hs-test/", "hst-config")
334 c.suite.assertNil(err)
335 defer os.Remove(f.Name())
337 err = template.Execute(f, values)
338 c.suite.assertNil(err)
341 c.suite.assertNil(err)
343 c.copy(f.Name(), targetConfigName)
347 cmd := exec.Command("mkdir", "-p", logDir)
348 if err := cmd.Run(); err != nil {