github_incoming.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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. chanErr := fmt.Errorf("")
  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. resp, err := client.Actions.CancelWorkflowRunByID(context.Background(), owner, repo, run.GetID())
  175. if err != nil && resp.StatusCode != http.StatusAccepted {
  176. // the go library we are using returns a 202 Accepted status as an error
  177. // in this case, we should rule this out as an error
  178. chanErr = fmt.Errorf("%s: error cancelling %s: %w", chanErr.Error(), run.GetHTMLURL(), err)
  179. }
  180. }
  181. } else {
  182. chanErr = fmt.Errorf("%s: error listing workflows for status %s: %w", chanErr.Error(), status, err)
  183. }
  184. }(status)
  185. }
  186. wg.Wait()
  187. err = c.deleteDeployment(r, depl, env, client)
  188. if err != nil {
  189. deleteErr := fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, deploymentID: %d, prNumber: %d] "+
  190. "error deleting deployment: %w", webhookID, owner, repo, env.ID, depl.ID, event.GetPullRequest().GetNumber(), err)
  191. if chanErr.Error() != "" {
  192. deleteErr = fmt.Errorf("%s. errors found while trying to cancel active workflow runs %w", deleteErr.Error(), chanErr)
  193. }
  194. return deleteErr
  195. } else if chanErr.Error() != "" {
  196. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, deploymentID: %d, prNumber: %d] "+
  197. "deployment deleted but errors found while trying to cancel active workflow runs %w", webhookID, owner, repo, env.ID, depl.ID,
  198. event.GetPullRequest().GetNumber(), chanErr)
  199. }
  200. }
  201. }
  202. return nil
  203. }
  204. func (c *GithubIncomingWebhookHandler) deleteDeployment(
  205. r *http.Request,
  206. depl *models.Deployment,
  207. env *models.Environment,
  208. client *github.Client,
  209. ) error {
  210. cluster, err := c.Repo().Cluster().ReadCluster(env.ProjectID, env.ClusterID)
  211. if err != nil {
  212. return fmt.Errorf("[projectID: %d, clusterID: %d] error reading cluster when deleting existing deployment: %w",
  213. env.ProjectID, env.ClusterID, err)
  214. }
  215. agent, err := c.GetAgent(r, cluster, "")
  216. if err != nil {
  217. return err
  218. }
  219. // make sure we don't delete default or kube-system by checking for prefix, for now
  220. if strings.Contains(depl.Namespace, "pr-") {
  221. err = agent.DeleteNamespace(depl.Namespace)
  222. if err != nil {
  223. return fmt.Errorf("[owner: %s, repo: %s, environmentID: %d, deploymentID: %d] error deleting namespace '%s': %w",
  224. env.GitRepoOwner, env.GitRepoName, env.ID, depl.ID, depl.Namespace, err)
  225. }
  226. }
  227. // Create new deployment status to indicate deployment is ready
  228. state := "inactive"
  229. deploymentStatusRequest := github.DeploymentStatusRequest{
  230. State: &state,
  231. }
  232. client.Repositories.CreateDeploymentStatus(
  233. context.Background(),
  234. env.GitRepoOwner,
  235. env.GitRepoName,
  236. depl.GHDeploymentID,
  237. &deploymentStatusRequest,
  238. )
  239. depl.Status = types.DeploymentStatusInactive
  240. // update the deployment to mark it inactive
  241. _, err = c.Repo().Environment().UpdateDeployment(depl)
  242. if err != nil {
  243. return fmt.Errorf("[owner: %s, repo: %s, environmentID: %d, deploymentID: %d] error updating deployment: %w",
  244. env.GitRepoOwner, env.GitRepoName, env.ID, depl.ID, err)
  245. }
  246. return nil
  247. }
  248. func getGithubClientFromEnvironment(config *config.Config, env *models.Environment) (*github.Client, error) {
  249. // get the github app client
  250. ghAppId, err := strconv.Atoi(config.ServerConf.GithubAppID)
  251. if err != nil {
  252. return nil, err
  253. }
  254. // authenticate as github app installation
  255. itr, err := ghinstallation.NewKeyFromFile(
  256. http.DefaultTransport,
  257. int64(ghAppId),
  258. int64(env.GitInstallationID),
  259. config.ServerConf.GithubAppSecretPath,
  260. )
  261. if err != nil {
  262. return nil, err
  263. }
  264. return github.NewClient(&http.Client{Transport: itr}), nil
  265. }