-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathserver.go
More file actions
576 lines (474 loc) · 14.5 KB
/
server.go
File metadata and controls
576 lines (474 loc) · 14.5 KB
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
package server
import (
"context"
"fmt"
"reflect"
"time"
"github.com/src-d/lookout"
"github.com/src-d/lookout/store"
"github.com/src-d/lookout/store/models"
"github.com/src-d/lookout/util/ctxlog"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"gopkg.in/src-d/lookout-sdk.v0/pb"
log "gopkg.in/src-d/go-log.v1"
yaml "gopkg.in/yaml.v2"
)
var grpcErrorMessages = map[lookout.EventType]map[codes.Code]string{
pb.PushEventType: map[codes.Code]string{
codes.DeadlineExceeded: "timeout exceeded, try increasing analyzer_push in config.yml",
},
pb.ReviewEventType: map[codes.Code]string{
codes.DeadlineExceeded: "timeout exceeded, try increasing analyzer_review in config.yml",
},
}
// Config is a server configuration
type Config struct {
Analyzers []lookout.AnalyzerConfig
}
type reqSent func(
ctx context.Context,
client lookout.AnalyzerClient,
settings map[string]interface{},
) ([]*lookout.Comment, error)
// Server implements glue between providers / data-server / analyzers
type Server struct {
poster lookout.Poster
fileGetter lookout.FileGetter
analyzers map[string]lookout.Analyzer
eventOp store.EventOperator
commentOp store.CommentOperator
organizationOp store.OrganizationOperator
analyzerReviewTimeout time.Duration
analyzerPushTimeout time.Duration
exitOnError bool
}
// Options defines the options for NewServer
type Options struct {
Poster lookout.Poster
FileGetter lookout.FileGetter
Analyzers map[string]lookout.Analyzer
// EventOp is the operator for the Event persistence. Can be left unset.
EventOp store.EventOperator
// CommentOp is the operator for the Comment persistence. Can be left unset.
CommentOp store.CommentOperator
// OrganizationOp is the operator for the Organization persistence. Can be left unset.
OrganizationOp store.OrganizationOperator
// ReviewTimeout is the timeout for an analyzer to reply a NotifyReviewEvent.
// Zero means no timeout.
ReviewTimeout time.Duration
// PushTimeout is the timeout for an analyzer to reply a NotifyPushEvent.
// Zero means no timeout.
PushTimeout time.Duration
// ExitOnError set to true will stop the server and return an error
// if any analyzer Notify* call or a posting call fails
ExitOnError bool
}
// NewServer creates a new Server with the given options
func NewServer(opt Options) *Server {
server := Server{
poster: opt.Poster,
fileGetter: opt.FileGetter,
analyzers: opt.Analyzers,
eventOp: opt.EventOp,
commentOp: opt.CommentOp,
organizationOp: opt.OrganizationOp,
analyzerReviewTimeout: opt.ReviewTimeout,
analyzerPushTimeout: opt.PushTimeout,
exitOnError: opt.ExitOnError,
}
if opt.EventOp == nil {
server.eventOp = &store.NoopEventOperator{}
}
if opt.CommentOp == nil {
server.commentOp = &store.NoopCommentOperator{}
}
if opt.OrganizationOp == nil {
server.organizationOp = &store.NoopOrganizationOperator{}
}
return &server
}
// HandleEvent processes the event calling the analyzers, and posting the results
func (s *Server) HandleEvent(ctx context.Context, e lookout.Event) error {
ctx, logger := ctxlog.WithLogFields(ctx, log.Fields{
"event-type": reflect.TypeOf(e).String(),
"event-id": e.ID().String(),
"repo": e.Revision().Head.InternalRepositoryURL,
"head": e.Revision().Head.ReferenceName,
})
status, err := s.eventOp.Save(ctx, e)
if err != nil {
logger.Errorf(err, "can't save event to database")
return err
}
if status == models.EventStatusProcessed {
logger.Debugf("event successfully processed, skipping...")
return nil
}
// TODO(max): we need some retry policy here depends on errors
if status == models.EventStatusFailed {
logger.Debugf("event processing failed, skipping...")
return nil
}
// positing started before but never changed to success of failure
// we need to retry analyzis but post only new comments (poster should handle it)
safePosting := status == models.EventStatusPosting
switch ev := e.(type) {
case *lookout.ReviewEvent:
err = s.HandleReview(ctx, ev, safePosting)
case *lookout.PushEvent:
err = s.HandlePush(ctx, ev, safePosting)
default:
logger.Debugf("ignoring unsupported event: %s", ev)
}
if err == nil {
status = models.EventStatusProcessed
} else {
logger.Errorf(err, "event processing failed")
status = models.EventStatusFailed
}
if updateErr := s.eventOp.UpdateStatus(ctx, e, status); updateErr != nil {
logger.Errorf(updateErr, "can't update status in database")
}
// don't fail on event processing error, just skip it
if !s.exitOnError {
return nil
}
return err
}
// HandleReview sends request to analyzers concurrently
func (s *Server) HandleReview(ctx context.Context, e *lookout.ReviewEvent, safePosting bool) error {
ctx, logger := ctxlog.WithLogFields(ctx, log.Fields{
"provider": e.Provider,
})
logger.Infof("processing pull request")
if err := e.Validate(); err != nil {
return err
}
repoConf, err := s.getConfig(ctx, e)
if err != nil {
return err
}
orgConf, err := s.getOrgConfig(ctx, e)
if err != nil {
return err
}
conf := mergeConfigs(orgConf, repoConf)
s.status(ctx, e, lookout.PendingAnalysisStatus)
send := func(
ctx context.Context,
a lookout.AnalyzerClient,
settings map[string]interface{},
) ([]*lookout.Comment, error) {
st := pb.ToStruct(settings)
if st != nil {
e.Configuration = *st
}
if s.analyzerReviewTimeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, s.analyzerReviewTimeout)
defer cancel()
}
resp, err := a.NotifyReviewEvent(ctx, &e.ReviewEvent)
if err != nil {
return nil, err
}
return resp.Comments, nil
}
comments, err := s.concurrentRequest(ctx, conf, send, grpcErrorMessages[pb.ReviewEventType])
if err != nil {
return err
}
if err := s.post(ctx, e, comments, safePosting); err != nil {
s.status(ctx, e, lookout.ErrorAnalysisStatus)
return fmt.Errorf("posting analysis failed: %s", err)
}
s.status(ctx, e, lookout.SuccessAnalysisStatus)
return nil
}
// HandlePush sends request to analyzers concurrently
func (s *Server) HandlePush(ctx context.Context, e *lookout.PushEvent, safePosting bool) error {
ctx, logger := ctxlog.WithLogFields(ctx, log.Fields{
"provider": e.Provider,
})
logger.Infof("processing push")
if err := e.Validate(); err != nil {
return err
}
repoConf, err := s.getConfig(ctx, e)
if err != nil {
return err
}
orgConf, err := s.getOrgConfig(ctx, e)
if err != nil {
return err
}
conf := mergeConfigs(orgConf, repoConf)
s.status(ctx, e, lookout.PendingAnalysisStatus)
send := func(
ctx context.Context,
a lookout.AnalyzerClient,
settings map[string]interface{},
) ([]*lookout.Comment, error) {
st := pb.ToStruct(settings)
if st != nil {
e.Configuration = *st
}
if s.analyzerPushTimeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, s.analyzerPushTimeout)
defer cancel()
}
resp, err := a.NotifyPushEvent(ctx, &e.PushEvent)
if err != nil {
return nil, err
}
return resp.Comments, nil
}
comments, err := s.concurrentRequest(ctx, conf, send, grpcErrorMessages[pb.PushEventType])
if err != nil {
return err
}
if err := s.post(ctx, e, comments, safePosting); err != nil {
s.status(ctx, e, lookout.ErrorAnalysisStatus)
return fmt.Errorf("posting analysis failed: %s", err)
}
s.status(ctx, e, lookout.SuccessAnalysisStatus)
return nil
}
func (s *Server) getConfig(ctx context.Context, e lookout.Event) (map[string]lookout.AnalyzerConfig, error) {
rev := e.Revision()
ctxlog.Get(ctx).Debugf("getting .lookout.yml")
scanner, err := s.fileGetter.GetFiles(ctx, &lookout.FilesRequest{
Revision: &rev.Head,
IncludePattern: `^\.lookout\.yml$`,
WantContents: true,
})
if err != nil {
return nil, fmt.Errorf("Can't get .lookout.yml in revision %s: %s", rev.Head, err)
}
var configContent []byte
if scanner.Next() {
configContent = scanner.File().Content
}
scanner.Close()
if err := scanner.Err(); err != nil {
return nil, err
}
if len(configContent) == 0 {
ctxlog.Get(ctx).Infof("repository config is not found")
return nil, nil
}
parseCtx, _ := ctxlog.WithLogFields(ctx, log.Fields{"config-file": "repository .lookout.yml"})
conf, err := s.parseConfig(parseCtx, configContent)
if err != nil {
return nil, fmt.Errorf("failed to get the local .lookout.yml file from the repository: %s", err)
}
return conf, nil
}
func (s *Server) parseConfig(ctx context.Context, configContent []byte) (map[string]lookout.AnalyzerConfig, error) {
var conf Config
if err := yaml.Unmarshal(configContent, &conf); err != nil {
return nil, fmt.Errorf("can't parse configuration file: %s", err)
}
res := make(map[string]lookout.AnalyzerConfig, len(s.analyzers))
for name, a := range s.analyzers {
res[name] = a.Config
}
for _, aConf := range conf.Analyzers {
if _, ok := s.analyzers[aConf.Name]; !ok {
ctxlog.Get(ctx).Warningf("analyzer '%s' required by configuration file isn't enabled on server", aConf.Name)
continue
}
res[aConf.Name] = aConf
}
return res, nil
}
func (s *Server) getOrgConfig(ctx context.Context, e lookout.Event) (map[string]lookout.AnalyzerConfig, error) {
configContent, err := s.organizationOp.Config(ctx, e.GetProvider(), e.GetOrganizationID())
if err != nil {
return nil, fmt.Errorf("could not load default configuration for organization from the DB: %s", err)
}
parseCtx, _ := ctxlog.WithLogFields(ctx, log.Fields{"config-file": "organization default"})
conf, err := s.parseConfig(parseCtx, []byte(configContent))
if err != nil {
return nil, fmt.Errorf("failed to get the organization default configuration from the DB: %s", err)
}
return conf, nil
}
func (s *Server) concurrentRequest(ctx context.Context, conf map[string]lookout.AnalyzerConfig, send reqSent, logErrorMessages map[codes.Code]string) ([]lookout.AnalyzerComments, error) {
var cancel context.CancelFunc
ctx, cancel = context.WithCancel(ctx)
defer cancel()
commentsCh := make(chan *lookout.AnalyzerComments, len(s.analyzers))
errCh := make(chan error)
for name, a := range s.analyzers {
if a.Config.Disabled || conf[name].Disabled {
ctxlog.Get(ctx).Infof("analyzer %s disabled by local repository configuration", name)
commentsCh <- nil
continue
}
go func(name string, a lookout.Analyzer) {
var result *lookout.AnalyzerComments
defer func() { commentsCh <- result }()
ctx, aLogger := ctxlog.WithLogFields(ctx, log.Fields{
"analyzer": name,
})
settings := mergeSettings(a.Config.Settings, conf[name].Settings)
cs, err := send(ctx, a.Client, settings)
if err != nil {
grpcStatus := status.Convert(err)
errMessage := "analysis failed"
friendlyMessage, ok := logErrorMessages[grpcStatus.Code()]
if ok {
errMessage = fmt.Sprintf("%s: %s", errMessage, friendlyMessage)
}
aLogger.Errorf(err, errMessage)
if s.exitOnError {
errCh <- err
}
return
}
if len(cs) == 0 {
aLogger.Infof("no comments were produced")
return
}
result = &lookout.AnalyzerComments{
Config: a.Config,
Comments: cs,
}
}(name, a)
}
var comments []lookout.AnalyzerComments
for i := 0; i < len(s.analyzers); i++ {
select {
case err := <-errCh:
return nil, err
case cs := <-commentsCh:
if cs != nil {
comments = append(comments, *cs)
}
}
}
return comments, nil
}
func mergeConfigs(global, local map[string]lookout.AnalyzerConfig) map[string]lookout.AnalyzerConfig {
if local == nil {
return global
}
if global == nil {
return local
}
merged := make(map[string]lookout.AnalyzerConfig)
for k, v := range global {
merged[k] = v
}
for k, v := range local {
if globalV, ok := merged[k]; ok {
globalV.Settings = mergeMaps(globalV.Settings, v.Settings)
merged[k] = globalV
continue
}
merged[k] = v
}
return merged
}
func mergeSettings(global, local map[string]interface{}) map[string]interface{} {
if local == nil {
return global
}
if global == nil {
return local
}
return mergeMaps(global, local)
}
func mergeMaps(global, local map[string]interface{}) map[string]interface{} {
merged := make(map[string]interface{})
for k, v := range global {
merged[k] = v
}
for k, v := range local {
if subMap, ok := v.(map[string]interface{}); ok {
gv, ok := merged[k]
if ok {
if gvMap, ok := gv.(map[string]interface{}); ok {
merged[k] = mergeMaps(gvMap, subMap)
continue
}
}
}
merged[k] = v
}
return merged
}
func (s *Server) post(ctx context.Context, e lookout.Event, comments lookout.AnalyzerCommentsGroups, safe bool) error {
comments, err := comments.Dedup().Filter(func(c *lookout.Comment) (bool, error) {
yes, err := s.commentOp.Posted(ctx, e, c)
if err != nil {
ctxlog.Get(ctx).Errorf(err, "comment posted check failed")
return false, err
}
return yes, nil
})
if err != nil {
return err
}
if len(comments) == 0 {
return nil
}
// update event status just before posting comments
// in case the server would die while doing it we will know that process has started
// and poster can handle it correctly
if err := s.eventOp.UpdateStatus(ctx, e, models.EventStatusPosting); err != nil {
return err
}
ctxlog.Get(ctx).With(log.Fields{
"comments": comments.Count(),
}).Infof("posting analysis")
if err := s.poster.Post(ctx, e, comments, safe); err != nil {
return err
}
for _, cg := range comments {
for _, c := range cg.Comments {
if err := s.commentOp.Save(ctx, e, c, cg.Config.Name); err != nil {
ctxlog.Get(ctx).Errorf(err, "can't save comment")
}
}
}
return nil
}
func (s *Server) status(ctx context.Context, e lookout.Event, st lookout.AnalysisStatus) {
if err := s.poster.Status(ctx, e, st); err != nil {
ctxlog.Get(ctx).With(log.Fields{"status": st}).Errorf(err, "posting status failed")
}
}
type LogPoster struct {
Log log.Logger
}
func (p *LogPoster) Post(ctx context.Context, e lookout.Event,
aCommentsList []lookout.AnalyzerComments, safe bool) error {
for _, aComments := range aCommentsList {
for _, c := range aComments.Comments {
logger := p.Log.With(log.Fields{
"text": c.Text,
})
if c.File == "" {
logger.Infof("global comment")
continue
}
logger = logger.With(log.Fields{"file": c.File})
if c.Line == 0 {
logger.Infof("file comment")
continue
}
logger.With(log.Fields{"line": c.Line}).Infof("line comment")
}
}
return nil
}
func (p *LogPoster) Status(ctx context.Context, e lookout.Event,
status lookout.AnalysisStatus) error {
p.Log.Infof("status: %s", status)
return nil
}
var _ lookout.Poster = &LogPoster{}