apply.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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/porter-dev/porter/internal/kubernetes/environment_groups"
  14. "github.com/porter-dev/porter/internal/models"
  15. "github.com/cli/cli/git"
  16. "github.com/fatih/color"
  17. "github.com/porter-dev/api-contracts/generated/go/helpers"
  18. porterv1 "github.com/porter-dev/api-contracts/generated/go/porter/v1"
  19. api "github.com/porter-dev/porter/api/client"
  20. "github.com/porter-dev/porter/cli/cmd/config"
  21. )
  22. // Apply implements the functionality of the `porter apply` command for validate apply v2 projects
  23. func Apply(ctx context.Context, cliConf config.CLIConfig, client api.Client, porterYamlPath string, appName string) error {
  24. const forceBuild = true
  25. var b64AppProto string
  26. targetResp, err := client.DefaultDeploymentTarget(ctx, cliConf.Project, cliConf.Cluster)
  27. if err != nil {
  28. return fmt.Errorf("error calling default deployment target endpoint: %w", err)
  29. }
  30. if targetResp.DeploymentTargetID == "" {
  31. return errors.New("deployment target id is empty")
  32. }
  33. porterYamlExists := len(porterYamlPath) != 0
  34. if porterYamlExists {
  35. _, err = os.Stat(filepath.Clean(porterYamlPath))
  36. if err != nil {
  37. if !os.IsNotExist(err) {
  38. return fmt.Errorf("error checking if porter yaml exists at path %s: %w", porterYamlPath, err)
  39. }
  40. // If a path was specified but the file does not exist, we will not immediately error out.
  41. // This supports users migrated from v1 who use a workflow file that always specifies a porter yaml path
  42. // in the apply command.
  43. porterYamlExists = false
  44. }
  45. }
  46. if porterYamlExists {
  47. porterYaml, err := os.ReadFile(filepath.Clean(porterYamlPath))
  48. if err != nil {
  49. return fmt.Errorf("could not read porter yaml file: %w", err)
  50. }
  51. b64YAML := base64.StdEncoding.EncodeToString(porterYaml)
  52. // last argument is passed to accommodate users with v1 porter yamls
  53. parseResp, err := client.ParseYAML(ctx, cliConf.Project, cliConf.Cluster, b64YAML, appName)
  54. if err != nil {
  55. return fmt.Errorf("error calling parse yaml endpoint: %w", err)
  56. }
  57. if parseResp.B64AppProto == "" {
  58. return errors.New("b64 app proto is empty")
  59. }
  60. b64AppProto = parseResp.B64AppProto
  61. // override app name if provided
  62. appName, err = appNameFromB64AppProto(parseResp.B64AppProto)
  63. if err != nil {
  64. return fmt.Errorf("error getting app name from b64 app proto: %w", err)
  65. }
  66. // we only need to create the app if a porter yaml is provided (otherwise it must already exist)
  67. createPorterAppDBEntryInp, err := createPorterAppDbEntryInputFromProtoAndEnv(parseResp.B64AppProto)
  68. if err != nil {
  69. return fmt.Errorf("unable to form porter app creation input from yaml: %w", err)
  70. }
  71. err = client.CreatePorterAppDBEntry(ctx, cliConf.Project, cliConf.Cluster, createPorterAppDBEntryInp)
  72. if err != nil {
  73. if err.Error() == porter_app.ErrMissingSourceType.Error() {
  74. return fmt.Errorf("cannot find existing Porter app with name %s and no build or image settings were specified in porter.yaml", appName)
  75. }
  76. return fmt.Errorf("unable to create porter app from yaml: %w", err)
  77. }
  78. envGroupResp, err := client.CreateOrUpdateAppEnvironment(ctx, cliConf.Project, cliConf.Cluster, appName, targetResp.DeploymentTargetID, parseResp.EnvVariables, parseResp.EnvSecrets, parseResp.B64AppProto)
  79. if err != nil {
  80. return fmt.Errorf("error calling create or update app environment group endpoint: %w", err)
  81. }
  82. b64AppProto, err = updateEnvGroupsInProto(ctx, b64AppProto, envGroupResp.EnvGroups)
  83. if err != nil {
  84. return fmt.Errorf("error updating app env group in proto: %w", err)
  85. }
  86. color.New(color.FgGreen).Printf("Successfully parsed Porter YAML: applying app \"%s\"\n", appName) // nolint:errcheck,gosec
  87. }
  88. if appName == "" {
  89. return errors.New("App name is empty. Please provide a Porter YAML file specifying the name of the app or set the PORTER_APP_NAME environment variable.")
  90. }
  91. var commitSHA string
  92. if os.Getenv("PORTER_COMMIT_SHA") != "" {
  93. commitSHA = os.Getenv("PORTER_COMMIT_SHA")
  94. } else if os.Getenv("GITHUB_SHA") != "" {
  95. commitSHA = os.Getenv("GITHUB_SHA")
  96. } else if commit, err := git.LastCommit(); err == nil && commit != nil {
  97. commitSHA = commit.Sha
  98. }
  99. validateResp, err := client.ValidatePorterApp(ctx, cliConf.Project, cliConf.Cluster, appName, b64AppProto, targetResp.DeploymentTargetID, commitSHA)
  100. if err != nil {
  101. return fmt.Errorf("error calling validate endpoint: %w", err)
  102. }
  103. if validateResp.ValidatedBase64AppProto == "" {
  104. return errors.New("validated b64 app proto is empty")
  105. }
  106. base64AppProto := validateResp.ValidatedBase64AppProto
  107. applyResp, err := client.ApplyPorterApp(ctx, cliConf.Project, cliConf.Cluster, base64AppProto, targetResp.DeploymentTargetID, "", forceBuild)
  108. if err != nil {
  109. return fmt.Errorf("error calling apply endpoint: %w", err)
  110. }
  111. if applyResp.AppRevisionId == "" {
  112. return errors.New("app revision id is empty")
  113. }
  114. if applyResp.CLIAction == porterv1.EnumCLIAction_ENUM_CLI_ACTION_BUILD {
  115. color.New(color.FgGreen).Printf("Building new image...\n") // nolint:errcheck,gosec
  116. eventID, _ := createBuildEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, targetResp.DeploymentTargetID)
  117. if commitSHA == "" {
  118. _ = reportBuildFailure(ctx, client, appName, cliConf, targetResp.DeploymentTargetID, applyResp.AppRevisionId, eventID)
  119. 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.")
  120. }
  121. buildSettings, err := buildSettingsFromBase64AppProto(base64AppProto)
  122. if err != nil {
  123. _ = reportBuildFailure(ctx, client, appName, cliConf, targetResp.DeploymentTargetID, applyResp.AppRevisionId, eventID)
  124. return fmt.Errorf("error building settings from base64 app proto: %w", err)
  125. }
  126. currentAppRevisionResp, err := client.CurrentAppRevision(ctx, cliConf.Project, cliConf.Cluster, appName, targetResp.DeploymentTargetID)
  127. if err != nil {
  128. _ = reportBuildFailure(ctx, client, appName, cliConf, targetResp.DeploymentTargetID, applyResp.AppRevisionId, eventID)
  129. return fmt.Errorf("error getting current app revision: %w", err)
  130. }
  131. if currentAppRevisionResp == nil {
  132. _ = reportBuildFailure(ctx, client, appName, cliConf, targetResp.DeploymentTargetID, applyResp.AppRevisionId, eventID)
  133. return errors.New("current app revision is nil")
  134. }
  135. appRevision := currentAppRevisionResp.AppRevision
  136. if appRevision.B64AppProto == "" {
  137. _ = reportBuildFailure(ctx, client, appName, cliConf, targetResp.DeploymentTargetID, applyResp.AppRevisionId, eventID)
  138. return errors.New("current app revision b64 app proto is empty")
  139. }
  140. currentImageTag, err := imageTagFromBase64AppProto(appRevision.B64AppProto)
  141. if err != nil {
  142. _ = reportBuildFailure(ctx, client, appName, cliConf, targetResp.DeploymentTargetID, applyResp.AppRevisionId, eventID)
  143. return fmt.Errorf("error getting image tag from current app revision: %w", err)
  144. }
  145. buildSettings.CurrentImageTag = currentImageTag
  146. buildSettings.ProjectID = cliConf.Project
  147. buildEnv, err := client.GetBuildEnv(ctx, cliConf.Project, cliConf.Cluster, appName, appRevision.ID)
  148. if err != nil {
  149. _ = reportBuildFailure(ctx, client, appName, cliConf, targetResp.DeploymentTargetID, applyResp.AppRevisionId, eventID)
  150. return fmt.Errorf("error getting build env: %w", err)
  151. }
  152. buildSettings.Env = buildEnv.BuildEnvVariables
  153. err = build(ctx, client, buildSettings)
  154. if err != nil {
  155. _ = reportBuildFailure(ctx, client, appName, cliConf, targetResp.DeploymentTargetID, applyResp.AppRevisionId, eventID)
  156. return fmt.Errorf("error building app: %w", err)
  157. }
  158. color.New(color.FgGreen).Printf("Successfully built image (tag: %s)\n", buildSettings.ImageTag) // nolint:errcheck,gosec
  159. buildMetadata := make(map[string]interface{})
  160. buildMetadata["end_time"] = time.Now().UTC()
  161. _ = updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, targetResp.DeploymentTargetID, eventID, types.PorterAppEventStatus_Success, buildMetadata)
  162. applyResp, err = client.ApplyPorterApp(ctx, cliConf.Project, cliConf.Cluster, "", "", applyResp.AppRevisionId, !forceBuild)
  163. if err != nil {
  164. return fmt.Errorf("apply error post-build: %w", err)
  165. }
  166. }
  167. color.New(color.FgGreen).Printf("Image tag exists in repository\n") // nolint:errcheck,gosec
  168. if applyResp.CLIAction == porterv1.EnumCLIAction_ENUM_CLI_ACTION_TRACK_PREDEPLOY {
  169. color.New(color.FgGreen).Printf("Waiting for predeploy to complete...\n") // nolint:errcheck,gosec
  170. now := time.Now().UTC()
  171. eventID, _ := createPredeployEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, targetResp.DeploymentTargetID, now, applyResp.AppRevisionId)
  172. eventStatus := types.PorterAppEventStatus_Success
  173. for {
  174. if time.Since(now) > checkPredeployTimeout {
  175. return errors.New("timed out waiting for predeploy to complete")
  176. }
  177. predeployStatusResp, err := client.PredeployStatus(ctx, cliConf.Project, cliConf.Cluster, appName, applyResp.AppRevisionId)
  178. if err != nil {
  179. return fmt.Errorf("error calling predeploy status endpoint: %w", err)
  180. }
  181. if predeployStatusResp.Status == porter_app.PredeployStatus_Failed {
  182. eventStatus = types.PorterAppEventStatus_Failed
  183. break
  184. }
  185. if predeployStatusResp.Status == porter_app.PredeployStatus_Successful {
  186. break
  187. }
  188. time.Sleep(checkPredeployFrequency)
  189. }
  190. metadata := make(map[string]interface{})
  191. metadata["end_time"] = time.Now().UTC()
  192. _ = updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, targetResp.DeploymentTargetID, eventID, eventStatus, metadata)
  193. applyResp, err = client.ApplyPorterApp(ctx, cliConf.Project, cliConf.Cluster, "", "", applyResp.AppRevisionId, !forceBuild)
  194. if err != nil {
  195. return fmt.Errorf("apply error post-predeploy: %w", err)
  196. }
  197. }
  198. if applyResp.CLIAction != porterv1.EnumCLIAction_ENUM_CLI_ACTION_NONE {
  199. return fmt.Errorf("unexpected CLI action: %s", applyResp.CLIAction)
  200. }
  201. color.New(color.FgGreen).Printf("Successfully applied new revision %s for app %s\n", applyResp.AppRevisionId, appName) // nolint:errcheck,gosec
  202. return nil
  203. }
  204. // checkPredeployTimeout is the maximum amount of time the CLI will wait for a predeploy to complete before calling apply again
  205. const checkPredeployTimeout = 60 * time.Minute
  206. // checkPredeployFrequency is the frequency at which the CLI will check the status of a predeploy
  207. const checkPredeployFrequency = 10 * time.Second
  208. func appNameFromB64AppProto(base64AppProto string) (string, error) {
  209. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  210. if err != nil {
  211. return "", fmt.Errorf("unable to decode base64 app for revision: %w", err)
  212. }
  213. app := &porterv1.PorterApp{}
  214. err = helpers.UnmarshalContractObject(decoded, app)
  215. if err != nil {
  216. return "", fmt.Errorf("unable to unmarshal app for revision: %w", err)
  217. }
  218. if app.Name == "" {
  219. return "", fmt.Errorf("app does not contain name")
  220. }
  221. return app.Name, nil
  222. }
  223. func createPorterAppDbEntryInputFromProtoAndEnv(base64AppProto string) (api.CreatePorterAppDBEntryInput, error) {
  224. var input api.CreatePorterAppDBEntryInput
  225. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  226. if err != nil {
  227. return input, 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 input, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  233. }
  234. if app.Name == "" {
  235. return input, fmt.Errorf("app does not contain name")
  236. }
  237. input.AppName = app.Name
  238. if app.Build != nil {
  239. if os.Getenv("GITHUB_REPOSITORY_ID") == "" {
  240. input.Local = true
  241. return input, nil
  242. }
  243. gitRepoId, err := strconv.Atoi(os.Getenv("GITHUB_REPOSITORY_ID"))
  244. if err != nil {
  245. return input, fmt.Errorf("unable to parse GITHUB_REPOSITORY_ID to int: %w", err)
  246. }
  247. input.GitRepoID = uint(gitRepoId)
  248. input.GitRepoName = os.Getenv("GITHUB_REPOSITORY")
  249. input.GitBranch = os.Getenv("GITHUB_REF_NAME")
  250. input.PorterYamlPath = "porter.yaml"
  251. return input, nil
  252. }
  253. if app.Image != nil {
  254. input.ImageRepository = app.Image.Repository
  255. input.ImageTag = app.Image.Tag
  256. return input, nil
  257. }
  258. return input, nil
  259. }
  260. func buildSettingsFromBase64AppProto(base64AppProto string) (buildInput, error) {
  261. var buildSettings buildInput
  262. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  263. if err != nil {
  264. return buildSettings, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  265. }
  266. app := &porterv1.PorterApp{}
  267. err = helpers.UnmarshalContractObject(decoded, app)
  268. if err != nil {
  269. return buildSettings, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  270. }
  271. if app.Name == "" {
  272. return buildSettings, fmt.Errorf("app does not contain name")
  273. }
  274. if app.Build == nil {
  275. return buildSettings, fmt.Errorf("app does not contain build settings")
  276. }
  277. if app.Image == nil {
  278. return buildSettings, fmt.Errorf("app does not contain image settings")
  279. }
  280. return buildInput{
  281. AppName: app.Name,
  282. BuildContext: app.Build.Context,
  283. Dockerfile: app.Build.Dockerfile,
  284. BuildMethod: app.Build.Method,
  285. Builder: app.Build.Builder,
  286. BuildPacks: app.Build.Buildpacks,
  287. ImageTag: app.Image.Tag,
  288. RepositoryURL: app.Image.Repository,
  289. }, nil
  290. }
  291. func imageTagFromBase64AppProto(base64AppProto string) (string, error) {
  292. var image string
  293. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  294. if err != nil {
  295. return image, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  296. }
  297. app := &porterv1.PorterApp{}
  298. err = helpers.UnmarshalContractObject(decoded, app)
  299. if err != nil {
  300. return image, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  301. }
  302. if app.Image == nil {
  303. return image, fmt.Errorf("app does not contain image settings")
  304. }
  305. if app.Image.Tag == "" {
  306. return image, fmt.Errorf("app does not contain image tag")
  307. }
  308. return app.Image.Tag, nil
  309. }
  310. func updateEnvGroupsInProto(ctx context.Context, base64AppProto string, envGroups []environment_groups.EnvironmentGroup) (string, error) {
  311. var editedB64AppProto string
  312. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  313. if err != nil {
  314. return editedB64AppProto, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  315. }
  316. app := &porterv1.PorterApp{}
  317. err = helpers.UnmarshalContractObject(decoded, app)
  318. if err != nil {
  319. return editedB64AppProto, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  320. }
  321. egs := make([]*porterv1.EnvGroup, 0)
  322. for _, envGroup := range envGroups {
  323. egs = append(egs, &porterv1.EnvGroup{
  324. Name: envGroup.Name,
  325. Version: int64(envGroup.Version),
  326. })
  327. }
  328. app.EnvGroups = egs
  329. marshalled, err := helpers.MarshalContractObject(ctx, app)
  330. if err != nil {
  331. return editedB64AppProto, fmt.Errorf("unable to marshal app back to json: %w", err)
  332. }
  333. editedB64AppProto = base64.StdEncoding.EncodeToString(marshalled)
  334. return editedB64AppProto, nil
  335. }
  336. func reportBuildFailure(ctx context.Context, client api.Client, appName string, cliConf config.CLIConfig, deploymentTargetID string, appRevisionID string, eventID string) error {
  337. buildMetadata := make(map[string]interface{})
  338. buildMetadata["end_time"] = time.Now().UTC()
  339. err := updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, deploymentTargetID, eventID, types.PorterAppEventStatus_Failed, buildMetadata)
  340. if err != nil {
  341. return err
  342. }
  343. _, err = client.UpdateRevisionStatus(ctx, cliConf.Project, cliConf.Cluster, appName, appRevisionID, models.AppRevisionStatus_BuildFailed)
  344. if err != nil {
  345. return err
  346. }
  347. return nil
  348. }