create.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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/encryption"
  16. "github.com/porter-dev/porter/internal/helm"
  17. "github.com/porter-dev/porter/internal/helm/loader"
  18. "github.com/porter-dev/porter/internal/integrations/ci/actions"
  19. "github.com/porter-dev/porter/internal/models"
  20. "github.com/porter-dev/porter/internal/oauth"
  21. "github.com/porter-dev/porter/internal/registry"
  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 := encryption.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. InstanceName: config.ServerConf.InstanceName,
  203. ServerURL: config.ServerConf.ServerURL,
  204. GithubOAuthIntegration: nil,
  205. GithubAppID: config.GithubAppConf.AppID,
  206. GithubAppSecretPath: config.GithubAppConf.SecretPath,
  207. GithubInstallationID: request.GitRepoID,
  208. GitRepoName: repoSplit[1],
  209. GitRepoOwner: repoSplit[0],
  210. Repo: config.Repo,
  211. ProjectID: projectID,
  212. ClusterID: clusterID,
  213. ReleaseName: name,
  214. ReleaseNamespace: namespace,
  215. GitBranch: request.GitBranch,
  216. DockerFilePath: request.DockerfilePath,
  217. FolderPath: request.FolderPath,
  218. ImageRepoURL: request.ImageRepoURI,
  219. PorterToken: encoded,
  220. Version: "v0.1.0",
  221. ShouldCreateWorkflow: request.ShouldCreateWorkflow,
  222. DryRun: release == nil,
  223. }
  224. // Save the github err for after creating the git action config. However, we
  225. // need to call Setup() in order to get the workflow file before writing the
  226. // action config, in the case of a dry run, since the dry run does not create
  227. // a git action config.
  228. workflowYAML, githubErr := gaRunner.Setup()
  229. if gaRunner.DryRun {
  230. if githubErr != nil {
  231. return nil, nil, githubErr
  232. }
  233. return nil, workflowYAML, nil
  234. }
  235. // handle write to the database
  236. ga, err := config.Repo.GitActionConfig().CreateGitActionConfig(&models.GitActionConfig{
  237. ReleaseID: release.ID,
  238. GitRepo: request.GitRepo,
  239. GitBranch: request.GitBranch,
  240. ImageRepoURI: request.ImageRepoURI,
  241. GitRepoID: request.GitRepoID,
  242. DockerfilePath: request.DockerfilePath,
  243. FolderPath: request.FolderPath,
  244. IsInstallation: true,
  245. Version: "v0.1.0",
  246. })
  247. if err != nil {
  248. return nil, nil, err
  249. }
  250. // update the release in the db with the image repo uri
  251. release.ImageRepoURI = ga.ImageRepoURI
  252. _, err = config.Repo.Release().UpdateRelease(release)
  253. if err != nil {
  254. return nil, nil, err
  255. }
  256. if githubErr != nil {
  257. return nil, nil, githubErr
  258. }
  259. return ga.ToGitActionConfigType(), workflowYAML, nil
  260. }
  261. func createBuildConfig(
  262. config *config.Config,
  263. release *models.Release,
  264. bcRequest *types.CreateBuildConfigRequest,
  265. ) (*types.BuildConfig, error) {
  266. data, err := json.Marshal(bcRequest.Config)
  267. if err != nil {
  268. return nil, err
  269. }
  270. // handle write to the database
  271. bc, err := config.Repo.BuildConfig().CreateBuildConfig(&models.BuildConfig{
  272. Builder: bcRequest.Builder,
  273. Buildpacks: strings.Join(bcRequest.Buildpacks, ","),
  274. Config: data,
  275. })
  276. if err != nil {
  277. return nil, err
  278. }
  279. release.BuildConfig = bc.ID
  280. _, err = config.Repo.Release().UpdateRelease(release)
  281. if err != nil {
  282. return nil, err
  283. }
  284. return bc.ToBuildConfigType(), nil
  285. }
  286. type containerEnvConfig struct {
  287. Container struct {
  288. Env struct {
  289. Normal map[string]string `yaml:"normal"`
  290. } `yaml:"env"`
  291. } `yaml:"container"`
  292. }
  293. func getGARunner(
  294. config *config.Config,
  295. userID, projectID, clusterID uint,
  296. ga *models.GitActionConfig,
  297. name, namespace string,
  298. release *models.Release,
  299. helmRelease *release.Release,
  300. ) (*actions.GithubActions, error) {
  301. cEnv := &containerEnvConfig{}
  302. rawValues, err := yaml.Marshal(helmRelease.Config)
  303. if err == nil {
  304. err = yaml.Unmarshal(rawValues, cEnv)
  305. // if unmarshal error, just set to empty map
  306. if err != nil {
  307. cEnv.Container.Env.Normal = make(map[string]string)
  308. }
  309. }
  310. repoSplit := strings.Split(ga.GitRepo, "/")
  311. if len(repoSplit) != 2 {
  312. return nil, fmt.Errorf("invalid formatting of repo name")
  313. }
  314. // create the commit in the git repo
  315. return &actions.GithubActions{
  316. ServerURL: config.ServerConf.ServerURL,
  317. GithubOAuthIntegration: nil,
  318. BuildEnv: cEnv.Container.Env.Normal,
  319. GithubAppID: config.GithubAppConf.AppID,
  320. GithubAppSecretPath: config.GithubAppConf.SecretPath,
  321. GithubInstallationID: ga.GitRepoID,
  322. GitRepoName: repoSplit[1],
  323. GitRepoOwner: repoSplit[0],
  324. Repo: config.Repo,
  325. ProjectID: projectID,
  326. ClusterID: clusterID,
  327. ReleaseName: name,
  328. GitBranch: ga.GitBranch,
  329. DockerFilePath: ga.DockerfilePath,
  330. FolderPath: ga.FolderPath,
  331. ImageRepoURL: ga.ImageRepoURI,
  332. Version: "v0.1.0",
  333. }, nil
  334. }