build.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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. buildLogFilename = "PORTER_BUILD_LOGS"
  18. )
  19. // buildInput is the input struct for the build method
  20. type buildInput struct {
  21. ProjectID uint
  22. // AppName is the name of the application being built and is used to name the repository
  23. AppName string
  24. BuildContext string
  25. Dockerfile string
  26. BuildMethod string
  27. // Builder is the image containing the components necessary to build the application in a pack build
  28. Builder string
  29. BuildPacks []string
  30. // ImageTag is the tag to apply to the new image
  31. ImageTag string
  32. // CurrentImageTag is used in docker build to cache from
  33. CurrentImageTag string
  34. RepositoryURL string
  35. Env map[string]string
  36. }
  37. type buildOutput struct {
  38. Error error
  39. Logs string
  40. }
  41. // build will create an image repository if it does not exist, and then build and push the image
  42. func build(ctx context.Context, client api.Client, inp buildInput) buildOutput {
  43. output := buildOutput{}
  44. if inp.ProjectID == 0 {
  45. output.Error = errors.New("must specify a project id")
  46. return output
  47. }
  48. projectID := inp.ProjectID
  49. if inp.ImageTag == "" {
  50. output.Error = errors.New("must specify an image tag")
  51. return output
  52. }
  53. tag := inp.ImageTag
  54. if inp.RepositoryURL == "" {
  55. output.Error = errors.New("must specify a registry url")
  56. return output
  57. }
  58. imageURL := strings.TrimPrefix(inp.RepositoryURL, "https://")
  59. err := createImageRepositoryIfNotExists(ctx, client, projectID, imageURL)
  60. if err != nil {
  61. output.Error = fmt.Errorf("error creating image repository: %w", err)
  62. return output
  63. }
  64. dockerAgent, err := docker.NewAgentWithAuthGetter(ctx, client, projectID)
  65. if err != nil {
  66. output.Error = fmt.Errorf("error getting docker agent: %w", err)
  67. return output
  68. }
  69. switch inp.BuildMethod {
  70. case buildMethodDocker:
  71. basePath, err := filepath.Abs(".")
  72. if err != nil {
  73. output.Error = fmt.Errorf("error getting absolute path: %w", err)
  74. return output
  75. }
  76. buildCtx, dockerfilePath, isDockerfileInCtx, err := resolveDockerPaths(
  77. basePath,
  78. inp.BuildContext,
  79. inp.Dockerfile,
  80. )
  81. if err != nil {
  82. output.Error = fmt.Errorf("error resolving docker paths: %w", err)
  83. return output
  84. }
  85. // create a temp file which build logs will be written to
  86. // temp file gets cleaned up when os exits (i.e. when the GHA completes), so no need to remove it manually
  87. logFile, _ := os.CreateTemp("", buildLogFilename)
  88. opts := &docker.BuildOpts{
  89. ImageRepo: inp.RepositoryURL,
  90. Tag: tag,
  91. CurrentTag: inp.CurrentImageTag,
  92. BuildContext: buildCtx,
  93. DockerfilePath: dockerfilePath,
  94. IsDockerfileInCtx: isDockerfileInCtx,
  95. Env: inp.Env,
  96. LogFile: logFile,
  97. }
  98. err = dockerAgent.BuildLocal(
  99. ctx,
  100. opts,
  101. )
  102. if err != nil {
  103. output.Error = fmt.Errorf("error building image with docker: %w", err)
  104. logString := "Error reading contents of build log file"
  105. if logFile != nil {
  106. content, err := os.ReadFile(logFile.Name())
  107. // only continue if we can read the file. if we cannot, logString will be the default
  108. if err == nil {
  109. logString = string(content)
  110. }
  111. }
  112. output.Logs = logString
  113. return output
  114. }
  115. case buildMethodPack:
  116. packAgent := &pack.Agent{}
  117. opts := &docker.BuildOpts{
  118. ImageRepo: imageURL,
  119. Tag: tag,
  120. BuildContext: inp.BuildContext,
  121. Env: inp.Env,
  122. }
  123. buildConfig := &types.BuildConfig{
  124. Builder: inp.Builder,
  125. Buildpacks: inp.BuildPacks,
  126. }
  127. err := packAgent.Build(ctx, opts, buildConfig, "")
  128. if err != nil {
  129. output.Error = fmt.Errorf("error building image with pack: %w", err)
  130. return output
  131. }
  132. default:
  133. output.Error = fmt.Errorf("invalid build method: %s", inp.BuildMethod)
  134. return output
  135. }
  136. err = dockerAgent.PushImage(ctx, fmt.Sprintf("%s:%s", imageURL, tag))
  137. if err != nil {
  138. output.Error = fmt.Errorf("error pushing image: %w", err)
  139. return output
  140. }
  141. return output
  142. }
  143. func createImageRepositoryIfNotExists(ctx context.Context, client api.Client, projectID uint, imageURL string) error {
  144. if projectID == 0 {
  145. return errors.New("must specify a project id")
  146. }
  147. if imageURL == "" {
  148. return errors.New("must specify an image url")
  149. }
  150. regList, err := client.ListRegistries(ctx, projectID)
  151. if err != nil {
  152. return fmt.Errorf("error calling list registries: %w", err)
  153. }
  154. if regList == nil {
  155. return errors.New("registry list is nil")
  156. }
  157. if len(*regList) == 0 {
  158. return errors.New("no registries found for project")
  159. }
  160. var registryID uint
  161. for _, registry := range *regList {
  162. if strings.Contains(strings.TrimPrefix(imageURL, "https://"), strings.TrimPrefix(registry.URL, "https://")) {
  163. registryID = registry.ID
  164. break
  165. }
  166. }
  167. if registryID == 0 {
  168. return errors.New("no registries match url")
  169. }
  170. err = client.CreateRepository(
  171. ctx,
  172. projectID,
  173. registryID,
  174. &types.CreateRegistryRepositoryRequest{
  175. ImageRepoURI: imageURL,
  176. },
  177. )
  178. if err != nil {
  179. return fmt.Errorf("error creating repository: %w", err)
  180. }
  181. return nil
  182. }
  183. // resolveDockerPaths returns a path to the dockerfile that is either relative or absolute, and a path
  184. // to the build context that is absolute.
  185. //
  186. // The return value will be relative if the dockerfile exists within the build context, absolute
  187. // otherwise. The second return value is true if the dockerfile exists within the build context,
  188. // false otherwise.
  189. func resolveDockerPaths(basePath string, buildContextPath string, dockerfilePath string) (
  190. absoluteBuildContextPath string,
  191. outputDockerfilePath string,
  192. isDockerfileRelative bool,
  193. err error,
  194. ) {
  195. absoluteBuildContextPath, err = filepath.Abs(buildContextPath)
  196. if err != nil {
  197. return "", "", false, fmt.Errorf("error getting absolute path: %w", err)
  198. }
  199. outputDockerfilePath = dockerfilePath
  200. if !filepath.IsAbs(dockerfilePath) {
  201. outputDockerfilePath = filepath.Join(basePath, dockerfilePath)
  202. }
  203. pathComp, err := filepath.Rel(absoluteBuildContextPath, outputDockerfilePath)
  204. if err != nil {
  205. return "", "", false, fmt.Errorf("error getting relative path: %w", err)
  206. }
  207. if !strings.HasPrefix(pathComp, ".."+string(os.PathSeparator)) {
  208. isDockerfileRelative = true
  209. return absoluteBuildContextPath, pathComp, isDockerfileRelative, nil
  210. }
  211. isDockerfileRelative = false
  212. outputDockerfilePath, err = filepath.Abs(outputDockerfilePath)
  213. if err != nil {
  214. return "", "", false, err
  215. }
  216. return absoluteBuildContextPath, outputDockerfilePath, isDockerfileRelative, nil
  217. }