您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

webhook.go 16KB

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