github_incoming.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. package webhook
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "strconv"
  7. "strings"
  8. "sync"
  9. "github.com/bradleyfalzon/ghinstallation/v2"
  10. "github.com/google/go-github/v41/github"
  11. "github.com/porter-dev/porter/api/server/authz"
  12. "github.com/porter-dev/porter/api/server/handlers"
  13. "github.com/porter-dev/porter/api/server/shared"
  14. "github.com/porter-dev/porter/api/server/shared/apierrors"
  15. "github.com/porter-dev/porter/api/server/shared/config"
  16. "github.com/porter-dev/porter/api/server/shared/requestutils"
  17. "github.com/porter-dev/porter/api/types"
  18. "github.com/porter-dev/porter/internal/models"
  19. )
  20. type GithubIncomingWebhookHandler struct {
  21. handlers.PorterHandlerReadWriter
  22. authz.KubernetesAgentGetter
  23. }
  24. func NewGithubIncomingWebhookHandler(
  25. config *config.Config,
  26. decoderValidator shared.RequestDecoderValidator,
  27. writer shared.ResultWriter,
  28. ) *GithubIncomingWebhookHandler {
  29. return &GithubIncomingWebhookHandler{
  30. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  31. KubernetesAgentGetter: authz.NewOutOfClusterAgentGetter(config),
  32. }
  33. }
  34. func (c *GithubIncomingWebhookHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  35. payload, err := github.ValidatePayload(r, []byte(c.Config().ServerConf.GithubIncomingWebhookSecret))
  36. if err != nil {
  37. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error validating webhook payload: %w", err)))
  38. return
  39. }
  40. event, err := github.ParseWebHook(github.WebHookType(r), payload)
  41. if err != nil {
  42. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error parsing webhook: %w", err)))
  43. return
  44. }
  45. switch event := event.(type) {
  46. case *github.PullRequestEvent:
  47. err = c.processPullRequestEvent(event, r)
  48. if err != nil {
  49. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error processing pull request webhook event: %w", err)))
  50. return
  51. }
  52. }
  53. }
  54. func (c *GithubIncomingWebhookHandler) processPullRequestEvent(event *github.PullRequestEvent, r *http.Request) error {
  55. // get the webhook id from the request
  56. webhookID, reqErr := requestutils.GetURLParamString(r, types.URLParamIncomingWebhookID)
  57. if reqErr != nil {
  58. return fmt.Errorf(reqErr.Error())
  59. }
  60. owner := event.GetRepo().GetOwner().GetLogin()
  61. repo := event.GetRepo().GetName()
  62. env, err := c.Repo().Environment().ReadEnvironmentByWebhookIDOwnerRepoName(webhookID, owner, repo)
  63. if err != nil {
  64. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s] error reading environment: %w", webhookID, owner, repo, err)
  65. }
  66. if event.GetPullRequest() == nil {
  67. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s] incoming webhook does not have pull request information: %w",
  68. webhookID, owner, repo, err)
  69. }
  70. // create deployment on GitHub API
  71. client, err := getGithubClientFromEnvironment(c.Config(), env)
  72. if err != nil {
  73. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, prNumber: %d] "+
  74. "error getting github client: %w", webhookID, owner, repo, env.ID, event.GetPullRequest().GetNumber(), err)
  75. }
  76. if env.Mode == "auto" && event.GetAction() == "opened" {
  77. depl := &models.Deployment{
  78. EnvironmentID: env.ID,
  79. Namespace: fmt.Sprintf("pr-%d-%s", event.GetPullRequest().GetNumber(),
  80. strings.ToLower(strings.ReplaceAll(repo, "_", "-"))),
  81. Status: types.DeploymentStatusCreating,
  82. PullRequestID: uint(event.GetPullRequest().GetNumber()),
  83. PRName: event.GetPullRequest().GetTitle(),
  84. RepoName: repo,
  85. RepoOwner: owner,
  86. CommitSHA: event.GetPullRequest().GetHead().GetSHA()[:7],
  87. PRBranchFrom: event.GetPullRequest().GetHead().GetRef(),
  88. PRBranchInto: event.GetPullRequest().GetBase().GetRef(),
  89. }
  90. _, err = c.Repo().Environment().CreateDeployment(depl)
  91. if err != nil {
  92. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, prNumber: %d] "+
  93. "error creating new deployment: %w", webhookID, owner, repo, env.ID, event.GetPullRequest().GetNumber(), err)
  94. }
  95. cluster, err := c.Repo().Cluster().ReadCluster(env.ProjectID, env.ClusterID)
  96. if err != nil {
  97. return fmt.Errorf("[projectID: %d, clusterID: %d] error reading cluster when creating new deployment: %w",
  98. env.ProjectID, env.ClusterID, err)
  99. }
  100. // create the backing namespace
  101. agent, err := c.GetAgent(r, cluster, "")
  102. if err != nil {
  103. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, prNumber: %d] "+
  104. "error getting k8s agent: %w", webhookID, owner, repo, env.ID, event.GetPullRequest().GetNumber(), err)
  105. }
  106. _, err = agent.CreateNamespace(depl.Namespace)
  107. if err != nil {
  108. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, prNumber: %d] "+
  109. "error creating k8s namespace: %w", webhookID, owner, repo, env.ID, event.GetPullRequest().GetNumber(), err)
  110. }
  111. _, err = client.Actions.CreateWorkflowDispatchEventByFileName(
  112. r.Context(), owner, repo, fmt.Sprintf("porter_%s_env.yml", env.Name),
  113. github.CreateWorkflowDispatchEventRequest{
  114. Ref: event.GetPullRequest().GetHead().GetRef(),
  115. Inputs: map[string]interface{}{
  116. "pr_number": strconv.FormatUint(uint64(event.GetPullRequest().GetNumber()), 10),
  117. "pr_title": event.GetPullRequest().GetTitle(),
  118. "pr_branch_from": event.GetPullRequest().GetHead().GetRef(),
  119. "pr_branch_into": event.GetPullRequest().GetBase().GetRef(),
  120. },
  121. },
  122. )
  123. if err != nil {
  124. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, prNumber: %d] "+
  125. "error creating workflow dispatch event: %w", webhookID, owner, repo, env.ID, event.GetPullRequest().GetNumber(), err)
  126. }
  127. } else if event.GetAction() == "synchronize" || event.GetAction() == "closed" {
  128. depl, err := c.Repo().Environment().ReadDeploymentByGitDetails(
  129. env.ID, owner, repo, uint(event.GetPullRequest().GetNumber()),
  130. )
  131. if err != nil {
  132. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, prNumber: %d] "+
  133. "error reading deployment: %w", webhookID, owner, repo, env.ID, event.GetPullRequest().GetNumber(), err)
  134. }
  135. if depl.Status == types.DeploymentStatusInactive {
  136. return nil
  137. }
  138. if event.GetAction() == "synchronize" {
  139. _, err := client.Actions.CreateWorkflowDispatchEventByFileName(
  140. r.Context(), owner, repo, fmt.Sprintf("porter_%s_env.yml", env.Name),
  141. github.CreateWorkflowDispatchEventRequest{
  142. Ref: event.GetPullRequest().GetHead().GetRef(),
  143. Inputs: map[string]interface{}{
  144. "pr_number": strconv.FormatUint(uint64(event.GetPullRequest().GetNumber()), 10),
  145. "pr_title": event.GetPullRequest().GetTitle(),
  146. "pr_branch_from": event.GetPullRequest().GetHead().GetRef(),
  147. "pr_branch_into": event.GetPullRequest().GetBase().GetRef(),
  148. },
  149. },
  150. )
  151. if err != nil {
  152. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, deploymentID: %d, prNumber: %d] "+
  153. "error creating workflow dispatch event: %w", webhookID, owner, repo, env.ID, depl.ID,
  154. event.GetPullRequest().GetNumber(), err)
  155. }
  156. } else {
  157. // check for already running workflows we should be cancelling
  158. var wg sync.WaitGroup
  159. statuses := []string{"in_progress", "queued", "requested", "waiting"}
  160. errChan := make(chan error)
  161. wg.Add(len(statuses))
  162. for _, status := range statuses {
  163. go func(status string) {
  164. defer wg.Done()
  165. runs, _, err := client.Actions.ListWorkflowRunsByFileName(
  166. context.Background(), owner, repo, fmt.Sprintf("porter_%s_env.yml", env.Name),
  167. &github.ListWorkflowRunsOptions{
  168. Branch: event.GetPullRequest().GetHead().GetRef(),
  169. Status: status,
  170. },
  171. )
  172. if err == nil {
  173. for _, run := range runs.WorkflowRuns {
  174. _, err := client.Actions.CancelWorkflowRunByID(context.Background(), owner, repo, run.GetID())
  175. if err != nil {
  176. errChan <- fmt.Errorf("error cancelling %s: %w", run.GetHTMLURL(), err)
  177. }
  178. }
  179. } else {
  180. errChan <- fmt.Errorf("error listing workflows for status %s: %w", status, err)
  181. }
  182. }(status)
  183. }
  184. wg.Wait()
  185. close(errChan)
  186. chanErr := fmt.Errorf("")
  187. for err := range errChan {
  188. chanErr = fmt.Errorf("%s: %w", chanErr.Error(), err)
  189. }
  190. err = c.deleteDeployment(r, depl, env, client)
  191. if err != nil {
  192. deleteErr := fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, deploymentID: %d, prNumber: %d] "+
  193. "error deleting deployment: %w", webhookID, owner, repo, env.ID, depl.ID, event.GetPullRequest().GetNumber(), err)
  194. if chanErr.Error() != "" {
  195. deleteErr = fmt.Errorf("%s. errors found while trying to cancel active workflow runs %w", deleteErr.Error(), chanErr)
  196. }
  197. return deleteErr
  198. } else if chanErr.Error() != "" {
  199. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, deploymentID: %d, prNumber: %d] "+
  200. "deployment deleted but errors found while trying to cancel active workflow runs %w", webhookID, owner, repo, env.ID, depl.ID,
  201. event.GetPullRequest().GetNumber(), chanErr)
  202. }
  203. }
  204. }
  205. return nil
  206. }
  207. func (c *GithubIncomingWebhookHandler) deleteDeployment(
  208. r *http.Request,
  209. depl *models.Deployment,
  210. env *models.Environment,
  211. client *github.Client,
  212. ) error {
  213. cluster, err := c.Repo().Cluster().ReadCluster(env.ProjectID, env.ClusterID)
  214. if err != nil {
  215. return fmt.Errorf("[projectID: %d, clusterID: %d] error reading cluster when deleting existing deployment: %w",
  216. env.ProjectID, env.ClusterID, err)
  217. }
  218. agent, err := c.GetAgent(r, cluster, "")
  219. if err != nil {
  220. return err
  221. }
  222. // make sure we don't delete default or kube-system by checking for prefix, for now
  223. if strings.Contains(depl.Namespace, "pr-") {
  224. err = agent.DeleteNamespace(depl.Namespace)
  225. if err != nil {
  226. return fmt.Errorf("[owner: %s, repo: %s, environmentID: %d, deploymentID: %d] error deleting namespace '%s': %w",
  227. env.GitRepoOwner, env.GitRepoName, env.ID, depl.ID, depl.Namespace, err)
  228. }
  229. }
  230. // Create new deployment status to indicate deployment is ready
  231. state := "inactive"
  232. deploymentStatusRequest := github.DeploymentStatusRequest{
  233. State: &state,
  234. }
  235. client.Repositories.CreateDeploymentStatus(
  236. context.Background(),
  237. env.GitRepoOwner,
  238. env.GitRepoName,
  239. depl.GHDeploymentID,
  240. &deploymentStatusRequest,
  241. )
  242. depl.Status = types.DeploymentStatusInactive
  243. // update the deployment to mark it inactive
  244. _, err = c.Repo().Environment().UpdateDeployment(depl)
  245. if err != nil {
  246. return fmt.Errorf("[owner: %s, repo: %s, environmentID: %d, deploymentID: %d] error updating deployment: %w",
  247. env.GitRepoOwner, env.GitRepoName, env.ID, depl.ID, err)
  248. }
  249. return nil
  250. }
  251. func getGithubClientFromEnvironment(config *config.Config, env *models.Environment) (*github.Client, error) {
  252. // get the github app client
  253. ghAppId, err := strconv.Atoi(config.ServerConf.GithubAppID)
  254. if err != nil {
  255. return nil, err
  256. }
  257. // authenticate as github app installation
  258. itr, err := ghinstallation.NewKeyFromFile(
  259. http.DefaultTransport,
  260. int64(ghAppId),
  261. int64(env.GitInstallationID),
  262. config.ServerConf.GithubAppSecretPath,
  263. )
  264. if err != nil {
  265. return nil, err
  266. }
  267. return github.NewClient(&http.Client{Transport: itr}), nil
  268. }