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.

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