create.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. package release
  2. import (
  3. "fmt"
  4. "net/http"
  5. "strings"
  6. "github.com/porter-dev/porter/api/server/authz"
  7. "github.com/porter-dev/porter/api/server/handlers"
  8. "github.com/porter-dev/porter/api/server/shared"
  9. "github.com/porter-dev/porter/api/server/shared/apierrors"
  10. "github.com/porter-dev/porter/api/server/shared/config"
  11. "github.com/porter-dev/porter/api/types"
  12. "github.com/porter-dev/porter/internal/analytics"
  13. "github.com/porter-dev/porter/internal/auth/token"
  14. "github.com/porter-dev/porter/internal/helm"
  15. "github.com/porter-dev/porter/internal/helm/loader"
  16. "github.com/porter-dev/porter/internal/integrations/ci/actions"
  17. "github.com/porter-dev/porter/internal/models"
  18. "github.com/porter-dev/porter/internal/oauth"
  19. "github.com/porter-dev/porter/internal/registry"
  20. "github.com/porter-dev/porter/internal/repository"
  21. "gopkg.in/yaml.v2"
  22. "helm.sh/helm/v3/pkg/release"
  23. )
  24. type CreateReleaseHandler struct {
  25. handlers.PorterHandlerReadWriter
  26. authz.KubernetesAgentGetter
  27. }
  28. func NewCreateReleaseHandler(
  29. config *config.Config,
  30. decoderValidator shared.RequestDecoderValidator,
  31. writer shared.ResultWriter,
  32. ) *CreateReleaseHandler {
  33. return &CreateReleaseHandler{
  34. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  35. KubernetesAgentGetter: authz.NewOutOfClusterAgentGetter(config),
  36. }
  37. }
  38. func (c *CreateReleaseHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  39. user, _ := r.Context().Value(types.UserScope).(*models.User)
  40. cluster, _ := r.Context().Value(types.ClusterScope).(*models.Cluster)
  41. namespace := r.Context().Value(types.NamespaceScope).(string)
  42. operationID := oauth.CreateRandomState()
  43. c.Config().AnalyticsClient.Track(analytics.ApplicationLaunchStartTrack(
  44. &analytics.ApplicationLaunchStartTrackOpts{
  45. ClusterScopedTrackOpts: analytics.GetClusterScopedTrackOpts(user.ID, cluster.ProjectID, cluster.ID),
  46. FlowID: operationID,
  47. },
  48. ))
  49. helmAgent, err := c.GetHelmAgent(r, cluster, "")
  50. if err != nil {
  51. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  52. return
  53. }
  54. request := &types.CreateReleaseRequest{}
  55. if ok := c.DecodeAndValidate(w, r, request); !ok {
  56. return
  57. }
  58. if request.RepoURL == "" {
  59. request.RepoURL = c.Config().ServerConf.DefaultApplicationHelmRepoURL
  60. }
  61. if request.TemplateVersion == "latest" {
  62. request.TemplateVersion = ""
  63. }
  64. chart, err := loader.LoadChartPublic(request.RepoURL, request.TemplateName, request.TemplateVersion)
  65. if err != nil {
  66. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  67. return
  68. }
  69. registries, err := c.Repo().Registry().ListRegistriesByProjectID(cluster.ProjectID)
  70. if err != nil {
  71. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  72. return
  73. }
  74. conf := &helm.InstallChartConfig{
  75. Chart: chart,
  76. Name: request.Name,
  77. Namespace: namespace,
  78. Values: request.Values,
  79. Cluster: cluster,
  80. Repo: c.Repo(),
  81. Registries: registries,
  82. }
  83. helmRelease, err := helmAgent.InstallChart(conf, c.Config().DOConf)
  84. if err != nil {
  85. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(
  86. fmt.Errorf("error installing a new chart: %s", err.Error()),
  87. http.StatusBadRequest,
  88. ))
  89. return
  90. }
  91. release, err := createReleaseFromHelmRelease(c.Config(), cluster.ProjectID, cluster.ID, helmRelease)
  92. if err != nil {
  93. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  94. return
  95. }
  96. if request.GithubActionConfig != nil {
  97. _, _, err := createGitAction(
  98. c.Config(),
  99. user.ID,
  100. cluster.ProjectID,
  101. cluster.ID,
  102. request.GithubActionConfig,
  103. request.Name,
  104. namespace,
  105. release,
  106. )
  107. if err != nil {
  108. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  109. return
  110. }
  111. }
  112. c.Config().AnalyticsClient.Track(analytics.ApplicationLaunchSuccessTrack(
  113. &analytics.ApplicationLaunchSuccessTrackOpts{
  114. ApplicationScopedTrackOpts: analytics.GetApplicationScopedTrackOpts(
  115. user.ID,
  116. cluster.ProjectID,
  117. cluster.ID,
  118. release.Name,
  119. release.Namespace,
  120. chart.Metadata.Name,
  121. ),
  122. FlowID: operationID,
  123. },
  124. ))
  125. }
  126. func createReleaseFromHelmRelease(
  127. config *config.Config,
  128. projectID, clusterID uint,
  129. helmRelease *release.Release,
  130. ) (*models.Release, error) {
  131. token, err := repository.GenerateRandomBytes(16)
  132. if err != nil {
  133. return nil, err
  134. }
  135. // create release with webhook token in db
  136. image, ok := helmRelease.Config["image"].(map[string]interface{})
  137. if !ok {
  138. return nil, fmt.Errorf("Could not find field image in config")
  139. }
  140. repository := image["repository"]
  141. repoStr, ok := repository.(string)
  142. if !ok {
  143. return nil, fmt.Errorf("Could not find field repository in config")
  144. }
  145. release := &models.Release{
  146. ClusterID: clusterID,
  147. ProjectID: projectID,
  148. Namespace: helmRelease.Namespace,
  149. Name: helmRelease.Name,
  150. WebhookToken: token,
  151. ImageRepoURI: repoStr,
  152. }
  153. return config.Repo.Release().CreateRelease(release)
  154. }
  155. func createGitAction(
  156. config *config.Config,
  157. userID, projectID, clusterID uint,
  158. request *types.CreateGitActionConfigRequest,
  159. name, namespace string,
  160. release *models.Release,
  161. ) (*types.GitActionConfig, []byte, error) {
  162. // if the registry was provisioned through Porter, create a repository if necessary
  163. if release != nil && request.RegistryID != 0 {
  164. // read the registry
  165. reg, err := config.Repo.Registry().ReadRegistry(projectID, request.RegistryID)
  166. if err != nil {
  167. return nil, nil, err
  168. }
  169. _reg := registry.Registry(*reg)
  170. regAPI := &_reg
  171. // parse the name from the registry
  172. nameSpl := strings.Split(request.ImageRepoURI, "/")
  173. repoName := nameSpl[len(nameSpl)-1]
  174. err = regAPI.CreateRepository(config.Repo, repoName)
  175. if err != nil {
  176. return nil, nil, err
  177. }
  178. }
  179. repoSplit := strings.Split(request.GitRepo, "/")
  180. if len(repoSplit) != 2 {
  181. return nil, nil, fmt.Errorf("invalid formatting of repo name")
  182. }
  183. // generate porter jwt token
  184. jwt, err := token.GetTokenForAPI(userID, projectID)
  185. if err != nil {
  186. return nil, nil, err
  187. }
  188. encoded, err := jwt.EncodeToken(config.TokenConf)
  189. if err != nil {
  190. return nil, nil, err
  191. }
  192. // create the commit in the git repo
  193. gaRunner := &actions.GithubActions{
  194. ServerURL: config.ServerConf.ServerURL,
  195. GithubOAuthIntegration: nil,
  196. GithubAppID: config.GithubAppConf.AppID,
  197. GithubAppSecretPath: config.GithubAppConf.SecretPath,
  198. GithubInstallationID: request.GitRepoID,
  199. GitRepoName: repoSplit[1],
  200. GitRepoOwner: repoSplit[0],
  201. Repo: config.Repo,
  202. ProjectID: projectID,
  203. ClusterID: clusterID,
  204. ReleaseName: name,
  205. ReleaseNamespace: namespace,
  206. GitBranch: request.GitBranch,
  207. DockerFilePath: request.DockerfilePath,
  208. FolderPath: request.FolderPath,
  209. ImageRepoURL: request.ImageRepoURI,
  210. PorterToken: encoded,
  211. Version: "v0.1.0",
  212. ShouldCreateWorkflow: request.ShouldCreateWorkflow,
  213. DryRun: release == nil,
  214. }
  215. workflowYAML, err := gaRunner.Setup()
  216. if err != nil {
  217. return nil, nil, err
  218. }
  219. if gaRunner.DryRun {
  220. return nil, workflowYAML, nil
  221. }
  222. // handle write to the database
  223. ga, err := config.Repo.GitActionConfig().CreateGitActionConfig(&models.GitActionConfig{
  224. ReleaseID: release.ID,
  225. GitRepo: request.GitRepo,
  226. GitBranch: request.GitBranch,
  227. ImageRepoURI: request.ImageRepoURI,
  228. // TODO: github installation id here?
  229. GitRepoID: request.GitRepoID,
  230. DockerfilePath: request.DockerfilePath,
  231. FolderPath: request.FolderPath,
  232. IsInstallation: true,
  233. Version: "v0.1.0",
  234. })
  235. if err != nil {
  236. return nil, nil, err
  237. }
  238. // update the release in the db with the image repo uri
  239. release.ImageRepoURI = ga.ImageRepoURI
  240. _, err = config.Repo.Release().UpdateRelease(release)
  241. if err != nil {
  242. return nil, nil, err
  243. }
  244. return ga.ToGitActionConfigType(), workflowYAML, nil
  245. }
  246. type containerEnvConfig struct {
  247. Container struct {
  248. Env struct {
  249. Normal map[string]string `yaml:"normal"`
  250. } `yaml:"env"`
  251. } `yaml:"container"`
  252. }
  253. func getGARunner(
  254. config *config.Config,
  255. userID, projectID, clusterID uint,
  256. ga *models.GitActionConfig,
  257. name, namespace string,
  258. release *models.Release,
  259. helmRelease *release.Release,
  260. ) (*actions.GithubActions, error) {
  261. cEnv := &containerEnvConfig{}
  262. rawValues, err := yaml.Marshal(helmRelease.Config)
  263. if err == nil {
  264. err = yaml.Unmarshal(rawValues, cEnv)
  265. // if unmarshal error, just set to empty map
  266. if err != nil {
  267. cEnv.Container.Env.Normal = make(map[string]string)
  268. }
  269. }
  270. repoSplit := strings.Split(ga.GitRepo, "/")
  271. if len(repoSplit) != 2 {
  272. return nil, fmt.Errorf("invalid formatting of repo name")
  273. }
  274. // create the commit in the git repo
  275. return &actions.GithubActions{
  276. ServerURL: config.ServerConf.ServerURL,
  277. GithubOAuthIntegration: nil,
  278. BuildEnv: cEnv.Container.Env.Normal,
  279. GithubAppID: config.GithubAppConf.AppID,
  280. GithubAppSecretPath: config.GithubAppConf.SecretPath,
  281. GithubInstallationID: ga.GitRepoID,
  282. GitRepoName: repoSplit[1],
  283. GitRepoOwner: repoSplit[0],
  284. Repo: config.Repo,
  285. ProjectID: projectID,
  286. ClusterID: clusterID,
  287. ReleaseName: name,
  288. GitBranch: ga.GitBranch,
  289. DockerFilePath: ga.DockerfilePath,
  290. FolderPath: ga.FolderPath,
  291. ImageRepoURL: ga.ImageRepoURI,
  292. Version: "v0.1.0",
  293. }, nil
  294. }