-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscrapeloop.go
370 lines (346 loc) · 10.3 KB
/
scrapeloop.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
package walker
import (
"context"
"crypto/tls"
"errors"
"fmt"
"net"
"net/http"
"net/http/cookiejar"
"net/url"
"strconv"
"strings"
"time"
"github.com/foomo/walker/htmlschema"
"github.com/foomo/walker/vo"
"github.com/temoto/robotstxt"
)
type poolClient struct {
agent string
client *http.Client
busy bool
}
type clientPool struct {
agent string
concurrency int
useCookies bool
clients []*poolClient
}
type contextKeyRedirects struct{}
func getRedirectsFromRequest(r *http.Request) []vo.Redirect {
via := r.Context().Value(contextKeyRedirects{})
if via != nil {
return via.([]vo.Redirect)
}
return []vo.Redirect{}
}
func newClientPool(concurrency int, agent string, useCookies bool) *clientPool {
clients := make([]*poolClient, concurrency)
for i := 0; i < concurrency; i++ {
client := &http.Client{
Timeout: time.Second * 10,
Transport: &http.Transport{
DialContext: (&net.Dialer{
Timeout: 5 * time.Second,
KeepAlive: 5 * time.Second,
}).DialContext,
MaxIdleConns: 100,
MaxIdleConnsPerHost: 50,
IdleConnTimeout: 15 * time.Second,
TLSHandshakeTimeout: 5 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
TLSClientConfig: &tls.Config{
// disable SSL certificate verification
InsecureSkipVerify: true,
},
},
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if len(via) > 9 {
return errors.New("stopped after 10 redirects")
}
c := req.Context()
vias := getRedirectsFromRequest(req)
newR := req.WithContext(
context.WithValue(
c,
contextKeyRedirects{}, append(vias, vo.Redirect{
Code: req.Response.StatusCode,
URL: req.URL.String(),
})))
*req = *newR
return nil
},
}
if useCookies {
cookieJar, _ := cookiejar.New(nil)
client.Jar = cookieJar
}
clients[i] = &poolClient{
client: client,
busy: false,
agent: agent,
}
}
return &clientPool{
agent: agent,
concurrency: concurrency,
clients: clients,
useCookies: useCookies,
}
}
func (w *Walker) scrapeloop() {
summaryVec,
counterVec,
totalCounter,
progressGaugeOpen,
progressGaugeComplete,
counterVecStatus,
trackValidationScore,
trackValidationPenalties := setupMetrics()
running := 0
concurrency := 0
groupHeader := ""
ignoreRobots := false
scrapeLoopStarted := false
var chanLoopComplete chan vo.Status
var scrapeFunc ScrapeFunc
var validationFunc ValidationFunc
var linkListFilterFunc LinkListFilterFunc
var scrapeResultModifierFunc ScrapeResultModifierFunc
ll := linkLimitations{}
var jobs map[string]bool
var results map[string]vo.ScrapeResult
var baseURL *url.URL
paths := []string{}
var cp *clientPool
var robotsGroup *robotstxt.Group
var groupValidator *htmlschema.GroupValidator
restart := func(startURL *url.URL, configPaths []string) {
scrapeLoopStarted = false
summaryVec.Reset()
counterVec.Reset()
counterVecStatus.Reset()
baseURL = startURL
paths = configPaths
running = 0
baseURLString := baseURL.Scheme + "://" + baseURL.Host
// port := baseURL.Port()
// if port != "" {
// baseURLString += ":" + port
// }
baseURLString += baseURL.RawPath
q := ""
if len(baseURL.Query()) > 0 {
q = "?" + baseURL.RawQuery
}
jobs = map[string]bool{}
for _, p := range paths {
jobs[baseURLString+p+q] = false
}
results = map[string]vo.ScrapeResult{}
scrapeLoopStarted = true
}
getStatus := func() vo.Status {
resultsCopy := make(map[string]vo.ScrapeResult, len(results))
jobsCopy := make(map[string]bool, len(jobs))
if results != nil {
for targetURL, result := range results {
resultsCopy[targetURL] = result
}
for targetURL, active := range jobs {
jobsCopy[targetURL] = active
}
}
scrapeWindowSeconds := 60
scrapeWindow := time.Second * time.Duration(scrapeWindowSeconds)
scrapeWindowCount := int64(0)
now := time.Now()
first := now.Unix()
scrapeWindowFirst := now.Unix()
totalCount := int64(0)
for _, r := range results {
// the results are not sorted baby
totalCount++
if first > r.Time.Unix() {
first = r.Time.Unix()
}
if now.Sub(r.Time) < scrapeWindow {
if scrapeWindowFirst > r.Time.Unix() {
scrapeWindowFirst = r.Time.Unix()
}
scrapeWindowCount++
}
}
currentScrapeWindowSeconds := now.Unix() - scrapeWindowFirst
scrapeTotalSeconds := now.Unix() - first
return vo.Status{
Results: resultsCopy,
ScrapeSpeed: float64(scrapeWindowCount) / float64(currentScrapeWindowSeconds),
ScrapeSpeedAverage: float64(totalCount) / float64(scrapeTotalSeconds),
ScrapeWindowRequests: scrapeWindowCount,
ScrapeWindowSeconds: currentScrapeWindowSeconds,
ScrapeTotalRequests: totalCount,
ScrapeTotalSeconds: scrapeTotalSeconds,
Jobs: jobsCopy,
}
}
for {
if scrapeLoopStarted {
progressGaugeComplete.Set(float64(len(results)))
progressGaugeOpen.Set(float64(len(jobs)))
if len(jobs) > 0 {
JobLoop:
for jobURL, jobActive := range jobs {
if running >= concurrency {
// concurrency limit
break
}
if !jobActive {
for _, poolClient := range cp.clients {
if !poolClient.busy {
running++
jobs[jobURL] = true
poolClient.busy = true
go scrape(poolClient, jobURL, baseURL, groupHeader, scrapeFunc, validationFunc, groupValidator, w.chanResult)
continue JobLoop
}
}
break JobLoop
}
}
}
}
// time to restart
if results != nil && len(jobs) == 0 && running == 0 && baseURL != nil {
fmt.Println("restarting", baseURL, paths)
w.CompleteStatus = &vo.Status{
Results: results,
Jobs: jobs,
}
if chanLoopComplete != nil {
go reportSchemaValidationMetrics(
*w.CompleteStatus,
paths,
trackValidationPenalties,
trackValidationScore,
)
chanLoopComplete <- *w.CompleteStatus
}
restart(baseURL, paths)
}
select {
case <-time.After(time.Millisecond * 1000):
// make sure we do not get stuck
case st := <-w.chanStart:
robotsGroup = nil
groupHeader = st.conf.GroupHeader
concurrency = st.conf.Concurrency
scrapeFunc = st.scrapeFunc
validationFunc = st.validationFunc
linkListFilterFunc = st.linkListFilterFunc
ll.ignorePathPrefixes = st.conf.Ignore
ll.depth = st.conf.Depth
ll.paging = st.conf.Paging
groupValidator = st.groupValidator
ll.includePathPrefixes = st.conf.Target.Paths
ignoreRobots = st.conf.IgnoreRobots
ll.ignoreQueriesWith = st.conf.IgnoreQueriesWith
ll.ignoreAllQueries = st.conf.IgnoreAllQueries
scrapeResultModifierFunc = st.scrapeResultModifierFunc
if cp == nil || cp.agent != st.conf.Agent || cp.concurrency != st.conf.Concurrency || cp.useCookies != st.conf.UseCookies {
cp = newClientPool(st.conf.Concurrency, st.conf.Agent, st.conf.UseCookies)
}
var errStart error
startU, errParseStartU := url.Parse(st.conf.Target.BaseURL)
if errParseStartU != nil {
errStart = errParseStartU
}
if errStart == nil && !ignoreRobots {
robotsData, errRobotsGroup := getRobotsData(st.conf.Target.BaseURL)
if errRobotsGroup == nil {
robotsGroup = robotsData.FindGroup(st.conf.Agent)
robotForbiddenPath := []string{}
for _, p := range st.conf.Target.Paths {
if !robotsGroup.Test(p) {
robotForbiddenPath = append(robotForbiddenPath, p)
}
}
if len(robotForbiddenPath) > 0 {
errStart = errors.New("robots.txt does not allow access to the following path (you can either ignore robots or try as a different user agent): " + strings.Join(robotForbiddenPath, ", "))
}
} else {
errStart = errRobotsGroup
}
}
if errStart == nil {
restart(startU, st.conf.Target.Paths)
chanLoopComplete = make(chan vo.Status)
w.chanStarted <- started{
Err: errStart,
ChanLoopComplete: chanLoopComplete,
}
} else {
chanLoopComplete = nil
w.chanStarted <- started{
Err: errStart,
}
}
case <-w.chanStatus:
w.chanStatus <- getStatus()
case <-w.chanStop:
w.chanStop <- getStatus()
return
case scanResult := <-w.chanResult:
running--
delete(jobs, scanResult.result.TargetURL)
if scrapeResultModifierFunc != nil {
modifiedScrapeResult, errModify := scrapeResultModifierFunc(scanResult.result)
if errModify == nil {
scanResult.result = modifiedScrapeResult
} else {
fmt.Println("cound not modify scrape result", errModify)
}
}
scanResult.poolClient.busy = false
scanResult.result.Time = time.Now()
statusCodeAsString := strconv.Itoa(scanResult.result.Code)
counterVecStatus.WithLabelValues(statusCodeAsString).Inc()
results[scanResult.result.TargetURL] = scanResult.result
summaryVec.WithLabelValues(scanResult.result.Group).Observe(scanResult.result.Duration.Seconds())
counterVec.WithLabelValues(scanResult.result.Group, statusCodeAsString).Inc()
totalCounter.Inc()
var linksToScrape vo.LinkList
if linkListFilterFunc != nil {
if scanResult.result.Error != "" {
fmt.Println("there was an error", scanResult.result.Error)
} else if scanResult.doc != nil {
linksToScrapeFromFromLilterFunc, errFilterLinkList := linkListFilterFunc(baseURL, scanResult.docURL, scanResult.doc)
if errFilterLinkList != nil {
fmt.Println("aua", errFilterLinkList)
}
linksToScrape = linksToScrapeFromFromLilterFunc
}
} else if ignoreRobots || !strings.Contains(scanResult.result.Structure.Robots, "nofollow") {
linkNextNormalized := ""
linkPrevNormalized := ""
// should we follow the links
linkNextNormalizedURL, errNormalizeNext := NormalizeLink(baseURL, scanResult.result.Structure.LinkNext)
if errNormalizeNext == nil {
linkNextNormalized = linkNextNormalizedURL.String()
}
linkPrevNormalizedURL, errNormalizedPrev := NormalizeLink(baseURL, scanResult.result.Structure.LinkPrev)
if errNormalizedPrev == nil {
linkPrevNormalized = linkPrevNormalizedURL.String()
}
linksToScrape = filterScrapeLinks(scanResult.result.Links, baseURL, linkNextNormalized, linkPrevNormalized, ll, robotsGroup)
}
for linkToScrape := range linksToScrape {
_, existingResultOK := results[linkToScrape]
_, existingJobOK := jobs[linkToScrape]
if !existingResultOK && !existingJobOK {
jobs[linkToScrape] = false
}
}
}
}
}