apply.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  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/cli/cli/git"
  14. "github.com/fatih/color"
  15. "github.com/porter-dev/api-contracts/generated/go/helpers"
  16. porterv1 "github.com/porter-dev/api-contracts/generated/go/porter/v1"
  17. api "github.com/porter-dev/porter/api/client"
  18. "github.com/porter-dev/porter/cli/cmd/config"
  19. )
  20. // Apply implements the functionality of the `porter apply` command for validate apply v2 projects
  21. func Apply(ctx context.Context, cliConf config.CLIConfig, client api.Client, porterYamlPath string) error {
  22. if len(porterYamlPath) == 0 {
  23. return fmt.Errorf("porter yaml is empty")
  24. }
  25. porterYaml, err := os.ReadFile(filepath.Clean(porterYamlPath))
  26. if err != nil {
  27. return fmt.Errorf("could not read porter yaml file: %w", err)
  28. }
  29. b64YAML := base64.StdEncoding.EncodeToString(porterYaml)
  30. // last argument is passed to accommodate users with v1 porter yamls
  31. parseResp, err := client.ParseYAML(ctx, cliConf.Project, cliConf.Cluster, b64YAML, os.Getenv("PORTER_STACK_NAME"))
  32. if err != nil {
  33. return fmt.Errorf("error calling parse yaml endpoint: %w", err)
  34. }
  35. if parseResp.B64AppProto == "" {
  36. return errors.New("b64 app proto is empty")
  37. }
  38. appName, err := appNameFromB64AppProto(parseResp.B64AppProto)
  39. if err != nil {
  40. return fmt.Errorf("error getting app name from b64 app proto: %w", err)
  41. }
  42. color.New(color.FgGreen).Printf("Successfully parsed Porter YAML: applying app \"%s\"\n", appName) // nolint:errcheck,gosec
  43. targetResp, err := client.DefaultDeploymentTarget(ctx, cliConf.Project, cliConf.Cluster)
  44. if err != nil {
  45. return fmt.Errorf("error calling default deployment target endpoint: %w", err)
  46. }
  47. if targetResp.DeploymentTargetID == "" {
  48. return errors.New("deployment target id is empty")
  49. }
  50. var commitSHA string
  51. if os.Getenv("PORTER_COMMIT_SHA") != "" {
  52. commitSHA = os.Getenv("PORTER_COMMIT_SHA")
  53. } else if os.Getenv("GITHUB_SHA") != "" {
  54. commitSHA = os.Getenv("GITHUB_SHA")
  55. } else if commit, err := git.LastCommit(); err == nil && commit != nil {
  56. commitSHA = commit.Sha
  57. }
  58. validateResp, err := client.ValidatePorterApp(ctx, cliConf.Project, cliConf.Cluster, parseResp.B64AppProto, targetResp.DeploymentTargetID, commitSHA)
  59. if err != nil {
  60. return fmt.Errorf("error calling validate endpoint: %w", err)
  61. }
  62. if validateResp.ValidatedBase64AppProto == "" {
  63. return errors.New("validated b64 app proto is empty")
  64. }
  65. base64AppProto := validateResp.ValidatedBase64AppProto
  66. createPorterAppDBEntryInp, err := createPorterAppDbEntryInputFromProtoAndEnv(validateResp.ValidatedBase64AppProto)
  67. if err != nil {
  68. return fmt.Errorf("error creating porter app db entry input from proto: %w", err)
  69. }
  70. err = client.CreatePorterAppDBEntry(ctx, cliConf.Project, cliConf.Cluster, createPorterAppDBEntryInp)
  71. if err != nil {
  72. return fmt.Errorf("error creating porter app db entry: %w", err)
  73. }
  74. base64AppProtoWithSubdomains, err := addPorterSubdomainsIfNecessary(ctx, client, cliConf.Project, cliConf.Cluster, base64AppProto)
  75. if err != nil {
  76. return fmt.Errorf("error creating subdomains: %w", err)
  77. }
  78. applyResp, err := client.ApplyPorterApp(ctx, cliConf.Project, cliConf.Cluster, base64AppProtoWithSubdomains, targetResp.DeploymentTargetID, "")
  79. if err != nil {
  80. return fmt.Errorf("error calling apply endpoint: %w", err)
  81. }
  82. if applyResp.AppRevisionId == "" {
  83. return errors.New("app revision id is empty")
  84. }
  85. if applyResp.CLIAction == porterv1.EnumCLIAction_ENUM_CLI_ACTION_BUILD {
  86. color.New(color.FgGreen).Printf("Building new image...\n") // nolint:errcheck,gosec
  87. eventID, _ := createBuildEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, targetResp.DeploymentTargetID)
  88. if commitSHA == "" {
  89. 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.")
  90. }
  91. buildSettings, err := buildSettingsFromBase64AppProto(base64AppProto)
  92. if err != nil {
  93. return fmt.Errorf("error building settings from base64 app proto: %w", err)
  94. }
  95. currentAppRevisionResp, err := client.CurrentAppRevision(ctx, cliConf.Project, cliConf.Cluster, appName, targetResp.DeploymentTargetID)
  96. if err != nil {
  97. return fmt.Errorf("error getting current app revision: %w", err)
  98. }
  99. if currentAppRevisionResp == nil {
  100. return errors.New("current app revision is nil")
  101. }
  102. appRevision := currentAppRevisionResp.AppRevision
  103. if appRevision.B64AppProto == "" {
  104. return errors.New("current app revision b64 app proto is empty")
  105. }
  106. currentImageTag, err := imageTagFromBase64AppProto(appRevision.B64AppProto)
  107. if err != nil {
  108. return fmt.Errorf("error getting image tag from current app revision: %w", err)
  109. }
  110. buildSettings.CurrentImageTag = currentImageTag
  111. buildSettings.ProjectID = cliConf.Project
  112. err = build(ctx, client, buildSettings)
  113. buildMetadata := make(map[string]interface{})
  114. buildMetadata["end_time"] = time.Now().UTC()
  115. if err != nil {
  116. _ = updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, targetResp.DeploymentTargetID, eventID, types.PorterAppEventStatus_Failed, buildMetadata)
  117. return fmt.Errorf("error building app: %w", err)
  118. }
  119. color.New(color.FgGreen).Printf("Successfully built image (tag: %s)\n", buildSettings.ImageTag) // nolint:errcheck,gosec
  120. _ = updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, targetResp.DeploymentTargetID, eventID, types.PorterAppEventStatus_Success, buildMetadata)
  121. applyResp, err = client.ApplyPorterApp(ctx, cliConf.Project, cliConf.Cluster, "", "", applyResp.AppRevisionId)
  122. if err != nil {
  123. return fmt.Errorf("apply error post-build: %w", err)
  124. }
  125. }
  126. if applyResp.CLIAction == porterv1.EnumCLIAction_ENUM_CLI_ACTION_TRACK_PREDEPLOY {
  127. color.New(color.FgGreen).Printf("Waiting for predeploy to complete...\n") // nolint:errcheck,gosec
  128. now := time.Now().UTC()
  129. eventID, _ := createPredeployEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, targetResp.DeploymentTargetID, now, applyResp.AppRevisionId)
  130. eventStatus := types.PorterAppEventStatus_Success
  131. for {
  132. if time.Since(now) > checkPredeployTimeout {
  133. return errors.New("timed out waiting for predeploy to complete")
  134. }
  135. predeployStatusResp, err := client.PredeployStatus(ctx, cliConf.Project, cliConf.Cluster, appName, applyResp.AppRevisionId)
  136. if err != nil {
  137. return fmt.Errorf("error calling predeploy status endpoint: %w", err)
  138. }
  139. if predeployStatusResp.Status == porter_app.PredeployStatus_Failed {
  140. eventStatus = types.PorterAppEventStatus_Failed
  141. break
  142. }
  143. if predeployStatusResp.Status == porter_app.PredeployStatus_Successful {
  144. break
  145. }
  146. time.Sleep(checkPredeployFrequency)
  147. }
  148. metadata := make(map[string]interface{})
  149. metadata["end_time"] = time.Now().UTC()
  150. _ = updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, targetResp.DeploymentTargetID, eventID, eventStatus, metadata)
  151. applyResp, err = client.ApplyPorterApp(ctx, cliConf.Project, cliConf.Cluster, "", "", applyResp.AppRevisionId)
  152. if err != nil {
  153. return fmt.Errorf("apply error post-predeploy: %w", err)
  154. }
  155. }
  156. if applyResp.CLIAction != porterv1.EnumCLIAction_ENUM_CLI_ACTION_NONE {
  157. return fmt.Errorf("unexpected CLI action: %s", applyResp.CLIAction)
  158. }
  159. color.New(color.FgGreen).Printf("Successfully applied new revision %s for app %s\n", applyResp.AppRevisionId, appName) // nolint:errcheck,gosec
  160. return nil
  161. }
  162. // checkPredeployTimeout is the maximum amount of time the CLI will wait for a predeploy to complete before calling apply again
  163. const checkPredeployTimeout = 60 * time.Minute
  164. // checkPredeployFrequency is the frequency at which the CLI will check the status of a predeploy
  165. const checkPredeployFrequency = 10 * time.Second
  166. func appNameFromB64AppProto(base64AppProto string) (string, error) {
  167. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  168. if err != nil {
  169. return "", fmt.Errorf("unable to decode base64 app for revision: %w", err)
  170. }
  171. app := &porterv1.PorterApp{}
  172. err = helpers.UnmarshalContractObject(decoded, app)
  173. if err != nil {
  174. return "", fmt.Errorf("unable to unmarshal app for revision: %w", err)
  175. }
  176. if app.Name == "" {
  177. return "", fmt.Errorf("app does not contain name")
  178. }
  179. return app.Name, nil
  180. }
  181. func createPorterAppDbEntryInputFromProtoAndEnv(base64AppProto string) (api.CreatePorterAppDBEntryInput, error) {
  182. var input api.CreatePorterAppDBEntryInput
  183. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  184. if err != nil {
  185. return input, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  186. }
  187. app := &porterv1.PorterApp{}
  188. err = helpers.UnmarshalContractObject(decoded, app)
  189. if err != nil {
  190. return input, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  191. }
  192. if app.Name == "" {
  193. return input, fmt.Errorf("app does not contain name")
  194. }
  195. input.AppName = app.Name
  196. if app.Build != nil {
  197. if os.Getenv("GITHUB_REPOSITORY_ID") == "" {
  198. input.Local = true
  199. return input, nil
  200. }
  201. gitRepoId, err := strconv.Atoi(os.Getenv("GITHUB_REPOSITORY_ID"))
  202. if err != nil {
  203. return input, fmt.Errorf("unable to parse GITHUB_REPOSITORY_ID to int: %w", err)
  204. }
  205. input.GitRepoID = uint(gitRepoId)
  206. input.GitRepoName = os.Getenv("GITHUB_REPOSITORY")
  207. input.GitBranch = os.Getenv("GITHUB_REF_NAME")
  208. input.PorterYamlPath = "porter.yaml"
  209. return input, nil
  210. }
  211. if app.Image != nil {
  212. input.ImageRepository = app.Image.Repository
  213. input.ImageTag = app.Image.Tag
  214. return input, nil
  215. }
  216. return input, fmt.Errorf("app does not contain build or image settings")
  217. }
  218. func addPorterSubdomainsIfNecessary(ctx context.Context, client api.Client, project uint, cluster uint, base64AppProto string) (string, error) {
  219. var editedB64AppProto string
  220. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  221. if err != nil {
  222. return editedB64AppProto, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  223. }
  224. app := &porterv1.PorterApp{}
  225. err = helpers.UnmarshalContractObject(decoded, app)
  226. if err != nil {
  227. return editedB64AppProto, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  228. }
  229. for serviceName, service := range app.Services {
  230. if service.Type == porterv1.ServiceType_SERVICE_TYPE_WEB {
  231. if service.GetWebConfig() == nil {
  232. return editedB64AppProto, fmt.Errorf("web service %s does not contain web config", serviceName)
  233. }
  234. webConfig := service.GetWebConfig()
  235. if !webConfig.Private && len(webConfig.Domains) == 0 {
  236. color.New(color.FgYellow).Printf("Service %s is public but does not contain any domains, creating Porter domain\n", serviceName) // nolint:errcheck,gosec
  237. domain, err := client.CreateSubdomain(ctx, project, cluster, app.Name, serviceName)
  238. if err != nil {
  239. return editedB64AppProto, fmt.Errorf("error creating subdomain: %w", err)
  240. }
  241. if domain.Subdomain == "" {
  242. return editedB64AppProto, errors.New("response subdomain is empty")
  243. }
  244. webConfig.Domains = []*porterv1.Domain{
  245. {Name: domain.Subdomain},
  246. }
  247. service.Config = &porterv1.Service_WebConfig{WebConfig: webConfig}
  248. }
  249. }
  250. }
  251. marshalled, err := helpers.MarshalContractObject(ctx, app)
  252. if err != nil {
  253. return editedB64AppProto, fmt.Errorf("unable to marshal app back to json: %w", err)
  254. }
  255. editedB64AppProto = base64.StdEncoding.EncodeToString(marshalled)
  256. return editedB64AppProto, nil
  257. }
  258. func buildSettingsFromBase64AppProto(base64AppProto string) (buildInput, error) {
  259. var buildSettings buildInput
  260. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  261. if err != nil {
  262. return buildSettings, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  263. }
  264. app := &porterv1.PorterApp{}
  265. err = helpers.UnmarshalContractObject(decoded, app)
  266. if err != nil {
  267. return buildSettings, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  268. }
  269. if app.Name == "" {
  270. return buildSettings, fmt.Errorf("app does not contain name")
  271. }
  272. if app.Build == nil {
  273. return buildSettings, fmt.Errorf("app does not contain build settings")
  274. }
  275. if app.Image == nil {
  276. return buildSettings, fmt.Errorf("app does not contain image settings")
  277. }
  278. return buildInput{
  279. AppName: app.Name,
  280. BuildContext: app.Build.Context,
  281. Dockerfile: app.Build.Dockerfile,
  282. BuildMethod: app.Build.Method,
  283. Builder: app.Build.Builder,
  284. BuildPacks: app.Build.Buildpacks,
  285. ImageTag: app.Image.Tag,
  286. RepositoryURL: app.Image.Repository,
  287. }, nil
  288. }
  289. func imageTagFromBase64AppProto(base64AppProto string) (string, error) {
  290. var image string
  291. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  292. if err != nil {
  293. return image, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  294. }
  295. app := &porterv1.PorterApp{}
  296. err = helpers.UnmarshalContractObject(decoded, app)
  297. if err != nil {
  298. return image, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  299. }
  300. if app.Image == nil {
  301. return image, fmt.Errorf("app does not contain image settings")
  302. }
  303. if app.Image.Tag == "" {
  304. return image, fmt.Errorf("app does not contain image tag")
  305. }
  306. return app.Image.Tag, nil
  307. }