webhook.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  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 `xorm:"TEXT"`
  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. var payloader api.Payloader
  340. for _, w := range ws {
  341. switch event {
  342. case HOOK_EVENT_CREATE:
  343. if !w.HasCreateEvent() {
  344. continue
  345. }
  346. case HOOK_EVENT_PUSH:
  347. if !w.HasPushEvent() {
  348. continue
  349. }
  350. }
  351. // Use separate objects so modifcations won't be made on payload on non-Gogs type hooks.
  352. switch w.HookTaskType {
  353. case SLACK:
  354. payloader, err = GetSlackPayload(p, event, w.Meta)
  355. if err != nil {
  356. return fmt.Errorf("GetSlackPayload: %v", err)
  357. }
  358. default:
  359. p.SetSecret(w.Secret)
  360. payloader = p
  361. }
  362. if err = CreateHookTask(&HookTask{
  363. RepoID: repo.ID,
  364. HookID: w.ID,
  365. Type: w.HookTaskType,
  366. URL: w.URL,
  367. Payloader: payloader,
  368. ContentType: w.ContentType,
  369. EventType: HOOK_EVENT_PUSH,
  370. IsSSL: w.IsSSL,
  371. }); err != nil {
  372. return fmt.Errorf("CreateHookTask: %v", err)
  373. }
  374. }
  375. return nil
  376. }
  377. // UniqueQueue represents a queue that guarantees only one instance of same ID is in the line.
  378. type UniqueQueue struct {
  379. lock sync.Mutex
  380. ids map[string]bool
  381. queue chan string
  382. }
  383. func (q *UniqueQueue) Queue() <-chan string {
  384. return q.queue
  385. }
  386. func NewUniqueQueue(queueLength int) *UniqueQueue {
  387. if queueLength <= 0 {
  388. queueLength = 100
  389. }
  390. return &UniqueQueue{
  391. ids: make(map[string]bool),
  392. queue: make(chan string, queueLength),
  393. }
  394. }
  395. func (q *UniqueQueue) Remove(id interface{}) {
  396. q.lock.Lock()
  397. defer q.lock.Unlock()
  398. delete(q.ids, com.ToStr(id))
  399. }
  400. func (q *UniqueQueue) AddFunc(id interface{}, fn func()) {
  401. newid := com.ToStr(id)
  402. if q.Exist(id) {
  403. return
  404. }
  405. q.lock.Lock()
  406. q.ids[newid] = true
  407. if fn != nil {
  408. fn()
  409. }
  410. q.lock.Unlock()
  411. q.queue <- newid
  412. }
  413. func (q *UniqueQueue) Add(id interface{}) {
  414. q.AddFunc(id, nil)
  415. }
  416. func (q *UniqueQueue) Exist(id interface{}) bool {
  417. q.lock.Lock()
  418. defer q.lock.Unlock()
  419. return q.ids[com.ToStr(id)]
  420. }
  421. var HookQueue = NewUniqueQueue(setting.Webhook.QueueLength)
  422. func (t *HookTask) deliver() {
  423. t.IsDelivered = true
  424. timeout := time.Duration(setting.Webhook.DeliverTimeout) * time.Second
  425. req := httplib.Post(t.URL).SetTimeout(timeout, timeout).
  426. Header("X-Gogs-Delivery", t.UUID).
  427. Header("X-Gogs-Event", string(t.EventType)).
  428. SetTLSClientConfig(&tls.Config{InsecureSkipVerify: setting.Webhook.SkipTLSVerify})
  429. switch t.ContentType {
  430. case JSON:
  431. req = req.Header("Content-Type", "application/json").Body(t.PayloadContent)
  432. case FORM:
  433. req.Param("payload", t.PayloadContent)
  434. }
  435. // Record delivery information.
  436. t.RequestInfo = &HookRequest{
  437. Headers: map[string]string{},
  438. }
  439. for k, vals := range req.Headers() {
  440. t.RequestInfo.Headers[k] = strings.Join(vals, ",")
  441. }
  442. t.ResponseInfo = &HookResponse{
  443. Headers: map[string]string{},
  444. }
  445. defer func() {
  446. t.Delivered = time.Now().UTC().UnixNano()
  447. if t.IsSucceed {
  448. log.Trace("Hook delivered: %s", t.UUID)
  449. } else {
  450. log.Trace("Hook delivery failed: %s", t.UUID)
  451. }
  452. // Update webhook last delivery status.
  453. w, err := GetWebhookByID(t.HookID)
  454. if err != nil {
  455. log.Error(5, "GetWebhookByID: %v", err)
  456. return
  457. }
  458. if t.IsSucceed {
  459. w.LastStatus = HOOK_STATUS_SUCCEED
  460. } else {
  461. w.LastStatus = HOOK_STATUS_FAILED
  462. }
  463. if err = UpdateWebhook(w); err != nil {
  464. log.Error(5, "UpdateWebhook: %v", err)
  465. return
  466. }
  467. }()
  468. resp, err := req.Response()
  469. if err != nil {
  470. t.ResponseInfo.Body = fmt.Sprintf("Delivery: %v", err)
  471. return
  472. }
  473. defer resp.Body.Close()
  474. // Status code is 20x can be seen as succeed.
  475. t.IsSucceed = resp.StatusCode/100 == 2
  476. t.ResponseInfo.Status = resp.StatusCode
  477. for k, vals := range resp.Header {
  478. t.ResponseInfo.Headers[k] = strings.Join(vals, ",")
  479. }
  480. p, err := ioutil.ReadAll(resp.Body)
  481. if err != nil {
  482. t.ResponseInfo.Body = fmt.Sprintf("read body: %s", err)
  483. return
  484. }
  485. t.ResponseInfo.Body = string(p)
  486. switch t.Type {
  487. case SLACK:
  488. if t.ResponseInfo.Body != "ok" {
  489. log.Error(5, "slack failed with: %s", t.ResponseInfo.Body)
  490. t.IsSucceed = false
  491. }
  492. }
  493. }
  494. // DeliverHooks checks and delivers undelivered hooks.
  495. // TODO: shoot more hooks at same time.
  496. func DeliverHooks() {
  497. tasks := make([]*HookTask, 0, 10)
  498. x.Where("is_delivered=?", false).Iterate(new(HookTask),
  499. func(idx int, bean interface{}) error {
  500. t := bean.(*HookTask)
  501. t.deliver()
  502. tasks = append(tasks, t)
  503. return nil
  504. })
  505. // Update hook task status.
  506. for _, t := range tasks {
  507. if err := UpdateHookTask(t); err != nil {
  508. log.Error(4, "UpdateHookTask [%d]: %v", t.ID, err)
  509. }
  510. }
  511. // Start listening on new hook requests.
  512. for repoID := range HookQueue.Queue() {
  513. log.Trace("DeliverHooks [%v]: processing delivery hooks", repoID)
  514. HookQueue.Remove(repoID)
  515. tasks = make([]*HookTask, 0, 5)
  516. if err := x.Where("repo_id=? AND is_delivered=?", repoID, false).Find(&tasks); err != nil {
  517. log.Error(4, "Get repository [%d] hook tasks: %v", repoID, err)
  518. continue
  519. }
  520. for _, t := range tasks {
  521. t.deliver()
  522. if err := UpdateHookTask(t); err != nil {
  523. log.Error(4, "UpdateHookTask [%d]: %v", t.ID, err)
  524. continue
  525. }
  526. }
  527. }
  528. }
  529. func InitDeliverHooks() {
  530. go DeliverHooks()
  531. }