create.go 8.2 KB

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