apply.go 11 KB

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