webhook.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "crypto/hmac"
  7. "crypto/sha256"
  8. "crypto/tls"
  9. "encoding/hex"
  10. "encoding/json"
  11. "fmt"
  12. "io/ioutil"
  13. "strings"
  14. "time"
  15. "github.com/go-xorm/xorm"
  16. gouuid "github.com/satori/go.uuid"
  17. log "gopkg.in/clog.v1"
  18. api "github.com/gogits/go-gogs-client"
  19. "github.com/gogits/gogs/modules/httplib"
  20. "github.com/gogits/gogs/modules/setting"
  21. "github.com/gogits/gogs/modules/sync"
  22. )
  23. var HookQueue = sync.NewUniqueQueue(setting.Webhook.QueueLength)
  24. type HookContentType int
  25. const (
  26. JSON HookContentType = iota + 1
  27. FORM
  28. )
  29. var hookContentTypes = map[string]HookContentType{
  30. "json": JSON,
  31. "form": FORM,
  32. }
  33. // ToHookContentType returns HookContentType by given name.
  34. func ToHookContentType(name string) HookContentType {
  35. return hookContentTypes[name]
  36. }
  37. func (t HookContentType) Name() string {
  38. switch t {
  39. case JSON:
  40. return "json"
  41. case FORM:
  42. return "form"
  43. }
  44. return ""
  45. }
  46. // IsValidHookContentType returns true if given name is a valid hook content type.
  47. func IsValidHookContentType(name string) bool {
  48. _, ok := hookContentTypes[name]
  49. return ok
  50. }
  51. type HookEvents struct {
  52. Create bool `json:"create"`
  53. Delete bool `json:"delete"`
  54. Fork bool `json:"fork"`
  55. Push bool `json:"push"`
  56. Issues bool `json:"issues"`
  57. IssueComment bool `json:"issue_comment"`
  58. PullRequest bool `json:"pull_request"`
  59. Release bool `json:"release"`
  60. }
  61. // HookEvent represents events that will delivery hook.
  62. type HookEvent struct {
  63. PushOnly bool `json:"push_only"`
  64. SendEverything bool `json:"send_everything"`
  65. ChooseEvents bool `json:"choose_events"`
  66. HookEvents `json:"events"`
  67. }
  68. type HookStatus int
  69. const (
  70. HOOK_STATUS_NONE = iota
  71. HOOK_STATUS_SUCCEED
  72. HOOK_STATUS_FAILED
  73. )
  74. // Webhook represents a web hook object.
  75. type Webhook struct {
  76. ID int64 `xorm:"pk autoincr"`
  77. RepoID int64
  78. OrgID int64
  79. URL string `xorm:"url TEXT"`
  80. ContentType HookContentType
  81. Secret string `xorm:"TEXT"`
  82. Events string `xorm:"TEXT"`
  83. *HookEvent `xorm:"-"`
  84. IsSSL bool `xorm:"is_ssl"`
  85. IsActive bool
  86. HookTaskType HookTaskType
  87. Meta string `xorm:"TEXT"` // store hook-specific attributes
  88. LastStatus HookStatus // Last delivery status
  89. Created time.Time `xorm:"-"`
  90. CreatedUnix int64
  91. Updated time.Time `xorm:"-"`
  92. UpdatedUnix int64
  93. }
  94. func (w *Webhook) BeforeInsert() {
  95. w.CreatedUnix = time.Now().Unix()
  96. w.UpdatedUnix = w.CreatedUnix
  97. }
  98. func (w *Webhook) BeforeUpdate() {
  99. w.UpdatedUnix = time.Now().Unix()
  100. }
  101. func (w *Webhook) AfterSet(colName string, _ xorm.Cell) {
  102. var err error
  103. switch colName {
  104. case "events":
  105. w.HookEvent = &HookEvent{}
  106. if err = json.Unmarshal([]byte(w.Events), w.HookEvent); err != nil {
  107. log.Error(3, "Unmarshal [%d]: %v", w.ID, err)
  108. }
  109. case "created_unix":
  110. w.Created = time.Unix(w.CreatedUnix, 0).Local()
  111. case "updated_unix":
  112. w.Updated = time.Unix(w.UpdatedUnix, 0).Local()
  113. }
  114. }
  115. func (w *Webhook) GetSlackHook() *SlackMeta {
  116. s := &SlackMeta{}
  117. if err := json.Unmarshal([]byte(w.Meta), s); err != nil {
  118. log.Error(2, "GetSlackHook [%d]: %v", w.ID, err)
  119. }
  120. return s
  121. }
  122. // History returns history of webhook by given conditions.
  123. func (w *Webhook) History(page int) ([]*HookTask, error) {
  124. return HookTasks(w.ID, page)
  125. }
  126. // UpdateEvent handles conversion from HookEvent to Events.
  127. func (w *Webhook) UpdateEvent() error {
  128. data, err := json.Marshal(w.HookEvent)
  129. w.Events = string(data)
  130. return err
  131. }
  132. // HasCreateEvent returns true if hook enabled create event.
  133. func (w *Webhook) HasCreateEvent() bool {
  134. return w.SendEverything ||
  135. (w.ChooseEvents && w.HookEvents.Create)
  136. }
  137. // HasDeleteEvent returns true if hook enabled delete event.
  138. func (w *Webhook) HasDeleteEvent() bool {
  139. return w.SendEverything ||
  140. (w.ChooseEvents && w.HookEvents.Delete)
  141. }
  142. // HasForkEvent returns true if hook enabled fork event.
  143. func (w *Webhook) HasForkEvent() bool {
  144. return w.SendEverything ||
  145. (w.ChooseEvents && w.HookEvents.Fork)
  146. }
  147. // HasPushEvent returns true if hook enabled push event.
  148. func (w *Webhook) HasPushEvent() bool {
  149. return w.PushOnly || w.SendEverything ||
  150. (w.ChooseEvents && w.HookEvents.Push)
  151. }
  152. // HasIssuesEvent returns true if hook enabled issues event.
  153. func (w *Webhook) HasIssuesEvent() bool {
  154. return w.SendEverything ||
  155. (w.ChooseEvents && w.HookEvents.Issues)
  156. }
  157. // HasIssueCommentEvent returns true if hook enabled issue comment event.
  158. func (w *Webhook) HasIssueCommentEvent() bool {
  159. return w.SendEverything ||
  160. (w.ChooseEvents && w.HookEvents.IssueComment)
  161. }
  162. // HasPullRequestEvent returns true if hook enabled pull request event.
  163. func (w *Webhook) HasPullRequestEvent() bool {
  164. return w.SendEverything ||
  165. (w.ChooseEvents && w.HookEvents.PullRequest)
  166. }
  167. // HasReleaseEvent returns true if hook enabled release event.
  168. func (w *Webhook) HasReleaseEvent() bool {
  169. return w.SendEverything ||
  170. (w.ChooseEvents && w.HookEvents.Release)
  171. }
  172. type eventChecker struct {
  173. checker func() bool
  174. typ HookEventType
  175. }
  176. func (w *Webhook) EventsArray() []string {
  177. events := make([]string, 0, 7)
  178. eventCheckers := []eventChecker{
  179. {w.HasCreateEvent, HOOK_EVENT_CREATE},
  180. {w.HasDeleteEvent, HOOK_EVENT_DELETE},
  181. {w.HasForkEvent, HOOK_EVENT_FORK},
  182. {w.HasPushEvent, HOOK_EVENT_PUSH},
  183. {w.HasIssuesEvent, HOOK_EVENT_ISSUES},
  184. {w.HasIssueCommentEvent, HOOK_EVENT_ISSUE_COMMENT},
  185. {w.HasPullRequestEvent, HOOK_EVENT_PULL_REQUEST},
  186. {w.HasReleaseEvent, HOOK_EVENT_RELEASE},
  187. }
  188. for _, c := range eventCheckers {
  189. if c.checker() {
  190. events = append(events, string(c.typ))
  191. }
  192. }
  193. return events
  194. }
  195. // CreateWebhook creates a new web hook.
  196. func CreateWebhook(w *Webhook) error {
  197. _, err := x.Insert(w)
  198. return err
  199. }
  200. // getWebhook uses argument bean as query condition,
  201. // ID must be specified and do not assign unnecessary fields.
  202. func getWebhook(bean *Webhook) (*Webhook, error) {
  203. has, err := x.Get(bean)
  204. if err != nil {
  205. return nil, err
  206. } else if !has {
  207. return nil, ErrWebhookNotExist{bean.ID}
  208. }
  209. return bean, nil
  210. }
  211. // GetWebhookByID returns webhook by given ID.
  212. // Use this function with caution of accessing unauthorized webhook,
  213. // which means should only be used in non-user interactive functions.
  214. func GetWebhookByID(id int64) (*Webhook, error) {
  215. return getWebhook(&Webhook{
  216. ID: id,
  217. })
  218. }
  219. // GetWebhookOfRepoByID returns webhook of repository by given ID.
  220. func GetWebhookOfRepoByID(repoID, id int64) (*Webhook, error) {
  221. return getWebhook(&Webhook{
  222. ID: id,
  223. RepoID: repoID,
  224. })
  225. }
  226. // GetWebhookByOrgID returns webhook of organization by given ID.
  227. func GetWebhookByOrgID(orgID, id int64) (*Webhook, error) {
  228. return getWebhook(&Webhook{
  229. ID: id,
  230. OrgID: orgID,
  231. })
  232. }
  233. // getActiveWebhooksByRepoID returns all active webhooks of repository.
  234. func getActiveWebhooksByRepoID(e Engine, repoID int64) ([]*Webhook, error) {
  235. webhooks := make([]*Webhook, 0, 5)
  236. return webhooks, e.Where("repo_id = ?", repoID).And("is_active = ?", true).Find(&webhooks)
  237. }
  238. // GetWebhooksByRepoID returns all webhooks of a repository.
  239. func GetWebhooksByRepoID(repoID int64) ([]*Webhook, error) {
  240. webhooks := make([]*Webhook, 0, 5)
  241. return webhooks, x.Find(&webhooks, &Webhook{RepoID: repoID})
  242. }
  243. // UpdateWebhook updates information of webhook.
  244. func UpdateWebhook(w *Webhook) error {
  245. _, err := x.Id(w.ID).AllCols().Update(w)
  246. return err
  247. }
  248. // deleteWebhook uses argument bean as query condition,
  249. // ID must be specified and do not assign unnecessary fields.
  250. func deleteWebhook(bean *Webhook) (err error) {
  251. sess := x.NewSession()
  252. defer sessionRelease(sess)
  253. if err = sess.Begin(); err != nil {
  254. return err
  255. }
  256. if _, err = sess.Delete(bean); err != nil {
  257. return err
  258. } else if _, err = sess.Delete(&HookTask{HookID: bean.ID}); err != nil {
  259. return err
  260. }
  261. return sess.Commit()
  262. }
  263. // DeleteWebhookOfRepoByID deletes webhook of repository by given ID.
  264. func DeleteWebhookOfRepoByID(repoID, id int64) error {
  265. return deleteWebhook(&Webhook{
  266. ID: id,
  267. RepoID: repoID,
  268. })
  269. }
  270. // DeleteWebhookOfOrgByID deletes webhook of organization by given ID.
  271. func DeleteWebhookOfOrgByID(orgID, id int64) error {
  272. return deleteWebhook(&Webhook{
  273. ID: id,
  274. OrgID: orgID,
  275. })
  276. }
  277. // GetWebhooksByOrgID returns all webhooks for an organization.
  278. func GetWebhooksByOrgID(orgID int64) (ws []*Webhook, err error) {
  279. err = x.Find(&ws, &Webhook{OrgID: orgID})
  280. return ws, err
  281. }
  282. // getActiveWebhooksByOrgID returns all active webhooks for an organization.
  283. func getActiveWebhooksByOrgID(e Engine, orgID int64) ([]*Webhook, error) {
  284. ws := make([]*Webhook, 0, 3)
  285. return ws, e.Where("org_id=?", orgID).And("is_active=?", true).Find(&ws)
  286. }
  287. // ___ ___ __ ___________ __
  288. // / | \ ____ ____ | | _\__ ___/____ _____| | __
  289. // / ~ \/ _ \ / _ \| |/ / | | \__ \ / ___/ |/ /
  290. // \ Y ( <_> | <_> ) < | | / __ \_\___ \| <
  291. // \___|_ / \____/ \____/|__|_ \ |____| (____ /____ >__|_ \
  292. // \/ \/ \/ \/ \/
  293. type HookTaskType int
  294. const (
  295. GOGS HookTaskType = iota + 1
  296. SLACK
  297. DISCORD
  298. )
  299. var hookTaskTypes = map[string]HookTaskType{
  300. "gogs": GOGS,
  301. "slack": SLACK,
  302. "discord": DISCORD,
  303. }
  304. // ToHookTaskType returns HookTaskType by given name.
  305. func ToHookTaskType(name string) HookTaskType {
  306. return hookTaskTypes[name]
  307. }
  308. func (t HookTaskType) Name() string {
  309. switch t {
  310. case GOGS:
  311. return "gogs"
  312. case SLACK:
  313. return "slack"
  314. case DISCORD:
  315. return "discord"
  316. }
  317. return ""
  318. }
  319. // IsValidHookTaskType returns true if given name is a valid hook task type.
  320. func IsValidHookTaskType(name string) bool {
  321. _, ok := hookTaskTypes[name]
  322. return ok
  323. }
  324. type HookEventType string
  325. const (
  326. HOOK_EVENT_CREATE HookEventType = "create"
  327. HOOK_EVENT_DELETE HookEventType = "delete"
  328. HOOK_EVENT_FORK HookEventType = "fork"
  329. HOOK_EVENT_PUSH HookEventType = "push"
  330. HOOK_EVENT_ISSUES HookEventType = "issues"
  331. HOOK_EVENT_ISSUE_COMMENT HookEventType = "issue_comment"
  332. HOOK_EVENT_PULL_REQUEST HookEventType = "pull_request"
  333. HOOK_EVENT_RELEASE HookEventType = "release"
  334. )
  335. // HookRequest represents hook task request information.
  336. type HookRequest struct {
  337. Headers map[string]string `json:"headers"`
  338. }
  339. // HookResponse represents hook task response information.
  340. type HookResponse struct {
  341. Status int `json:"status"`
  342. Headers map[string]string `json:"headers"`
  343. Body string `json:"body"`
  344. }
  345. // HookTask represents a hook task.
  346. type HookTask struct {
  347. ID int64 `xorm:"pk autoincr"`
  348. RepoID int64 `xorm:"INDEX"`
  349. HookID int64
  350. UUID string
  351. Type HookTaskType
  352. URL string `xorm:"TEXT"`
  353. Signature string `xorm:"TEXT"`
  354. api.Payloader `xorm:"-"`
  355. PayloadContent string `xorm:"TEXT"`
  356. ContentType HookContentType
  357. EventType HookEventType
  358. IsSSL bool
  359. IsDelivered bool
  360. Delivered int64
  361. DeliveredString string `xorm:"-"`
  362. // History info.
  363. IsSucceed bool
  364. RequestContent string `xorm:"TEXT"`
  365. RequestInfo *HookRequest `xorm:"-"`
  366. ResponseContent string `xorm:"TEXT"`
  367. ResponseInfo *HookResponse `xorm:"-"`
  368. }
  369. func (t *HookTask) BeforeUpdate() {
  370. if t.RequestInfo != nil {
  371. t.RequestContent = t.MarshalJSON(t.RequestInfo)
  372. }
  373. if t.ResponseInfo != nil {
  374. t.ResponseContent = t.MarshalJSON(t.ResponseInfo)
  375. }
  376. }
  377. func (t *HookTask) AfterSet(colName string, _ xorm.Cell) {
  378. var err error
  379. switch colName {
  380. case "delivered":
  381. t.DeliveredString = time.Unix(0, t.Delivered).Format("2006-01-02 15:04:05 MST")
  382. case "request_content":
  383. if len(t.RequestContent) == 0 {
  384. return
  385. }
  386. t.RequestInfo = &HookRequest{}
  387. if err = json.Unmarshal([]byte(t.RequestContent), t.RequestInfo); err != nil {
  388. log.Error(3, "Unmarshal[%d]: %v", t.ID, err)
  389. }
  390. case "response_content":
  391. if len(t.ResponseContent) == 0 {
  392. return
  393. }
  394. t.ResponseInfo = &HookResponse{}
  395. if err = json.Unmarshal([]byte(t.ResponseContent), t.ResponseInfo); err != nil {
  396. log.Error(3, "Unmarshal [%d]: %v", t.ID, err)
  397. }
  398. }
  399. }
  400. func (t *HookTask) MarshalJSON(v interface{}) string {
  401. p, err := json.Marshal(v)
  402. if err != nil {
  403. log.Error(3, "Marshal [%d]: %v", t.ID, err)
  404. }
  405. return string(p)
  406. }
  407. // HookTasks returns a list of hook tasks by given conditions.
  408. func HookTasks(hookID int64, page int) ([]*HookTask, error) {
  409. tasks := make([]*HookTask, 0, setting.Webhook.PagingNum)
  410. return tasks, x.Limit(setting.Webhook.PagingNum, (page-1)*setting.Webhook.PagingNum).Where("hook_id=?", hookID).Desc("id").Find(&tasks)
  411. }
  412. // createHookTask creates a new hook task,
  413. // it handles conversion from Payload to PayloadContent.
  414. func createHookTask(e Engine, t *HookTask) error {
  415. data, err := t.Payloader.JSONPayload()
  416. if err != nil {
  417. return err
  418. }
  419. t.UUID = gouuid.NewV4().String()
  420. t.PayloadContent = string(data)
  421. _, err = e.Insert(t)
  422. return err
  423. }
  424. // UpdateHookTask updates information of hook task.
  425. func UpdateHookTask(t *HookTask) error {
  426. _, err := x.Id(t.ID).AllCols().Update(t)
  427. return err
  428. }
  429. // prepareHookTasks adds list of webhooks to task queue.
  430. func prepareHookTasks(e Engine, repo *Repository, event HookEventType, p api.Payloader, webhooks []*Webhook) (err error) {
  431. if len(webhooks) == 0 {
  432. return nil
  433. }
  434. var payloader api.Payloader
  435. for _, w := range webhooks {
  436. switch event {
  437. case HOOK_EVENT_CREATE:
  438. if !w.HasCreateEvent() {
  439. continue
  440. }
  441. case HOOK_EVENT_DELETE:
  442. if !w.HasDeleteEvent() {
  443. continue
  444. }
  445. case HOOK_EVENT_FORK:
  446. if !w.HasForkEvent() {
  447. continue
  448. }
  449. case HOOK_EVENT_PUSH:
  450. if !w.HasPushEvent() {
  451. continue
  452. }
  453. case HOOK_EVENT_ISSUES:
  454. if !w.HasIssuesEvent() {
  455. continue
  456. }
  457. case HOOK_EVENT_ISSUE_COMMENT:
  458. if !w.HasIssueCommentEvent() {
  459. continue
  460. }
  461. case HOOK_EVENT_PULL_REQUEST:
  462. if !w.HasPullRequestEvent() {
  463. continue
  464. }
  465. case HOOK_EVENT_RELEASE:
  466. if !w.HasReleaseEvent() {
  467. continue
  468. }
  469. }
  470. // Use separate objects so modifcations won't be made on payload on non-Gogs type hooks.
  471. switch w.HookTaskType {
  472. case SLACK:
  473. payloader, err = GetSlackPayload(p, event, w.Meta)
  474. if err != nil {
  475. return fmt.Errorf("GetSlackPayload: %v", err)
  476. }
  477. case DISCORD:
  478. payloader, err = GetDiscordPayload(p, event, w.Meta)
  479. if err != nil {
  480. return fmt.Errorf("GetDiscordPayload: %v", err)
  481. }
  482. default:
  483. payloader = p
  484. }
  485. var signature string
  486. if len(w.Secret) > 0 {
  487. data, err := payloader.JSONPayload()
  488. if err != nil {
  489. log.Error(2, "prepareWebhooks.JSONPayload: %v", err)
  490. }
  491. sig := hmac.New(sha256.New, []byte(w.Secret))
  492. sig.Write(data)
  493. signature = hex.EncodeToString(sig.Sum(nil))
  494. }
  495. if err = createHookTask(e, &HookTask{
  496. RepoID: repo.ID,
  497. HookID: w.ID,
  498. Type: w.HookTaskType,
  499. URL: w.URL,
  500. Signature: signature,
  501. Payloader: payloader,
  502. ContentType: w.ContentType,
  503. EventType: event,
  504. IsSSL: w.IsSSL,
  505. }); err != nil {
  506. return fmt.Errorf("createHookTask: %v", err)
  507. }
  508. }
  509. // It's safe to fail when the whole function is called during hook execution
  510. // because resource released after exit.
  511. // FIXME: need a more safe way to not call this function if it's during hook execution.
  512. go HookQueue.Add(repo.ID)
  513. return nil
  514. }
  515. func prepareWebhooks(e Engine, repo *Repository, event HookEventType, p api.Payloader) error {
  516. webhooks, err := getActiveWebhooksByRepoID(e, repo.ID)
  517. if err != nil {
  518. return fmt.Errorf("getActiveWebhooksByRepoID [%d]: %v", repo.ID, err)
  519. }
  520. // check if repo belongs to org and append additional webhooks
  521. if repo.mustOwner(e).IsOrganization() {
  522. // get hooks for org
  523. orgws, err := getActiveWebhooksByOrgID(e, repo.OwnerID)
  524. if err != nil {
  525. return fmt.Errorf("getActiveWebhooksByOrgID [%d]: %v", repo.OwnerID, err)
  526. }
  527. webhooks = append(webhooks, orgws...)
  528. }
  529. return prepareHookTasks(e, repo, event, p, webhooks)
  530. }
  531. // PrepareWebhooks adds all active webhooks to task queue.
  532. func PrepareWebhooks(repo *Repository, event HookEventType, p api.Payloader) error {
  533. return prepareWebhooks(x, repo, event, p)
  534. }
  535. // TestWebhook adds the test webhook matches the ID to task queue.
  536. func TestWebhook(repo *Repository, event HookEventType, p api.Payloader, webhookID int64) error {
  537. webhook, err := GetWebhookOfRepoByID(repo.ID, webhookID)
  538. if err != nil {
  539. return fmt.Errorf("GetWebhookOfRepoByID [repo_id: %d, id: %d]: %v", repo.ID, webhookID, err)
  540. }
  541. return prepareHookTasks(x, repo, event, p, []*Webhook{webhook})
  542. }
  543. func (t *HookTask) deliver() {
  544. t.IsDelivered = true
  545. timeout := time.Duration(setting.Webhook.DeliverTimeout) * time.Second
  546. req := httplib.Post(t.URL).SetTimeout(timeout, timeout).
  547. Header("X-Gogs-Delivery", t.UUID).
  548. Header("X-Gogs-Signature", t.Signature).
  549. Header("X-Gogs-Event", string(t.EventType)).
  550. SetTLSClientConfig(&tls.Config{InsecureSkipVerify: setting.Webhook.SkipTLSVerify})
  551. switch t.ContentType {
  552. case JSON:
  553. req = req.Header("Content-Type", "application/json").Body(t.PayloadContent)
  554. case FORM:
  555. req.Param("payload", t.PayloadContent)
  556. }
  557. // Record delivery information.
  558. t.RequestInfo = &HookRequest{
  559. Headers: map[string]string{},
  560. }
  561. for k, vals := range req.Headers() {
  562. t.RequestInfo.Headers[k] = strings.Join(vals, ",")
  563. }
  564. t.ResponseInfo = &HookResponse{
  565. Headers: map[string]string{},
  566. }
  567. defer func() {
  568. t.Delivered = time.Now().UnixNano()
  569. if t.IsSucceed {
  570. log.Trace("Hook delivered: %s", t.UUID)
  571. } else {
  572. log.Trace("Hook delivery failed: %s", t.UUID)
  573. }
  574. // Update webhook last delivery status.
  575. w, err := GetWebhookByID(t.HookID)
  576. if err != nil {
  577. log.Error(3, "GetWebhookByID: %v", err)
  578. return
  579. }
  580. if t.IsSucceed {
  581. w.LastStatus = HOOK_STATUS_SUCCEED
  582. } else {
  583. w.LastStatus = HOOK_STATUS_FAILED
  584. }
  585. if err = UpdateWebhook(w); err != nil {
  586. log.Error(3, "UpdateWebhook: %v", err)
  587. return
  588. }
  589. }()
  590. resp, err := req.Response()
  591. if err != nil {
  592. t.ResponseInfo.Body = fmt.Sprintf("Delivery: %v", err)
  593. return
  594. }
  595. defer resp.Body.Close()
  596. // Status code is 20x can be seen as succeed.
  597. t.IsSucceed = resp.StatusCode/100 == 2
  598. t.ResponseInfo.Status = resp.StatusCode
  599. for k, vals := range resp.Header {
  600. t.ResponseInfo.Headers[k] = strings.Join(vals, ",")
  601. }
  602. p, err := ioutil.ReadAll(resp.Body)
  603. if err != nil {
  604. t.ResponseInfo.Body = fmt.Sprintf("read body: %s", err)
  605. return
  606. }
  607. t.ResponseInfo.Body = string(p)
  608. }
  609. // DeliverHooks checks and delivers undelivered hooks.
  610. // TODO: shoot more hooks at same time.
  611. func DeliverHooks() {
  612. tasks := make([]*HookTask, 0, 10)
  613. x.Where("is_delivered=?", false).Iterate(new(HookTask),
  614. func(idx int, bean interface{}) error {
  615. t := bean.(*HookTask)
  616. t.deliver()
  617. tasks = append(tasks, t)
  618. return nil
  619. })
  620. // Update hook task status.
  621. for _, t := range tasks {
  622. if err := UpdateHookTask(t); err != nil {
  623. log.Error(4, "UpdateHookTask [%d]: %v", t.ID, err)
  624. }
  625. }
  626. // Start listening on new hook requests.
  627. for repoID := range HookQueue.Queue() {
  628. log.Trace("DeliverHooks [repo_id: %v]", repoID)
  629. HookQueue.Remove(repoID)
  630. tasks = make([]*HookTask, 0, 5)
  631. if err := x.Where("repo_id=? AND is_delivered=?", repoID, false).Find(&tasks); err != nil {
  632. log.Error(4, "Get repository [%s] hook tasks: %v", repoID, err)
  633. continue
  634. }
  635. for _, t := range tasks {
  636. t.deliver()
  637. if err := UpdateHookTask(t); err != nil {
  638. log.Error(4, "UpdateHookTask [%d]: %v", t.ID, err)
  639. continue
  640. }
  641. }
  642. }
  643. }
  644. func InitDeliverHooks() {
  645. go DeliverHooks()
  646. }