10 "github.com/edwarnicke/exechelper"
14 logDir string = "/tmp/hs-test/"
18 workDir, _ = os.Getwd()
27 type Container struct {
32 extraRunningArgs string
33 volumes map[string]Volume
34 envVars map[string]string
35 vppInstance *VppInstance
38 func NewContainer(yamlInput ContainerConfig) (*Container, error) {
39 containerName := yamlInput["name"].(string)
40 if len(containerName) == 0 {
41 err := fmt.Errorf("container name must not be blank")
45 var container = new(Container)
46 container.volumes = make(map[string]Volume)
47 container.envVars = make(map[string]string)
48 container.name = containerName
50 if image, ok := yamlInput["image"]; ok {
51 container.image = image.(string)
53 container.image = "hs-test/vpp"
56 if args, ok := yamlInput["extra-args"]; ok {
57 container.extraRunningArgs = args.(string)
59 container.extraRunningArgs = ""
62 if isOptional, ok := yamlInput["is-optional"]; ok {
63 container.isOptional = isOptional.(bool)
65 container.isOptional = false
68 if _, ok := yamlInput["volumes"]; ok {
69 r := strings.NewReplacer("$HST_DIR", workDir)
70 for _, volu := range yamlInput["volumes"].([]interface{}) {
71 volumeMap := volu.(ContainerConfig)
72 hostDir := r.Replace(volumeMap["host-dir"].(string))
73 containerDir := volumeMap["container-dir"].(string)
74 isDefaultWorkDir := false
76 if isDefault, ok := volumeMap["is-default-work-dir"]; ok {
77 isDefaultWorkDir = isDefault.(bool)
80 container.addVolume(hostDir, containerDir, isDefaultWorkDir)
85 if _, ok := yamlInput["vars"]; ok {
86 for _, envVar := range yamlInput["vars"].([]interface{}) {
87 envVarMap := envVar.(ContainerConfig)
88 name := envVarMap["name"].(string)
89 value := envVarMap["value"].(string)
90 container.addEnvVar(name, value)
96 func (c *Container) Suite() *HstSuite {
100 func (c *Container) getWorkDirVolume() (res Volume, exists bool) {
101 for _, v := range c.volumes {
102 if v.isDefaultWorkDir {
111 func (c *Container) GetHostWorkDir() (res string) {
112 if v, ok := c.getWorkDirVolume(); ok {
118 func (c *Container) GetContainerWorkDir() (res string) {
119 if v, ok := c.getWorkDirVolume(); ok {
125 func (c *Container) getContainerArguments() string {
126 args := "--cap-add=all --privileged --network host --rm"
127 args += c.getVolumesAsCliOption()
128 args += c.getEnvVarsAsCliOption()
129 args += " --name " + c.name + " " + c.image
133 func (c *Container) create() {
134 cmd := "docker create " + c.getContainerArguments()
138 func (c *Container) start() {
139 cmd := "docker start " + c.name
143 func (c *Container) run() error {
145 return fmt.Errorf("run container failed: name is blank")
148 cmd := "docker run -d " + c.getContainerArguments() + " " + c.extraRunningArgs
150 err := exechelper.Run(cmd)
152 return fmt.Errorf("container run failed: %s", err)
158 func (c *Container) addVolume(hostDir string, containerDir string, isDefaultWorkDir bool) {
160 volume.hostDir = hostDir
161 volume.containerDir = containerDir
162 volume.isDefaultWorkDir = isDefaultWorkDir
163 c.volumes[hostDir] = volume
166 func (c *Container) getVolumesAsCliOption() string {
169 if len(c.volumes) > 0 {
170 for _, volume := range c.volumes {
171 cliOption += fmt.Sprintf(" -v %s:%s", volume.hostDir, volume.containerDir)
178 func (c *Container) addEnvVar(name string, value string) {
179 c.envVars[name] = value
182 func (c *Container) getEnvVarsAsCliOption() string {
184 if len(c.envVars) == 0 {
188 for name, value := range c.envVars {
189 cliOption += fmt.Sprintf(" -e %s=%s", name, value)
194 func (c *Container) newVppInstance(additionalConfig ...Stanza) (*VppInstance, error) {
195 vpp := new(VppInstance)
198 if len(additionalConfig) > 0 {
199 vpp.additionalConfig = additionalConfig[0]
207 func (c *Container) copy(sourceFileName string, targetFileName string) error {
208 cmd := exec.Command("docker", "cp", sourceFileName, c.name+":"+targetFileName)
212 func (c *Container) createFile(destFileName string, content string) error {
213 f, err := os.CreateTemp("/tmp", "hst-config")
217 defer os.Remove(f.Name())
219 if _, err := f.Write([]byte(content)); err != nil {
222 if err := f.Close(); err != nil {
225 c.copy(f.Name(), destFileName)
230 * Executes in detached mode so that the started application can continue to run
231 * without blocking execution of test
233 func (c *Container) execServer(command string, arguments ...any) {
234 serverCommand := fmt.Sprintf(command, arguments...)
235 containerExecCommand := "docker exec -d" + c.getEnvVarsAsCliOption() +
236 " " + c.name + " " + serverCommand
237 c.Suite().T().Helper()
238 c.Suite().log(containerExecCommand)
239 c.Suite().assertNil(exechelper.Run(containerExecCommand))
242 func (c *Container) exec(command string, arguments ...any) string {
243 cliCommand := fmt.Sprintf(command, arguments...)
244 containerExecCommand := "docker exec" + c.getEnvVarsAsCliOption() +
245 " " + c.name + " " + cliCommand
246 c.Suite().T().Helper()
247 c.Suite().log(containerExecCommand)
248 byteOutput, err := exechelper.CombinedOutput(containerExecCommand)
249 c.Suite().assertNil(err)
250 return string(byteOutput)
253 func (c *Container) getLogDirPath() string {
254 testId := c.Suite().getTestId()
255 testName := c.Suite().T().Name()
256 logDirPath := logDir + testName + "/" + testId + "/"
258 cmd := exec.Command("mkdir", "-p", logDirPath)
259 if err := cmd.Run(); err != nil {
260 c.Suite().T().Fatalf("mkdir error: %v", err)
266 func (c *Container) saveLogs() {
267 cmd := exec.Command("docker", "inspect", "--format='{{.State.Status}}'", c.name)
268 if output, _ := cmd.CombinedOutput(); !strings.Contains(string(output), "running") {
272 testLogFilePath := c.getLogDirPath() + "container-" + c.name + ".log"
274 cmd = exec.Command("docker", "logs", "--details", "-t", c.name)
275 output, err := cmd.CombinedOutput()
277 c.Suite().T().Fatalf("fetching logs error: %v", err)
280 f, err := os.Create(testLogFilePath)
282 c.Suite().T().Fatalf("file create error: %v", err)
284 fmt.Fprintf(f, string(output))
288 func (c *Container) log() string {
289 cmd := "docker logs " + c.name
291 o, err := exechelper.CombinedOutput(cmd)
292 c.Suite().assertNil(err)
296 func (c *Container) stop() error {
297 if c.vppInstance != nil && c.vppInstance.apiChannel != nil {
298 c.vppInstance.saveLogs()
299 c.vppInstance.disconnect()
303 return exechelper.Run("docker stop " + c.name + " -t 0")
306 func (c *Container) createConfig(targetConfigName string, templateName string, values any) {
307 template := template.Must(template.ParseFiles(templateName))
309 f, err := os.CreateTemp("/tmp/hs-test/", "hst-config")
310 c.Suite().assertNil(err)
311 defer os.Remove(f.Name())
313 err = template.Execute(f, values)
314 c.Suite().assertNil(err)
317 c.Suite().assertNil(err)
319 c.copy(f.Name(), targetConfigName)