build.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. package v2
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. "github.com/porter-dev/porter/api/types"
  10. "github.com/porter-dev/porter/cli/cmd/pack"
  11. "github.com/porter-dev/porter/cli/cmd/docker"
  12. api "github.com/porter-dev/porter/api/client"
  13. )
  14. const (
  15. buildMethodPack = "pack"
  16. buildMethodDocker = "docker"
  17. )
  18. // buildInput is the input struct for the build method
  19. type buildInput struct {
  20. ProjectID uint
  21. // AppName is the name of the application being built and is used to name the repository
  22. AppName string
  23. BuildContext string
  24. Dockerfile string
  25. BuildMethod string
  26. // Builder is the image containing the components necessary to build the application in a pack build
  27. Builder string
  28. BuildPacks []string
  29. // ImageTag is the tag to apply to the new image
  30. ImageTag string
  31. // CurrentImageTag is used in docker build to cache from
  32. CurrentImageTag string
  33. RepositoryURL string
  34. }
  35. // build will create an image repository if it does not exist, and then build and push the image
  36. func build(ctx context.Context, client *api.Client, inp buildInput) error {
  37. if inp.ProjectID == 0 {
  38. return errors.New("must specify a project id")
  39. }
  40. projectID := inp.ProjectID
  41. if inp.ImageTag == "" {
  42. return errors.New("must specify an image tag")
  43. }
  44. tag := inp.ImageTag
  45. if inp.RepositoryURL == "" {
  46. return errors.New("must specify a registry url")
  47. }
  48. imageURL := strings.TrimPrefix(inp.RepositoryURL, "https://")
  49. err := createImageRepositoryIfNotExists(ctx, client, projectID, imageURL)
  50. if err != nil {
  51. return fmt.Errorf("error creating image repository: %w", err)
  52. }
  53. dockerAgent, err := docker.NewAgentWithAuthGetter(client, projectID)
  54. if err != nil {
  55. return fmt.Errorf("error getting docker agent: %w", err)
  56. }
  57. switch inp.BuildMethod {
  58. case buildMethodDocker:
  59. basePath, err := filepath.Abs(".")
  60. if err != nil {
  61. return fmt.Errorf("error getting absolute path: %w", err)
  62. }
  63. buildCtx, dockerfilePath, isDockerfileInCtx, err := resolveDockerPaths(
  64. basePath,
  65. inp.BuildContext,
  66. inp.Dockerfile,
  67. )
  68. if err != nil {
  69. return fmt.Errorf("error resolving docker paths: %w", err)
  70. }
  71. opts := &docker.BuildOpts{
  72. ImageRepo: inp.RepositoryURL,
  73. Tag: tag,
  74. CurrentTag: inp.CurrentImageTag,
  75. BuildContext: buildCtx,
  76. DockerfilePath: dockerfilePath,
  77. IsDockerfileInCtx: isDockerfileInCtx,
  78. }
  79. err = dockerAgent.BuildLocal(
  80. opts,
  81. )
  82. if err != nil {
  83. return fmt.Errorf("error building image with docker: %w", err)
  84. }
  85. case buildMethodPack:
  86. packAgent := &pack.Agent{}
  87. opts := &docker.BuildOpts{
  88. ImageRepo: imageURL,
  89. Tag: tag,
  90. BuildContext: inp.BuildContext,
  91. }
  92. buildConfig := &types.BuildConfig{
  93. Builder: inp.Builder,
  94. Buildpacks: inp.BuildPacks,
  95. }
  96. err := packAgent.Build(opts, buildConfig, "")
  97. if err != nil {
  98. return fmt.Errorf("error building image with pack: %w", err)
  99. }
  100. default:
  101. return fmt.Errorf("invalid build method: %s", inp.BuildMethod)
  102. }
  103. err = dockerAgent.PushImage(fmt.Sprintf("%s:%s", imageURL, tag))
  104. if err != nil {
  105. return fmt.Errorf("error pushing image url: %w\n", err)
  106. }
  107. return nil
  108. }
  109. func createImageRepositoryIfNotExists(ctx context.Context, client *api.Client, projectID uint, imageURL string) error {
  110. if projectID == 0 {
  111. return errors.New("must specify a project id")
  112. }
  113. if imageURL == "" {
  114. return errors.New("must specify an image url")
  115. }
  116. regList, err := client.ListRegistries(ctx, projectID)
  117. if err != nil {
  118. return fmt.Errorf("error calling list registries: %w", err)
  119. }
  120. if regList == nil {
  121. return errors.New("registry list is nil")
  122. }
  123. if len(*regList) == 0 {
  124. return errors.New("no registries found for project")
  125. }
  126. var registryID uint
  127. for _, registry := range *regList {
  128. if strings.Contains(strings.TrimPrefix(imageURL, "https://"), strings.TrimPrefix(registry.URL, "https://")) {
  129. registryID = registry.ID
  130. break
  131. }
  132. }
  133. if registryID == 0 {
  134. return errors.New("no registries match url")
  135. }
  136. err = client.CreateRepository(
  137. ctx,
  138. projectID,
  139. registryID,
  140. &types.CreateRegistryRepositoryRequest{
  141. ImageRepoURI: imageURL,
  142. },
  143. )
  144. if err != nil {
  145. return fmt.Errorf("error creating repository: %w", err)
  146. }
  147. return nil
  148. }
  149. // resolveDockerPaths returns a path to the dockerfile that is either relative or absolute, and a path
  150. // to the build context that is absolute.
  151. //
  152. // The return value will be relative if the dockerfile exists within the build context, absolute
  153. // otherwise. The second return value is true if the dockerfile exists within the build context,
  154. // false otherwise.
  155. func resolveDockerPaths(basePath string, buildContextPath string, dockerfilePath string) (
  156. absoluteBuildContextPath string,
  157. outputDockerfilePath string,
  158. isDockerfileRelative bool,
  159. err error,
  160. ) {
  161. absoluteBuildContextPath, err = filepath.Abs(buildContextPath)
  162. if err != nil {
  163. return "", "", false, fmt.Errorf("error getting absolute path: %w", err)
  164. }
  165. outputDockerfilePath = dockerfilePath
  166. if !filepath.IsAbs(dockerfilePath) {
  167. outputDockerfilePath = filepath.Join(basePath, dockerfilePath)
  168. }
  169. pathComp, err := filepath.Rel(absoluteBuildContextPath, outputDockerfilePath)
  170. if err != nil {
  171. return "", "", false, fmt.Errorf("error getting relative path: %w", err)
  172. }
  173. if !strings.HasPrefix(pathComp, ".."+string(os.PathSeparator)) {
  174. isDockerfileRelative = true
  175. return absoluteBuildContextPath, pathComp, isDockerfileRelative, nil
  176. }
  177. isDockerfileRelative = false
  178. outputDockerfilePath, err = filepath.Abs(outputDockerfilePath)
  179. if err != nil {
  180. return "", "", false, err
  181. }
  182. return absoluteBuildContextPath, outputDockerfilePath, isDockerfileRelative, nil
  183. }