apply.go 12 KB

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