create.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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. _, err = createBuildConfig(c.Config(), release, request.BuildConfig)
  114. if err != nil {
  115. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  116. return
  117. }
  118. c.Config().AnalyticsClient.Track(analytics.ApplicationLaunchSuccessTrack(
  119. &analytics.ApplicationLaunchSuccessTrackOpts{
  120. ApplicationScopedTrackOpts: analytics.GetApplicationScopedTrackOpts(
  121. user.ID,
  122. cluster.ProjectID,
  123. cluster.ID,
  124. release.Name,
  125. release.Namespace,
  126. chart.Metadata.Name,
  127. ),
  128. FlowID: operationID,
  129. },
  130. ))
  131. }
  132. func createReleaseFromHelmRelease(
  133. config *config.Config,
  134. projectID, clusterID uint,
  135. helmRelease *release.Release,
  136. ) (*models.Release, error) {
  137. token, err := repository.GenerateRandomBytes(16)
  138. if err != nil {
  139. return nil, err
  140. }
  141. // create release with webhook token in db
  142. image, ok := helmRelease.Config["image"].(map[string]interface{})
  143. if !ok {
  144. return nil, fmt.Errorf("Could not find field image in config")
  145. }
  146. repository := image["repository"]
  147. repoStr, ok := repository.(string)
  148. if !ok {
  149. return nil, fmt.Errorf("Could not find field repository in config")
  150. }
  151. release := &models.Release{
  152. ClusterID: clusterID,
  153. ProjectID: projectID,
  154. Namespace: helmRelease.Namespace,
  155. Name: helmRelease.Name,
  156. WebhookToken: token,
  157. ImageRepoURI: repoStr,
  158. }
  159. return config.Repo.Release().CreateRelease(release)
  160. }
  161. func createGitAction(
  162. config *config.Config,
  163. userID, projectID, clusterID uint,
  164. request *types.CreateGitActionConfigRequest,
  165. name, namespace string,
  166. release *models.Release,
  167. ) (*types.GitActionConfig, []byte, error) {
  168. // if the registry was provisioned through Porter, create a repository if necessary
  169. if release != nil && request.RegistryID != 0 {
  170. // read the registry
  171. reg, err := config.Repo.Registry().ReadRegistry(projectID, request.RegistryID)
  172. if err != nil {
  173. return nil, nil, err
  174. }
  175. _reg := registry.Registry(*reg)
  176. regAPI := &_reg
  177. // parse the name from the registry
  178. nameSpl := strings.Split(request.ImageRepoURI, "/")
  179. repoName := nameSpl[len(nameSpl)-1]
  180. err = regAPI.CreateRepository(config.Repo, repoName)
  181. if err != nil {
  182. return nil, nil, err
  183. }
  184. }
  185. repoSplit := strings.Split(request.GitRepo, "/")
  186. if len(repoSplit) != 2 {
  187. return nil, nil, fmt.Errorf("invalid formatting of repo name")
  188. }
  189. // generate porter jwt token
  190. jwt, err := token.GetTokenForAPI(userID, projectID)
  191. if err != nil {
  192. return nil, nil, err
  193. }
  194. encoded, err := jwt.EncodeToken(config.TokenConf)
  195. if err != nil {
  196. return nil, nil, err
  197. }
  198. // create the commit in the git repo
  199. gaRunner := &actions.GithubActions{
  200. ServerURL: config.ServerConf.ServerURL,
  201. GithubOAuthIntegration: nil,
  202. GithubAppID: config.GithubAppConf.AppID,
  203. GithubAppSecretPath: config.GithubAppConf.SecretPath,
  204. GithubInstallationID: request.GitRepoID,
  205. GitRepoName: repoSplit[1],
  206. GitRepoOwner: repoSplit[0],
  207. Repo: config.Repo,
  208. ProjectID: projectID,
  209. ClusterID: clusterID,
  210. ReleaseName: name,
  211. ReleaseNamespace: namespace,
  212. GitBranch: request.GitBranch,
  213. DockerFilePath: request.DockerfilePath,
  214. FolderPath: request.FolderPath,
  215. ImageRepoURL: request.ImageRepoURI,
  216. PorterToken: encoded,
  217. Version: "v0.1.0",
  218. ShouldCreateWorkflow: request.ShouldCreateWorkflow,
  219. DryRun: release == nil,
  220. }
  221. // Save the github err for after creating the git action config. However, we
  222. // need to call Setup() in order to get the workflow file before writing the
  223. // action config, in the case of a dry run, since the dry run does not create
  224. // a git action config.
  225. workflowYAML, githubErr := gaRunner.Setup()
  226. if gaRunner.DryRun {
  227. if githubErr != nil {
  228. return nil, nil, githubErr
  229. }
  230. return nil, workflowYAML, nil
  231. }
  232. // handle write to the database
  233. ga, err := config.Repo.GitActionConfig().CreateGitActionConfig(&models.GitActionConfig{
  234. ReleaseID: release.ID,
  235. GitRepo: request.GitRepo,
  236. GitBranch: request.GitBranch,
  237. ImageRepoURI: request.ImageRepoURI,
  238. GitRepoID: request.GitRepoID,
  239. DockerfilePath: request.DockerfilePath,
  240. FolderPath: request.FolderPath,
  241. IsInstallation: true,
  242. Version: "v0.1.0",
  243. })
  244. if err != nil {
  245. return nil, nil, err
  246. }
  247. // update the release in the db with the image repo uri
  248. release.ImageRepoURI = ga.ImageRepoURI
  249. _, err = config.Repo.Release().UpdateRelease(release)
  250. if err != nil {
  251. return nil, nil, err
  252. }
  253. if githubErr != nil {
  254. return nil, nil, githubErr
  255. }
  256. return ga.ToGitActionConfigType(), workflowYAML, nil
  257. }
  258. func createBuildConfig(
  259. config *config.Config,
  260. release *models.Release,
  261. bcRequest *types.CreateBuildConfigRequest,
  262. ) (*types.BuildConfig, error) {
  263. data, err := json.Marshal(bcRequest.Config)
  264. if err != nil {
  265. return nil, err
  266. }
  267. // handle write to the database
  268. bc, err := config.Repo.BuildConfig().CreateBuildConfig(&models.BuildConfig{
  269. Builder: bcRequest.Builder,
  270. Buildpacks: strings.Join(bcRequest.Buildpacks, ","),
  271. Config: data,
  272. })
  273. if err != nil {
  274. return nil, err
  275. }
  276. release.BuildConfig = bc.ID
  277. _, err = config.Repo.Release().UpdateRelease(release)
  278. if err != nil {
  279. return nil, err
  280. }
  281. return bc.ToBuildConfigType(), nil
  282. }
  283. type containerEnvConfig struct {
  284. Container struct {
  285. Env struct {
  286. Normal map[string]string `yaml:"normal"`
  287. } `yaml:"env"`
  288. } `yaml:"container"`
  289. }
  290. func getGARunner(
  291. config *config.Config,
  292. userID, projectID, clusterID uint,
  293. ga *models.GitActionConfig,
  294. name, namespace string,
  295. release *models.Release,
  296. helmRelease *release.Release,
  297. ) (*actions.GithubActions, error) {
  298. cEnv := &containerEnvConfig{}
  299. rawValues, err := yaml.Marshal(helmRelease.Config)
  300. if err == nil {
  301. err = yaml.Unmarshal(rawValues, cEnv)
  302. // if unmarshal error, just set to empty map
  303. if err != nil {
  304. cEnv.Container.Env.Normal = make(map[string]string)
  305. }
  306. }
  307. repoSplit := strings.Split(ga.GitRepo, "/")
  308. if len(repoSplit) != 2 {
  309. return nil, fmt.Errorf("invalid formatting of repo name")
  310. }
  311. // create the commit in the git repo
  312. return &actions.GithubActions{
  313. ServerURL: config.ServerConf.ServerURL,
  314. GithubOAuthIntegration: nil,
  315. BuildEnv: cEnv.Container.Env.Normal,
  316. GithubAppID: config.GithubAppConf.AppID,
  317. GithubAppSecretPath: config.GithubAppConf.SecretPath,
  318. GithubInstallationID: ga.GitRepoID,
  319. GitRepoName: repoSplit[1],
  320. GitRepoOwner: repoSplit[0],
  321. Repo: config.Repo,
  322. ProjectID: projectID,
  323. ClusterID: clusterID,
  324. ReleaseName: name,
  325. GitBranch: ga.GitBranch,
  326. DockerFilePath: ga.DockerfilePath,
  327. FolderPath: ga.FolderPath,
  328. ImageRepoURL: ga.ImageRepoURI,
  329. Version: "v0.1.0",
  330. }, nil
  331. }