apply.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. package v2
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "errors"
  6. "fmt"
  7. "os"
  8. "os/signal"
  9. "path/filepath"
  10. "strconv"
  11. "strings"
  12. "syscall"
  13. "time"
  14. "github.com/fatih/color"
  15. "github.com/porter-dev/porter/api/server/handlers/porter_app"
  16. "github.com/porter-dev/porter/api/types"
  17. "github.com/porter-dev/porter/internal/models"
  18. "github.com/cli/cli/git"
  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. // ImageTagOverride is the image tag to use for the app
  33. ImageTagOverride string
  34. // PreviewApply is true when Apply should create a new deployment target matching current git branch and apply to that target
  35. PreviewApply bool
  36. // WaitForSuccessfulDeployment is true when Apply should wait for the update to complete before returning
  37. WaitForSuccessfulDeployment bool
  38. // PullImageBeforeBuild will attempt to pull the image before building if true
  39. PullImageBeforeBuild bool
  40. // WithPredeploy is true when Apply should run the predeploy step
  41. WithPredeploy bool
  42. // Exact is true when Apply should use the exact app config provided by the user
  43. Exact bool
  44. }
  45. // Apply implements the functionality of the `porter apply` command for validate apply v2 projects
  46. func Apply(ctx context.Context, inp ApplyInput) error {
  47. ctx, cancel := context.WithCancel(ctx)
  48. defer cancel()
  49. go func() {
  50. termChan := make(chan os.Signal, 1)
  51. signal.Notify(termChan, syscall.SIGINT, syscall.SIGTERM)
  52. select {
  53. case <-termChan:
  54. color.New(color.FgYellow).Printf("Shutdown signal received, cancelling processes\n") // nolint:errcheck,gosec
  55. cancel()
  56. case <-ctx.Done():
  57. }
  58. }()
  59. cliConf := inp.CLIConfig
  60. client := inp.Client
  61. deploymentTargetID, err := deploymentTargetFromConfig(ctx, client, cliConf.Project, cliConf.Cluster, inp.PreviewApply)
  62. if err != nil {
  63. return fmt.Errorf("error getting deployment target from config: %w", err)
  64. }
  65. var prNumber int
  66. prNumberEnv := os.Getenv("PORTER_PR_NUMBER")
  67. if prNumberEnv != "" {
  68. prNumber, err = strconv.Atoi(prNumberEnv)
  69. if err != nil {
  70. return fmt.Errorf("error parsing PORTER_PR_NUMBER to int: %w", err)
  71. }
  72. }
  73. porterYamlExists := len(inp.PorterYamlPath) != 0
  74. if porterYamlExists {
  75. _, err := os.Stat(filepath.Clean(inp.PorterYamlPath))
  76. if err != nil {
  77. if !os.IsNotExist(err) {
  78. return fmt.Errorf("error checking if porter yaml exists at path %s: %w", inp.PorterYamlPath, err)
  79. }
  80. // If a path was specified but the file does not exist, we will not immediately error out.
  81. // This supports users migrated from v1 who use a workflow file that always specifies a porter yaml path
  82. // in the apply command.
  83. porterYamlExists = false
  84. }
  85. }
  86. var b64YAML string
  87. if porterYamlExists {
  88. porterYaml, err := os.ReadFile(filepath.Clean(inp.PorterYamlPath))
  89. if err != nil {
  90. return fmt.Errorf("could not read porter yaml file: %w", err)
  91. }
  92. b64YAML = base64.StdEncoding.EncodeToString(porterYaml)
  93. color.New(color.FgGreen).Printf("Using Porter YAML at path: %s\n", inp.PorterYamlPath) // nolint:errcheck,gosec
  94. }
  95. commitSHA := commitSHAFromEnv()
  96. gitSource, err := gitSourceFromEnv()
  97. if err != nil {
  98. return fmt.Errorf("error getting git source from env: %w", err)
  99. }
  100. updateInput := api.UpdateAppInput{
  101. ProjectID: cliConf.Project,
  102. ClusterID: cliConf.Cluster,
  103. Name: inp.AppName,
  104. ImageTagOverride: inp.ImageTagOverride,
  105. GitSource: gitSource,
  106. DeploymentTargetId: deploymentTargetID,
  107. CommitSHA: commitSHA,
  108. Base64PorterYAML: b64YAML,
  109. WithPredeploy: inp.WithPredeploy,
  110. Exact: inp.Exact,
  111. }
  112. updateResp, err := client.UpdateApp(ctx, updateInput)
  113. if err != nil {
  114. return fmt.Errorf("error calling update app endpoint: %w", err)
  115. }
  116. if updateResp.AppRevisionId == "" {
  117. return errors.New("app revision id is empty")
  118. }
  119. appName := updateResp.AppName
  120. buildSettings, err := client.GetBuildFromRevision(ctx, cliConf.Project, cliConf.Cluster, appName, updateResp.AppRevisionId)
  121. if err != nil {
  122. return fmt.Errorf("error getting build from revision: %w", err)
  123. }
  124. if buildSettings != nil && buildSettings.Build.Method != "" {
  125. eventID, _ := createBuildEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, deploymentTargetID, commitSHA)
  126. var buildFinished bool
  127. var buildError error
  128. var buildLogs string
  129. defer func() {
  130. if buildError != nil && !errors.Is(buildError, context.Canceled) {
  131. reportBuildFailureInput := reportBuildFailureInput{
  132. client: client,
  133. appName: appName,
  134. cliConf: cliConf,
  135. deploymentTargetID: deploymentTargetID,
  136. appRevisionID: updateResp.AppRevisionId,
  137. eventID: eventID,
  138. commitSHA: commitSHA,
  139. prNumber: prNumber,
  140. buildError: buildError,
  141. buildLogs: buildLogs,
  142. }
  143. _ = reportBuildFailure(ctx, reportBuildFailureInput)
  144. return
  145. }
  146. if !buildFinished {
  147. buildMetadata := make(map[string]interface{})
  148. buildMetadata["end_time"] = time.Now().UTC()
  149. _ = updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, deploymentTargetID, types.PorterAppEventType_Build, eventID, types.PorterAppEventStatus_Canceled, buildMetadata)
  150. return
  151. }
  152. }()
  153. if commitSHA == "" {
  154. 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")
  155. }
  156. color.New(color.FgGreen).Printf("Building new image with tag %s...\n", commitSHA) // nolint:errcheck,gosec
  157. buildEnvVariables := make(map[string]string)
  158. for k, v := range buildSettings.BuildEnvVariables {
  159. buildEnvVariables[k] = v
  160. }
  161. // use all env variables from running container in build
  162. env := os.Environ()
  163. for _, v := range env {
  164. pair := strings.SplitN(v, "=", 2)
  165. if len(pair) == 2 {
  166. buildEnvVariables[pair[0]] = pair[1]
  167. }
  168. }
  169. buildInput, err := buildInputFromBuildSettings(buildInputFromBuildSettingsInput{
  170. projectID: cliConf.Project,
  171. appName: appName,
  172. commitSHA: commitSHA,
  173. image: buildSettings.Image,
  174. build: buildSettings.Build,
  175. buildEnv: buildEnvVariables,
  176. pullImageBeforeBuild: inp.PullImageBeforeBuild,
  177. })
  178. if err != nil {
  179. buildError = fmt.Errorf("error creating build input from build settings: %w", err)
  180. return buildError
  181. }
  182. buildOutput := build(ctx, client, buildInput)
  183. if buildOutput.Error != nil {
  184. buildError = fmt.Errorf("error building app: %w", buildOutput.Error)
  185. buildLogs = buildOutput.Logs
  186. return buildError
  187. }
  188. _, err = client.UpdateRevisionStatus(ctx, cliConf.Project, cliConf.Cluster, appName, updateResp.AppRevisionId, models.AppRevisionStatus_BuildSuccessful)
  189. if err != nil {
  190. buildError = fmt.Errorf("error updating revision status post build: %w", err)
  191. return buildError
  192. }
  193. color.New(color.FgGreen).Printf("Successfully built image (tag: %s)\n", commitSHA) // 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. buildFinished = true
  198. }
  199. color.New(color.FgGreen).Printf("Deploying new revision %s for app %s...\n", updateResp.AppRevisionId, appName) // nolint:errcheck,gosec
  200. now := time.Now().UTC()
  201. for {
  202. if time.Since(now) > checkDeployTimeout {
  203. return errors.New("timed out waiting for app to deploy")
  204. }
  205. status, err := client.GetRevisionStatus(ctx, cliConf.Project, cliConf.Cluster, appName, updateResp.AppRevisionId)
  206. if err != nil {
  207. return fmt.Errorf("error getting app revision status: %w", err)
  208. }
  209. if status == nil {
  210. return errors.New("unable to determine status of app revision")
  211. }
  212. if status.AppRevisionStatus.IsInTerminalStatus {
  213. break
  214. }
  215. if status.AppRevisionStatus.PredeployStarted {
  216. color.New(color.FgGreen).Printf("Waiting for predeploy to complete...\n") // nolint:errcheck,gosec
  217. }
  218. if status.AppRevisionStatus.InstallStarted {
  219. color.New(color.FgGreen).Printf("Waiting for deploy to complete...\n") // nolint:errcheck,gosec
  220. }
  221. time.Sleep(checkDeployFrequency)
  222. }
  223. _, _ = client.ReportRevisionStatus(ctx, api.ReportRevisionStatusInput{
  224. ProjectID: cliConf.Project,
  225. ClusterID: cliConf.Cluster,
  226. AppName: appName,
  227. AppRevisionID: updateResp.AppRevisionId,
  228. PRNumber: prNumber,
  229. CommitSHA: commitSHA,
  230. })
  231. status, err := client.GetRevisionStatus(ctx, cliConf.Project, cliConf.Cluster, appName, updateResp.AppRevisionId)
  232. if err != nil {
  233. return fmt.Errorf("error getting app revision status: %w", err)
  234. }
  235. if status == nil {
  236. return errors.New("unable to determine status of app revision")
  237. }
  238. if status.AppRevisionStatus.InstallFailed {
  239. return errors.New("app failed to deploy")
  240. }
  241. if status.AppRevisionStatus.PredeployFailed {
  242. return errors.New("predeploy failed for new revision")
  243. }
  244. color.New(color.FgGreen).Printf("Successfully applied new revision %s\n", updateResp.AppRevisionId) // nolint:errcheck,gosec
  245. if inp.WaitForSuccessfulDeployment {
  246. return waitForAppRevisionStatus(ctx, waitForAppRevisionStatusInput{
  247. ProjectID: cliConf.Project,
  248. ClusterID: cliConf.Cluster,
  249. AppName: appName,
  250. RevisionID: updateResp.AppRevisionId,
  251. Client: client,
  252. })
  253. }
  254. return nil
  255. }
  256. func commitSHAFromEnv() string {
  257. var commitSHA string
  258. if os.Getenv("PORTER_COMMIT_SHA") != "" {
  259. commitSHA = os.Getenv("PORTER_COMMIT_SHA")
  260. } else if os.Getenv("GITHUB_SHA") != "" {
  261. commitSHA = os.Getenv("GITHUB_SHA")
  262. } else if commit, err := git.LastCommit(); err == nil && commit != nil {
  263. commitSHA = commit.Sha
  264. }
  265. return commitSHA
  266. }
  267. func deploymentTargetFromConfig(ctx context.Context, client api.Client, projectID, clusterID uint, previewApply bool) (string, error) {
  268. var deploymentTargetID string
  269. if os.Getenv("PORTER_DEPLOYMENT_TARGET_ID") != "" {
  270. deploymentTargetID = os.Getenv("PORTER_DEPLOYMENT_TARGET_ID")
  271. }
  272. if deploymentTargetID == "" {
  273. targetResp, err := client.DefaultDeploymentTarget(ctx, projectID, clusterID)
  274. if err != nil {
  275. return deploymentTargetID, fmt.Errorf("error calling default deployment target endpoint: %w", err)
  276. }
  277. deploymentTargetID = targetResp.DeploymentTargetID
  278. }
  279. if previewApply {
  280. var branchName string
  281. // branch name is set to different values in the GH env, depending on whether or not the workflow is triggered by a PR
  282. // issue is being tracked here: https://github.com/github/docs/issues/15319
  283. if os.Getenv("GITHUB_HEAD_REF") != "" {
  284. branchName = os.Getenv("GITHUB_HEAD_REF")
  285. } else if os.Getenv("GITHUB_REF_NAME") != "" {
  286. branchName = os.Getenv("GITHUB_REF_NAME")
  287. } else if branch, err := git.CurrentBranch(); err == nil {
  288. branchName = branch
  289. }
  290. if branchName == "" {
  291. return deploymentTargetID, errors.New("branch name is empty. Please run apply in a git repository with access to the git CLI")
  292. }
  293. targetResp, err := client.CreateDeploymentTarget(ctx, projectID, clusterID, branchName, true)
  294. if err != nil {
  295. return deploymentTargetID, fmt.Errorf("error calling create deployment target endpoint: %w", err)
  296. }
  297. deploymentTargetID = targetResp.DeploymentTargetID
  298. }
  299. if deploymentTargetID == "" {
  300. return deploymentTargetID, errors.New("deployment target id is empty")
  301. }
  302. return deploymentTargetID, nil
  303. }
  304. type reportBuildFailureInput struct {
  305. client api.Client
  306. appName string
  307. cliConf config.CLIConfig
  308. deploymentTargetID string
  309. appRevisionID string
  310. eventID string
  311. buildError error
  312. buildLogs string
  313. commitSHA string
  314. prNumber int
  315. }
  316. func reportBuildFailure(ctx context.Context, inp reportBuildFailureInput) error {
  317. _, err := inp.client.UpdateRevisionStatus(ctx, inp.cliConf.Project, inp.cliConf.Cluster, inp.appName, inp.appRevisionID, models.AppRevisionStatus_BuildFailed)
  318. if err != nil {
  319. return err
  320. }
  321. buildMetadata := make(map[string]interface{})
  322. buildMetadata["end_time"] = time.Now().UTC()
  323. // the below is a temporary solution until we can report build errors via telemetry from the CLI
  324. errorStringMap := make(map[string]string)
  325. errorStringMap["build-error"] = fmt.Sprintf("%+v", inp.buildError)
  326. b64BuildLogs := base64.StdEncoding.EncodeToString([]byte(inp.buildLogs))
  327. // the key name below must be kept the same so that reportBuildStatus in the CreateOrUpdatePorterAppEvent handler reports logs correctly
  328. errorStringMap["b64-build-logs"] = b64BuildLogs
  329. buildMetadata["errors"] = errorStringMap
  330. err = updateExistingEvent(ctx, inp.client, inp.appName, inp.cliConf.Project, inp.cliConf.Cluster, inp.deploymentTargetID, types.PorterAppEventType_Build, inp.eventID, types.PorterAppEventStatus_Failed, buildMetadata)
  331. if err != nil {
  332. return err
  333. }
  334. _, err = inp.client.ReportRevisionStatus(ctx, api.ReportRevisionStatusInput{
  335. ProjectID: inp.cliConf.Project,
  336. ClusterID: inp.cliConf.Cluster,
  337. AppName: inp.appName,
  338. AppRevisionID: inp.appRevisionID,
  339. PRNumber: inp.prNumber,
  340. CommitSHA: inp.commitSHA,
  341. })
  342. if err != nil {
  343. return err
  344. }
  345. return nil
  346. }
  347. // checkDeployTimeout is the timeout for checking if an app has been deployed
  348. const checkDeployTimeout = 15 * time.Minute
  349. // checkDeployFrequency is the frequency for checking if an app has been deployed
  350. const checkDeployFrequency = 10 * time.Second
  351. func gitSourceFromEnv() (porter_app.GitSource, error) {
  352. var source porter_app.GitSource
  353. var repoID uint
  354. if os.Getenv("GITHUB_REPOSITORY_ID") != "" {
  355. id, err := strconv.Atoi(os.Getenv("GITHUB_REPOSITORY_ID"))
  356. if err != nil {
  357. return source, fmt.Errorf("unable to parse GITHUB_REPOSITORY_ID to int: %w", err)
  358. }
  359. repoID = uint(id)
  360. }
  361. return porter_app.GitSource{
  362. GitBranch: os.Getenv("GITHUB_REF_NAME"),
  363. GitRepoID: repoID,
  364. GitRepoName: os.Getenv("GITHUB_REPOSITORY"),
  365. }, nil
  366. }
  367. type buildInputFromBuildSettingsInput struct {
  368. projectID uint
  369. appName string
  370. commitSHA string
  371. image porter_app.Image
  372. build porter_app.BuildSettings
  373. buildEnv map[string]string
  374. pullImageBeforeBuild bool
  375. }
  376. func buildInputFromBuildSettings(inp buildInputFromBuildSettingsInput) (buildInput, error) {
  377. var buildSettings buildInput
  378. if inp.appName == "" {
  379. return buildSettings, errors.New("app name is empty")
  380. }
  381. if inp.image.Repository == "" {
  382. return buildSettings, errors.New("image repository is empty")
  383. }
  384. if inp.build.Method == "" {
  385. return buildSettings, errors.New("build method is empty")
  386. }
  387. if inp.commitSHA == "" {
  388. return buildSettings, errors.New("commit SHA is empty")
  389. }
  390. return buildInput{
  391. ProjectID: inp.projectID,
  392. AppName: inp.appName,
  393. BuildContext: inp.build.Context,
  394. Dockerfile: inp.build.Dockerfile,
  395. BuildMethod: inp.build.Method,
  396. Builder: inp.build.Builder,
  397. BuildPacks: inp.build.Buildpacks,
  398. ImageTag: inp.commitSHA,
  399. RepositoryURL: inp.image.Repository,
  400. CurrentImageTag: inp.image.Tag,
  401. Env: inp.buildEnv,
  402. PullImageBeforeBuild: inp.pullImageBeforeBuild,
  403. }, nil
  404. }