apply.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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. // we only need to create the app if a porter yaml is provided (otherwise it must already exist)
  62. createPorterAppDBEntryInp, err := createPorterAppDbEntryInputFromProtoAndEnv(parseResp.B64AppProto)
  63. if err != nil {
  64. return fmt.Errorf("error creating porter app db entry input from proto: %w", err)
  65. }
  66. err = client.CreatePorterAppDBEntry(ctx, cliConf.Project, cliConf.Cluster, createPorterAppDBEntryInp)
  67. if err != nil {
  68. return fmt.Errorf("error creating porter app db entry: %w", err)
  69. }
  70. // override app name if provided
  71. appName, err = appNameFromB64AppProto(parseResp.B64AppProto)
  72. if err != nil {
  73. return fmt.Errorf("error getting app name from b64 app proto: %w", err)
  74. }
  75. envGroupResp, err := client.CreateOrUpdateAppEnvironment(ctx, cliConf.Project, cliConf.Cluster, appName, targetResp.DeploymentTargetID, parseResp.EnvVariables, parseResp.EnvSecrets, parseResp.B64AppProto)
  76. if err != nil {
  77. return fmt.Errorf("error calling create or update app environment group endpoint: %w", err)
  78. }
  79. b64AppProto, err = updateEnvGroupsInProto(ctx, b64AppProto, envGroupResp.EnvGroups)
  80. if err != nil {
  81. return fmt.Errorf("error updating app env group in proto: %w", err)
  82. }
  83. color.New(color.FgGreen).Printf("Successfully parsed Porter YAML: applying app \"%s\"\n", appName) // nolint:errcheck,gosec
  84. }
  85. if appName == "" {
  86. 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.")
  87. }
  88. var commitSHA string
  89. if os.Getenv("PORTER_COMMIT_SHA") != "" {
  90. commitSHA = os.Getenv("PORTER_COMMIT_SHA")
  91. } else if os.Getenv("GITHUB_SHA") != "" {
  92. commitSHA = os.Getenv("GITHUB_SHA")
  93. } else if commit, err := git.LastCommit(); err == nil && commit != nil {
  94. commitSHA = commit.Sha
  95. }
  96. validateResp, err := client.ValidatePorterApp(ctx, cliConf.Project, cliConf.Cluster, appName, b64AppProto, targetResp.DeploymentTargetID, commitSHA)
  97. if err != nil {
  98. return fmt.Errorf("error calling validate endpoint: %w", err)
  99. }
  100. if validateResp.ValidatedBase64AppProto == "" {
  101. return errors.New("validated b64 app proto is empty")
  102. }
  103. base64AppProto := validateResp.ValidatedBase64AppProto
  104. applyResp, err := client.ApplyPorterApp(ctx, cliConf.Project, cliConf.Cluster, base64AppProto, targetResp.DeploymentTargetID, "", forceBuild)
  105. if err != nil {
  106. return fmt.Errorf("error calling apply endpoint: %w", err)
  107. }
  108. if applyResp.AppRevisionId == "" {
  109. return errors.New("app revision id is empty")
  110. }
  111. if applyResp.CLIAction == porterv1.EnumCLIAction_ENUM_CLI_ACTION_BUILD {
  112. color.New(color.FgGreen).Printf("Building new image...\n") // nolint:errcheck,gosec
  113. eventID, _ := createBuildEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, targetResp.DeploymentTargetID)
  114. if commitSHA == "" {
  115. 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.")
  116. }
  117. buildSettings, err := buildSettingsFromBase64AppProto(base64AppProto)
  118. if err != nil {
  119. return fmt.Errorf("error building settings from base64 app proto: %w", err)
  120. }
  121. currentAppRevisionResp, err := client.CurrentAppRevision(ctx, cliConf.Project, cliConf.Cluster, appName, targetResp.DeploymentTargetID)
  122. if err != nil {
  123. return fmt.Errorf("error getting current app revision: %w", err)
  124. }
  125. if currentAppRevisionResp == nil {
  126. return errors.New("current app revision is nil")
  127. }
  128. appRevision := currentAppRevisionResp.AppRevision
  129. if appRevision.B64AppProto == "" {
  130. return errors.New("current app revision b64 app proto is empty")
  131. }
  132. currentImageTag, err := imageTagFromBase64AppProto(appRevision.B64AppProto)
  133. if err != nil {
  134. return fmt.Errorf("error getting image tag from current app revision: %w", err)
  135. }
  136. buildSettings.CurrentImageTag = currentImageTag
  137. buildSettings.ProjectID = cliConf.Project
  138. buildEnv, err := client.GetBuildEnv(ctx, cliConf.Project, cliConf.Cluster, appName, targetResp.DeploymentTargetID)
  139. if err != nil {
  140. return fmt.Errorf("error getting build env: %w", err)
  141. }
  142. buildSettings.Env = buildEnv.BuildEnvVariables
  143. err = build(ctx, client, buildSettings)
  144. buildMetadata := make(map[string]interface{})
  145. buildMetadata["end_time"] = time.Now().UTC()
  146. if err != nil {
  147. _ = updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, targetResp.DeploymentTargetID, eventID, types.PorterAppEventStatus_Failed, buildMetadata)
  148. _, _ = client.UpdateRevisionStatus(ctx, cliConf.Project, cliConf.Cluster, appName, applyResp.AppRevisionId, models.AppRevisionStatus_BuildFailed)
  149. return fmt.Errorf("error building app: %w", err)
  150. }
  151. color.New(color.FgGreen).Printf("Successfully built image (tag: %s)\n", buildSettings.ImageTag) // nolint:errcheck,gosec
  152. _ = updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, targetResp.DeploymentTargetID, eventID, types.PorterAppEventStatus_Success, buildMetadata)
  153. applyResp, err = client.ApplyPorterApp(ctx, cliConf.Project, cliConf.Cluster, "", "", applyResp.AppRevisionId, !forceBuild)
  154. if err != nil {
  155. return fmt.Errorf("apply error post-build: %w", err)
  156. }
  157. }
  158. color.New(color.FgGreen).Printf("Image tag exists in repository\n") // nolint:errcheck,gosec
  159. if applyResp.CLIAction == porterv1.EnumCLIAction_ENUM_CLI_ACTION_TRACK_PREDEPLOY {
  160. color.New(color.FgGreen).Printf("Waiting for predeploy to complete...\n") // nolint:errcheck,gosec
  161. now := time.Now().UTC()
  162. eventID, _ := createPredeployEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, targetResp.DeploymentTargetID, now, applyResp.AppRevisionId)
  163. eventStatus := types.PorterAppEventStatus_Success
  164. for {
  165. if time.Since(now) > checkPredeployTimeout {
  166. return errors.New("timed out waiting for predeploy to complete")
  167. }
  168. predeployStatusResp, err := client.PredeployStatus(ctx, cliConf.Project, cliConf.Cluster, appName, applyResp.AppRevisionId)
  169. if err != nil {
  170. return fmt.Errorf("error calling predeploy status endpoint: %w", err)
  171. }
  172. if predeployStatusResp.Status == porter_app.PredeployStatus_Failed {
  173. eventStatus = types.PorterAppEventStatus_Failed
  174. break
  175. }
  176. if predeployStatusResp.Status == porter_app.PredeployStatus_Successful {
  177. break
  178. }
  179. time.Sleep(checkPredeployFrequency)
  180. }
  181. metadata := make(map[string]interface{})
  182. metadata["end_time"] = time.Now().UTC()
  183. _ = updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, targetResp.DeploymentTargetID, eventID, eventStatus, metadata)
  184. applyResp, err = client.ApplyPorterApp(ctx, cliConf.Project, cliConf.Cluster, "", "", applyResp.AppRevisionId, !forceBuild)
  185. if err != nil {
  186. return fmt.Errorf("apply error post-predeploy: %w", err)
  187. }
  188. }
  189. if applyResp.CLIAction != porterv1.EnumCLIAction_ENUM_CLI_ACTION_NONE {
  190. return fmt.Errorf("unexpected CLI action: %s", applyResp.CLIAction)
  191. }
  192. color.New(color.FgGreen).Printf("Successfully applied new revision %s for app %s\n", applyResp.AppRevisionId, appName) // nolint:errcheck,gosec
  193. return nil
  194. }
  195. // checkPredeployTimeout is the maximum amount of time the CLI will wait for a predeploy to complete before calling apply again
  196. const checkPredeployTimeout = 60 * time.Minute
  197. // checkPredeployFrequency is the frequency at which the CLI will check the status of a predeploy
  198. const checkPredeployFrequency = 10 * time.Second
  199. func appNameFromB64AppProto(base64AppProto string) (string, error) {
  200. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  201. if err != nil {
  202. return "", fmt.Errorf("unable to decode base64 app for revision: %w", err)
  203. }
  204. app := &porterv1.PorterApp{}
  205. err = helpers.UnmarshalContractObject(decoded, app)
  206. if err != nil {
  207. return "", fmt.Errorf("unable to unmarshal app for revision: %w", err)
  208. }
  209. if app.Name == "" {
  210. return "", fmt.Errorf("app does not contain name")
  211. }
  212. return app.Name, nil
  213. }
  214. func createPorterAppDbEntryInputFromProtoAndEnv(base64AppProto string) (api.CreatePorterAppDBEntryInput, error) {
  215. var input api.CreatePorterAppDBEntryInput
  216. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  217. if err != nil {
  218. return input, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  219. }
  220. app := &porterv1.PorterApp{}
  221. err = helpers.UnmarshalContractObject(decoded, app)
  222. if err != nil {
  223. return input, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  224. }
  225. if app.Name == "" {
  226. return input, fmt.Errorf("app does not contain name")
  227. }
  228. input.AppName = app.Name
  229. if app.Build != nil {
  230. if os.Getenv("GITHUB_REPOSITORY_ID") == "" {
  231. input.Local = true
  232. return input, nil
  233. }
  234. gitRepoId, err := strconv.Atoi(os.Getenv("GITHUB_REPOSITORY_ID"))
  235. if err != nil {
  236. return input, fmt.Errorf("unable to parse GITHUB_REPOSITORY_ID to int: %w", err)
  237. }
  238. input.GitRepoID = uint(gitRepoId)
  239. input.GitRepoName = os.Getenv("GITHUB_REPOSITORY")
  240. input.GitBranch = os.Getenv("GITHUB_REF_NAME")
  241. input.PorterYamlPath = "porter.yaml"
  242. return input, nil
  243. }
  244. if app.Image != nil {
  245. input.ImageRepository = app.Image.Repository
  246. input.ImageTag = app.Image.Tag
  247. return input, nil
  248. }
  249. return input, fmt.Errorf("app does not contain build or image settings")
  250. }
  251. func buildSettingsFromBase64AppProto(base64AppProto string) (buildInput, error) {
  252. var buildSettings buildInput
  253. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  254. if err != nil {
  255. return buildSettings, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  256. }
  257. app := &porterv1.PorterApp{}
  258. err = helpers.UnmarshalContractObject(decoded, app)
  259. if err != nil {
  260. return buildSettings, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  261. }
  262. if app.Name == "" {
  263. return buildSettings, fmt.Errorf("app does not contain name")
  264. }
  265. if app.Build == nil {
  266. return buildSettings, fmt.Errorf("app does not contain build settings")
  267. }
  268. if app.Image == nil {
  269. return buildSettings, fmt.Errorf("app does not contain image settings")
  270. }
  271. return buildInput{
  272. AppName: app.Name,
  273. BuildContext: app.Build.Context,
  274. Dockerfile: app.Build.Dockerfile,
  275. BuildMethod: app.Build.Method,
  276. Builder: app.Build.Builder,
  277. BuildPacks: app.Build.Buildpacks,
  278. ImageTag: app.Image.Tag,
  279. RepositoryURL: app.Image.Repository,
  280. }, nil
  281. }
  282. func imageTagFromBase64AppProto(base64AppProto string) (string, error) {
  283. var image string
  284. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  285. if err != nil {
  286. return image, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  287. }
  288. app := &porterv1.PorterApp{}
  289. err = helpers.UnmarshalContractObject(decoded, app)
  290. if err != nil {
  291. return image, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  292. }
  293. if app.Image == nil {
  294. return image, fmt.Errorf("app does not contain image settings")
  295. }
  296. if app.Image.Tag == "" {
  297. return image, fmt.Errorf("app does not contain image tag")
  298. }
  299. return app.Image.Tag, nil
  300. }
  301. func updateEnvGroupsInProto(ctx context.Context, base64AppProto string, envGroups []environment_groups.EnvironmentGroup) (string, error) {
  302. var editedB64AppProto string
  303. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  304. if err != nil {
  305. return editedB64AppProto, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  306. }
  307. app := &porterv1.PorterApp{}
  308. err = helpers.UnmarshalContractObject(decoded, app)
  309. if err != nil {
  310. return editedB64AppProto, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  311. }
  312. egs := make([]*porterv1.EnvGroup, 0)
  313. for _, envGroup := range envGroups {
  314. egs = append(egs, &porterv1.EnvGroup{
  315. Name: envGroup.Name,
  316. Version: int64(envGroup.Version),
  317. })
  318. }
  319. app.EnvGroups = egs
  320. marshalled, err := helpers.MarshalContractObject(ctx, app)
  321. if err != nil {
  322. return editedB64AppProto, fmt.Errorf("unable to marshal app back to json: %w", err)
  323. }
  324. editedB64AppProto = base64.StdEncoding.EncodeToString(marshalled)
  325. return editedB64AppProto, nil
  326. }