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

760 lines
20 KiB

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