build.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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. repositoryURL := strings.TrimPrefix(inp.RepositoryURL, "https://")
  59. err := createImageRepositoryIfNotExists(ctx, client, projectID, repositoryURL)
  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. // create a temp file which build logs will be written to
  70. // temp file gets cleaned up when os exits (i.e. when the GHA completes), so no need to remove it manually
  71. logFile, _ := os.CreateTemp("", buildLogFilename)
  72. switch inp.BuildMethod {
  73. case buildMethodDocker:
  74. basePath, err := filepath.Abs(".")
  75. if err != nil {
  76. output.Error = fmt.Errorf("error getting absolute path: %w", err)
  77. return output
  78. }
  79. buildCtx, dockerfilePath, isDockerfileInCtx, err := resolveDockerPaths(
  80. basePath,
  81. inp.BuildContext,
  82. inp.Dockerfile,
  83. )
  84. if err != nil {
  85. output.Error = fmt.Errorf("error resolving docker paths: %w", err)
  86. return output
  87. }
  88. opts := &docker.BuildOpts{
  89. ImageRepo: 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: repositoryURL,
  119. Tag: tag,
  120. BuildContext: inp.BuildContext,
  121. Env: inp.Env,
  122. LogFile: logFile,
  123. }
  124. buildConfig := &types.BuildConfig{
  125. Builder: inp.Builder,
  126. Buildpacks: inp.BuildPacks,
  127. }
  128. err := packAgent.Build(ctx, opts, buildConfig, "")
  129. if err != nil {
  130. output.Error = fmt.Errorf("error building image with pack: %w", err)
  131. logString := "Error reading contents of build log file"
  132. if logFile != nil {
  133. content, err := os.ReadFile(logFile.Name())
  134. // only continue if we can read the file. if we cannot, logString will be the default
  135. if err == nil {
  136. logString = string(content)
  137. }
  138. }
  139. output.Logs = logString
  140. return output
  141. }
  142. default:
  143. output.Error = fmt.Errorf("invalid build method: %s", inp.BuildMethod)
  144. return output
  145. }
  146. err = dockerAgent.PushImage(ctx, fmt.Sprintf("%s:%s", repositoryURL, tag))
  147. if err != nil {
  148. output.Error = fmt.Errorf("error pushing image: %w", err)
  149. return output
  150. }
  151. return output
  152. }
  153. func createImageRepositoryIfNotExists(ctx context.Context, client api.Client, projectID uint, imageURL string) error {
  154. if projectID == 0 {
  155. return errors.New("must specify a project id")
  156. }
  157. if imageURL == "" {
  158. return errors.New("must specify an image url")
  159. }
  160. regList, err := client.ListRegistries(ctx, projectID)
  161. if err != nil {
  162. return fmt.Errorf("error calling list registries: %w", err)
  163. }
  164. if regList == nil {
  165. return errors.New("registry list is nil")
  166. }
  167. if len(*regList) == 0 {
  168. return errors.New("no registries found for project")
  169. }
  170. var registryID uint
  171. for _, registry := range *regList {
  172. if strings.Contains(strings.TrimPrefix(imageURL, "https://"), strings.TrimPrefix(registry.URL, "https://")) {
  173. registryID = registry.ID
  174. break
  175. }
  176. }
  177. if registryID == 0 {
  178. return errors.New("no registries match url")
  179. }
  180. err = client.CreateRepository(
  181. ctx,
  182. projectID,
  183. registryID,
  184. &types.CreateRegistryRepositoryRequest{
  185. ImageRepoURI: imageURL,
  186. },
  187. )
  188. if err != nil {
  189. return fmt.Errorf("error creating repository: %w", err)
  190. }
  191. return nil
  192. }
  193. // resolveDockerPaths returns a path to the dockerfile that is either relative or absolute, and a path
  194. // to the build context that is absolute.
  195. //
  196. // The return value will be relative if the dockerfile exists within the build context, absolute
  197. // otherwise. The second return value is true if the dockerfile exists within the build context,
  198. // false otherwise.
  199. func resolveDockerPaths(basePath string, buildContextPath string, dockerfilePath string) (
  200. absoluteBuildContextPath string,
  201. outputDockerfilePath string,
  202. isDockerfileRelative bool,
  203. err error,
  204. ) {
  205. absoluteBuildContextPath, err = filepath.Abs(buildContextPath)
  206. if err != nil {
  207. return "", "", false, fmt.Errorf("error getting absolute path: %w", err)
  208. }
  209. outputDockerfilePath = dockerfilePath
  210. if !filepath.IsAbs(dockerfilePath) {
  211. outputDockerfilePath = filepath.Join(basePath, dockerfilePath)
  212. }
  213. pathComp, err := filepath.Rel(absoluteBuildContextPath, outputDockerfilePath)
  214. if err != nil {
  215. return "", "", false, fmt.Errorf("error getting relative path: %w", err)
  216. }
  217. if !strings.HasPrefix(pathComp, ".."+string(os.PathSeparator)) {
  218. isDockerfileRelative = true
  219. return absoluteBuildContextPath, pathComp, isDockerfileRelative, nil
  220. }
  221. isDockerfileRelative = false
  222. outputDockerfilePath, err = filepath.Abs(outputDockerfilePath)
  223. if err != nil {
  224. return "", "", false, err
  225. }
  226. return absoluteBuildContextPath, outputDockerfilePath, isDockerfileRelative, nil
  227. }