Execute executes the script inside a docker container
(test TestCase)
| 30 | |
| 31 | // Execute executes the script inside a docker container |
| 32 | func (e DockerExecutor) Execute(test TestCase) TestResult { |
| 33 | log.Printf("DOCKER_HOST: %s \n", os.Getenv("DOCKER_HOST")) |
| 34 | log.Printf("DOCKER_CERT_PATH: %s \n", os.Getenv("DOCKER_CERT_PATH")) |
| 35 | log.Printf("DOCKER_API_VERSION: %s \n", os.Getenv("DOCKER_API_VERSION")) |
| 36 | |
| 37 | ctx := context.Background() |
| 38 | cli, err := client.NewClientWithOpts(client.WithAPIVersionNegotiation(), client.FromEnv) |
| 39 | if err != nil { |
| 40 | test.Result.Error = err |
| 41 | return TestResult{ |
| 42 | TestCase: test, |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | authConfig := types.AuthConfig{ |
| 47 | Username: e.RegistryUser, |
| 48 | Password: e.RegistryPass, |
| 49 | } |
| 50 | encodedJSON, err := json.Marshal(authConfig) |
| 51 | if err != nil { |
| 52 | panic(err) |
| 53 | } |
| 54 | authStr := base64.URLEncoding.EncodeToString(encodedJSON) |
| 55 | |
| 56 | log.Printf("Pulling image %s\n", e.Image) |
| 57 | reader, err := cli.ImagePull(ctx, e.Image, types.ImagePullOptions{ |
| 58 | RegistryAuth: authStr, |
| 59 | }) |
| 60 | if err != nil { |
| 61 | test.Result.Error = fmt.Errorf("could not pull image '%s' with error: '%s'", e.Image, err) |
| 62 | return TestResult{ |
| 63 | TestCase: test, |
| 64 | } |
| 65 | } |
| 66 | buf := bytes.Buffer{} |
| 67 | buf.ReadFrom(reader) |
| 68 | log.Printf("Pull log image'%s':\n %s\n", e.Image, buf.String()) |
| 69 | |
| 70 | var env []string |
| 71 | for k, v := range test.Command.Env { |
| 72 | env = append(env, fmt.Sprintf("%s=%s", k, v)) |
| 73 | } |
| 74 | |
| 75 | log.Printf("Create container %s\n", e.Image) |
| 76 | resp, err := cli.ContainerCreate(ctx, |
| 77 | &container.Config{ |
| 78 | Image: e.Image, |
| 79 | WorkingDir: test.Command.Dir, |
| 80 | Env: env, |
| 81 | User: e.ExecUser, |
| 82 | Cmd: []string{"/bin/sh", "-c", test.Command.Cmd}, |
| 83 | Tty: false, |
| 84 | }, nil, nil, nil, "") |
| 85 | if err != nil { |
| 86 | test.Result.Error = fmt.Errorf("could not pull image '%s' with error: '%s'", e.Image, err) |
| 87 | return TestResult{ |
| 88 | TestCase: test, |
| 89 | } |