webhook.go 15 KB

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