You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

619 lines
14 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  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. }
  447. // Update webhook last delivery status.
  448. w, err := GetWebhookByID(t.HookID)
  449. if err != nil {
  450. log.Error(5, "GetWebhookByID: %v", err)
  451. return
  452. }
  453. if t.IsSucceed {
  454. w.LastStatus = HOOK_STATUS_SUCCEED
  455. } else {
  456. w.LastStatus = HOOK_STATUS_FAILED
  457. }
  458. if err = UpdateWebhook(w); err != nil {
  459. log.Error(5, "UpdateWebhook: %v", err)
  460. return
  461. }
  462. }()
  463. resp, err := req.Response()
  464. if err != nil {
  465. t.ResponseInfo.Body = fmt.Sprintf("Delivery: %v", err)
  466. return
  467. }
  468. defer resp.Body.Close()
  469. // Status code is 20x can be seen as succeed.
  470. t.IsSucceed = resp.StatusCode/100 == 2
  471. t.ResponseInfo.Status = resp.StatusCode
  472. for k, vals := range resp.Header {
  473. t.ResponseInfo.Headers[k] = strings.Join(vals, ",")
  474. }
  475. p, err := ioutil.ReadAll(resp.Body)
  476. if err != nil {
  477. t.ResponseInfo.Body = fmt.Sprintf("read body: %s", err)
  478. return
  479. }
  480. t.ResponseInfo.Body = string(p)
  481. switch t.Type {
  482. case SLACK:
  483. if t.ResponseInfo.Body != "ok" {
  484. log.Error(5, "slack failed with: %s", t.ResponseInfo.Body)
  485. t.IsSucceed = false
  486. }
  487. }
  488. }
  489. // DeliverHooks checks and delivers undelivered hooks.
  490. // TODO: shoot more hooks at same time.
  491. func DeliverHooks() {
  492. tasks := make([]*HookTask, 0, 10)
  493. x.Where("is_delivered=?", false).Iterate(new(HookTask),
  494. func(idx int, bean interface{}) error {
  495. t := bean.(*HookTask)
  496. t.deliver()
  497. tasks = append(tasks, t)
  498. return nil
  499. })
  500. // Update hook task status.
  501. for _, t := range tasks {
  502. if err := UpdateHookTask(t); err != nil {
  503. log.Error(4, "UpdateHookTask(%d): %v", t.ID, err)
  504. }
  505. }
  506. // Start listening on new hook requests.
  507. for repoID := range HookQueue.Queue() {
  508. log.Trace("DeliverHooks[%v]: processing delivery hooks", repoID)
  509. HookQueue.Remove(repoID)
  510. tasks = make([]*HookTask, 0, 5)
  511. if err := x.Where("repo_id=? AND is_delivered=?", repoID, false).Find(&tasks); err != nil {
  512. log.Error(4, "Get repository(%d) hook tasks: %v", repoID, err)
  513. continue
  514. }
  515. for _, t := range tasks {
  516. t.deliver()
  517. if err := UpdateHookTask(t); err != nil {
  518. log.Error(4, "UpdateHookTask[%d]: %v", t.ID, err)
  519. continue
  520. }
  521. }
  522. }
  523. }
  524. func InitDeliverHooks() {
  525. go DeliverHooks()
  526. }