-
Notifications
You must be signed in to change notification settings - Fork 0
/
governor.go
298 lines (265 loc) · 8.3 KB
/
governor.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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
package main
import (
"bufio"
"context"
"errors"
"flag"
"net/http"
"net/url"
"os"
"strings"
"sync"
"time"
"github.com/lib/pq"
"github.com/zeebo/errs"
"go.uber.org/zap"
"golang.org/x/sync/errgroup"
"github.com/storj/changesetchihuahua/app"
"github.com/storj/changesetchihuahua/gerrit"
"github.com/storj/changesetchihuahua/gerrit/events"
"github.com/storj/changesetchihuahua/slack"
)
var notificationTimeout = flag.Duration("notify-timeout", time.Minute*30, "Maximum amount of time to spend trying to deliver a notification")
// Governor controls the Changeset Chihuahua functionality at a top level. It knows about
// all registered teams.
type Governor struct {
topContext context.Context
logger *zap.Logger
teamsLock sync.Mutex
teams map[string]*Team
teamFileLock sync.Mutex
teamFile string
}
// Team is a Slack team that is registered with Changeset Chihuahua.
type Team struct {
id string
logger *zap.Logger
canceler context.CancelFunc
teamApp *app.App
setupData string
runError error
}
type vanillaGerritConnector struct{}
func (v vanillaGerritConnector) OpenGerrit(ctx context.Context, logger *zap.Logger, address string) (gerrit.Client, error) {
return gerrit.OpenClient(ctx, logger, address)
}
// NewGovernor creates a new Governor.
func NewGovernor(ctx context.Context, logger *zap.Logger, teamFile string) (*Governor, error) {
teamData, err := readTeamFile(teamFile)
if err != nil {
if !os.IsNotExist(err) {
return nil, err
}
teamData = make(map[string]string)
}
g := &Governor{
topContext: ctx,
logger: logger,
teams: make(map[string]*Team),
teamFile: teamFile,
}
logger.Info("changeset-chihuahua governor starting up", zap.String("version", Version), zap.Int("num-teams", len(teamData)))
for teamID, setupData := range teamData {
if err := g.StartTeam(teamID, setupData); err != nil {
logger.Error("failed to start team", zap.String("team-id", teamID), zap.Error(err))
}
}
return g, nil
}
func readTeamFile(fileName string) (teamData map[string]string, err error) {
f, err := os.Open(fileName)
if err != nil {
return nil, err
}
defer func() { err = errs.Combine(err, f.Close()) }()
teamData = make(map[string]string)
scanner := bufio.NewScanner(f)
for scanner.Scan() {
teamLine := strings.TrimSpace(scanner.Text())
if teamLine == "" || strings.HasPrefix(teamLine, "#") {
continue
}
parts := strings.SplitN(teamLine, " ", 2)
if len(parts) < 2 {
return nil, errs.New("invalid team definition line in %q", fileName)
}
teamData[parts[0]] = parts[1]
}
if err := scanner.Err(); err != nil {
return nil, errs.New("reading from %q: %v", fileName, err)
}
return teamData, nil
}
// NewTeam is called when a new Slack team is registered with Changeset Chihuahua. It adds the
// team definition so that we will still have it after a restart, then creates a new Team
// instance and calls Run on it.
func (g *Governor) NewTeam(teamID string, setupData string) error {
g.teamsLock.Lock()
defer g.teamsLock.Unlock()
if _, ok := g.teams[teamID]; ok {
return errs.New("team %s is already active", teamID)
}
if strings.ContainsAny(teamID, " \n") {
return errs.New("invalid team ID")
}
if strings.Contains(setupData, "\n") {
return errs.New("invalid setup data")
}
if err := g.appendTeamDefinition(teamID, setupData); err != nil {
return errs.New("could not add team definition: %v", err)
}
team := &Team{
id: teamID,
setupData: setupData,
logger: g.logger.Named(teamID),
}
g.teams[teamID] = team
go team.Run(g.topContext)
return nil
}
// StartTeam is called at program start for already-registered teams. It creates the
// appropriate Team instance and calls Run on it.
func (g *Governor) StartTeam(teamID, setupData string) error {
g.teamsLock.Lock()
defer g.teamsLock.Unlock()
if _, ok := g.teams[teamID]; ok {
return errs.New("team %s is already active", teamID)
}
team := &Team{
id: teamID,
setupData: setupData,
logger: g.logger.Named(teamID),
}
g.teams[teamID] = team
go team.Run(g.topContext)
return nil
}
// Run takes care of all per-team functionality. It creates a Slack client for the team,
// manages the database for team config and events, and arranges for periodic Gerrit
// reports.
func (t *Team) Run(ctx context.Context) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
defer func() {
if t.runError != nil {
t.logger.Error("Failed to run", zap.Error(t.runError))
}
}()
slackClient, err := slack.NewSlackInterface(t.logger.Named("chat"), t.setupData)
if err != nil {
t.runError = errs.New("could not initialize slack connection: %v", err)
return
}
teamDBSource, err := addSearchPath(*persistentDBSource, "team-"+t.id)
if err != nil {
t.runError = errs.New("could not parse %q: %v", *persistentDBSource, err)
return
}
persistentDB, err := app.NewPersistentDB(t.logger.Named("db"), teamDBSource)
if err != nil {
t.runError = errs.New("could not open db: %v", err)
return
}
t.teamApp = app.New(ctx, t.logger, slackClient, &slack.Formatter{}, persistentDB, vanillaGerritConnector{})
var errGroup errgroup.Group
errGroup.Go(func() error {
return t.teamApp.PeriodicTeamReports(ctx, time.Now)
})
errGroup.Go(func() error {
return t.teamApp.PeriodicPersonalReports(ctx, time.Now)
})
err = errGroup.Wait()
t.logger.Info("Team errgroup exited", zap.String("team-id", t.id), zap.Error(err))
err = t.Close()
if err != nil {
t.logger.Error("failed to close team", zap.Error(err))
}
}
// GerritEventReceived is called when an event is received from Gerrit. The Governor determines
// the appropriate Team and passes the event on to it.
func (g *Governor) GerritEventReceived(teamID string, event events.GerritEvent) {
g.teamsLock.Lock()
team, ok := g.teams[teamID]
g.teamsLock.Unlock()
if !ok {
g.logger.Info("received event for unknown team", zap.String("team-id", teamID))
return
}
go func() {
ctx, cancel := context.WithTimeout(g.topContext, *notificationTimeout)
defer cancel()
team.teamApp.GerritEvent(ctx, event)
}()
}
// VerifyAndHandleChatEvent is called when an HTTP request is received which purports to be
// from Slack. The request is verified, and if valid, is passed on to the appropriate Team.
func (g *Governor) VerifyAndHandleChatEvent(header http.Header, messageBody []byte) (responseBytes []byte, err error) {
event, teamID, err := slack.VerifyEventMessage(header, messageBody)
if err != nil {
return nil, err
}
g.teamsLock.Lock()
team, ok := g.teams[teamID]
g.teamsLock.Unlock()
if !ok {
g.logger.Info("received chat event for unknown team", zap.String("team-id", teamID), zap.Any("event", event))
responseBytes = slack.HandleNoTeamEvent(g.topContext, event)
return responseBytes, nil
}
go func() {
err := team.teamApp.ChatEvent(g.topContext, event)
if errors.Is(err, slack.ErrStopTeam) {
g.logger.Info("uninstalled from team", zap.String("team-id", teamID))
g.teamsLock.Lock()
delete(g.teams, teamID)
g.teamsLock.Unlock()
if err := team.teamApp.Close(); err != nil {
g.logger.Info("failed to close team", zap.String("team-id", teamID), zap.Error(err))
}
} else if err != nil {
g.logger.Error("Unexpected error from teamApp.ChatEvent", zap.Error(err))
}
}()
return nil, nil
}
func (g *Governor) appendTeamDefinition(teamID, setupData string) (err error) {
g.teamFileLock.Lock()
defer g.teamFileLock.Unlock()
f, err := os.OpenFile(g.teamFile, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0o644)
if err != nil {
return err
}
defer func() { err = errs.Combine(err, f.Close()) }()
dataLine := teamID + " " + setupData + "\n"
if _, err := f.Write([]byte(dataLine)); err != nil {
return err
}
return nil
}
// Close shuts down functionality for a Team.
func (t *Team) Close() error {
t.canceler()
return t.teamApp.Close()
}
func addSearchPath(dbURL, schemaName string) (string, error) {
u, err := url.Parse(dbURL)
if err != nil {
return "", err
}
switch u.Scheme {
case "postgres", "postgresql":
query := u.Query()
query.Set("options", "--search_path="+pq.QuoteIdentifier(schemaName))
u.RawQuery = query.Encode()
case "sqlite", "sqlite3":
addSuffix := ""
if strings.HasSuffix(u.Opaque, ".db") {
addSuffix = ".db"
u.Opaque = u.Opaque[:len(u.Opaque)-3]
}
u.Opaque += "." + schemaName + addSuffix
default:
return "", errs.New("unrecognized db scheme %q", u.Scheme)
}
return u.String(), nil
}