apply.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. package v2
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "errors"
  6. "fmt"
  7. "os"
  8. "path/filepath"
  9. "strconv"
  10. "github.com/fatih/color"
  11. "github.com/porter-dev/api-contracts/generated/go/helpers"
  12. porterv1 "github.com/porter-dev/api-contracts/generated/go/porter/v1"
  13. api "github.com/porter-dev/porter/api/client"
  14. "github.com/porter-dev/porter/cli/cmd/config"
  15. )
  16. // Apply implements the functionality of the `porter apply` command for validate apply v2 projects
  17. func Apply(ctx context.Context, cliConf config.CLIConfig, client api.Client, porterYamlPath string) error {
  18. if len(porterYamlPath) == 0 {
  19. return fmt.Errorf("porter yaml is empty")
  20. }
  21. porterYaml, err := os.ReadFile(filepath.Clean(porterYamlPath))
  22. if err != nil {
  23. return fmt.Errorf("could not read porter yaml file: %w", err)
  24. }
  25. b64YAML := base64.StdEncoding.EncodeToString(porterYaml)
  26. parseResp, err := client.ParseYAML(ctx, cliConf.Project, cliConf.Cluster, b64YAML)
  27. if err != nil {
  28. return fmt.Errorf("error calling parse yaml endpoint: %w", err)
  29. }
  30. if parseResp.B64AppProto == "" {
  31. return errors.New("b64 app proto is empty")
  32. }
  33. targetResp, err := client.DefaultDeploymentTarget(ctx, cliConf.Project, cliConf.Cluster)
  34. if err != nil {
  35. return fmt.Errorf("error calling default deployment target endpoint: %w", err)
  36. }
  37. if targetResp.DeploymentTargetID == "" {
  38. return errors.New("deployment target id is empty")
  39. }
  40. validateResp, err := client.ValidatePorterApp(ctx, cliConf.Project, cliConf.Cluster, parseResp.B64AppProto, targetResp.DeploymentTargetID)
  41. if err != nil {
  42. return fmt.Errorf("error calling validate endpoint: %w", err)
  43. }
  44. if validateResp.ValidatedBase64AppProto == "" {
  45. return errors.New("validated b64 app proto is empty")
  46. }
  47. base64AppProto := validateResp.ValidatedBase64AppProto
  48. createPorterAppDBEntryInp, err := createPorterAppDbEntryInputFromProtoAndEnv(validateResp.ValidatedBase64AppProto)
  49. if err != nil {
  50. return fmt.Errorf("error creating porter app db entry input from proto: %w", err)
  51. }
  52. err = client.CreatePorterAppDBEntry(ctx, cliConf.Project, cliConf.Cluster, createPorterAppDBEntryInp)
  53. if err != nil {
  54. return fmt.Errorf("error creating porter app db entry: %w", err)
  55. }
  56. base64AppProtoWithSubdomains, err := addPorterSubdomainsIfNecessary(ctx, client, cliConf.Project, cliConf.Cluster, base64AppProto)
  57. if err != nil {
  58. return fmt.Errorf("error creating subdomains: %w", err)
  59. }
  60. applyResp, err := client.ApplyPorterApp(ctx, cliConf.Project, cliConf.Cluster, base64AppProtoWithSubdomains, targetResp.DeploymentTargetID, "")
  61. if err != nil {
  62. return fmt.Errorf("error calling apply endpoint: %w", err)
  63. }
  64. if applyResp.AppRevisionId == "" {
  65. return errors.New("app revision id is empty")
  66. }
  67. if applyResp.CLIAction == porterv1.EnumCLIAction_ENUM_CLI_ACTION_BUILD {
  68. buildSettings, err := buildSettingsFromBase64AppProto(base64AppProto)
  69. if err != nil {
  70. return fmt.Errorf("error building settings from base64 app proto: %w", err)
  71. }
  72. currentAppRevisionResp, err := client.CurrentAppRevision(ctx, cliConf.Project, cliConf.Cluster, buildSettings.AppName, targetResp.DeploymentTargetID)
  73. if err != nil {
  74. return fmt.Errorf("error getting current app revision: %w", err)
  75. }
  76. if currentAppRevisionResp == nil {
  77. return errors.New("current app revision is nil")
  78. }
  79. appRevision := currentAppRevisionResp.AppRevision
  80. if appRevision.B64AppProto == "" {
  81. return errors.New("current app revision b64 app proto is empty")
  82. }
  83. currentImageTag, err := imageTagFromBase64AppProto(appRevision.B64AppProto)
  84. if err != nil {
  85. return fmt.Errorf("error getting image tag from current app revision: %w", err)
  86. }
  87. buildSettings.CurrentImageTag = currentImageTag
  88. buildSettings.ProjectID = cliConf.Project
  89. err = build(ctx, client, buildSettings)
  90. if err != nil {
  91. return fmt.Errorf("error building app: %w", err)
  92. }
  93. applyResp, err = client.ApplyPorterApp(ctx, cliConf.Project, cliConf.Cluster, "", "", applyResp.AppRevisionId)
  94. if err != nil {
  95. return fmt.Errorf("error calling apply endpoint after build: %w", err)
  96. }
  97. }
  98. if applyResp.CLIAction != porterv1.EnumCLIAction_ENUM_CLI_ACTION_NONE {
  99. return fmt.Errorf("unexpected CLI action: %s", applyResp.CLIAction)
  100. }
  101. color.New(color.FgGreen).Printf("Successfully applied Porter YAML as revision %v, next action: %v\n", applyResp.AppRevisionId, applyResp.CLIAction) // nolint:errcheck,gosec
  102. return nil
  103. }
  104. func createPorterAppDbEntryInputFromProtoAndEnv(base64AppProto string) (api.CreatePorterAppDBEntryInput, error) {
  105. var input api.CreatePorterAppDBEntryInput
  106. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  107. if err != nil {
  108. return input, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  109. }
  110. app := &porterv1.PorterApp{}
  111. err = helpers.UnmarshalContractObject(decoded, app)
  112. if err != nil {
  113. return input, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  114. }
  115. if app.Name == "" {
  116. return input, fmt.Errorf("app does not contain name")
  117. }
  118. input.AppName = app.Name
  119. if app.Build != nil {
  120. if os.Getenv("GITHUB_REPOSITORY_ID") == "" {
  121. input.Local = true
  122. return input, nil
  123. }
  124. gitRepoId, err := strconv.Atoi(os.Getenv("GITHUB_REPOSITORY_ID"))
  125. if err != nil {
  126. return input, fmt.Errorf("unable to parse GITHUB_REPOSITORY_ID to int: %w", err)
  127. }
  128. input.GitRepoID = uint(gitRepoId)
  129. input.GitRepoName = os.Getenv("GITHUB_REPOSITORY")
  130. input.GitBranch = os.Getenv("GITHUB_REF_NAME")
  131. input.PorterYamlPath = "porter.yaml"
  132. return input, nil
  133. }
  134. if app.Image != nil {
  135. input.ImageRepository = app.Image.Repository
  136. input.ImageTag = app.Image.Tag
  137. return input, nil
  138. }
  139. return input, fmt.Errorf("app does not contain build or image settings")
  140. }
  141. func addPorterSubdomainsIfNecessary(ctx context.Context, client api.Client, project uint, cluster uint, base64AppProto string) (string, error) {
  142. var editedB64AppProto string
  143. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  144. if err != nil {
  145. return editedB64AppProto, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  146. }
  147. app := &porterv1.PorterApp{}
  148. err = helpers.UnmarshalContractObject(decoded, app)
  149. if err != nil {
  150. return editedB64AppProto, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  151. }
  152. for serviceName, service := range app.Services {
  153. if service.Type == porterv1.ServiceType_SERVICE_TYPE_WEB {
  154. if service.GetWebConfig() == nil {
  155. return editedB64AppProto, fmt.Errorf("web service %s does not contain web config", serviceName)
  156. }
  157. webConfig := service.GetWebConfig()
  158. if !webConfig.Private && len(webConfig.Domains) == 0 {
  159. color.New(color.FgYellow).Printf("Service %s is public but does not contain any domains, creating Porter domain\n", serviceName) // nolint:errcheck,gosec
  160. domain, err := client.CreateSubdomain(ctx, project, cluster, app.Name, serviceName)
  161. if err != nil {
  162. return editedB64AppProto, fmt.Errorf("error creating subdomain: %w", err)
  163. }
  164. if domain.Subdomain == "" {
  165. return editedB64AppProto, errors.New("response subdomain is empty")
  166. }
  167. webConfig.Domains = []*porterv1.Domain{
  168. {Name: domain.Subdomain},
  169. }
  170. service.Config = &porterv1.Service_WebConfig{WebConfig: webConfig}
  171. }
  172. }
  173. }
  174. marshalled, err := helpers.MarshalContractObject(ctx, app)
  175. if err != nil {
  176. return editedB64AppProto, fmt.Errorf("unable to marshal app back to json: %w", err)
  177. }
  178. editedB64AppProto = base64.StdEncoding.EncodeToString(marshalled)
  179. return editedB64AppProto, nil
  180. }
  181. func buildSettingsFromBase64AppProto(base64AppProto string) (buildInput, error) {
  182. var buildSettings buildInput
  183. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  184. if err != nil {
  185. return buildSettings, 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 buildSettings, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  191. }
  192. if app.Name == "" {
  193. return buildSettings, fmt.Errorf("app does not contain name")
  194. }
  195. if app.Build == nil {
  196. return buildSettings, fmt.Errorf("app does not contain build settings")
  197. }
  198. if app.Image == nil {
  199. return buildSettings, fmt.Errorf("app does not contain image settings")
  200. }
  201. return buildInput{
  202. AppName: app.Name,
  203. BuildContext: app.Build.Context,
  204. Dockerfile: app.Build.Dockerfile,
  205. BuildMethod: app.Build.Method,
  206. Builder: app.Build.Builder,
  207. BuildPacks: app.Build.Buildpacks,
  208. ImageTag: app.Image.Tag,
  209. RepositoryURL: app.Image.Repository,
  210. }, nil
  211. }
  212. func imageTagFromBase64AppProto(base64AppProto string) (string, error) {
  213. var image string
  214. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  215. if err != nil {
  216. return image, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  217. }
  218. app := &porterv1.PorterApp{}
  219. err = helpers.UnmarshalContractObject(decoded, app)
  220. if err != nil {
  221. return image, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  222. }
  223. if app.Image == nil {
  224. return image, fmt.Errorf("app does not contain image settings")
  225. }
  226. if app.Image.Tag == "" {
  227. return image, fmt.Errorf("app does not contain image tag")
  228. }
  229. return app.Image.Tag, nil
  230. }