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 17 kB

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