-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathengine.go
More file actions
225 lines (197 loc) · 4.57 KB
/
Copy pathengine.go
File metadata and controls
225 lines (197 loc) · 4.57 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
package youcrawl
import (
"fmt"
"github.com/PuerkitoBio/goquery"
"github.com/sirupsen/logrus"
"net/http"
"net/http/cookiejar"
"sync"
)
var EngineLogger *logrus.Entry = logrus.WithField("scope", "engine")
// tracking request task
type Task struct {
ID string
Url string
Context Context
Requested bool
Completed bool
}
// request task pool
// youcrawl engine
type Engine struct {
sync.Mutex
*EngineOption
// dispatch task
Pool TaskPool
Parsers []HTMLParser
Middlewares []Middleware
Pipelines []Pipeline
GlobalStore GlobalStore
PostProcess []PostProcess
Plugins []Plugin
// receive signal: force stop pool
InterruptChan chan struct{}
// receive signal: stop pool when all task has done
StopPoolChan chan struct{}
}
// share data in crawl process
type Context struct {
Request *http.Request
Response *http.Response
Item interface{}
GlobalStore GlobalStore
Pool TaskPool
Cookie *cookiejar.Jar
Doc *goquery.Document
}
// init engine config
type EngineOption struct {
// max running in same time
MaxRequest int
// true for:
// keep running until manually stopped
Daemon bool
}
// init new engine
func NewEngine(option *EngineOption) *Engine {
globalStore := &MemoryGlobalStore{}
err := globalStore.Init()
if err != nil {
logrus.Fatal("init global store failed")
}
pool := NewRequestPool(RequestPoolOption{
PreventStop: option.Daemon,
}, globalStore)
newEngine := &Engine{
Pool: pool,
EngineOption: option,
Pipelines: []Pipeline{},
Middlewares: []Middleware{},
Parsers: []HTMLParser{},
GlobalStore: globalStore,
InterruptChan: make(chan struct{}),
StopPoolChan: make(chan struct{}),
}
return newEngine
}
// add url to crawl
// unsafe operation,engine must not in running status
//
// in engine running ,use RequestPool.AddURLs method
func (e *Engine) AddURLs(urls ...string) {
e.Pool.AddURLs(urls...)
}
// add task to crawl
// unsafe operation,engine must not in running status
//
// in engine running ,use RequestPool.AddURLs method
func (e *Engine) AddTasks(tasks ...*Task) {
e.Pool.AddTasks(tasks...)
}
// add parse
func (e *Engine) AddHTMLParser(parsers ...HTMLParser) {
for _, htmlParser := range parsers {
e.Parsers = append(e.Parsers, htmlParser)
}
}
// add pipelines
func (e *Engine) AddPipelines(pipelines ...Pipeline) {
for _, pipeline := range pipelines {
e.Pipelines = append(e.Pipelines, pipeline)
}
}
// add middleware
func (e *Engine) UseMiddleware(middlewares ...Middleware) {
e.Middlewares = append(e.Middlewares, middlewares...)
}
// use taskPool
func (e *Engine) UseTaskPool(taskPool TaskPool) {
e.Pool = taskPool
}
// add postprocess
func (e *Engine) AddPostProcess(postprocessList ...PostProcess) {
e.PostProcess = append(e.PostProcess, postprocessList...)
}
// add plugins
func (e *Engine) AddPlugins(plugins ...Plugin) {
e.Plugins = append(e.Plugins, plugins...)
}
func CrawlProcess(taskChannel chan struct{}, e *Engine, task *Task) {
defer e.Pool.OnTaskDone(task)
requestBody, err := RequestWithURL(task, e.Middlewares...)
if err != nil {
EngineLogger.Info(err)
taskChannel <- struct{}{}
return
}
taskChannel <- struct{}{}
// parse html
doc, err := goquery.NewDocumentFromReader(requestBody)
if err != nil {
EngineLogger.Error(err)
}
// run parser one by one
task.Context.Doc = doc
for _, parser := range e.Parsers {
err = ParseHTML(parser, &task.Context)
if err != nil {
EngineLogger.Error(err)
continue
}
}
for _, pipeline := range e.Pipelines {
err := pipeline.Process(task.Context.Item, e.GlobalStore)
if err != nil {
EngineLogger.Error(err)
continue
}
}
}
// run and wait it done
func (e *Engine) RunAndWait() {
var wg sync.WaitGroup
wg.Add(1)
e.Run(&wg)
wg.Wait()
}
// run crawl engine
func (e *Engine) Run(wg *sync.WaitGroup) {
defer func() {
EngineLogger.Info("all done ,send stop signal")
wg.Done()
}()
taskChannel := make(chan struct{}, e.MaxRequest)
for idx := 0; idx < e.MaxRequest; idx++ {
taskChannel <- struct{}{}
}
// run interrupt chan
go func() {
select {
case <-e.InterruptChan:
e.Pool.Close()
case <-e.StopPoolChan:
e.Pool.SetPrevent(false)
}
}()
for _, plugin := range e.Plugins {
go plugin.Run(e)
}
Loop:
for {
select {
case task := <-e.Pool.GetOneTask(e):
<-taskChannel
go CrawlProcess(taskChannel, e, task)
case <-e.Pool.GetDoneChan():
break Loop
}
}
EngineLogger.Info("into post process")
for _, postProcess := range e.PostProcess {
err := postProcess.Process(e.GlobalStore)
if err != nil {
fmt.Println(err)
}
}
return
}