create.go 11 KB

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