-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathengine.go
719 lines (649 loc) · 22.5 KB
/
engine.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
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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
package engine
import (
"bufio"
"context"
"fmt"
"net/url"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"sync/atomic"
"go.lsp.dev/uri"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/propagation"
"github.com/cbroglie/mustache"
"github.com/go-logr/logr"
"github.com/konveyor/analyzer-lsp/engine/internal"
"github.com/konveyor/analyzer-lsp/engine/labels"
"github.com/konveyor/analyzer-lsp/output/v1/konveyor"
"github.com/konveyor/analyzer-lsp/tracing"
)
type RuleEngine interface {
RunRules(context context.Context, rules []RuleSet, selectors ...RuleSelector) []konveyor.RuleSet
RunRulesScoped(ctx context.Context, ruleSets []RuleSet, scopes Scope, selectors ...RuleSelector) []konveyor.RuleSet
Stop()
}
type ruleMessage struct {
rule Rule
ruleSetName string
conditionContext ConditionContext
scope Scope
returnChan chan response
carrier propagation.TextMapCarrier
}
type response struct {
ConditionResponse ConditionResponse `yaml:"conditionResponse"`
Err error `yaml:"err"`
Rule Rule `yaml:"rule"`
RuleSetName string
}
type ruleEngine struct {
// Buffered channel where Rule Processors are watching
ruleProcessing chan ruleMessage
cancelFunc context.CancelFunc
logger logr.Logger
wg *sync.WaitGroup
incidentLimit int
codeSnipLimit int
contextLines int
incidentSelector string
locationPrefixes []string
}
type Option func(engine *ruleEngine)
func WithIncidentLimit(i int) Option {
return func(engine *ruleEngine) {
engine.incidentLimit = i
}
}
func WithContextLines(i int) Option {
return func(engine *ruleEngine) {
engine.contextLines = i
}
}
func WithCodeSnipLimit(i int) Option {
return func(engine *ruleEngine) {
engine.codeSnipLimit = i
}
}
func WithIncidentSelector(selector string) Option {
return func(engine *ruleEngine) {
engine.incidentSelector = selector
}
}
func WithLocationPrefixes(location []string) Option {
return func(engine *ruleEngine) {
engine.locationPrefixes = location
}
}
func CreateRuleEngine(ctx context.Context, workers int, log logr.Logger, options ...Option) RuleEngine {
// Only allow for 10 rules to be waiting in the buffer at once.
// Adding more workers will increase the number of rules running at once.
ruleProcessor := make(chan ruleMessage, 10)
ctx, cancelFunc := context.WithCancel(ctx)
wg := &sync.WaitGroup{}
for i := 0; i < workers; i++ {
logger := log.WithValues("worker", i)
wg.Add(1)
go processRuleWorker(ctx, ruleProcessor, logger, wg)
}
r := &ruleEngine{
ruleProcessing: ruleProcessor,
cancelFunc: cancelFunc,
logger: log,
wg: wg,
}
for _, o := range options {
o(r)
}
return r
}
func (r *ruleEngine) Stop() {
r.cancelFunc()
r.logger.V(5).Info("rule engine stopping")
r.wg.Wait()
}
func processRuleWorker(ctx context.Context, ruleMessages chan ruleMessage, logger logr.Logger, wg *sync.WaitGroup) {
prop := otel.GetTextMapPropagator()
for {
select {
case m := <-ruleMessages:
logger.V(5).Info("taking rule", "ruleset", m.ruleSetName, "rule", m.rule.RuleID)
newLogger := logger.WithValues("ruleID", m.rule.RuleID)
//We createa new rule context for a every rule run, here we need to apply the scope
m.conditionContext.Template = make(map[string]ChainTemplate)
if m.scope != nil {
m.scope.AddToContext(&m.conditionContext)
}
logger.Info("Adding Carrier span info to context")
ctx = prop.Extract(ctx, m.carrier)
bo, err := processRule(ctx, m.rule, m.conditionContext, newLogger)
logger.V(5).Info("finished rule", "found", len(bo.Incidents), "error", err, "rule", m.rule.RuleID)
m.returnChan <- response{
ConditionResponse: bo,
Err: err,
Rule: m.rule,
RuleSetName: m.ruleSetName,
}
case <-ctx.Done():
logger.V(5).Info("stopping rule worker")
wg.Done()
return
}
}
}
func (r *ruleEngine) createRuleSet(ruleSet RuleSet) *konveyor.RuleSet {
rs := &konveyor.RuleSet{
Name: ruleSet.Name,
Description: ruleSet.Description,
Tags: []string{},
Violations: map[string]konveyor.Violation{},
Insights: map[string]konveyor.Violation{},
Errors: map[string]string{},
Unmatched: []string{},
Skipped: []string{},
}
return rs
}
// This will run tagging rules first, synchronously, generating tags to pass on further as context to other rules
// then runs remaining rules async, fanning them out, fanning them in, finally generating the results. will block until completed.
func (r *ruleEngine) RunRules(ctx context.Context, ruleSets []RuleSet, selectors ...RuleSelector) []konveyor.RuleSet {
return r.RunRulesScoped(ctx, ruleSets, nil, selectors...)
}
func (r *ruleEngine) RunRulesScoped(ctx context.Context, ruleSets []RuleSet, scopes Scope, selectors ...RuleSelector) []konveyor.RuleSet {
// determine if we should run
conditionContext := ConditionContext{
Tags: make(map[string]interface{}),
Template: make(map[string]ChainTemplate),
}
if scopes != nil {
r.logger.Info("using scopes", "scope", scopes.Name())
err := scopes.AddToContext(&conditionContext)
if err != nil {
r.logger.Error(err, "unable to apply scopes to ruleContext")
// Call this, even though it is not used, to make sure that
// we don't leak anything.
return []konveyor.RuleSet{}
}
r.logger.Info("added scopes to condition context", "scopes", scopes, "conditionContext", conditionContext)
}
carrier := propagation.MapCarrier{}
otel.GetTextMapPropagator().Inject(ctx, carrier)
r.logger.Info("inject span info", "carrier", carrier)
ctx, cancelFunc := context.WithCancel(ctx)
taggingRules, otherRules, mapRuleSets := r.filterRules(ruleSets, selectors...)
ruleContext := r.runTaggingRules(ctx, taggingRules, mapRuleSets, conditionContext, scopes)
// Need a better name for this thing
ret := make(chan response)
var matchedRules int32
var unmatchedRules int32
var failedRules int32
wg := &sync.WaitGroup{}
// Handle returns
go func() {
for {
select {
case response := <-ret:
func() {
r.logger.Info("rule returned", "ruleID", response.Rule.RuleID)
defer wg.Done()
if response.Err != nil {
atomic.AddInt32(&failedRules, 1)
r.logger.Error(response.Err, "failed to evaluate rule", "ruleID", response.Rule.RuleID)
if rs, ok := mapRuleSets[response.RuleSetName]; ok {
rs.Errors[response.Rule.RuleID] = response.Err.Error()
}
} else if response.ConditionResponse.Matched && len(response.ConditionResponse.Incidents) > 0 {
violation, err := r.createViolation(ctx, response.ConditionResponse, response.Rule, scopes)
if err != nil {
r.logger.Error(err, "unable to create violation from response", "ruleID", response.Rule.RuleID)
}
if len(violation.Incidents) == 0 {
r.logger.V(5).Info("rule was evaluated and incidents were filtered out to make it unmatched", "ruleID", response.Rule.RuleID)
atomic.AddInt32(&unmatchedRules, 1)
if rs, ok := mapRuleSets[response.RuleSetName]; ok {
rs.Unmatched = append(rs.Unmatched, response.Rule.RuleID)
}
} else {
atomic.AddInt32(&matchedRules, 1)
rs, ok := mapRuleSets[response.RuleSetName]
if !ok {
r.logger.Info("this should never happen that we don't find the ruleset")
return
}
// when a rule has 0 effort, we should create an insight instead
if response.Rule.Effort == nil || *response.Rule.Effort == 0 {
rs.Insights[response.Rule.RuleID] = violation
} else {
rs.Violations[response.Rule.RuleID] = violation
}
}
} else {
atomic.AddInt32(&unmatchedRules, 1)
// Log that rule did not pass
r.logger.V(5).Info("rule was evaluated, and we did not find a violation", "ruleID", response.Rule.RuleID)
if rs, ok := mapRuleSets[response.RuleSetName]; ok {
rs.Unmatched = append(rs.Unmatched, response.Rule.RuleID)
}
}
r.logger.V(5).Info("rule response received", "total", len(otherRules), "failed", failedRules, "matched", matchedRules, "unmatched", unmatchedRules)
}()
case <-ctx.Done():
// At this point we should just return the function, we may want to close the wait group too.
return
}
}
}()
for _, rule := range otherRules {
newContext := ruleContext.Copy()
newContext.RuleID = rule.rule.RuleID
wg.Add(1)
rule.returnChan = ret
rule.conditionContext = newContext
rule.scope = scopes
rule.carrier = carrier
r.ruleProcessing <- rule
}
r.logger.V(5).Info("All rules added buffer, waiting for engine to complete", "size", len(otherRules))
done := make(chan struct{})
go func() {
defer close(done)
wg.Wait()
}()
// Wait for all the rules to process
select {
case <-done:
r.logger.V(2).Info("done processing all the rules")
case <-ctx.Done():
r.logger.V(1).Info("processing of rules was canceled")
}
responses := []konveyor.RuleSet{}
for _, ruleSet := range mapRuleSets {
if ruleSet != nil {
responses = append(responses, *ruleSet)
}
}
// Cannel running go-routine
cancelFunc()
return responses
}
// filterRules splits rules into tagging and other rules
func (r *ruleEngine) filterRules(ruleSets []RuleSet, selectors ...RuleSelector) ([]ruleMessage, []ruleMessage, map[string]*konveyor.RuleSet) {
// filter rules that generate tags, they run first
taggingRules := []ruleMessage{}
mapRuleSets := map[string]*konveyor.RuleSet{}
// all rules except meta
otherRules := []ruleMessage{}
for _, ruleSet := range ruleSets {
mapRuleSets[ruleSet.Name] = r.createRuleSet(ruleSet)
for _, rule := range ruleSet.Rules {
// labels on ruleset apply to all rules in it
rule.Labels = append(rule.Labels, ruleSet.Labels...)
// skip rule when doesn't match any selector
if !matchesAllSelectors(rule.RuleMeta, selectors...) {
mapRuleSets[ruleSet.Name].Skipped = append(mapRuleSets[ruleSet.Name].Skipped, rule.RuleID)
r.logger.V(5).Info("one or more selectors did not match for rule, skipping", "ruleID", rule.RuleID)
continue
}
if rule.Perform.Tag == nil {
otherRules = append(otherRules, ruleMessage{
rule: rule,
ruleSetName: ruleSet.Name,
})
} else {
taggingRules = append(taggingRules, ruleMessage{
rule: rule,
ruleSetName: ruleSet.Name,
})
// if both message and tag are set, split message part into a new rule if effort is non-zero
// if effort is zero, we do not want to create a violation but only tag and an insight
if rule.Perform.Message.Text != nil && rule.Effort != nil && *rule.Effort != 0 {
rule.Perform.Tag = nil
otherRules = append(
otherRules,
ruleMessage{
rule: rule,
ruleSetName: ruleSet.Name,
},
)
}
}
}
}
return taggingRules, otherRules, mapRuleSets
}
// runTaggingRules filters and runs info rules synchronously
// returns list of non-info rules, a context to pass to them
func (r *ruleEngine) runTaggingRules(ctx context.Context, infoRules []ruleMessage, mapRuleSets map[string]*konveyor.RuleSet, context ConditionContext, scope Scope) ConditionContext {
// track unique tags per ruleset
rulesetTagsCache := map[string]map[string]bool{}
for _, ruleMessage := range infoRules {
rule := ruleMessage.rule
response, err := processRule(ctx, rule, context, r.logger)
if err != nil {
r.logger.Error(err, "failed to evaluate rule", "ruleID", rule.RuleID)
if rs, ok := mapRuleSets[ruleMessage.ruleSetName]; ok {
rs.Errors[rule.RuleID] = err.Error()
}
} else if response.Matched && len(response.Incidents) > 0 {
r.logger.V(5).Info("info rule was matched", "ruleID", rule.RuleID)
tags := map[string]bool{}
for _, tagString := range rule.Perform.Tag {
if strings.Contains(tagString, "{{") && strings.Contains(tagString, "}}") {
for _, incident := range response.Incidents {
// If this is the case then we neeed to use the reponse variables to get the tag
variables := make(map[string]interface{})
for key, value := range incident.Variables {
variables[key] = value
}
if incident.LineNumber != nil {
variables["lineNumber"] = *incident.LineNumber
}
templateString, err := r.createPerformString(tagString, variables)
if err != nil {
r.logger.Error(err, "unable to create tag string", "ruleID", rule.RuleID)
continue
}
tags[templateString] = true
}
} else {
tags[tagString] = true
}
for t := range tags {
tags, err := parseTagsFromPerformString(t)
if err != nil {
r.logger.Error(err, "unable to create tags", "ruleID", rule.RuleID)
continue
}
for _, tag := range tags {
context.Tags[tag] = true
}
}
}
rs, ok := mapRuleSets[ruleMessage.ruleSetName]
if !ok {
r.logger.Info("this should never happen that we don't find the ruleset")
} else {
if _, ok := rulesetTagsCache[rs.Name]; !ok {
rulesetTagsCache[rs.Name] = make(map[string]bool)
}
for tag := range tags {
if _, ok := rulesetTagsCache[rs.Name][tag]; !ok {
rulesetTagsCache[rs.Name][tag] = true
rs.Tags = append(rs.Tags, tag)
}
}
mapRuleSets[ruleMessage.ruleSetName] = rs
}
// create an insight for this tag
violation, err := r.createViolation(ctx, response, rule, scope)
if err != nil {
r.logger.Error(err, "unable to create violation from response", "ruleID", rule.RuleID)
}
if rs, ok := mapRuleSets[ruleMessage.ruleSetName]; ok {
violation.Effort = nil
violation.Category = nil
// we need to tie these incidents back to tags that created them
for tag := range tags {
violation.Labels = append(violation.Labels, fmt.Sprintf("tag=%s", tag))
}
rs.Insights[rule.RuleID] = violation
}
} else {
r.logger.Info("info rule not matched", "rule", rule.RuleID)
if rs, ok := mapRuleSets[ruleMessage.ruleSetName]; ok {
rs.Unmatched = append(rs.Unmatched, rule.RuleID)
}
}
}
return context
}
func parseTagsFromPerformString(tagString string) ([]string, error) {
tags := []string{}
pattern := regexp.MustCompile(`^(?:[\w- \(\)]+=){0,1}([\w- \(\)]+(?:, *[\w- \(\),]+)*),?$`)
if !pattern.MatchString(tagString) {
return nil, fmt.Errorf("unexpected tag string %s", tagString)
}
for _, groups := range pattern.FindAllStringSubmatch(tagString, -1) {
for _, tag := range strings.Split(groups[1], ",") {
if tag != "" {
tags = append(tags, strings.Trim(tag, " "))
}
}
}
return tags, nil
}
func processRule(ctx context.Context, rule Rule, ruleCtx ConditionContext, log logr.Logger) (ConditionResponse, error) {
ctx, span := tracing.StartNewSpan(
ctx, "process-rule", attribute.Key("rule").String(rule.RuleID))
defer span.End()
// Here is what a worker should run when getting a rule.
// For now, lets not fan out the running of conditions.
return rule.When.Evaluate(ctx, log, ruleCtx)
}
func (r *ruleEngine) getRelativePathForViolation(fileURI uri.URI) (uri.URI, error) {
var sourceLocation string
if fileURI != "" {
u, err := url.ParseRequestURI(string(fileURI))
if err != nil || u.Scheme != uri.FileScheme {
return fileURI, nil
}
file := fileURI.Filename()
// get the correct source
for _, locationPrefix := range r.locationPrefixes {
if strings.Contains(file, locationPrefix) {
sourceLocation = locationPrefix
break
}
}
absPath, err := filepath.Abs(sourceLocation)
if err != nil {
return fileURI, nil
}
// given a relative path for source
if absPath != sourceLocation {
relPath := filepath.Join(sourceLocation, strings.TrimPrefix(file, absPath))
newURI := fmt.Sprintf("file:///%s", filepath.Join(strings.TrimPrefix(relPath, "/")))
return uri.URI(newURI), nil
}
}
return fileURI, nil
}
func (r *ruleEngine) createViolation(ctx context.Context, conditionResponse ConditionResponse, rule Rule, scope Scope) (konveyor.Violation, error) {
incidents := []konveyor.Incident{}
fileCodeSnipCount := map[string]int{}
incidentsSet := map[string]struct{}{} // Set of incidents
var incidentSelector *labels.LabelSelector[internal.VariableLabelSelector]
var err error
if r.incidentSelector != "" {
incidentSelector, err = labels.NewLabelSelector[internal.VariableLabelSelector](r.incidentSelector, internal.MatchVariables)
if err != nil {
return konveyor.Violation{}, err
}
}
for _, m := range conditionResponse.Incidents {
// Exit loop, we don't care about any incidents past the filter.
if r.incidentLimit != 0 && len(incidents) == r.incidentLimit {
break
}
// If we should remove the incident because the provider didn't filter it
// and the user asked for a certain scope of incidents.
if scope != nil && scope.FilterResponse(m) {
continue
}
trimmedUri, err := r.getRelativePathForViolation(m.FileURI)
if err != nil {
return konveyor.Violation{}, err
}
for val := range m.Variables {
if val == "file" {
m.Variables["file"] = trimmedUri
}
}
incident := konveyor.Incident{
URI: trimmedUri,
LineNumber: m.LineNumber,
// This allows us to change m.Variables and it will be set
// because it is a pointer.
Variables: m.Variables,
}
if m.LineNumber != nil {
lineNumber := *m.LineNumber
incident.LineNumber = &lineNumber
}
// Some violations may not have a location in code.
limitSnip := (r.codeSnipLimit != 0 && fileCodeSnipCount[string(m.FileURI)] == r.codeSnipLimit)
if !limitSnip {
codeSnip, err := r.getCodeLocation(ctx, m, rule)
if err != nil || codeSnip == "" {
r.logger.V(6).Error(err, "unable to get code location")
} else {
incident.CodeSnip = codeSnip
}
fileCodeSnipCount[string(m.FileURI)] += 1
}
if len(rule.CustomVariables) > 0 {
var originalCodeSnip string
re := regexp.MustCompile(`^(\s*[0-9]+ )?(.*)`)
scanner := bufio.NewScanner(strings.NewReader(incident.CodeSnip))
for scanner.Scan() {
if incident.LineNumber != nil && strings.HasPrefix(strings.TrimSpace(scanner.Text()), fmt.Sprintf("%v", *incident.LineNumber)) {
originalCodeSnip = strings.TrimSpace(re.ReplaceAllString(scanner.Text(), "$2"))
r.logger.V(5).Info("found originalCodeSnip", "lineNuber", incident.LineNumber, "original", originalCodeSnip)
break
}
}
for _, cv := range rule.CustomVariables {
match := cv.Pattern.FindStringSubmatch(originalCodeSnip)
if cv.NameOfCaptureGroup != "" && cv.Pattern.SubexpIndex(cv.NameOfCaptureGroup) >= 0 &&
cv.Pattern.SubexpIndex(cv.NameOfCaptureGroup) < len(match) {
m.Variables[cv.Name] = strings.TrimSpace(match[cv.Pattern.SubexpIndex(cv.NameOfCaptureGroup)])
continue
} else {
switch len(match) {
case 0:
m.Variables[cv.Name] = cv.DefaultValue
continue
case 1:
m.Variables[cv.Name] = strings.TrimSpace(match[0])
continue
case 2:
m.Variables[cv.Name] = strings.TrimSpace(match[1])
}
}
}
}
if rule.Perform.Message.Text != nil {
variables := make(map[string]interface{})
for key, value := range m.Variables {
variables[key] = value
}
if m.LineNumber != nil {
variables["lineNumber"] = *m.LineNumber
}
templateString, err := r.createPerformString(*rule.Perform.Message.Text, variables)
if err != nil {
r.logger.Error(err, "unable to create template string")
}
incident.Message = templateString
}
incidentLineNumber := -1
if incident.LineNumber != nil {
incidentLineNumber = *incident.LineNumber
}
// Deterime if we can filter out based on incident selector.
if r.incidentSelector != "" {
v := internal.VariableLabelSelector(incident.Variables)
b, err := incidentSelector.Matches(v)
if err != nil {
r.logger.Error(err, "unable to determine if incident should filter out, defautl to adding")
}
if !b {
r.logger.V(8).Info("filtering out incident based on incident selector")
continue
}
}
incidentString := fmt.Sprintf("%s-%s-%d", incident.URI, incident.Message, incidentLineNumber) // Formating a unique string for an incident
// Adding it to list and set if no duplicates found
if _, isDuplicate := incidentsSet[incidentString]; !isDuplicate {
incidents = append(incidents, incident)
incidentsSet[incidentString] = struct{}{}
}
}
rule.Labels = deduplicateLabels(rule.Labels)
return konveyor.Violation{
Description: rule.Description,
Labels: rule.Labels,
Category: rule.Category,
Incidents: incidents,
Extras: []byte{},
Effort: rule.Effort,
Links: rule.Perform.Message.Links,
}, nil
}
func (r *ruleEngine) getCodeLocation(_ context.Context, m IncidentContext, rule Rule) (codeSnip string, err error) {
if m.CodeLocation == nil {
r.logger.V(6).Info("unable to get the code snip", "URI", m.FileURI)
return "", nil
}
// We need to move this up, because the code only lives in the
// provider's
if rule.Snipper != nil {
return rule.Snipper.GetCodeSnip(m.FileURI, *m.CodeLocation)
}
if strings.HasPrefix(string(m.FileURI), uri.FileScheme) {
//Find the file, open it in a buffer.
readFile, err := os.Open(m.FileURI.Filename())
if err != nil {
r.logger.V(5).Error(err, "Unable to read file")
return "", err
}
defer readFile.Close()
scanner := bufio.NewScanner(readFile)
lineNumber := 0
codeSnip := ""
paddingSize := len(strconv.Itoa(m.CodeLocation.EndPosition.Line + r.contextLines))
for scanner.Scan() {
if (lineNumber - r.contextLines) == m.CodeLocation.EndPosition.Line {
codeSnip = codeSnip + fmt.Sprintf("%*d %v", paddingSize, lineNumber+1, scanner.Text())
break
}
if (lineNumber + r.contextLines) >= m.CodeLocation.StartPosition.Line {
codeSnip = codeSnip + fmt.Sprintf("%*d %v\n", paddingSize, lineNumber+1, scanner.Text())
}
lineNumber += 1
}
return codeSnip, nil
}
// if it is not a file ask the provider
return "", nil
}
func (r *ruleEngine) createPerformString(messageTemplate string, ctx map[string]interface{}) (string, error) {
return mustache.Render(messageTemplate, ctx)
}
// matchesAllSelectors returns false when any one of the selectors does not match
// selectors can be of different types e.g. label-selector, or category-selector
// when multiple selectors are present, we want all of them to match to filter-in the rule.
func matchesAllSelectors(m RuleMeta, selectors ...RuleSelector) bool {
for _, s := range selectors {
got, err := s.Matches(&m)
if err != nil || !got {
return false
}
}
return true
}
func deduplicateLabels(labels []string) []string {
present := map[string]bool{}
uniquelabels := []string{}
for _, label := range labels {
if !present[label] {
present[label] = true
uniquelabels = append(uniquelabels, label)
}
}
return uniquelabels
}