github_incoming.go 11 KB

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