builder.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. package docker
  2. import (
  3. "archive/tar"
  4. "bytes"
  5. "context"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. "log"
  11. "os"
  12. "os/exec"
  13. "path/filepath"
  14. "time"
  15. "github.com/docker/docker/api/types"
  16. "github.com/docker/docker/pkg/archive"
  17. "github.com/docker/docker/pkg/fileutils"
  18. "github.com/moby/buildkit/frontend/dockerfile/dockerignore"
  19. "github.com/moby/moby/pkg/jsonmessage"
  20. "github.com/moby/moby/pkg/stringid"
  21. "github.com/moby/term"
  22. "mvdan.cc/sh/v3/shell"
  23. )
  24. type BuildOpts struct {
  25. ImageRepo string
  26. Tag string
  27. CurrentTag string
  28. BuildContext string
  29. DockerfilePath string
  30. IsDockerfileInCtx bool
  31. UseCache bool
  32. Env map[string]string
  33. LogFile *os.File
  34. }
  35. // BuildLocal builds a Dockerfile using the local Docker daemon
  36. func (a *Agent) BuildLocal(ctx context.Context, opts *BuildOpts) (err error) {
  37. if opts == nil {
  38. return errors.New("build opts cannot be nil")
  39. }
  40. if opts.UseCache {
  41. err = a.PullImage(ctx, fmt.Sprintf("%s:%s", opts.ImageRepo, opts.CurrentTag))
  42. if err != nil {
  43. log.Printf("unable to pull image. Continuing with build: %s", err.Error())
  44. }
  45. }
  46. if os.Getenv("DOCKER_BUILDKIT") == "1" {
  47. return buildLocalWithBuildkit(ctx, *opts)
  48. }
  49. dockerfilePath := opts.DockerfilePath
  50. // attempt to read dockerignore file and paths
  51. dockerIgnoreBytes, _ := os.ReadFile(".dockerignore")
  52. var excludes []string
  53. if len(dockerIgnoreBytes) != 0 {
  54. excludes, err = dockerignore.ReadAll(bytes.NewBuffer(dockerIgnoreBytes))
  55. if err != nil {
  56. return fmt.Errorf("error reading .dockerignore: %w", err)
  57. }
  58. }
  59. excludes = trimBuildFilesFromExcludes(excludes, dockerfilePath)
  60. tar, err := archive.TarWithOptions(opts.BuildContext, &archive.TarOptions{
  61. ExcludePatterns: excludes,
  62. })
  63. if err != nil {
  64. return fmt.Errorf("error creating tar: %w", err)
  65. }
  66. var writer io.Writer = os.Stderr
  67. if opts.LogFile != nil {
  68. writer = io.MultiWriter(os.Stderr, opts.LogFile)
  69. }
  70. if !opts.IsDockerfileInCtx {
  71. dockerfileCtx, err := os.Open(dockerfilePath)
  72. if err != nil {
  73. return fmt.Errorf("error opening Dockerfile: %w", err)
  74. }
  75. defer dockerfileCtx.Close()
  76. // add the dockerfile to the build context
  77. tar, dockerfilePath, err = AddDockerfileToBuildContext(dockerfileCtx, tar)
  78. if err != nil {
  79. return fmt.Errorf("error adding Dockerfile to build context: %w", err)
  80. }
  81. }
  82. buildArgs := make(map[string]*string)
  83. for key, val := range opts.Env {
  84. valCopy := val
  85. buildArgs[key] = &valCopy
  86. }
  87. // attach BUILDKIT_INLINE_CACHE=1 by default, to take advantage of caching
  88. inlineCacheVal := "1"
  89. buildArgs["BUILDKIT_INLINE_CACHE"] = &inlineCacheVal
  90. out, err := a.ImageBuild(ctx, tar, types.ImageBuildOptions{
  91. Dockerfile: dockerfilePath,
  92. BuildArgs: buildArgs,
  93. Tags: []string{
  94. fmt.Sprintf("%s:%s", opts.ImageRepo, opts.Tag),
  95. },
  96. CacheFrom: []string{
  97. fmt.Sprintf("%s:%s", opts.ImageRepo, opts.CurrentTag),
  98. },
  99. Remove: true,
  100. Platform: "linux/amd64",
  101. })
  102. if err != nil {
  103. return fmt.Errorf("error building image: %w", err)
  104. }
  105. defer out.Body.Close()
  106. termFd, isTerm := term.GetFdInfo(os.Stderr)
  107. return jsonmessage.DisplayJSONMessagesStream(out.Body, writer, termFd, isTerm, nil)
  108. }
  109. func trimBuildFilesFromExcludes(excludes []string, dockerfile string) []string {
  110. if keep, _ := fileutils.Matches(".dockerignore", excludes); keep {
  111. excludes = append(excludes, "!.dockerignore")
  112. }
  113. if keep, _ := fileutils.Matches(dockerfile, excludes); keep {
  114. excludes = append(excludes, "!"+dockerfile)
  115. }
  116. return excludes
  117. }
  118. // AddDockerfileToBuildContext from a ReadCloser, returns a new archive and
  119. // the relative path to the dockerfile in the context.
  120. func AddDockerfileToBuildContext(dockerfileCtx io.ReadCloser, buildCtx io.ReadCloser) (io.ReadCloser, string, error) {
  121. file, err := ioutil.ReadAll(dockerfileCtx)
  122. dockerfileCtx.Close()
  123. if err != nil {
  124. return nil, "", err
  125. }
  126. now := time.Now()
  127. hdrTmpl := &tar.Header{
  128. Mode: 0o600,
  129. Uid: 0,
  130. Gid: 0,
  131. ModTime: now,
  132. Typeflag: tar.TypeReg,
  133. AccessTime: now,
  134. ChangeTime: now,
  135. }
  136. randomName := ".dockerfile." + stringid.GenerateRandomID()[:20]
  137. buildCtx = archive.ReplaceFileTarWrapper(buildCtx, map[string]archive.TarModifierFunc{
  138. // Add the dockerfile with a random filename
  139. randomName: func(_ string, h *tar.Header, content io.Reader) (*tar.Header, []byte, error) {
  140. return hdrTmpl, file, nil
  141. },
  142. // Update .dockerignore to include the random filename
  143. ".dockerignore": func(_ string, h *tar.Header, content io.Reader) (*tar.Header, []byte, error) {
  144. if h == nil {
  145. h = hdrTmpl
  146. }
  147. b := &bytes.Buffer{}
  148. if content != nil {
  149. if _, err := b.ReadFrom(content); err != nil {
  150. return nil, nil, err
  151. }
  152. } else {
  153. b.WriteString(".dockerignore")
  154. }
  155. b.WriteString("\n" + randomName + "\n")
  156. return h, b.Bytes(), nil
  157. },
  158. })
  159. return buildCtx, randomName, nil
  160. }
  161. func buildLocalWithBuildkit(ctx context.Context, opts BuildOpts) error {
  162. if _, err := exec.LookPath("docker"); err != nil {
  163. return fmt.Errorf("unable to find docker binary in PATH for buildkit build: %w", err)
  164. }
  165. // prepare Dockerfile if the location isn't inside the build context
  166. dockerfileName := opts.DockerfilePath
  167. if !opts.IsDockerfileInCtx {
  168. var err error
  169. dockerfileName, err = injectDockerfileIntoBuildContext(opts.BuildContext, opts.DockerfilePath)
  170. if err != nil {
  171. return fmt.Errorf("unable to inject Dockerfile into build context: %w", err)
  172. }
  173. }
  174. // parse any arguments
  175. var extraDockerArgs []string
  176. if buildkitArgs := os.Getenv("PORTER_BUILDKIT_ARGS"); buildkitArgs != "" {
  177. parsedFields, err := shell.Fields(buildkitArgs, func(name string) string {
  178. return os.Getenv(name)
  179. })
  180. if err != nil {
  181. return fmt.Errorf("error while parsing buildkit args: %w", err)
  182. }
  183. extraDockerArgs = parsedFields
  184. }
  185. commandArgs := []string{
  186. "build",
  187. "-f", dockerfileName,
  188. "--tag", fmt.Sprintf("%s:%s", opts.ImageRepo, opts.Tag),
  189. "--cache-from", fmt.Sprintf("%s:%s", opts.ImageRepo, opts.CurrentTag),
  190. }
  191. for key, val := range opts.Env {
  192. commandArgs = append(commandArgs, "--build-arg", fmt.Sprintf("%s=%s", key, val))
  193. }
  194. if !sliceContainsString(extraDockerArgs, "--platform") {
  195. commandArgs = append(commandArgs, "--platform", "linux/amd64")
  196. }
  197. commandArgs = append(commandArgs, extraDockerArgs...)
  198. // note: the path _must_ be the last argument
  199. commandArgs = append(commandArgs, opts.BuildContext)
  200. stdoutWriters := []io.Writer{os.Stdout}
  201. stderrWriters := []io.Writer{os.Stderr}
  202. if opts.LogFile != nil {
  203. stdoutWriters = append(stdoutWriters, opts.LogFile)
  204. stderrWriters = append(stderrWriters, opts.LogFile)
  205. }
  206. // #nosec G204 - The command is meant to be variable
  207. cmd := exec.CommandContext(ctx, "docker", commandArgs...)
  208. cmd.Dir = opts.BuildContext
  209. cmd.Stdout = io.MultiWriter(stdoutWriters...)
  210. cmd.Stderr = io.MultiWriter(stderrWriters...)
  211. if err := cmd.Start(); err != nil {
  212. return fmt.Errorf("unable to start the build command: %w", err)
  213. }
  214. exitCode := 0
  215. execErr := cmd.Wait()
  216. if execErr != nil {
  217. if exitError, ok := execErr.(*exec.ExitError); ok {
  218. exitCode = exitError.ExitCode()
  219. }
  220. }
  221. if err := ctx.Err(); err != nil && err == context.Canceled {
  222. return fmt.Errorf("build command canceled: %w", ctx.Err())
  223. }
  224. if err := ctx.Err(); err != nil {
  225. return fmt.Errorf("error while running build: %w", err)
  226. }
  227. if exitCode != 0 {
  228. return fmt.Errorf("build exited with non-zero exit code %d", exitCode)
  229. }
  230. if execErr != nil {
  231. return fmt.Errorf("error while running build: %w", execErr)
  232. }
  233. return nil
  234. }
  235. func injectDockerfileIntoBuildContext(buildContext string, dockerfilePath string) (string, error) {
  236. randomName := ".dockerfile." + stringid.GenerateRandomID()[:20]
  237. data := map[string]func() ([]byte, error){
  238. randomName: func() ([]byte, error) {
  239. return os.ReadFile(filepath.Clean(dockerfilePath))
  240. },
  241. ".dockerignore": func() ([]byte, error) {
  242. dockerignorePath := filepath.Join(buildContext, ".dockerignore")
  243. dockerignorePath = filepath.Clean(dockerignorePath)
  244. if _, err := os.Stat(dockerignorePath); errors.Is(err, os.ErrNotExist) {
  245. if err := os.WriteFile(dockerignorePath, []byte{}, os.FileMode(0o600)); err != nil {
  246. return []byte{}, err
  247. }
  248. }
  249. data, err := os.ReadFile(dockerignorePath)
  250. if err != nil {
  251. return data, err
  252. }
  253. b := bytes.NewBuffer(data)
  254. b.WriteString(".dockerignore")
  255. b.WriteString("\n" + randomName + "\n")
  256. return b.Bytes(), nil
  257. },
  258. }
  259. for filename, fn := range data {
  260. bytes, err := fn()
  261. if err != nil {
  262. return randomName, fmt.Errorf("failed to get file contents: %w", err)
  263. }
  264. return randomName, os.WriteFile(filepath.Join(buildContext, filename), bytes, os.FileMode(0o600))
  265. }
  266. return randomName, nil
  267. }
  268. // sliceContainsString implements slice.Contains and should be removed on upgrade to golang 1.21
  269. func sliceContainsString(haystack []string, needle string) bool {
  270. for _, value := range haystack {
  271. if value == needle {
  272. return true
  273. }
  274. }
  275. return false
  276. }