apply.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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. 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.")
  119. }
  120. buildSettings, err := buildSettingsFromBase64AppProto(base64AppProto)
  121. if err != nil {
  122. return fmt.Errorf("error building settings from base64 app proto: %w", err)
  123. }
  124. currentAppRevisionResp, err := client.CurrentAppRevision(ctx, cliConf.Project, cliConf.Cluster, appName, targetResp.DeploymentTargetID)
  125. if err != nil {
  126. return fmt.Errorf("error getting current app revision: %w", err)
  127. }
  128. if currentAppRevisionResp == nil {
  129. return errors.New("current app revision is nil")
  130. }
  131. appRevision := currentAppRevisionResp.AppRevision
  132. if appRevision.B64AppProto == "" {
  133. return errors.New("current app revision b64 app proto is empty")
  134. }
  135. currentImageTag, err := imageTagFromBase64AppProto(appRevision.B64AppProto)
  136. if err != nil {
  137. return fmt.Errorf("error getting image tag from current app revision: %w", err)
  138. }
  139. buildSettings.CurrentImageTag = currentImageTag
  140. buildSettings.ProjectID = cliConf.Project
  141. buildEnv, err := client.GetBuildEnv(ctx, cliConf.Project, cliConf.Cluster, appName, appRevision.ID)
  142. if err != nil {
  143. return fmt.Errorf("error getting build env: %w", err)
  144. }
  145. buildSettings.Env = buildEnv.BuildEnvVariables
  146. err = build(ctx, client, buildSettings)
  147. buildMetadata := make(map[string]interface{})
  148. buildMetadata["end_time"] = time.Now().UTC()
  149. if err != nil {
  150. _ = updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, targetResp.DeploymentTargetID, eventID, types.PorterAppEventStatus_Failed, buildMetadata)
  151. _, _ = client.UpdateRevisionStatus(ctx, cliConf.Project, cliConf.Cluster, appName, applyResp.AppRevisionId, models.AppRevisionStatus_BuildFailed)
  152. return fmt.Errorf("error building app: %w", err)
  153. }
  154. color.New(color.FgGreen).Printf("Successfully built image (tag: %s)\n", buildSettings.ImageTag) // nolint:errcheck,gosec
  155. _ = updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, targetResp.DeploymentTargetID, eventID, types.PorterAppEventStatus_Success, buildMetadata)
  156. applyResp, err = client.ApplyPorterApp(ctx, cliConf.Project, cliConf.Cluster, "", "", applyResp.AppRevisionId, !forceBuild)
  157. if err != nil {
  158. return fmt.Errorf("apply error post-build: %w", err)
  159. }
  160. }
  161. color.New(color.FgGreen).Printf("Image tag exists in repository\n") // nolint:errcheck,gosec
  162. if applyResp.CLIAction == porterv1.EnumCLIAction_ENUM_CLI_ACTION_TRACK_PREDEPLOY {
  163. color.New(color.FgGreen).Printf("Waiting for predeploy to complete...\n") // nolint:errcheck,gosec
  164. now := time.Now().UTC()
  165. eventID, _ := createPredeployEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, targetResp.DeploymentTargetID, now, applyResp.AppRevisionId)
  166. eventStatus := types.PorterAppEventStatus_Success
  167. for {
  168. if time.Since(now) > checkPredeployTimeout {
  169. return errors.New("timed out waiting for predeploy to complete")
  170. }
  171. predeployStatusResp, err := client.PredeployStatus(ctx, cliConf.Project, cliConf.Cluster, appName, applyResp.AppRevisionId)
  172. if err != nil {
  173. return fmt.Errorf("error calling predeploy status endpoint: %w", err)
  174. }
  175. if predeployStatusResp.Status == porter_app.PredeployStatus_Failed {
  176. eventStatus = types.PorterAppEventStatus_Failed
  177. break
  178. }
  179. if predeployStatusResp.Status == porter_app.PredeployStatus_Successful {
  180. break
  181. }
  182. time.Sleep(checkPredeployFrequency)
  183. }
  184. metadata := make(map[string]interface{})
  185. metadata["end_time"] = time.Now().UTC()
  186. _ = updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, targetResp.DeploymentTargetID, eventID, eventStatus, metadata)
  187. applyResp, err = client.ApplyPorterApp(ctx, cliConf.Project, cliConf.Cluster, "", "", applyResp.AppRevisionId, !forceBuild)
  188. if err != nil {
  189. return fmt.Errorf("apply error post-predeploy: %w", err)
  190. }
  191. }
  192. if applyResp.CLIAction != porterv1.EnumCLIAction_ENUM_CLI_ACTION_NONE {
  193. return fmt.Errorf("unexpected CLI action: %s", applyResp.CLIAction)
  194. }
  195. color.New(color.FgGreen).Printf("Successfully applied new revision %s for app %s\n", applyResp.AppRevisionId, appName) // nolint:errcheck,gosec
  196. return nil
  197. }
  198. // checkPredeployTimeout is the maximum amount of time the CLI will wait for a predeploy to complete before calling apply again
  199. const checkPredeployTimeout = 60 * time.Minute
  200. // checkPredeployFrequency is the frequency at which the CLI will check the status of a predeploy
  201. const checkPredeployFrequency = 10 * time.Second
  202. func appNameFromB64AppProto(base64AppProto string) (string, error) {
  203. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  204. if err != nil {
  205. return "", fmt.Errorf("unable to decode base64 app for revision: %w", err)
  206. }
  207. app := &porterv1.PorterApp{}
  208. err = helpers.UnmarshalContractObject(decoded, app)
  209. if err != nil {
  210. return "", fmt.Errorf("unable to unmarshal app for revision: %w", err)
  211. }
  212. if app.Name == "" {
  213. return "", fmt.Errorf("app does not contain name")
  214. }
  215. return app.Name, nil
  216. }
  217. func createPorterAppDbEntryInputFromProtoAndEnv(base64AppProto string) (api.CreatePorterAppDBEntryInput, error) {
  218. var input api.CreatePorterAppDBEntryInput
  219. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  220. if err != nil {
  221. return input, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  222. }
  223. app := &porterv1.PorterApp{}
  224. err = helpers.UnmarshalContractObject(decoded, app)
  225. if err != nil {
  226. return input, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  227. }
  228. if app.Name == "" {
  229. return input, fmt.Errorf("app does not contain name")
  230. }
  231. input.AppName = app.Name
  232. if app.Build != nil {
  233. if os.Getenv("GITHUB_REPOSITORY_ID") == "" {
  234. input.Local = true
  235. return input, nil
  236. }
  237. gitRepoId, err := strconv.Atoi(os.Getenv("GITHUB_REPOSITORY_ID"))
  238. if err != nil {
  239. return input, fmt.Errorf("unable to parse GITHUB_REPOSITORY_ID to int: %w", err)
  240. }
  241. input.GitRepoID = uint(gitRepoId)
  242. input.GitRepoName = os.Getenv("GITHUB_REPOSITORY")
  243. input.GitBranch = os.Getenv("GITHUB_REF_NAME")
  244. input.PorterYamlPath = "porter.yaml"
  245. return input, nil
  246. }
  247. if app.Image != nil {
  248. input.ImageRepository = app.Image.Repository
  249. input.ImageTag = app.Image.Tag
  250. return input, nil
  251. }
  252. return input, nil
  253. }
  254. func buildSettingsFromBase64AppProto(base64AppProto string) (buildInput, error) {
  255. var buildSettings buildInput
  256. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  257. if err != nil {
  258. return buildSettings, 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 buildSettings, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  264. }
  265. if app.Name == "" {
  266. return buildSettings, fmt.Errorf("app does not contain name")
  267. }
  268. if app.Build == nil {
  269. return buildSettings, fmt.Errorf("app does not contain build settings")
  270. }
  271. if app.Image == nil {
  272. return buildSettings, fmt.Errorf("app does not contain image settings")
  273. }
  274. return buildInput{
  275. AppName: app.Name,
  276. BuildContext: app.Build.Context,
  277. Dockerfile: app.Build.Dockerfile,
  278. BuildMethod: app.Build.Method,
  279. Builder: app.Build.Builder,
  280. BuildPacks: app.Build.Buildpacks,
  281. ImageTag: app.Image.Tag,
  282. RepositoryURL: app.Image.Repository,
  283. }, nil
  284. }
  285. func imageTagFromBase64AppProto(base64AppProto string) (string, error) {
  286. var image string
  287. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  288. if err != nil {
  289. return image, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  290. }
  291. app := &porterv1.PorterApp{}
  292. err = helpers.UnmarshalContractObject(decoded, app)
  293. if err != nil {
  294. return image, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  295. }
  296. if app.Image == nil {
  297. return image, fmt.Errorf("app does not contain image settings")
  298. }
  299. if app.Image.Tag == "" {
  300. return image, fmt.Errorf("app does not contain image tag")
  301. }
  302. return app.Image.Tag, nil
  303. }
  304. func updateEnvGroupsInProto(ctx context.Context, base64AppProto string, envGroups []environment_groups.EnvironmentGroup) (string, error) {
  305. var editedB64AppProto string
  306. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  307. if err != nil {
  308. return editedB64AppProto, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  309. }
  310. app := &porterv1.PorterApp{}
  311. err = helpers.UnmarshalContractObject(decoded, app)
  312. if err != nil {
  313. return editedB64AppProto, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  314. }
  315. egs := make([]*porterv1.EnvGroup, 0)
  316. for _, envGroup := range envGroups {
  317. egs = append(egs, &porterv1.EnvGroup{
  318. Name: envGroup.Name,
  319. Version: int64(envGroup.Version),
  320. })
  321. }
  322. app.EnvGroups = egs
  323. marshalled, err := helpers.MarshalContractObject(ctx, app)
  324. if err != nil {
  325. return editedB64AppProto, fmt.Errorf("unable to marshal app back to json: %w", err)
  326. }
  327. editedB64AppProto = base64.StdEncoding.EncodeToString(marshalled)
  328. return editedB64AppProto, nil
  329. }