build.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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. err := packAgent.Build(ctx, opts, buildConfig, "")
  134. if err != nil {
  135. output.Error = fmt.Errorf("error building image with pack: %w", err)
  136. logString := "Error reading contents of build log file"
  137. if logFile != nil {
  138. content, err := os.ReadFile(logFile.Name())
  139. // only continue if we can read the file. if we cannot, logString will be the default
  140. if err == nil {
  141. logString = string(content)
  142. }
  143. }
  144. output.Logs = logString
  145. return output
  146. }
  147. default:
  148. output.Error = fmt.Errorf("invalid build method: %s", inp.BuildMethod)
  149. return output
  150. }
  151. if !inp.SkipPush {
  152. err = dockerAgent.PushImage(ctx, fmt.Sprintf("%s:%s", repositoryURL, tag))
  153. if err != nil {
  154. output.Error = fmt.Errorf("error pushing image: %w", err)
  155. return output
  156. }
  157. }
  158. return output
  159. }
  160. type pushInput struct {
  161. ProjectID uint
  162. ImageTag string
  163. RepositoryURL string
  164. }
  165. func push(ctx context.Context, client api.Client, inp pushInput) error {
  166. if inp.ProjectID == 0 {
  167. return errors.New("must specify a project id")
  168. }
  169. projectID := inp.ProjectID
  170. if inp.ImageTag == "" {
  171. return errors.New("must specify an image tag")
  172. }
  173. tag := inp.ImageTag
  174. if inp.RepositoryURL == "" {
  175. return errors.New("must specify a registry url")
  176. }
  177. repositoryURL := strings.TrimPrefix(inp.RepositoryURL, "https://")
  178. dockerAgent, err := docker.NewAgentWithAuthGetter(ctx, client, projectID)
  179. if err != nil {
  180. return fmt.Errorf("error getting docker agent: %w", err)
  181. }
  182. err = dockerAgent.PushImage(ctx, fmt.Sprintf("%s:%s", repositoryURL, tag))
  183. if err != nil {
  184. return fmt.Errorf("error pushing image: %w", err)
  185. }
  186. return nil
  187. }
  188. func createImageRepositoryIfNotExists(ctx context.Context, client api.Client, projectID uint, imageURL string) error {
  189. if projectID == 0 {
  190. return errors.New("must specify a project id")
  191. }
  192. if imageURL == "" {
  193. return errors.New("must specify an image url")
  194. }
  195. regList, err := client.ListRegistries(ctx, projectID)
  196. if err != nil {
  197. return fmt.Errorf("error calling list registries: %w", err)
  198. }
  199. if regList == nil {
  200. return errors.New("registry list is nil")
  201. }
  202. if len(*regList) == 0 {
  203. return errors.New("no registries found for project")
  204. }
  205. var registryID uint
  206. for _, registry := range *regList {
  207. if strings.Contains(strings.TrimPrefix(imageURL, "https://"), strings.TrimPrefix(registry.URL, "https://")) {
  208. registryID = registry.ID
  209. break
  210. }
  211. }
  212. if registryID == 0 {
  213. return errors.New("no registries match url")
  214. }
  215. err = client.CreateRepository(
  216. ctx,
  217. projectID,
  218. registryID,
  219. &types.CreateRegistryRepositoryRequest{
  220. ImageRepoURI: imageURL,
  221. },
  222. )
  223. if err != nil {
  224. return fmt.Errorf("error creating repository: %w", err)
  225. }
  226. return nil
  227. }
  228. // resolveDockerPaths returns a path to the dockerfile that is either relative or absolute, and a path
  229. // to the build context that is absolute.
  230. //
  231. // The return value will be relative if the dockerfile exists within the build context, absolute
  232. // otherwise. The second return value is true if the dockerfile exists within the build context,
  233. // false otherwise.
  234. func resolveDockerPaths(basePath string, buildContextPath string, dockerfilePath string) (
  235. absoluteBuildContextPath string,
  236. outputDockerfilePath string,
  237. isDockerfileRelative bool,
  238. err error,
  239. ) {
  240. absoluteBuildContextPath, err = filepath.Abs(buildContextPath)
  241. if err != nil {
  242. return "", "", false, fmt.Errorf("error getting absolute path: %w", err)
  243. }
  244. outputDockerfilePath = dockerfilePath
  245. if !filepath.IsAbs(dockerfilePath) {
  246. outputDockerfilePath = filepath.Join(basePath, dockerfilePath)
  247. }
  248. pathComp, err := filepath.Rel(absoluteBuildContextPath, outputDockerfilePath)
  249. if err != nil {
  250. return "", "", false, fmt.Errorf("error getting relative path: %w", err)
  251. }
  252. if !strings.HasPrefix(pathComp, ".."+string(os.PathSeparator)) {
  253. isDockerfileRelative = true
  254. return absoluteBuildContextPath, pathComp, isDockerfileRelative, nil
  255. }
  256. isDockerfileRelative = false
  257. outputDockerfilePath, err = filepath.Abs(outputDockerfilePath)
  258. if err != nil {
  259. return "", "", false, err
  260. }
  261. return absoluteBuildContextPath, outputDockerfilePath, isDockerfileRelative, nil
  262. }