webhook.go 20 KB

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