webhook.go 18 KB

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