apply.go 11 KB

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