webhook.go 19 KB

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