You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

webhook.go 18 kB

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