apply.go 13 KB

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