apply.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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. // ApplyInput is the input for the Apply function
  23. type ApplyInput struct {
  24. // CLIConfig is the CLI configuration
  25. CLIConfig config.CLIConfig
  26. // Client is the Porter API client
  27. Client api.Client
  28. // PorterYamlPath is the path to the porter.yaml file
  29. PorterYamlPath string
  30. // AppName is the name of the app
  31. AppName string
  32. // PreviewApply is true when Apply should create a new deployment target matching current git branch and apply to that target
  33. PreviewApply bool
  34. }
  35. // Apply implements the functionality of the `porter apply` command for validate apply v2 projects
  36. func Apply(ctx context.Context, inp ApplyInput) error {
  37. const forceBuild = true
  38. var b64AppProto string
  39. cliConf := inp.CLIConfig
  40. client := inp.Client
  41. deploymentTargetID, err := deploymentTargetFromConfig(ctx, client, cliConf.Project, cliConf.Cluster, inp.PreviewApply)
  42. if err != nil {
  43. return fmt.Errorf("error getting deployment target from config: %w", err)
  44. }
  45. porterYamlExists := len(inp.PorterYamlPath) != 0
  46. if porterYamlExists {
  47. _, err := os.Stat(filepath.Clean(inp.PorterYamlPath))
  48. if err != nil {
  49. if !os.IsNotExist(err) {
  50. return fmt.Errorf("error checking if porter yaml exists at path %s: %w", inp.PorterYamlPath, err)
  51. }
  52. // If a path was specified but the file does not exist, we will not immediately error out.
  53. // This supports users migrated from v1 who use a workflow file that always specifies a porter yaml path
  54. // in the apply command.
  55. porterYamlExists = false
  56. }
  57. }
  58. // overrides incorporated into the app contract baed on the deployment target
  59. var b64AppOverrides string
  60. appName := inp.AppName
  61. if porterYamlExists {
  62. porterYaml, err := os.ReadFile(filepath.Clean(inp.PorterYamlPath))
  63. if err != nil {
  64. return fmt.Errorf("could not read porter yaml file: %w", err)
  65. }
  66. b64YAML := base64.StdEncoding.EncodeToString(porterYaml)
  67. // last argument is passed to accommodate users with v1 porter yamls
  68. parseResp, err := client.ParseYAML(ctx, cliConf.Project, cliConf.Cluster, b64YAML, appName)
  69. if err != nil {
  70. return fmt.Errorf("error calling parse yaml endpoint: %w", err)
  71. }
  72. if parseResp.B64AppProto == "" {
  73. return errors.New("b64 app proto is empty")
  74. }
  75. b64AppProto = parseResp.B64AppProto
  76. // override app name if provided
  77. appName, err = appNameFromB64AppProto(parseResp.B64AppProto)
  78. if err != nil {
  79. return fmt.Errorf("error getting app name from porter.yaml: %w", err)
  80. }
  81. // we only need to create the app if a porter yaml is provided (otherwise it must already exist)
  82. createPorterAppDBEntryInp, err := createPorterAppDbEntryInputFromProtoAndEnv(parseResp.B64AppProto)
  83. if err != nil {
  84. return fmt.Errorf("unable to form porter app creation input from yaml: %w", err)
  85. }
  86. err = client.CreatePorterAppDBEntry(ctx, cliConf.Project, cliConf.Cluster, createPorterAppDBEntryInp)
  87. if err != nil {
  88. if err.Error() == porter_app.ErrMissingSourceType.Error() {
  89. return fmt.Errorf("cannot find existing Porter app with name %s and no build or image settings were specified in porter.yaml", appName)
  90. }
  91. return fmt.Errorf("unable to create porter app from yaml: %w", err)
  92. }
  93. envGroupResp, err := client.CreateOrUpdateAppEnvironment(ctx, cliConf.Project, cliConf.Cluster, appName, deploymentTargetID, parseResp.EnvVariables, parseResp.EnvSecrets, parseResp.B64AppProto)
  94. if err != nil {
  95. return fmt.Errorf("error calling create or update app environment group endpoint: %w", err)
  96. }
  97. b64AppProto, err = updateEnvGroupsInProto(ctx, b64AppProto, envGroupResp.EnvGroups)
  98. if err != nil {
  99. return fmt.Errorf("error updating app env group in proto: %w", err)
  100. }
  101. if inp.PreviewApply && parseResp.PreviewApp != nil {
  102. b64AppOverrides = parseResp.PreviewApp.B64AppProto
  103. envGroupResp, err := client.CreateOrUpdateAppEnvironment(ctx, cliConf.Project, cliConf.Cluster, appName, deploymentTargetID, parseResp.PreviewApp.EnvVariables, parseResp.PreviewApp.EnvSecrets, parseResp.PreviewApp.B64AppProto)
  104. if err != nil {
  105. return fmt.Errorf("error calling create or update app environment group endpoint: %w", err)
  106. }
  107. b64AppOverrides, err = updateEnvGroupsInProto(ctx, b64AppOverrides, envGroupResp.EnvGroups)
  108. if err != nil {
  109. return fmt.Errorf("error updating app env group in proto: %w", err)
  110. }
  111. }
  112. color.New(color.FgGreen).Printf("Successfully parsed Porter YAML: applying app \"%s\"\n", appName) // nolint:errcheck,gosec
  113. }
  114. if appName == "" {
  115. 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.")
  116. }
  117. commitSHA := commitSHAFromEnv()
  118. validateResp, err := client.ValidatePorterApp(ctx, api.ValidatePorterAppInput{
  119. ProjectID: cliConf.Project,
  120. ClusterID: cliConf.Cluster,
  121. AppName: appName,
  122. Base64AppProto: b64AppProto,
  123. Base64AppOverrides: b64AppOverrides,
  124. DeploymentTarget: deploymentTargetID,
  125. CommitSHA: commitSHA,
  126. })
  127. if err != nil {
  128. return fmt.Errorf("error calling validate endpoint: %w", err)
  129. }
  130. if validateResp.ValidatedBase64AppProto == "" {
  131. return errors.New("validated b64 app proto is empty")
  132. }
  133. base64AppProto := validateResp.ValidatedBase64AppProto
  134. applyResp, err := client.ApplyPorterApp(ctx, cliConf.Project, cliConf.Cluster, base64AppProto, deploymentTargetID, "", forceBuild)
  135. if err != nil {
  136. return fmt.Errorf("error calling apply endpoint: %w", err)
  137. }
  138. if applyResp.AppRevisionId == "" {
  139. return errors.New("app revision id is empty")
  140. }
  141. if applyResp.CLIAction == porterv1.EnumCLIAction_ENUM_CLI_ACTION_BUILD {
  142. color.New(color.FgGreen).Printf("Building new image...\n") // nolint:errcheck,gosec
  143. eventID, _ := createBuildEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, deploymentTargetID)
  144. if commitSHA == "" {
  145. err := 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.")
  146. _ = reportBuildFailure(ctx, client, appName, cliConf, deploymentTargetID, applyResp.AppRevisionId, eventID, err)
  147. return err
  148. }
  149. buildSettings, err := buildSettingsFromBase64AppProto(base64AppProto)
  150. if err != nil {
  151. err := fmt.Errorf("error getting build settings from base64 app proto: %w", err)
  152. _ = reportBuildFailure(ctx, client, appName, cliConf, deploymentTargetID, applyResp.AppRevisionId, eventID, err)
  153. return err
  154. }
  155. currentAppRevisionResp, err := client.CurrentAppRevision(ctx, cliConf.Project, cliConf.Cluster, appName, deploymentTargetID)
  156. if err != nil {
  157. err := fmt.Errorf("error getting current app revision: %w", err)
  158. _ = reportBuildFailure(ctx, client, appName, cliConf, deploymentTargetID, applyResp.AppRevisionId, eventID, err)
  159. return err
  160. }
  161. if currentAppRevisionResp == nil {
  162. err := errors.New("current app revision is nil")
  163. _ = reportBuildFailure(ctx, client, appName, cliConf, deploymentTargetID, applyResp.AppRevisionId, eventID, err)
  164. return err
  165. }
  166. appRevision := currentAppRevisionResp.AppRevision
  167. if appRevision.B64AppProto == "" {
  168. err := errors.New("current app revision b64 app proto is empty")
  169. _ = reportBuildFailure(ctx, client, appName, cliConf, deploymentTargetID, applyResp.AppRevisionId, eventID, err)
  170. return err
  171. }
  172. currentImageTag, err := imageTagFromBase64AppProto(appRevision.B64AppProto)
  173. if err != nil {
  174. err := fmt.Errorf("error getting image tag from current app revision: %w", err)
  175. _ = reportBuildFailure(ctx, client, appName, cliConf, deploymentTargetID, applyResp.AppRevisionId, eventID, err)
  176. return err
  177. }
  178. buildSettings.CurrentImageTag = currentImageTag
  179. buildSettings.ProjectID = cliConf.Project
  180. buildEnv, err := client.GetBuildEnv(ctx, cliConf.Project, cliConf.Cluster, appName, appRevision.ID)
  181. if err != nil {
  182. err := fmt.Errorf("error getting build env: %w", err)
  183. _ = reportBuildFailure(ctx, client, appName, cliConf, deploymentTargetID, applyResp.AppRevisionId, eventID, err)
  184. return err
  185. }
  186. buildSettings.Env = buildEnv.BuildEnvVariables
  187. err = build(ctx, client, buildSettings)
  188. if err != nil {
  189. err := fmt.Errorf("error building app: %w", err)
  190. _ = reportBuildFailure(ctx, client, appName, cliConf, deploymentTargetID, applyResp.AppRevisionId, eventID, err)
  191. return err
  192. }
  193. color.New(color.FgGreen).Printf("Successfully built image (tag: %s)\n", buildSettings.ImageTag) // nolint:errcheck,gosec
  194. buildMetadata := make(map[string]interface{})
  195. buildMetadata["end_time"] = time.Now().UTC()
  196. _ = updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, deploymentTargetID, types.PorterAppEventType_Build, eventID, types.PorterAppEventStatus_Success, buildMetadata)
  197. applyResp, err = client.ApplyPorterApp(ctx, cliConf.Project, cliConf.Cluster, "", "", applyResp.AppRevisionId, !forceBuild)
  198. if err != nil {
  199. return fmt.Errorf("apply error post-build: %w", err)
  200. }
  201. }
  202. color.New(color.FgGreen).Printf("Image tag exists in repository\n") // nolint:errcheck,gosec
  203. if applyResp.CLIAction == porterv1.EnumCLIAction_ENUM_CLI_ACTION_TRACK_PREDEPLOY {
  204. color.New(color.FgGreen).Printf("Waiting for predeploy to complete...\n") // nolint:errcheck,gosec
  205. now := time.Now().UTC()
  206. eventID, _ := createPredeployEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, deploymentTargetID, now, applyResp.AppRevisionId)
  207. eventStatus := types.PorterAppEventStatus_Success
  208. for {
  209. if time.Since(now) > checkPredeployTimeout {
  210. return errors.New("timed out waiting for predeploy to complete")
  211. }
  212. predeployStatusResp, err := client.PredeployStatus(ctx, cliConf.Project, cliConf.Cluster, appName, applyResp.AppRevisionId)
  213. if err != nil {
  214. return fmt.Errorf("error calling predeploy status endpoint: %w", err)
  215. }
  216. if predeployStatusResp.Status == porter_app.PredeployStatus_Failed {
  217. eventStatus = types.PorterAppEventStatus_Failed
  218. break
  219. }
  220. if predeployStatusResp.Status == porter_app.PredeployStatus_Successful {
  221. break
  222. }
  223. time.Sleep(checkPredeployFrequency)
  224. }
  225. metadata := make(map[string]interface{})
  226. metadata["end_time"] = time.Now().UTC()
  227. _ = updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, deploymentTargetID, types.PorterAppEventType_PreDeploy, eventID, eventStatus, metadata)
  228. applyResp, err = client.ApplyPorterApp(ctx, cliConf.Project, cliConf.Cluster, "", "", applyResp.AppRevisionId, !forceBuild)
  229. if err != nil {
  230. return fmt.Errorf("apply error post-predeploy: %w", err)
  231. }
  232. }
  233. if applyResp.CLIAction != porterv1.EnumCLIAction_ENUM_CLI_ACTION_NONE {
  234. return fmt.Errorf("unexpected CLI action: %s", applyResp.CLIAction)
  235. }
  236. color.New(color.FgGreen).Printf("Successfully applied new revision %s for app %s\n", applyResp.AppRevisionId, appName) // nolint:errcheck,gosec
  237. return nil
  238. }
  239. func commitSHAFromEnv() string {
  240. var commitSHA string
  241. if os.Getenv("PORTER_COMMIT_SHA") != "" {
  242. commitSHA = os.Getenv("PORTER_COMMIT_SHA")
  243. } else if os.Getenv("GITHUB_SHA") != "" {
  244. commitSHA = os.Getenv("GITHUB_SHA")
  245. } else if commit, err := git.LastCommit(); err == nil && commit != nil {
  246. commitSHA = commit.Sha
  247. }
  248. return commitSHA
  249. }
  250. // checkPredeployTimeout is the maximum amount of time the CLI will wait for a predeploy to complete before calling apply again
  251. const checkPredeployTimeout = 60 * time.Minute
  252. // checkPredeployFrequency is the frequency at which the CLI will check the status of a predeploy
  253. const checkPredeployFrequency = 10 * time.Second
  254. func appNameFromB64AppProto(base64AppProto string) (string, error) {
  255. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  256. if err != nil {
  257. return "", fmt.Errorf("unable to decode base64 app for revision: %w", err)
  258. }
  259. app := &porterv1.PorterApp{}
  260. err = helpers.UnmarshalContractObject(decoded, app)
  261. if err != nil {
  262. return "", fmt.Errorf("unable to unmarshal app for revision: %w", err)
  263. }
  264. if app.Name == "" {
  265. return "", fmt.Errorf("app does not contain name")
  266. }
  267. return app.Name, nil
  268. }
  269. func createPorterAppDbEntryInputFromProtoAndEnv(base64AppProto string) (api.CreatePorterAppDBEntryInput, error) {
  270. var input api.CreatePorterAppDBEntryInput
  271. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  272. if err != nil {
  273. return input, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  274. }
  275. app := &porterv1.PorterApp{}
  276. err = helpers.UnmarshalContractObject(decoded, app)
  277. if err != nil {
  278. return input, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  279. }
  280. if app.Name == "" {
  281. return input, fmt.Errorf("app does not contain name")
  282. }
  283. input.AppName = app.Name
  284. if app.Build != nil {
  285. if os.Getenv("GITHUB_REPOSITORY_ID") == "" {
  286. input.Local = true
  287. return input, nil
  288. }
  289. gitRepoId, err := strconv.Atoi(os.Getenv("GITHUB_REPOSITORY_ID"))
  290. if err != nil {
  291. return input, fmt.Errorf("unable to parse GITHUB_REPOSITORY_ID to int: %w", err)
  292. }
  293. input.GitRepoID = uint(gitRepoId)
  294. input.GitRepoName = os.Getenv("GITHUB_REPOSITORY")
  295. input.GitBranch = os.Getenv("GITHUB_REF_NAME")
  296. input.PorterYamlPath = "porter.yaml"
  297. return input, nil
  298. }
  299. if app.Image != nil {
  300. input.ImageRepository = app.Image.Repository
  301. input.ImageTag = app.Image.Tag
  302. return input, nil
  303. }
  304. return input, nil
  305. }
  306. func buildSettingsFromBase64AppProto(base64AppProto string) (buildInput, error) {
  307. var buildSettings buildInput
  308. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  309. if err != nil {
  310. return buildSettings, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  311. }
  312. app := &porterv1.PorterApp{}
  313. err = helpers.UnmarshalContractObject(decoded, app)
  314. if err != nil {
  315. return buildSettings, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  316. }
  317. if app.Name == "" {
  318. return buildSettings, fmt.Errorf("app does not contain name")
  319. }
  320. if app.Build == nil {
  321. return buildSettings, fmt.Errorf("app does not contain build settings")
  322. }
  323. if app.Image == nil {
  324. return buildSettings, fmt.Errorf("app does not contain image settings")
  325. }
  326. return buildInput{
  327. AppName: app.Name,
  328. BuildContext: app.Build.Context,
  329. Dockerfile: app.Build.Dockerfile,
  330. BuildMethod: app.Build.Method,
  331. Builder: app.Build.Builder,
  332. BuildPacks: app.Build.Buildpacks,
  333. ImageTag: app.Image.Tag,
  334. RepositoryURL: app.Image.Repository,
  335. }, nil
  336. }
  337. func deploymentTargetFromConfig(ctx context.Context, client api.Client, projectID, clusterID uint, previewApply bool) (string, error) {
  338. var deploymentTargetID string
  339. targetResp, err := client.DefaultDeploymentTarget(ctx, projectID, clusterID)
  340. if err != nil {
  341. return deploymentTargetID, fmt.Errorf("error calling default deployment target endpoint: %w", err)
  342. }
  343. deploymentTargetID = targetResp.DeploymentTargetID
  344. if previewApply {
  345. var branchName string
  346. // branch name is set to different values in the GH env, depending on whether or not the workflow is triggered by a PR
  347. // issue is being tracked here: https://github.com/github/docs/issues/15319
  348. if os.Getenv("GITHUB_HEAD_REF") != "" {
  349. branchName = os.Getenv("GITHUB_HEAD_REF")
  350. } else if os.Getenv("GITHUB_REF_NAME") != "" {
  351. branchName = os.Getenv("GITHUB_REF_NAME")
  352. } else if branch, err := git.CurrentBranch(); err == nil {
  353. branchName = branch
  354. }
  355. if branchName == "" {
  356. return deploymentTargetID, errors.New("Branch name is empty. Please run apply in a git repository with access to the git CLI.")
  357. }
  358. targetResp, err := client.CreateDeploymentTarget(ctx, projectID, clusterID, branchName, true)
  359. if err != nil {
  360. return deploymentTargetID, fmt.Errorf("error calling create deployment target endpoint: %w", err)
  361. }
  362. deploymentTargetID = targetResp.DeploymentTargetID
  363. }
  364. if deploymentTargetID == "" {
  365. return deploymentTargetID, errors.New("deployment target id is empty")
  366. }
  367. return deploymentTargetID, nil
  368. }
  369. func imageTagFromBase64AppProto(base64AppProto string) (string, error) {
  370. var image string
  371. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  372. if err != nil {
  373. return image, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  374. }
  375. app := &porterv1.PorterApp{}
  376. err = helpers.UnmarshalContractObject(decoded, app)
  377. if err != nil {
  378. return image, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  379. }
  380. if app.Image == nil {
  381. return image, fmt.Errorf("app does not contain image settings")
  382. }
  383. if app.Image.Tag == "" {
  384. return image, fmt.Errorf("app does not contain image tag")
  385. }
  386. return app.Image.Tag, nil
  387. }
  388. func updateEnvGroupsInProto(ctx context.Context, base64AppProto string, envGroups []environment_groups.EnvironmentGroup) (string, error) {
  389. var editedB64AppProto string
  390. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  391. if err != nil {
  392. return editedB64AppProto, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  393. }
  394. app := &porterv1.PorterApp{}
  395. err = helpers.UnmarshalContractObject(decoded, app)
  396. if err != nil {
  397. return editedB64AppProto, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  398. }
  399. egs := make([]*porterv1.EnvGroup, 0)
  400. for _, envGroup := range envGroups {
  401. egs = append(egs, &porterv1.EnvGroup{
  402. Name: envGroup.Name,
  403. Version: int64(envGroup.Version),
  404. })
  405. }
  406. app.EnvGroups = egs
  407. marshalled, err := helpers.MarshalContractObject(ctx, app)
  408. if err != nil {
  409. return editedB64AppProto, fmt.Errorf("unable to marshal app back to json: %w", err)
  410. }
  411. editedB64AppProto = base64.StdEncoding.EncodeToString(marshalled)
  412. return editedB64AppProto, nil
  413. }
  414. func reportBuildFailure(ctx context.Context, client api.Client, appName string, cliConf config.CLIConfig, deploymentTargetID string, appRevisionID string, eventID string, buildError error) error {
  415. buildMetadata := make(map[string]interface{})
  416. buildMetadata["end_time"] = time.Now().UTC()
  417. // the below is a temporary solution until we can report build errors via telemetry from the CLI
  418. errorStringMap := make(map[string]string)
  419. errorStringMap["build-error"] = fmt.Sprintf("%+v", buildError)
  420. buildMetadata["errors"] = errorStringMap
  421. err := updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, deploymentTargetID, types.PorterAppEventType_Build, eventID, types.PorterAppEventStatus_Failed, buildMetadata)
  422. if err != nil {
  423. return err
  424. }
  425. _, err = client.UpdateRevisionStatus(ctx, cliConf.Project, cliConf.Cluster, appName, appRevisionID, models.AppRevisionStatus_BuildFailed)
  426. if err != nil {
  427. return err
  428. }
  429. return nil
  430. }