-
Notifications
You must be signed in to change notification settings - Fork 15
/
server.go
267 lines (229 loc) · 7.32 KB
/
server.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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
package freebot
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"path/filepath"
"reflect"
"strings"
"time"
"github.com/fatedier/freebot/pkg/client"
"github.com/fatedier/freebot/pkg/client/githubapp"
"github.com/fatedier/freebot/pkg/config"
"github.com/fatedier/freebot/pkg/httputil"
"github.com/fatedier/freebot/pkg/log"
"github.com/fatedier/freebot/pkg/notify"
"github.com/fatedier/freebot/plugin"
_ "github.com/fatedier/freebot/plugin/assign"
_ "github.com/fatedier/freebot/plugin/label"
_ "github.com/fatedier/freebot/plugin/lgtm"
_ "github.com/fatedier/freebot/plugin/lifecycle"
_ "github.com/fatedier/freebot/plugin/merge"
_ "github.com/fatedier/freebot/plugin/module"
_ "github.com/fatedier/freebot/plugin/notify"
_ "github.com/fatedier/freebot/plugin/status"
_ "github.com/fatedier/freebot/plugin/trigger"
"github.com/google/go-github/github"
"golang.org/x/oauth2"
)
type Config struct {
BindAddr string `json:"bind_addr"`
LogLevel string `json:"log_level"`
LogFile string `json:"log_file"`
LogMaxDays int64 `json:"log_max_days"`
GithubAccessToken string `json:"github_access_token"`
GithubAppPrivateKey string `json:"github_app_private_key"`
GithubAppID int `json:"github_app_id"`
// repo -> plugin
RepoConfs map[string]RepoConf `json:"repo_confs"`
RepoConfDir string `json:"repo_conf_dir"`
RepoConfDirUpdateIntervalS int `json:"repo_conf_dir_update_interval_s"`
}
type RepoConf struct {
Alias config.AliasOptions `json:"alias"`
Roles config.RoleOptions `json:"roles"` // role -> []string{user1, user2}
LabelRoles config.LabelRoles `json:"label_roles"` // label -> role -> users
Plugins map[string]PluginConfig `json:"plugins"`
}
type PluginConfig struct {
Disable bool `json:"disable"`
Preconditions []config.Precondition `json:"preconditions"`
Extra interface{} `json:"extra"`
}
type Service struct {
Config
eventHandler *EventHandler
cli client.ClientInterface
notifier notify.NotifyInterface
staticRepoConfs map[string]RepoConf
extraRepoConfs map[string]RepoConf
}
func NewService(cfg Config) (*Service, error) {
if cfg.LogMaxDays <= 0 {
cfg.LogMaxDays = 3
}
if cfg.LogFile == "" {
log.InitLog("console", "", cfg.LogLevel, cfg.LogMaxDays)
} else {
log.InitLog("file", cfg.LogFile, cfg.LogLevel, cfg.LogMaxDays)
}
if cfg.RepoConfDirUpdateIntervalS <= 0 {
cfg.RepoConfDirUpdateIntervalS = 5
}
svc := &Service{
Config: cfg,
}
svc.notifier = notify.NewNotifyController()
requireInstallation := false
if cfg.GithubAccessToken != "" {
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: cfg.GithubAccessToken},
)
tc := oauth2.NewClient(context.Background(), ts)
githubCli := github.NewClient(tc)
svc.cli = client.NewGithubClient(githubCli)
} else if cfg.GithubAppPrivateKey != "" {
tr, err := githubapp.NewGithubAppInstallTransport(http.DefaultTransport, cfg.GithubAppID, cfg.GithubAppPrivateKey)
if err != nil {
return nil, err
}
githubCli := github.NewClient(&http.Client{Transport: tr})
svc.cli = client.NewGithubClient(githubCli)
requireInstallation = true
}
svc.staticRepoConfs = cfg.RepoConfs
if svc.RepoConfDir != "" {
extraRepoConfs, err := svc.loadRepoConfsFromDir(svc.RepoConfDir)
if err != nil {
return nil, fmt.Errorf("load repo confs from dir error: %v", err)
}
svc.extraRepoConfs = extraRepoConfs
}
repoConfs := svc.mergeRepoConfsTo(nil, svc.staticRepoConfs)
repoConfs = svc.mergeRepoConfsTo(repoConfs, svc.extraRepoConfs)
plugins, err := svc.createPlugins(repoConfs)
if err != nil {
return nil, fmt.Errorf("create plugins error: %v", err)
}
svc.eventHandler = NewEventHandler(requireInstallation, plugins)
return svc, nil
}
func (svc *Service) Run() error {
go svc.updatePluginsWorker()
log.Info("freebot listen on %s", svc.BindAddr)
err := http.ListenAndServe(svc.BindAddr, http.HandlerFunc(svc.Handler))
return err
}
func (svc *Service) Handler(w http.ResponseWriter, r *http.Request) {
eventType := r.Header.Get("X-Github-Event")
if eventType == "" {
httputil.ReplyError(w, httputil.NewHttpError(400, "unsupport event"))
return
}
log.Debug("event [%s], id [%s]", eventType, r.Header.Get("X-GitHub-Delivery"))
content, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Warn("read request body error: %v", err)
httputil.ReplyError(w, httputil.NewHttpError(400, "read request error"))
return
}
err = svc.eventHandler.HandleEvent(r.Context(), eventType, string(content))
if err != nil {
log.Warn("handle event error: %v", err)
httputil.ReplyError(w, err)
return
}
w.WriteHeader(200)
}
func (svc *Service) loadRepoConfsFromDir(path string) (map[string]RepoConf, error) {
files, err := ioutil.ReadDir(path)
if err != nil {
return nil, err
}
out := make(map[string]RepoConf)
for _, file := range files {
if !file.IsDir() {
fpath := filepath.Join(path, file.Name())
buf, err := ioutil.ReadFile(fpath)
if err != nil {
return nil, err
}
tmp := make(map[string]RepoConf)
err = json.Unmarshal(buf, &tmp)
if err != nil {
return nil, fmt.Errorf("parse file [%s] error: %v", fpath, err)
}
out = svc.mergeRepoConfsTo(out, tmp)
}
}
return out, nil
}
func (svc *Service) mergeRepoConfsTo(dst map[string]RepoConf, src map[string]RepoConf) map[string]RepoConf {
if dst == nil {
dst = make(map[string]RepoConf)
}
for k, v := range src {
dst[k] = v
}
return dst
}
func (svc *Service) createPlugins(repoConfs map[string]RepoConf) (plugins map[string][]plugin.Plugin, err error) {
plugins = make(map[string][]plugin.Plugin)
for repoName, repoConf := range repoConfs {
log.Info("repo [%s] alias: %+v", repoName, repoConf.Alias)
log.Info("repo [%s] roles: %+v", repoName, repoConf.Roles)
for pluginName, pluginConf := range repoConf.Plugins {
if pluginConf.Disable {
continue
}
arrs := strings.Split(repoName, "/")
if len(arrs) < 2 {
return nil, fmt.Errorf("repo name invalid")
}
baseOptions := plugin.PluginOptions{}
baseOptions.Complete(arrs[0], arrs[1], repoConf.Alias, repoConf.Roles, repoConf.LabelRoles, pluginConf.Preconditions, pluginConf.Extra)
p, err := plugin.Create(svc.cli, svc.notifier, pluginName, baseOptions)
if err != nil {
err = fmt.Errorf("create plugin [%s] error: %v", pluginName, err)
log.Error("%v", err)
return nil, err
}
ps, ok := plugins[repoName]
if ok {
ps = append(ps, p)
} else {
ps = make([]plugin.Plugin, 1)
ps[0] = p
}
plugins[repoName] = ps
}
}
return plugins, nil
}
func (svc *Service) updatePluginsWorker() {
for {
time.Sleep(time.Duration(svc.RepoConfDirUpdateIntervalS) * time.Second)
if svc.RepoConfDir != "" {
repoConfs, err := svc.loadRepoConfsFromDir(svc.RepoConfDir)
if err != nil {
log.Error("load repo confs from dir error: %v", err)
continue
}
if !reflect.DeepEqual(svc.extraRepoConfs, repoConfs) {
log.Info("repo confs changed...")
all := svc.mergeRepoConfsTo(nil, repoConfs)
svc.mergeRepoConfsTo(all, svc.staticRepoConfs)
plugins, err := svc.createPlugins(all)
if err != nil {
log.Error("create plugins error: %v", err)
continue
}
svc.eventHandler.UpdatePlugins(plugins)
log.Info("update plugins success")
svc.extraRepoConfs = repoConfs
}
}
}
}