This repository has been archived by the owner on Feb 26, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
analyzer_multi.go
126 lines (106 loc) · 2.5 KB
/
analyzer_multi.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
package cortex
import (
"context"
"io"
"sync"
"time"
)
// MultiRun represents configuration for running multiple analyzers
type MultiRun struct {
aso *AnalyzerServiceOp
Timeout time.Duration
ctx context.Context
OnReport func(*Report)
OnError func(error, Observable, *Analyzer)
}
// NewMultiRun is a function that bootstraps MultiRun struct
func (a *AnalyzerServiceOp) NewMultiRun(ctx context.Context, d time.Duration) *MultiRun {
return &MultiRun{
aso: a,
Timeout: d,
ctx: ctx,
}
}
// Do analyzes an observable with all appropriate analyzers
func (m *MultiRun) Do(o Observable) error {
ans, _, err := m.aso.ListByType(m.ctx, o.Type())
if err != nil {
return err
}
var wg sync.WaitGroup
wg.Add(len(ans))
defer wg.Wait()
switch o.(type) {
case *FileTask:
err := m.AnalyzeFile(&wg, o.(*FileTask), ans...)
if err != nil {
return err
}
case *Task:
err := m.AnalyzeString(&wg, o.(*Task), ans...)
if err != nil {
return err
}
}
return nil
}
// AnalyzeFile analyses a file observable by multiple analyzers
func (m *MultiRun) AnalyzeFile(wg *sync.WaitGroup, ft *FileTask, ans ...Analyzer) error {
var (
readPipes []*io.PipeReader
writePipes []*io.PipeWriter
)
for i := range ans {
fr, fw := io.Pipe()
readPipes = append(readPipes, fr)
writePipes = append(writePipes, fw)
o := &FileTask{
FileName: ft.FileName,
Reader: fr,
FileTaskMeta: ft.FileTaskMeta,
}
go func(an Analyzer) error {
defer wg.Done()
report, err := m.aso.run(m.ctx, an.ID, o, m.Timeout)
if err != nil && m.OnError != nil {
m.OnError(err, o, &an)
}
if err == nil && report != nil && m.OnReport != nil {
m.OnReport(report)
}
return nil
}(ans[i])
}
wr := make([]io.Writer, len(writePipes))
for i := range writePipes {
wr[i] = writePipes[i]
}
mw := io.MultiWriter(wr...)
go func() error {
if _, err := io.Copy(mw, ft.Reader); err != nil {
return err
}
for i := range writePipes {
writePipes[i].Close()
}
return nil
}()
return nil
}
// AnalyzeString analyses a basic string-alike observable by multiple analyzers
func (m *MultiRun) AnalyzeString(wg *sync.WaitGroup, t *Task, ans ...Analyzer) error {
for i := range ans {
go func(an Analyzer) error {
defer wg.Done()
report, err := m.aso.run(m.ctx, an.ID, t, m.Timeout)
if err != nil && m.OnError != nil {
m.OnError(err, t, &an)
}
if err == nil && report != nil && m.OnReport != nil {
m.OnReport(report)
}
return nil
}(ans[i])
}
return nil
}