create.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. package release
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "strings"
  7. "time"
  8. "github.com/porter-dev/porter/api/server/authz"
  9. "github.com/porter-dev/porter/api/server/handlers"
  10. "github.com/porter-dev/porter/api/server/shared"
  11. "github.com/porter-dev/porter/api/server/shared/apierrors"
  12. "github.com/porter-dev/porter/api/server/shared/config"
  13. "github.com/porter-dev/porter/api/types"
  14. "github.com/porter-dev/porter/internal/analytics"
  15. "github.com/porter-dev/porter/internal/auth/token"
  16. "github.com/porter-dev/porter/internal/encryption"
  17. "github.com/porter-dev/porter/internal/helm"
  18. "github.com/porter-dev/porter/internal/helm/loader"
  19. "github.com/porter-dev/porter/internal/integrations/ci/actions"
  20. "github.com/porter-dev/porter/internal/models"
  21. "github.com/porter-dev/porter/internal/oauth"
  22. "github.com/porter-dev/porter/internal/registry"
  23. "golang.org/x/crypto/bcrypt"
  24. "gopkg.in/yaml.v2"
  25. "helm.sh/helm/v3/pkg/release"
  26. v1 "k8s.io/api/core/v1"
  27. )
  28. type CreateReleaseHandler struct {
  29. handlers.PorterHandlerReadWriter
  30. authz.KubernetesAgentGetter
  31. }
  32. func NewCreateReleaseHandler(
  33. config *config.Config,
  34. decoderValidator shared.RequestDecoderValidator,
  35. writer shared.ResultWriter,
  36. ) *CreateReleaseHandler {
  37. return &CreateReleaseHandler{
  38. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  39. KubernetesAgentGetter: authz.NewOutOfClusterAgentGetter(config),
  40. }
  41. }
  42. func (c *CreateReleaseHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  43. user, _ := r.Context().Value(types.UserScope).(*models.User)
  44. proj, _ := r.Context().Value(types.ProjectScope).(*models.Project)
  45. cluster, _ := r.Context().Value(types.ClusterScope).(*models.Cluster)
  46. namespace := r.Context().Value(types.NamespaceScope).(string)
  47. operationID := oauth.CreateRandomState()
  48. c.Config().AnalyticsClient.Track(analytics.ApplicationLaunchStartTrack(
  49. &analytics.ApplicationLaunchStartTrackOpts{
  50. ClusterScopedTrackOpts: analytics.GetClusterScopedTrackOpts(user.ID, cluster.ProjectID, cluster.ID),
  51. FlowID: operationID,
  52. },
  53. ))
  54. helmAgent, err := c.GetHelmAgent(r, cluster, "")
  55. if err != nil {
  56. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  57. return
  58. }
  59. request := &types.CreateReleaseRequest{}
  60. if ok := c.DecodeAndValidate(w, r, request); !ok {
  61. return
  62. }
  63. if request.RepoURL == "" {
  64. request.RepoURL = c.Config().ServerConf.DefaultApplicationHelmRepoURL
  65. }
  66. if request.TemplateVersion == "latest" {
  67. request.TemplateVersion = ""
  68. }
  69. chart, err := loader.LoadChartPublic(request.RepoURL, request.TemplateName, request.TemplateVersion)
  70. if err != nil {
  71. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  72. return
  73. }
  74. registries, err := c.Repo().Registry().ListRegistriesByProjectID(cluster.ProjectID)
  75. if err != nil {
  76. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  77. return
  78. }
  79. conf := &helm.InstallChartConfig{
  80. Chart: chart,
  81. Name: request.Name,
  82. Namespace: namespace,
  83. Values: request.Values,
  84. Cluster: cluster,
  85. Repo: c.Repo(),
  86. Registries: registries,
  87. }
  88. helmRelease, err := helmAgent.InstallChart(conf, c.Config().DOConf)
  89. if err != nil {
  90. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(
  91. fmt.Errorf("error installing a new chart: %s", err.Error()),
  92. http.StatusBadRequest,
  93. ))
  94. return
  95. }
  96. k8sAgent, err := c.GetAgent(r, cluster, "")
  97. if err != nil {
  98. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  99. return
  100. }
  101. configMaps := make([]*v1.ConfigMap, 0)
  102. if request.SyncedEnvGroups != nil && len(request.SyncedEnvGroups) > 0 {
  103. for _, envGroupName := range request.SyncedEnvGroups {
  104. // read the attached configmap
  105. cm, _, err := k8sAgent.GetLatestVersionedConfigMap(envGroupName, namespace)
  106. if err != nil {
  107. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(fmt.Errorf("Couldn't find the env group"), http.StatusNotFound))
  108. return
  109. }
  110. configMaps = append(configMaps, cm)
  111. }
  112. }
  113. release, err := CreateAppReleaseFromHelmRelease(c.Config(), cluster.ProjectID, cluster.ID, 0, helmRelease)
  114. if err != nil {
  115. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  116. return
  117. }
  118. if len(configMaps) > 0 {
  119. for _, cm := range configMaps {
  120. _, err = k8sAgent.AddApplicationToVersionedConfigMap(cm, release.Name)
  121. if err != nil {
  122. c.HandleAPIErrorNoWrite(w, r, apierrors.NewErrInternal(fmt.Errorf("Couldn't add %s to the config map %s", release.Name, cm.Name)))
  123. }
  124. }
  125. }
  126. if request.Tags != nil {
  127. tags, err := c.Repo().Tag().LinkTagsToRelease(request.Tags, release)
  128. if err == nil {
  129. release.Tags = append(release.Tags, tags...)
  130. }
  131. }
  132. if request.GithubActionConfig != nil {
  133. _, _, err := createGitAction(
  134. c.Config(),
  135. proj,
  136. user.ID,
  137. cluster.ProjectID,
  138. cluster.ID,
  139. request.GithubActionConfig,
  140. request.Name,
  141. namespace,
  142. release,
  143. )
  144. if err != nil {
  145. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  146. return
  147. }
  148. }
  149. if request.BuildConfig != nil {
  150. _, err = createBuildConfig(c.Config(), release, request.BuildConfig)
  151. }
  152. if err != nil {
  153. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  154. return
  155. }
  156. c.Config().AnalyticsClient.Track(analytics.ApplicationLaunchSuccessTrack(
  157. &analytics.ApplicationLaunchSuccessTrackOpts{
  158. ApplicationScopedTrackOpts: analytics.GetApplicationScopedTrackOpts(
  159. user.ID,
  160. cluster.ProjectID,
  161. cluster.ID,
  162. release.Name,
  163. release.Namespace,
  164. chart.Metadata.Name,
  165. ),
  166. FlowID: operationID,
  167. },
  168. ))
  169. }
  170. func CreateAppReleaseFromHelmRelease(
  171. config *config.Config,
  172. projectID, clusterID, stackResourceID uint,
  173. helmRelease *release.Release,
  174. ) (*models.Release, error) {
  175. token, err := encryption.GenerateRandomBytes(16)
  176. if err != nil {
  177. return nil, err
  178. }
  179. // create release with webhook token in db
  180. image, ok := helmRelease.Config["image"].(map[string]interface{})
  181. if !ok {
  182. return nil, fmt.Errorf("Could not find field image in config")
  183. }
  184. repository := image["repository"]
  185. repoStr, ok := repository.(string)
  186. if !ok {
  187. return nil, fmt.Errorf("Could not find field repository in config")
  188. }
  189. release := &models.Release{
  190. ClusterID: clusterID,
  191. ProjectID: projectID,
  192. Namespace: helmRelease.Namespace,
  193. Name: helmRelease.Name,
  194. WebhookToken: token,
  195. ImageRepoURI: repoStr,
  196. StackResourceID: stackResourceID,
  197. }
  198. return config.Repo.Release().CreateRelease(release)
  199. }
  200. func CreateAddonReleaseFromHelmRelease(
  201. config *config.Config,
  202. projectID, clusterID, stackResourceID uint,
  203. helmRelease *release.Release,
  204. ) (*models.Release, error) {
  205. release := &models.Release{
  206. ClusterID: clusterID,
  207. ProjectID: projectID,
  208. Namespace: helmRelease.Namespace,
  209. Name: helmRelease.Name,
  210. StackResourceID: stackResourceID,
  211. }
  212. return config.Repo.Release().CreateRelease(release)
  213. }
  214. func createGitAction(
  215. config *config.Config,
  216. project *models.Project,
  217. userID, projectID, clusterID uint,
  218. request *types.CreateGitActionConfigRequest,
  219. name, namespace string,
  220. release *models.Release,
  221. ) (*types.GitActionConfig, []byte, error) {
  222. // if the registry was provisioned through Porter, create a repository if necessary
  223. if release != nil && request.RegistryID != 0 {
  224. // read the registry
  225. reg, err := config.Repo.Registry().ReadRegistry(projectID, request.RegistryID)
  226. if err != nil {
  227. return nil, nil, err
  228. }
  229. _reg := registry.Registry(*reg)
  230. regAPI := &_reg
  231. // parse the name from the registry
  232. nameSpl := strings.Split(request.ImageRepoURI, "/")
  233. repoName := nameSpl[len(nameSpl)-1]
  234. err = regAPI.CreateRepository(config.Repo, repoName)
  235. if err != nil {
  236. return nil, nil, err
  237. }
  238. }
  239. isDryRun := release == nil
  240. repoSplit := strings.Split(request.GitRepo, "/")
  241. if len(repoSplit) != 2 {
  242. return nil, nil, fmt.Errorf("invalid formatting of repo name")
  243. }
  244. encoded := ""
  245. var err error
  246. // if this isn't a dry run, generate the token
  247. if !isDryRun {
  248. encoded, err = getToken(config, project, userID, projectID, clusterID, request)
  249. if err != nil {
  250. return nil, nil, err
  251. }
  252. }
  253. // create the commit in the git repo
  254. gaRunner := &actions.GithubActions{
  255. InstanceName: config.ServerConf.InstanceName,
  256. ServerURL: config.ServerConf.ServerURL,
  257. GithubOAuthIntegration: nil,
  258. GithubAppID: config.GithubAppConf.AppID,
  259. GithubAppSecretPath: config.GithubAppConf.SecretPath,
  260. GithubInstallationID: request.GitRepoID,
  261. GitRepoName: repoSplit[1],
  262. GitRepoOwner: repoSplit[0],
  263. Repo: config.Repo,
  264. ProjectID: projectID,
  265. ClusterID: clusterID,
  266. ReleaseName: name,
  267. ReleaseNamespace: namespace,
  268. GitBranch: request.GitBranch,
  269. DockerFilePath: request.DockerfilePath,
  270. FolderPath: request.FolderPath,
  271. ImageRepoURL: request.ImageRepoURI,
  272. PorterToken: encoded,
  273. Version: "v0.1.0",
  274. ShouldCreateWorkflow: request.ShouldCreateWorkflow,
  275. DryRun: isDryRun,
  276. }
  277. // Save the github err for after creating the git action config. However, we
  278. // need to call Setup() in order to get the workflow file before writing the
  279. // action config, in the case of a dry run, since the dry run does not create
  280. // a git action config.
  281. workflowYAML, githubErr := gaRunner.Setup()
  282. if gaRunner.DryRun {
  283. if githubErr != nil {
  284. return nil, nil, githubErr
  285. }
  286. return nil, workflowYAML, nil
  287. }
  288. // handle write to the database
  289. ga, err := config.Repo.GitActionConfig().CreateGitActionConfig(&models.GitActionConfig{
  290. ReleaseID: release.ID,
  291. GitRepo: request.GitRepo,
  292. GitBranch: request.GitBranch,
  293. ImageRepoURI: request.ImageRepoURI,
  294. GitRepoID: request.GitRepoID,
  295. DockerfilePath: request.DockerfilePath,
  296. FolderPath: request.FolderPath,
  297. IsInstallation: true,
  298. Version: "v0.1.0",
  299. })
  300. if err != nil {
  301. return nil, nil, err
  302. }
  303. // update the release in the db with the image repo uri
  304. release.ImageRepoURI = ga.ImageRepoURI
  305. _, err = config.Repo.Release().UpdateRelease(release)
  306. if err != nil {
  307. return nil, nil, err
  308. }
  309. if githubErr != nil {
  310. return nil, nil, githubErr
  311. }
  312. return ga.ToGitActionConfigType(), workflowYAML, nil
  313. }
  314. func getToken(
  315. config *config.Config,
  316. proj *models.Project,
  317. userID, projectID, clusterID uint,
  318. request *types.CreateGitActionConfigRequest,
  319. ) (string, error) {
  320. // create a policy for the token
  321. policy := []*types.PolicyDocument{
  322. {
  323. Scope: types.ProjectScope,
  324. Verbs: types.ReadWriteVerbGroup(),
  325. Children: map[types.PermissionScope]*types.PolicyDocument{
  326. types.ClusterScope: {
  327. Scope: types.ClusterScope,
  328. Verbs: types.ReadWriteVerbGroup(),
  329. },
  330. types.RegistryScope: {
  331. Scope: types.RegistryScope,
  332. Verbs: types.ReadVerbGroup(),
  333. },
  334. types.HelmRepoScope: {
  335. Scope: types.HelmRepoScope,
  336. Verbs: types.ReadVerbGroup(),
  337. },
  338. },
  339. },
  340. }
  341. uid, err := encryption.GenerateRandomBytes(16)
  342. if err != nil {
  343. return "", err
  344. }
  345. policyBytes, err := json.Marshal(policy)
  346. if err != nil {
  347. return "", err
  348. }
  349. policyModel := &models.Policy{
  350. ProjectID: projectID,
  351. UniqueID: uid,
  352. CreatedByUserID: userID,
  353. Name: strings.ToLower(fmt.Sprintf("repo-%s-token-policy", request.GitRepo)),
  354. PolicyBytes: policyBytes,
  355. }
  356. policyModel, err = config.Repo.Policy().CreatePolicy(policyModel)
  357. if err != nil {
  358. return "", err
  359. }
  360. // create the token in the database
  361. tokenUID, err := encryption.GenerateRandomBytes(16)
  362. if err != nil {
  363. return "", err
  364. }
  365. secretKey, err := encryption.GenerateRandomBytes(16)
  366. if err != nil {
  367. return "", err
  368. }
  369. // hash the secret key for storage in the db
  370. hashedToken, err := bcrypt.GenerateFromPassword([]byte(secretKey), 8)
  371. if err != nil {
  372. return "", err
  373. }
  374. expiresAt := time.Now().Add(time.Hour * 24 * 365)
  375. apiToken := &models.APIToken{
  376. UniqueID: tokenUID,
  377. ProjectID: projectID,
  378. CreatedByUserID: userID,
  379. Expiry: &expiresAt,
  380. Revoked: false,
  381. PolicyUID: policyModel.UniqueID,
  382. PolicyName: policyModel.Name,
  383. Name: strings.ToLower(fmt.Sprintf("repo-%s-token", request.GitRepo)),
  384. SecretKey: hashedToken,
  385. }
  386. if !proj.APITokensEnabled {
  387. return "", fmt.Errorf("api tokens are not enabled for this project")
  388. }
  389. apiToken, err = config.Repo.APIToken().CreateAPIToken(apiToken)
  390. if err != nil {
  391. return "", err
  392. }
  393. // generate porter jwt token
  394. jwt, err := token.GetStoredTokenForAPI(userID, projectID, apiToken.UniqueID, secretKey)
  395. if err != nil {
  396. return "", err
  397. }
  398. return jwt.EncodeToken(config.TokenConf)
  399. }
  400. func createBuildConfig(
  401. config *config.Config,
  402. release *models.Release,
  403. bcRequest *types.CreateBuildConfigRequest,
  404. ) (*types.BuildConfig, error) {
  405. data, err := json.Marshal(bcRequest.Config)
  406. if err != nil {
  407. return nil, err
  408. }
  409. // handle write to the database
  410. bc, err := config.Repo.BuildConfig().CreateBuildConfig(&models.BuildConfig{
  411. Builder: bcRequest.Builder,
  412. Buildpacks: strings.Join(bcRequest.Buildpacks, ","),
  413. Config: data,
  414. })
  415. if err != nil {
  416. return nil, err
  417. }
  418. release.BuildConfig = bc.ID
  419. _, err = config.Repo.Release().UpdateRelease(release)
  420. if err != nil {
  421. return nil, err
  422. }
  423. return bc.ToBuildConfigType(), nil
  424. }
  425. type containerEnvConfig struct {
  426. Container struct {
  427. Env struct {
  428. Normal map[string]string `yaml:"normal"`
  429. } `yaml:"env"`
  430. } `yaml:"container"`
  431. }
  432. func getGARunner(
  433. config *config.Config,
  434. userID, projectID, clusterID uint,
  435. ga *models.GitActionConfig,
  436. name, namespace string,
  437. release *models.Release,
  438. helmRelease *release.Release,
  439. ) (*actions.GithubActions, error) {
  440. cEnv := &containerEnvConfig{}
  441. rawValues, err := yaml.Marshal(helmRelease.Config)
  442. if err == nil {
  443. err = yaml.Unmarshal(rawValues, cEnv)
  444. // if unmarshal error, just set to empty map
  445. if err != nil {
  446. cEnv.Container.Env.Normal = make(map[string]string)
  447. }
  448. }
  449. repoSplit := strings.Split(ga.GitRepo, "/")
  450. if len(repoSplit) != 2 {
  451. return nil, fmt.Errorf("invalid formatting of repo name")
  452. }
  453. // create the commit in the git repo
  454. return &actions.GithubActions{
  455. ServerURL: config.ServerConf.ServerURL,
  456. GithubOAuthIntegration: nil,
  457. BuildEnv: cEnv.Container.Env.Normal,
  458. GithubAppID: config.GithubAppConf.AppID,
  459. GithubAppSecretPath: config.GithubAppConf.SecretPath,
  460. GithubInstallationID: ga.GitRepoID,
  461. GitRepoName: repoSplit[1],
  462. GitRepoOwner: repoSplit[0],
  463. Repo: config.Repo,
  464. ProjectID: projectID,
  465. ClusterID: clusterID,
  466. ReleaseName: name,
  467. GitBranch: ga.GitBranch,
  468. DockerFilePath: ga.DockerfilePath,
  469. FolderPath: ga.FolderPath,
  470. ImageRepoURL: ga.ImageRepoURI,
  471. Version: "v0.1.0",
  472. }, nil
  473. }