-
Notifications
You must be signed in to change notification settings - Fork 3
/
dispatcher.go
173 lines (139 loc) · 3.99 KB
/
dispatcher.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
package main
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"strings"
"sync"
"time"
"github.com/google/go-github/v36/github"
"github.com/opensourceways/community-robot-lib/githubclient"
"github.com/opensourceways/community-robot-lib/mq"
"github.com/sirupsen/logrus"
)
type dispatcher struct {
agent *demuxConfigAgent
// ec is an http client used for dispatching events
// to external service services.
ec http.Client
// Tracks running handlers for graceful shutdown
wg sync.WaitGroup
}
func (d *dispatcher) wait() {
d.wg.Wait() // Handle remaining requests
}
// HandlerMsg validates an incoming webhook and puts it into the event channel.
func (d *dispatcher) HandlerMsg(event mq.Event) error {
msg := event.Message()
eventType, uuid, payload, err := parseWebHookInfoFromMsg(msg)
if err != nil {
return err
}
l := logrus.WithFields(logrus.Fields{
"event-type": eventType,
"event_id": uuid,
})
h := http.Header{}
for k, v := range msg.Header {
h.Add(k, v)
}
return d.dispatch(eventType, payload, h, l)
}
func (d *dispatcher) dispatch(eventType string, payload []byte, h http.Header, l *logrus.Entry) error {
hook, err := github.ParseWebHook(eventType, payload)
if err != nil {
return err
}
org, repo := "", ""
switch hook := hook.(type) {
case *github.IssuesEvent:
org, repo = githubclient.GetOrgRepo(hook.GetRepo())
case *github.IssueCommentEvent:
org, repo = githubclient.GetOrgRepo(hook.GetRepo())
case *github.PullRequestEvent:
org, repo = githubclient.GetOrgRepo(hook.GetRepo())
case *github.PullRequestReviewEvent:
org, repo = githubclient.GetOrgRepo(hook.GetRepo())
case *github.PullRequestReviewCommentEvent:
org, repo = githubclient.GetOrgRepo(hook.GetRepo())
case *github.PushEvent:
org = hook.GetRepo().GetOwner().GetLogin()
repo = hook.GetRepo().GetName()
case *github.StatusEvent:
org, repo = githubclient.GetOrgRepo(hook.GetRepo())
case *github.CommitCommentEvent:
org, repo = githubclient.GetOrgRepo(hook.GetRepo())
default:
l.Debug("Ignoring unknown event type")
return nil
}
l = l.WithFields(logrus.Fields{
"org": org,
"repo": repo,
})
endpoints := d.agent.getEndpoints(org, repo, eventType)
l.WithField("endpoints", strings.Join(endpoints, ", ")).Info("start dispatching event.")
d.doDispatch(endpoints, payload, h, l)
return nil
}
func (d *dispatcher) doDispatch(endpoints []string, payload []byte, h http.Header, l *logrus.Entry) {
h.Set("User-Agent", "Robot-Github-Access")
newReq := func(endpoint string) (*http.Request, error) {
req, err := http.NewRequest(http.MethodPost, endpoint, bytes.NewBuffer(payload))
if err != nil {
return nil, err
}
req.Header = h
return req, nil
}
reqs := make([]*http.Request, 0, len(endpoints))
for _, endpoint := range endpoints {
if req, err := newReq(endpoint); err == nil {
reqs = append(reqs, req)
} else {
l.WithError(err).WithField("endpoint", endpoint).Error("Error generating http request.")
}
}
for _, req := range reqs {
d.wg.Add(1)
// concurrent action is sending request not generating it.
// so, generates requests first.
go func(req *http.Request) {
defer d.wg.Done()
if err := d.forwardTo(req); err != nil {
l.WithError(err).WithField("endpoint", req.URL.String()).Error("Error forwarding event.")
}
}(req)
}
}
func (d *dispatcher) forwardTo(req *http.Request) error {
resp, err := d.do(req)
if err != nil || resp == nil {
return err
}
defer resp.Body.Close()
rb, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return fmt.Errorf("response has status %q and body %q", resp.Status, string(rb))
}
return nil
}
func (d *dispatcher) do(req *http.Request) (resp *http.Response, err error) {
if resp, err = d.ec.Do(req); err == nil {
return
}
maxRetries := 4
backoff := 100 * time.Millisecond
for retries := 0; retries < maxRetries; retries++ {
time.Sleep(backoff)
backoff *= 2
if resp, err = d.ec.Do(req); err == nil {
break
}
}
return
}