build_image_driver.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. package preview
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "strings"
  8. "github.com/cli/cli/git"
  9. "github.com/docker/distribution/reference"
  10. "github.com/mitchellh/mapstructure"
  11. "github.com/porter-dev/porter/api/types"
  12. "github.com/porter-dev/porter/cli/cmd/config"
  13. "github.com/porter-dev/porter/cli/cmd/deploy"
  14. "github.com/porter-dev/porter/cli/cmd/docker"
  15. "github.com/porter-dev/switchboard/pkg/drivers"
  16. "github.com/porter-dev/switchboard/pkg/models"
  17. )
  18. type BuildDriverConfig struct {
  19. Build struct {
  20. ForceBuild bool `mapstructure:"force_build"`
  21. UsePackCache bool `mapstructure:"use_pack_cache"`
  22. Method string
  23. Context string
  24. Dockerfile string
  25. Builder string
  26. Buildpacks []string
  27. Image string
  28. }
  29. EnvGroups []types.EnvGroupMeta `mapstructure:"env_groups"`
  30. Values map[string]interface{}
  31. }
  32. type BuildDriver struct {
  33. source *Source
  34. target *Target
  35. config *BuildDriverConfig
  36. lookupTable *map[string]drivers.Driver
  37. output map[string]interface{}
  38. }
  39. func NewBuildDriver(resource *models.Resource, opts *drivers.SharedDriverOpts) (drivers.Driver, error) {
  40. driver := &BuildDriver{
  41. lookupTable: opts.DriverLookupTable,
  42. output: make(map[string]interface{}),
  43. }
  44. source, err := GetSource(resource.Source)
  45. if err != nil {
  46. return nil, err
  47. }
  48. driver.source = source
  49. target, err := GetTarget(resource.Target)
  50. if err != nil {
  51. return nil, err
  52. }
  53. if target.AppName == "" {
  54. return nil, fmt.Errorf("target app_name is missing")
  55. }
  56. driver.target = target
  57. return driver, nil
  58. }
  59. func (d *BuildDriver) ShouldApply(resource *models.Resource) bool {
  60. return true
  61. }
  62. func (d *BuildDriver) Apply(resource *models.Resource) (*models.Resource, error) {
  63. buildDriverConfig, err := d.getConfig(resource)
  64. if err != nil {
  65. return nil, err
  66. }
  67. d.config = buildDriverConfig
  68. client := config.GetAPIClient()
  69. // FIXME: give tag option in config build, but override if PORTER_TAG is present
  70. tag := os.Getenv("PORTER_TAG")
  71. if tag == "" {
  72. commit, err := git.LastCommit()
  73. if err != nil {
  74. return nil, err
  75. }
  76. tag = commit.Sha[:7]
  77. }
  78. // if the method is registry and a tag is defined, we use the provided tag
  79. if d.config.Build.Method == "registry" {
  80. imageSpl := strings.Split(d.config.Build.Image, ":")
  81. if len(imageSpl) == 2 {
  82. tag = imageSpl[1]
  83. }
  84. if tag == "" {
  85. tag = "latest"
  86. }
  87. }
  88. regList, err := client.ListRegistries(context.Background(), d.target.Project)
  89. if err != nil {
  90. return nil, err
  91. }
  92. var registryURL string
  93. if len(*regList) == 0 {
  94. return nil, fmt.Errorf("no registry found")
  95. } else {
  96. registryURL = (*regList)[0].URL
  97. }
  98. var repoSuffix string
  99. if repoName := os.Getenv("PORTER_REPO_NAME"); repoName != "" {
  100. if repoOwner := os.Getenv("PORTER_REPO_OWNER"); repoOwner != "" {
  101. repoSuffix = strings.ReplaceAll(fmt.Sprintf("%s-%s", repoOwner, repoName), "_", "-")
  102. }
  103. }
  104. createAgent := &deploy.CreateAgent{
  105. Client: client,
  106. CreateOpts: &deploy.CreateOpts{
  107. SharedOpts: &deploy.SharedOpts{
  108. ProjectID: d.target.Project,
  109. ClusterID: d.target.Cluster,
  110. OverrideTag: tag,
  111. Namespace: d.target.Namespace,
  112. LocalPath: d.config.Build.Context,
  113. LocalDockerfile: d.config.Build.Dockerfile,
  114. Method: deploy.DeployBuildType(d.config.Build.Method),
  115. EnvGroups: d.config.EnvGroups,
  116. UseCache: d.config.Build.UsePackCache,
  117. },
  118. Kind: d.source.Name,
  119. ReleaseName: d.target.AppName,
  120. RegistryURL: registryURL,
  121. RepoSuffix: repoSuffix,
  122. },
  123. }
  124. regID, imageURL, err := createAgent.GetImageRepoURL(d.target.AppName, d.target.Namespace)
  125. if err != nil {
  126. return nil, err
  127. }
  128. if d.config.Build.UsePackCache {
  129. err := config.SetDockerConfig(client)
  130. if err != nil {
  131. return nil, err
  132. }
  133. if d.config.Build.Method == "pack" {
  134. repoResp, err := client.ListRegistryRepositories(context.Background(), d.target.Project, regID)
  135. if err != nil {
  136. return nil, err
  137. }
  138. repos := *repoResp
  139. found := false
  140. for _, repo := range repos {
  141. if repo.URI == imageURL {
  142. found = true
  143. break
  144. }
  145. }
  146. if !found {
  147. err = client.CreateRepository(
  148. context.Background(),
  149. d.target.Project,
  150. regID,
  151. &types.CreateRegistryRepositoryRequest{
  152. ImageRepoURI: imageURL,
  153. },
  154. )
  155. if err != nil {
  156. return nil, err
  157. }
  158. }
  159. }
  160. }
  161. if d.config.Build.Method != "" {
  162. if d.config.Build.Method == string(deploy.DeployBuildTypeDocker) {
  163. if d.config.Build.Dockerfile == "" {
  164. hasDockerfile := createAgent.HasDefaultDockerfile(d.config.Build.Context)
  165. if !hasDockerfile {
  166. return nil, fmt.Errorf("dockerfile not found")
  167. }
  168. d.config.Build.Dockerfile = "Dockerfile"
  169. }
  170. }
  171. } else {
  172. // try to detect dockerfile, otherwise fall back to `pack`
  173. hasDockerfile := createAgent.HasDefaultDockerfile(d.config.Build.Context)
  174. if !hasDockerfile {
  175. d.config.Build.Method = string(deploy.DeployBuildTypePack)
  176. } else {
  177. d.config.Build.Method = string(deploy.DeployBuildTypeDocker)
  178. d.config.Build.Dockerfile = "Dockerfile"
  179. }
  180. }
  181. // create docker agent
  182. agent, err := docker.NewAgentWithAuthGetter(client, d.target.Project)
  183. if err != nil {
  184. return nil, err
  185. }
  186. imageExists := agent.CheckIfImageExists(imageURL, tag) // FIXME: does not seem to work with gcr.io images
  187. if imageExists && tag != "latest" && !d.config.Build.ForceBuild {
  188. fmt.Printf("%s:%s already exists in the registry, so skipping build\n", imageURL, tag)
  189. } else {
  190. _, mergedValues, err := createAgent.GetMergedValues(d.config.Values)
  191. if err != nil {
  192. return nil, err
  193. }
  194. env, err := deploy.GetEnvForRelease(
  195. client,
  196. mergedValues,
  197. d.target.Project,
  198. d.target.Cluster,
  199. d.target.Namespace,
  200. )
  201. if err != nil {
  202. env = map[string]string{}
  203. }
  204. buildEnv, err := deploy.GetNestedMap(mergedValues, "container", "env", "build")
  205. if err == nil {
  206. for key, val := range buildEnv {
  207. if valStr, ok := val.(string); ok {
  208. env[key] = valStr
  209. }
  210. }
  211. }
  212. buildAgent := &deploy.BuildAgent{
  213. SharedOpts: createAgent.CreateOpts.SharedOpts,
  214. APIClient: client,
  215. ImageRepo: imageURL,
  216. Env: env,
  217. ImageExists: false,
  218. }
  219. if d.config.Build.Method == string(deploy.DeployBuildTypeDocker) {
  220. basePath, err := filepath.Abs(".")
  221. if err != nil {
  222. return nil, err
  223. }
  224. err = buildAgent.BuildDocker(
  225. agent,
  226. basePath,
  227. d.config.Build.Context,
  228. d.config.Build.Dockerfile,
  229. tag,
  230. "",
  231. )
  232. } else {
  233. var buildConfig *types.BuildConfig
  234. if d.config.Build.Builder != "" {
  235. buildConfig = &types.BuildConfig{
  236. Builder: d.config.Build.Builder,
  237. Buildpacks: d.config.Build.Buildpacks,
  238. }
  239. }
  240. err = buildAgent.BuildPack(
  241. agent,
  242. d.config.Build.Context,
  243. tag,
  244. "",
  245. buildConfig,
  246. )
  247. }
  248. if err != nil {
  249. return nil, err
  250. }
  251. }
  252. named, _ := reference.ParseNamed(imageURL)
  253. domain := reference.Domain(named)
  254. imageRepo := reference.Path(named)
  255. d.output["registry_url"] = domain
  256. d.output["image_repo"] = imageRepo
  257. d.output["image_tag"] = tag
  258. d.output["image"] = fmt.Sprintf("%s:%s", imageURL, tag)
  259. return resource, nil
  260. }
  261. func (d *BuildDriver) Output() (map[string]interface{}, error) {
  262. return d.output, nil
  263. }
  264. func (d *BuildDriver) getConfig(resource *models.Resource) (*BuildDriverConfig, error) {
  265. populatedConf, err := drivers.ConstructConfig(&drivers.ConstructConfigOpts{
  266. RawConf: resource.Config,
  267. LookupTable: *d.lookupTable,
  268. Dependencies: resource.Dependencies,
  269. })
  270. if err != nil {
  271. return nil, err
  272. }
  273. config := &BuildDriverConfig{}
  274. err = mapstructure.Decode(populatedConf, config)
  275. if err != nil {
  276. return nil, err
  277. }
  278. return config, nil
  279. }