apply.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. package v2
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "errors"
  6. "fmt"
  7. "os"
  8. "path/filepath"
  9. "strconv"
  10. "time"
  11. "github.com/porter-dev/porter/api/server/handlers/porter_app"
  12. "github.com/porter-dev/porter/api/types"
  13. "github.com/cli/cli/git"
  14. "github.com/fatih/color"
  15. "github.com/porter-dev/api-contracts/generated/go/helpers"
  16. porterv1 "github.com/porter-dev/api-contracts/generated/go/porter/v1"
  17. api "github.com/porter-dev/porter/api/client"
  18. "github.com/porter-dev/porter/cli/cmd/config"
  19. )
  20. // Apply implements the functionality of the `porter apply` command for validate apply v2 projects
  21. func Apply(ctx context.Context, cliConf config.CLIConfig, client api.Client, porterYamlPath string) error {
  22. if len(porterYamlPath) == 0 {
  23. return fmt.Errorf("porter yaml is empty")
  24. }
  25. porterYaml, err := os.ReadFile(filepath.Clean(porterYamlPath))
  26. if err != nil {
  27. return fmt.Errorf("could not read porter yaml file: %w", err)
  28. }
  29. b64YAML := base64.StdEncoding.EncodeToString(porterYaml)
  30. // last argument is passed to accommodate users with v1 porter yamls
  31. parseResp, err := client.ParseYAML(ctx, cliConf.Project, cliConf.Cluster, b64YAML, os.Getenv("PORTER_STACK_NAME"))
  32. if err != nil {
  33. return fmt.Errorf("error calling parse yaml endpoint: %w", err)
  34. }
  35. if parseResp.B64AppProto == "" {
  36. return errors.New("b64 app proto is empty")
  37. }
  38. appName, err := appNameFromB64AppProto(parseResp.B64AppProto)
  39. if err != nil {
  40. return fmt.Errorf("error getting app name from b64 app proto: %w", err)
  41. }
  42. color.New(color.FgGreen).Printf("Successfully parsed Porter YAML: applying app \"%s\"\n", appName) // nolint:errcheck,gosec
  43. targetResp, err := client.DefaultDeploymentTarget(ctx, cliConf.Project, cliConf.Cluster)
  44. if err != nil {
  45. return fmt.Errorf("error calling default deployment target endpoint: %w", err)
  46. }
  47. if targetResp.DeploymentTargetID == "" {
  48. return errors.New("deployment target id is empty")
  49. }
  50. var commitSHA string
  51. if os.Getenv("PORTER_COMMIT_SHA") != "" {
  52. commitSHA = os.Getenv("PORTER_COMMIT_SHA")
  53. } else if os.Getenv("GITHUB_SHA") != "" {
  54. commitSHA = os.Getenv("GITHUB_SHA")
  55. } else if commit, err := git.LastCommit(); err == nil && commit != nil {
  56. commitSHA = commit.Sha
  57. }
  58. validateResp, err := client.ValidatePorterApp(ctx, cliConf.Project, cliConf.Cluster, parseResp.B64AppProto, targetResp.DeploymentTargetID, commitSHA)
  59. if err != nil {
  60. return fmt.Errorf("error calling validate endpoint: %w", err)
  61. }
  62. if validateResp.ValidatedBase64AppProto == "" {
  63. return errors.New("validated b64 app proto is empty")
  64. }
  65. base64AppProto := validateResp.ValidatedBase64AppProto
  66. createPorterAppDBEntryInp, err := createPorterAppDbEntryInputFromProtoAndEnv(validateResp.ValidatedBase64AppProto)
  67. if err != nil {
  68. return fmt.Errorf("error creating porter app db entry input from proto: %w", err)
  69. }
  70. err = client.CreatePorterAppDBEntry(ctx, cliConf.Project, cliConf.Cluster, createPorterAppDBEntryInp)
  71. if err != nil {
  72. return fmt.Errorf("error creating porter app db entry: %w", err)
  73. }
  74. applyResp, err := client.ApplyPorterApp(ctx, cliConf.Project, cliConf.Cluster, base64AppProto, targetResp.DeploymentTargetID, "")
  75. if err != nil {
  76. return fmt.Errorf("error calling apply endpoint: %w", err)
  77. }
  78. if applyResp.AppRevisionId == "" {
  79. return errors.New("app revision id is empty")
  80. }
  81. if applyResp.CLIAction == porterv1.EnumCLIAction_ENUM_CLI_ACTION_BUILD {
  82. color.New(color.FgGreen).Printf("Building new image...\n") // nolint:errcheck,gosec
  83. eventID, _ := createBuildEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, targetResp.DeploymentTargetID)
  84. if commitSHA == "" {
  85. 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.")
  86. }
  87. buildSettings, err := buildSettingsFromBase64AppProto(base64AppProto)
  88. if err != nil {
  89. return fmt.Errorf("error building settings from base64 app proto: %w", err)
  90. }
  91. currentAppRevisionResp, err := client.CurrentAppRevision(ctx, cliConf.Project, cliConf.Cluster, appName, targetResp.DeploymentTargetID)
  92. if err != nil {
  93. return fmt.Errorf("error getting current app revision: %w", err)
  94. }
  95. if currentAppRevisionResp == nil {
  96. return errors.New("current app revision is nil")
  97. }
  98. appRevision := currentAppRevisionResp.AppRevision
  99. if appRevision.B64AppProto == "" {
  100. return errors.New("current app revision b64 app proto is empty")
  101. }
  102. currentImageTag, err := imageTagFromBase64AppProto(appRevision.B64AppProto)
  103. if err != nil {
  104. return fmt.Errorf("error getting image tag from current app revision: %w", err)
  105. }
  106. buildSettings.CurrentImageTag = currentImageTag
  107. buildSettings.ProjectID = cliConf.Project
  108. err = build(ctx, client, buildSettings)
  109. buildMetadata := make(map[string]interface{})
  110. buildMetadata["end_time"] = time.Now().UTC()
  111. if err != nil {
  112. _ = updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, targetResp.DeploymentTargetID, eventID, types.PorterAppEventStatus_Failed, buildMetadata)
  113. return fmt.Errorf("error building app: %w", err)
  114. }
  115. color.New(color.FgGreen).Printf("Successfully built image (tag: %s)\n", buildSettings.ImageTag) // nolint:errcheck,gosec
  116. _ = updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, targetResp.DeploymentTargetID, eventID, types.PorterAppEventStatus_Success, buildMetadata)
  117. applyResp, err = client.ApplyPorterApp(ctx, cliConf.Project, cliConf.Cluster, "", "", applyResp.AppRevisionId)
  118. if err != nil {
  119. return fmt.Errorf("apply error post-build: %w", err)
  120. }
  121. }
  122. if applyResp.CLIAction == porterv1.EnumCLIAction_ENUM_CLI_ACTION_TRACK_PREDEPLOY {
  123. color.New(color.FgGreen).Printf("Waiting for predeploy to complete...\n") // nolint:errcheck,gosec
  124. now := time.Now().UTC()
  125. eventID, _ := createPredeployEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, targetResp.DeploymentTargetID, now, applyResp.AppRevisionId)
  126. eventStatus := types.PorterAppEventStatus_Success
  127. for {
  128. if time.Since(now) > checkPredeployTimeout {
  129. return errors.New("timed out waiting for predeploy to complete")
  130. }
  131. predeployStatusResp, err := client.PredeployStatus(ctx, cliConf.Project, cliConf.Cluster, appName, applyResp.AppRevisionId)
  132. if err != nil {
  133. return fmt.Errorf("error calling predeploy status endpoint: %w", err)
  134. }
  135. if predeployStatusResp.Status == porter_app.PredeployStatus_Failed {
  136. eventStatus = types.PorterAppEventStatus_Failed
  137. break
  138. }
  139. if predeployStatusResp.Status == porter_app.PredeployStatus_Successful {
  140. break
  141. }
  142. time.Sleep(checkPredeployFrequency)
  143. }
  144. metadata := make(map[string]interface{})
  145. metadata["end_time"] = time.Now().UTC()
  146. _ = updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, targetResp.DeploymentTargetID, eventID, eventStatus, metadata)
  147. applyResp, err = client.ApplyPorterApp(ctx, cliConf.Project, cliConf.Cluster, "", "", applyResp.AppRevisionId)
  148. if err != nil {
  149. return fmt.Errorf("apply error post-predeploy: %w", err)
  150. }
  151. }
  152. if applyResp.CLIAction != porterv1.EnumCLIAction_ENUM_CLI_ACTION_NONE {
  153. return fmt.Errorf("unexpected CLI action: %s", applyResp.CLIAction)
  154. }
  155. color.New(color.FgGreen).Printf("Successfully applied new revision %s for app %s\n", applyResp.AppRevisionId, appName) // nolint:errcheck,gosec
  156. return nil
  157. }
  158. // checkPredeployTimeout is the maximum amount of time the CLI will wait for a predeploy to complete before calling apply again
  159. const checkPredeployTimeout = 60 * time.Minute
  160. // checkPredeployFrequency is the frequency at which the CLI will check the status of a predeploy
  161. const checkPredeployFrequency = 10 * time.Second
  162. func appNameFromB64AppProto(base64AppProto string) (string, error) {
  163. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  164. if err != nil {
  165. return "", fmt.Errorf("unable to decode base64 app for revision: %w", err)
  166. }
  167. app := &porterv1.PorterApp{}
  168. err = helpers.UnmarshalContractObject(decoded, app)
  169. if err != nil {
  170. return "", fmt.Errorf("unable to unmarshal app for revision: %w", err)
  171. }
  172. if app.Name == "" {
  173. return "", fmt.Errorf("app does not contain name")
  174. }
  175. return app.Name, nil
  176. }
  177. func createPorterAppDbEntryInputFromProtoAndEnv(base64AppProto string) (api.CreatePorterAppDBEntryInput, error) {
  178. var input api.CreatePorterAppDBEntryInput
  179. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  180. if err != nil {
  181. return input, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  182. }
  183. app := &porterv1.PorterApp{}
  184. err = helpers.UnmarshalContractObject(decoded, app)
  185. if err != nil {
  186. return input, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  187. }
  188. if app.Name == "" {
  189. return input, fmt.Errorf("app does not contain name")
  190. }
  191. input.AppName = app.Name
  192. if app.Build != nil {
  193. if os.Getenv("GITHUB_REPOSITORY_ID") == "" {
  194. input.Local = true
  195. return input, nil
  196. }
  197. gitRepoId, err := strconv.Atoi(os.Getenv("GITHUB_REPOSITORY_ID"))
  198. if err != nil {
  199. return input, fmt.Errorf("unable to parse GITHUB_REPOSITORY_ID to int: %w", err)
  200. }
  201. input.GitRepoID = uint(gitRepoId)
  202. input.GitRepoName = os.Getenv("GITHUB_REPOSITORY")
  203. input.GitBranch = os.Getenv("GITHUB_REF_NAME")
  204. input.PorterYamlPath = "porter.yaml"
  205. return input, nil
  206. }
  207. if app.Image != nil {
  208. input.ImageRepository = app.Image.Repository
  209. input.ImageTag = app.Image.Tag
  210. return input, nil
  211. }
  212. return input, fmt.Errorf("app does not contain build or image settings")
  213. }
  214. func buildSettingsFromBase64AppProto(base64AppProto string) (buildInput, error) {
  215. var buildSettings buildInput
  216. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  217. if err != nil {
  218. return buildSettings, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  219. }
  220. app := &porterv1.PorterApp{}
  221. err = helpers.UnmarshalContractObject(decoded, app)
  222. if err != nil {
  223. return buildSettings, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  224. }
  225. if app.Name == "" {
  226. return buildSettings, fmt.Errorf("app does not contain name")
  227. }
  228. if app.Build == nil {
  229. return buildSettings, fmt.Errorf("app does not contain build settings")
  230. }
  231. if app.Image == nil {
  232. return buildSettings, fmt.Errorf("app does not contain image settings")
  233. }
  234. return buildInput{
  235. AppName: app.Name,
  236. BuildContext: app.Build.Context,
  237. Dockerfile: app.Build.Dockerfile,
  238. BuildMethod: app.Build.Method,
  239. Builder: app.Build.Builder,
  240. BuildPacks: app.Build.Buildpacks,
  241. ImageTag: app.Image.Tag,
  242. RepositoryURL: app.Image.Repository,
  243. }, nil
  244. }
  245. func imageTagFromBase64AppProto(base64AppProto string) (string, error) {
  246. var image string
  247. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  248. if err != nil {
  249. return image, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  250. }
  251. app := &porterv1.PorterApp{}
  252. err = helpers.UnmarshalContractObject(decoded, app)
  253. if err != nil {
  254. return image, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  255. }
  256. if app.Image == nil {
  257. return image, fmt.Errorf("app does not contain image settings")
  258. }
  259. if app.Image.Tag == "" {
  260. return image, fmt.Errorf("app does not contain image tag")
  261. }
  262. return app.Image.Tag, nil
  263. }