create.go 8.4 KB

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