create.go 10 KB

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