pipeline.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package service
  2. import (
  3. "context"
  4. "go-common/app/tool/saga/model"
  5. "go-common/app/tool/saga/service/notification"
  6. "go-common/library/log"
  7. )
  8. // PipelineChanged handle pipeline changed webhook
  9. func (s *Service) PipelineChanged(c context.Context, event *model.HookPipeline) (err error) {
  10. var (
  11. ok bool
  12. repo *model.Repo
  13. state bool
  14. lastPipeLineState bool
  15. wip bool
  16. )
  17. //get associated pipeline mr and check it's wip status, if wip is true and return
  18. if wip, err = s.checkMrStatus(c, event.Project.ID, event.ObjectAttributes.Ref); wip {
  19. log.Info("Pipeline associated mr is wip, project ID: [%d], branch: [%s]", event.Project.ID, event.ObjectAttributes.Ref)
  20. return
  21. }
  22. if ok, repo = s.findRepo(event.Project.GitSSHURL); !ok || !repo.Config.RelatePipeline {
  23. log.Info("PipelineChanged return repo: %s, ok: %t", event.Project.GitSSHURL, ok)
  24. return
  25. }
  26. if event.ObjectKind != model.HookPipelineType {
  27. log.Info("Pipeline hook object kind [%s] ignore", event.ObjectKind)
  28. return
  29. }
  30. if (event.ObjectAttributes.Status != model.PipelineFailed) && (event.ObjectAttributes.Status != model.PipelineSuccess) && (event.ObjectAttributes.Status != model.PipelineCanceled) {
  31. log.Info("Pipeline status [%s] ignore for project [%s]", event.ObjectAttributes.Status, event.Project.Name)
  32. return
  33. }
  34. go func() {
  35. if err = s.cmd.HookPipeline(event.Project.ID, event.ObjectAttributes.Ref, int(event.ObjectAttributes.ID)); err != nil {
  36. log.Error("CheckPipeline: %d %s %+v", event.Project.ID, event.ObjectAttributes.Ref, err)
  37. }
  38. }()
  39. // 查询上次pipeline状态,状态变化才发通知
  40. if lastPipeLineState, err = s.gitlab.LastPipeLineState(event.Project.ID, event.ObjectAttributes.Ref); err != nil {
  41. return
  42. }
  43. state = event.ObjectAttributes.Status == model.PipelineSuccess
  44. log.Info("status:%t, lastPipeLineState: %t", state, lastPipeLineState)
  45. if lastPipeLineState != state {
  46. go notification.MailPipeline(event)
  47. go notification.WechatPipeline(s.d, event)
  48. }
  49. return
  50. }
  51. func (s *Service) checkMrStatus(c context.Context, projectID int, branch string) (wip bool, err error) {
  52. var (
  53. ok bool
  54. mergeInfo *model.MergeInfo
  55. )
  56. if ok, mergeInfo, err = s.d.MergeInfo(c, projectID, branch); err != nil || !ok {
  57. return
  58. }
  59. if wip, _, _, err = s.gitlab.MergeStatus(projectID, mergeInfo.MRIID); err != nil {
  60. return
  61. }
  62. return
  63. }