apply.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. package v2
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "errors"
  6. "fmt"
  7. "os"
  8. "path/filepath"
  9. "strconv"
  10. "github.com/cli/cli/git"
  11. "github.com/fatih/color"
  12. "github.com/porter-dev/api-contracts/generated/go/helpers"
  13. porterv1 "github.com/porter-dev/api-contracts/generated/go/porter/v1"
  14. api "github.com/porter-dev/porter/api/client"
  15. "github.com/porter-dev/porter/cli/cmd/config"
  16. )
  17. // Apply implements the functionality of the `porter apply` command for validate apply v2 projects
  18. func Apply(ctx context.Context, cliConf config.CLIConfig, client api.Client, porterYamlPath string) error {
  19. if len(porterYamlPath) == 0 {
  20. return fmt.Errorf("porter yaml is empty")
  21. }
  22. porterYaml, err := os.ReadFile(filepath.Clean(porterYamlPath))
  23. if err != nil {
  24. return fmt.Errorf("could not read porter yaml file: %w", err)
  25. }
  26. b64YAML := base64.StdEncoding.EncodeToString(porterYaml)
  27. parseResp, err := client.ParseYAML(ctx, cliConf.Project, cliConf.Cluster, b64YAML)
  28. if err != nil {
  29. return fmt.Errorf("error calling parse yaml endpoint: %w", err)
  30. }
  31. if parseResp.B64AppProto == "" {
  32. return errors.New("b64 app proto is empty")
  33. }
  34. targetResp, err := client.DefaultDeploymentTarget(ctx, cliConf.Project, cliConf.Cluster)
  35. if err != nil {
  36. return fmt.Errorf("error calling default deployment target endpoint: %w", err)
  37. }
  38. if targetResp.DeploymentTargetID == "" {
  39. return errors.New("deployment target id is empty")
  40. }
  41. var commitSHA string
  42. if os.Getenv("PORTER_COMMIT_SHA") != "" {
  43. commitSHA = os.Getenv("PORTER_COMMIT_SHA")
  44. } else if commit, err := git.LastCommit(); err == nil && commit != nil {
  45. commitSHA = commit.Sha
  46. }
  47. validateResp, err := client.ValidatePorterApp(ctx, cliConf.Project, cliConf.Cluster, parseResp.B64AppProto, targetResp.DeploymentTargetID, commitSHA)
  48. if err != nil {
  49. return fmt.Errorf("error calling validate endpoint: %w", err)
  50. }
  51. if validateResp.ValidatedBase64AppProto == "" {
  52. return errors.New("validated b64 app proto is empty")
  53. }
  54. base64AppProto := validateResp.ValidatedBase64AppProto
  55. createPorterAppDBEntryInp, err := createPorterAppDbEntryInputFromProtoAndEnv(validateResp.ValidatedBase64AppProto)
  56. if err != nil {
  57. return fmt.Errorf("error creating porter app db entry input from proto: %w", err)
  58. }
  59. err = client.CreatePorterAppDBEntry(ctx, cliConf.Project, cliConf.Cluster, createPorterAppDBEntryInp)
  60. if err != nil {
  61. return fmt.Errorf("error creating porter app db entry: %w", err)
  62. }
  63. base64AppProtoWithSubdomains, err := addPorterSubdomainsIfNecessary(ctx, client, cliConf.Project, cliConf.Cluster, base64AppProto)
  64. if err != nil {
  65. return fmt.Errorf("error creating subdomains: %w", err)
  66. }
  67. applyResp, err := client.ApplyPorterApp(ctx, cliConf.Project, cliConf.Cluster, base64AppProtoWithSubdomains, targetResp.DeploymentTargetID, "")
  68. if err != nil {
  69. return fmt.Errorf("error calling apply endpoint: %w", err)
  70. }
  71. if applyResp.AppRevisionId == "" {
  72. return errors.New("app revision id is empty")
  73. }
  74. if applyResp.CLIAction == porterv1.EnumCLIAction_ENUM_CLI_ACTION_BUILD {
  75. if commitSHA == "" {
  76. return errors.New("Build is required but commit SHA cannot be identified. Please set the PORTER_COMMIT_SHA environment variable or run apply in git repository with access to the git CLI.")
  77. }
  78. buildSettings, err := buildSettingsFromBase64AppProto(base64AppProto)
  79. if err != nil {
  80. return fmt.Errorf("error building settings from base64 app proto: %w", err)
  81. }
  82. currentAppRevisionResp, err := client.CurrentAppRevision(ctx, cliConf.Project, cliConf.Cluster, buildSettings.AppName, targetResp.DeploymentTargetID)
  83. if err != nil {
  84. return fmt.Errorf("error getting current app revision: %w", err)
  85. }
  86. if currentAppRevisionResp == nil {
  87. return errors.New("current app revision is nil")
  88. }
  89. appRevision := currentAppRevisionResp.AppRevision
  90. if appRevision.B64AppProto == "" {
  91. return errors.New("current app revision b64 app proto is empty")
  92. }
  93. currentImageTag, err := imageTagFromBase64AppProto(appRevision.B64AppProto)
  94. if err != nil {
  95. return fmt.Errorf("error getting image tag from current app revision: %w", err)
  96. }
  97. buildSettings.CurrentImageTag = currentImageTag
  98. buildSettings.ProjectID = cliConf.Project
  99. err = build(ctx, client, buildSettings)
  100. if err != nil {
  101. return fmt.Errorf("error building app: %w", err)
  102. }
  103. applyResp, err = client.ApplyPorterApp(ctx, cliConf.Project, cliConf.Cluster, "", "", applyResp.AppRevisionId)
  104. if err != nil {
  105. return fmt.Errorf("error calling apply endpoint after build: %w", err)
  106. }
  107. }
  108. if applyResp.CLIAction != porterv1.EnumCLIAction_ENUM_CLI_ACTION_NONE {
  109. return fmt.Errorf("unexpected CLI action: %s", applyResp.CLIAction)
  110. }
  111. color.New(color.FgGreen).Printf("Successfully applied Porter YAML as revision %v, next action: %v\n", applyResp.AppRevisionId, applyResp.CLIAction) // nolint:errcheck,gosec
  112. return nil
  113. }
  114. func createPorterAppDbEntryInputFromProtoAndEnv(base64AppProto string) (api.CreatePorterAppDBEntryInput, error) {
  115. var input api.CreatePorterAppDBEntryInput
  116. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  117. if err != nil {
  118. return input, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  119. }
  120. app := &porterv1.PorterApp{}
  121. err = helpers.UnmarshalContractObject(decoded, app)
  122. if err != nil {
  123. return input, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  124. }
  125. if app.Name == "" {
  126. return input, fmt.Errorf("app does not contain name")
  127. }
  128. input.AppName = app.Name
  129. if app.Build != nil {
  130. if os.Getenv("GITHUB_REPOSITORY_ID") == "" {
  131. input.Local = true
  132. return input, nil
  133. }
  134. gitRepoId, err := strconv.Atoi(os.Getenv("GITHUB_REPOSITORY_ID"))
  135. if err != nil {
  136. return input, fmt.Errorf("unable to parse GITHUB_REPOSITORY_ID to int: %w", err)
  137. }
  138. input.GitRepoID = uint(gitRepoId)
  139. input.GitRepoName = os.Getenv("GITHUB_REPOSITORY")
  140. input.GitBranch = os.Getenv("GITHUB_REF_NAME")
  141. input.PorterYamlPath = "porter.yaml"
  142. return input, nil
  143. }
  144. if app.Image != nil {
  145. input.ImageRepository = app.Image.Repository
  146. input.ImageTag = app.Image.Tag
  147. return input, nil
  148. }
  149. return input, fmt.Errorf("app does not contain build or image settings")
  150. }
  151. func addPorterSubdomainsIfNecessary(ctx context.Context, client api.Client, project uint, cluster uint, base64AppProto string) (string, error) {
  152. var editedB64AppProto string
  153. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  154. if err != nil {
  155. return editedB64AppProto, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  156. }
  157. app := &porterv1.PorterApp{}
  158. err = helpers.UnmarshalContractObject(decoded, app)
  159. if err != nil {
  160. return editedB64AppProto, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  161. }
  162. for serviceName, service := range app.Services {
  163. if service.Type == porterv1.ServiceType_SERVICE_TYPE_WEB {
  164. if service.GetWebConfig() == nil {
  165. return editedB64AppProto, fmt.Errorf("web service %s does not contain web config", serviceName)
  166. }
  167. webConfig := service.GetWebConfig()
  168. if !webConfig.Private && len(webConfig.Domains) == 0 {
  169. color.New(color.FgYellow).Printf("Service %s is public but does not contain any domains, creating Porter domain\n", serviceName) // nolint:errcheck,gosec
  170. domain, err := client.CreateSubdomain(ctx, project, cluster, app.Name, serviceName)
  171. if err != nil {
  172. return editedB64AppProto, fmt.Errorf("error creating subdomain: %w", err)
  173. }
  174. if domain.Subdomain == "" {
  175. return editedB64AppProto, errors.New("response subdomain is empty")
  176. }
  177. webConfig.Domains = []*porterv1.Domain{
  178. {Name: domain.Subdomain},
  179. }
  180. service.Config = &porterv1.Service_WebConfig{WebConfig: webConfig}
  181. }
  182. }
  183. }
  184. marshalled, err := helpers.MarshalContractObject(ctx, app)
  185. if err != nil {
  186. return editedB64AppProto, fmt.Errorf("unable to marshal app back to json: %w", err)
  187. }
  188. editedB64AppProto = base64.StdEncoding.EncodeToString(marshalled)
  189. return editedB64AppProto, nil
  190. }
  191. func buildSettingsFromBase64AppProto(base64AppProto string) (buildInput, error) {
  192. var buildSettings buildInput
  193. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  194. if err != nil {
  195. return buildSettings, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  196. }
  197. app := &porterv1.PorterApp{}
  198. err = helpers.UnmarshalContractObject(decoded, app)
  199. if err != nil {
  200. return buildSettings, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  201. }
  202. if app.Name == "" {
  203. return buildSettings, fmt.Errorf("app does not contain name")
  204. }
  205. if app.Build == nil {
  206. return buildSettings, fmt.Errorf("app does not contain build settings")
  207. }
  208. if app.Image == nil {
  209. return buildSettings, fmt.Errorf("app does not contain image settings")
  210. }
  211. return buildInput{
  212. AppName: app.Name,
  213. BuildContext: app.Build.Context,
  214. Dockerfile: app.Build.Dockerfile,
  215. BuildMethod: app.Build.Method,
  216. Builder: app.Build.Builder,
  217. BuildPacks: app.Build.Buildpacks,
  218. ImageTag: app.Image.Tag,
  219. RepositoryURL: app.Image.Repository,
  220. }, nil
  221. }
  222. func imageTagFromBase64AppProto(base64AppProto string) (string, error) {
  223. var image string
  224. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  225. if err != nil {
  226. return image, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  227. }
  228. app := &porterv1.PorterApp{}
  229. err = helpers.UnmarshalContractObject(decoded, app)
  230. if err != nil {
  231. return image, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  232. }
  233. if app.Image == nil {
  234. return image, fmt.Errorf("app does not contain image settings")
  235. }
  236. if app.Image.Tag == "" {
  237. return image, fmt.Errorf("app does not contain image tag")
  238. }
  239. return app.Image.Tag, nil
  240. }