apply.go 11 KB

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