webhook.go 18 KB

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