apply.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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)
  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. if err != nil {
  114. _ = updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, eventID, types.PorterAppEventStatus_Failed, nil)
  115. return fmt.Errorf("error building app: %w", err)
  116. }
  117. color.New(color.FgGreen).Printf("Successfully built image (tag: %s)\n", buildSettings.ImageTag) // nolint:errcheck,gosec
  118. _ = updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, eventID, types.PorterAppEventStatus_Success, nil)
  119. applyResp, err = client.ApplyPorterApp(ctx, cliConf.Project, cliConf.Cluster, "", "", applyResp.AppRevisionId)
  120. if err != nil {
  121. return fmt.Errorf("apply error post-build: %w", err)
  122. }
  123. }
  124. if applyResp.CLIAction == porterv1.EnumCLIAction_ENUM_CLI_ACTION_TRACK_PREDEPLOY {
  125. color.New(color.FgGreen).Printf("Waiting for predeploy to complete...\n") // nolint:errcheck,gosec
  126. now := time.Now().UTC()
  127. eventID, _ := createPredeployEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, now)
  128. eventStatus := types.PorterAppEventStatus_Success
  129. for {
  130. if time.Since(now) > checkPredeployTimeout {
  131. return errors.New("timed out waiting for predeploy to complete")
  132. }
  133. predeployStatusResp, err := client.PredeployStatus(ctx, cliConf.Project, cliConf.Cluster, appName, applyResp.AppRevisionId)
  134. if err != nil {
  135. return fmt.Errorf("error calling predeploy status endpoint: %w", err)
  136. }
  137. if predeployStatusResp.Status == porter_app.PredeployStatus_Failed {
  138. eventStatus = types.PorterAppEventStatus_Failed
  139. break
  140. }
  141. if predeployStatusResp.Status == porter_app.PredeployStatus_Successful {
  142. break
  143. }
  144. time.Sleep(checkPredeployFrequency)
  145. }
  146. metadata := make(map[string]interface{})
  147. metadata["end_time"] = time.Now().UTC()
  148. _ = updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, eventID, eventStatus, metadata)
  149. applyResp, err = client.ApplyPorterApp(ctx, cliConf.Project, cliConf.Cluster, "", "", applyResp.AppRevisionId)
  150. if err != nil {
  151. return fmt.Errorf("apply error post-predeploy: %w", err)
  152. }
  153. }
  154. if applyResp.CLIAction != porterv1.EnumCLIAction_ENUM_CLI_ACTION_NONE {
  155. return fmt.Errorf("unexpected CLI action: %s", applyResp.CLIAction)
  156. }
  157. color.New(color.FgGreen).Printf("Successfully applied new revision %s for app %s\n", applyResp.AppRevisionId, appName) // nolint:errcheck,gosec
  158. return nil
  159. }
  160. // checkPredeployTimeout is the maximum amount of time the CLI will wait for a predeploy to complete before calling apply again
  161. const checkPredeployTimeout = 60 * time.Minute
  162. // checkPredeployFrequency is the frequency at which the CLI will check the status of a predeploy
  163. const checkPredeployFrequency = 10 * time.Second
  164. func appNameFromB64AppProto(base64AppProto string) (string, error) {
  165. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  166. if err != nil {
  167. return "", fmt.Errorf("unable to decode base64 app for revision: %w", err)
  168. }
  169. app := &porterv1.PorterApp{}
  170. err = helpers.UnmarshalContractObject(decoded, app)
  171. if err != nil {
  172. return "", fmt.Errorf("unable to unmarshal app for revision: %w", err)
  173. }
  174. if app.Name == "" {
  175. return "", fmt.Errorf("app does not contain name")
  176. }
  177. return app.Name, nil
  178. }
  179. func createPorterAppDbEntryInputFromProtoAndEnv(base64AppProto string) (api.CreatePorterAppDBEntryInput, error) {
  180. var input api.CreatePorterAppDBEntryInput
  181. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  182. if err != nil {
  183. return input, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  184. }
  185. app := &porterv1.PorterApp{}
  186. err = helpers.UnmarshalContractObject(decoded, app)
  187. if err != nil {
  188. return input, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  189. }
  190. if app.Name == "" {
  191. return input, fmt.Errorf("app does not contain name")
  192. }
  193. input.AppName = app.Name
  194. if app.Build != nil {
  195. if os.Getenv("GITHUB_REPOSITORY_ID") == "" {
  196. input.Local = true
  197. return input, nil
  198. }
  199. gitRepoId, err := strconv.Atoi(os.Getenv("GITHUB_REPOSITORY_ID"))
  200. if err != nil {
  201. return input, fmt.Errorf("unable to parse GITHUB_REPOSITORY_ID to int: %w", err)
  202. }
  203. input.GitRepoID = uint(gitRepoId)
  204. input.GitRepoName = os.Getenv("GITHUB_REPOSITORY")
  205. input.GitBranch = os.Getenv("GITHUB_REF_NAME")
  206. input.PorterYamlPath = "porter.yaml"
  207. return input, nil
  208. }
  209. if app.Image != nil {
  210. input.ImageRepository = app.Image.Repository
  211. input.ImageTag = app.Image.Tag
  212. return input, nil
  213. }
  214. return input, fmt.Errorf("app does not contain build or image settings")
  215. }
  216. func addPorterSubdomainsIfNecessary(ctx context.Context, client api.Client, project uint, cluster uint, base64AppProto string) (string, error) {
  217. var editedB64AppProto string
  218. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  219. if err != nil {
  220. return editedB64AppProto, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  221. }
  222. app := &porterv1.PorterApp{}
  223. err = helpers.UnmarshalContractObject(decoded, app)
  224. if err != nil {
  225. return editedB64AppProto, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  226. }
  227. for serviceName, service := range app.Services {
  228. if service.Type == porterv1.ServiceType_SERVICE_TYPE_WEB {
  229. if service.GetWebConfig() == nil {
  230. return editedB64AppProto, fmt.Errorf("web service %s does not contain web config", serviceName)
  231. }
  232. webConfig := service.GetWebConfig()
  233. if !webConfig.Private && len(webConfig.Domains) == 0 {
  234. color.New(color.FgYellow).Printf("Service %s is public but does not contain any domains, creating Porter domain\n", serviceName) // nolint:errcheck,gosec
  235. domain, err := client.CreateSubdomain(ctx, project, cluster, app.Name, serviceName)
  236. if err != nil {
  237. return editedB64AppProto, fmt.Errorf("error creating subdomain: %w", err)
  238. }
  239. if domain.Subdomain == "" {
  240. return editedB64AppProto, errors.New("response subdomain is empty")
  241. }
  242. webConfig.Domains = []*porterv1.Domain{
  243. {Name: domain.Subdomain},
  244. }
  245. service.Config = &porterv1.Service_WebConfig{WebConfig: webConfig}
  246. }
  247. }
  248. }
  249. marshalled, err := helpers.MarshalContractObject(ctx, app)
  250. if err != nil {
  251. return editedB64AppProto, fmt.Errorf("unable to marshal app back to json: %w", err)
  252. }
  253. editedB64AppProto = base64.StdEncoding.EncodeToString(marshalled)
  254. return editedB64AppProto, nil
  255. }
  256. func buildSettingsFromBase64AppProto(base64AppProto string) (buildInput, error) {
  257. var buildSettings buildInput
  258. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  259. if err != nil {
  260. return buildSettings, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  261. }
  262. app := &porterv1.PorterApp{}
  263. err = helpers.UnmarshalContractObject(decoded, app)
  264. if err != nil {
  265. return buildSettings, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  266. }
  267. if app.Name == "" {
  268. return buildSettings, fmt.Errorf("app does not contain name")
  269. }
  270. if app.Build == nil {
  271. return buildSettings, fmt.Errorf("app does not contain build settings")
  272. }
  273. if app.Image == nil {
  274. return buildSettings, fmt.Errorf("app does not contain image settings")
  275. }
  276. return buildInput{
  277. AppName: app.Name,
  278. BuildContext: app.Build.Context,
  279. Dockerfile: app.Build.Dockerfile,
  280. BuildMethod: app.Build.Method,
  281. Builder: app.Build.Builder,
  282. BuildPacks: app.Build.Buildpacks,
  283. ImageTag: app.Image.Tag,
  284. RepositoryURL: app.Image.Repository,
  285. }, nil
  286. }
  287. func imageTagFromBase64AppProto(base64AppProto string) (string, error) {
  288. var image string
  289. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  290. if err != nil {
  291. return image, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  292. }
  293. app := &porterv1.PorterApp{}
  294. err = helpers.UnmarshalContractObject(decoded, app)
  295. if err != nil {
  296. return image, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  297. }
  298. if app.Image == nil {
  299. return image, fmt.Errorf("app does not contain image settings")
  300. }
  301. if app.Image.Tag == "" {
  302. return image, fmt.Errorf("app does not contain image tag")
  303. }
  304. return app.Image.Tag, nil
  305. }