2
0

build.go 8.2 KB

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