-
Notifications
You must be signed in to change notification settings - Fork 45
/
crawler.go
697 lines (624 loc) · 16.4 KB
/
crawler.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
package gcse
import (
"context"
"crypto/tls"
"encoding/gob"
"encoding/json"
"errors"
"fmt"
godoc "go/doc"
"log"
"net/http"
"net/url"
"regexp"
"strings"
"sync"
"time"
"unicode/utf8"
"github.com/golangplus/bytes"
"github.com/golangplus/errors"
"github.com/golangplus/strings"
"github.com/golangplus/time"
"github.com/daviddengcn/gcse/configs"
"github.com/daviddengcn/gcse/spider/github"
"github.com/daviddengcn/gcse/store"
"github.com/daviddengcn/gcse/utils"
"github.com/daviddengcn/gddo/doc"
"github.com/daviddengcn/go-easybi"
"github.com/daviddengcn/go-index"
"github.com/daviddengcn/go-villa"
"github.com/daviddengcn/sophie"
"github.com/golang/gddo/gosrc"
gpb "github.com/daviddengcn/gcse/shared/proto"
glgddo "github.com/golang/gddo/doc"
)
const (
fnLinks = "links.json"
/*
Increase this to ignore etag of last versions to crawl and parse all
packages.
ChangeLog:
0 First version
1 Add TestImports/XTestImports to Imports
2 Parse markdown readme to text before selecting synopsis
from it
3 Add exported tokens to indexes
4 Move TestImports/XTestImports out of Imports, to TestImports
4 A bug of checking CrawlerVersion is fixed
*/
CrawlerVersion = 5
)
// AppendPackages appends a list packages to imports folder for crawler
// backend to read
func AppendPackages(pkgs []string) bool {
segm, err := configs.ImportSegments().GenNewSegment()
if err != nil {
log.Printf("genImportSegment failed: %v", err)
return false
}
log.Printf("Import to %v", segm)
if err := utils.WriteJsonFile(segm.Join(fnLinks), pkgs); err != nil {
log.Printf("WriteJsonFile failed: %v", err)
return false
}
if err := segm.Done(); err != nil {
log.Printf("segm.Done() failed: %v", err)
return false
}
return true
}
func ReadPackages(segm utils.Segment) ([]string, error) {
var pkgs []string
err := utils.ReadJsonFile(segm.Join(fnLinks), &pkgs)
return pkgs, err
}
type BlackRequest struct {
sync.RWMutex
badUrls map[string]http.Response
client doc.HttpClient
}
func (br *BlackRequest) Do(req *http.Request) (*http.Response, error) {
if req.Method != "GET" {
return br.client.Do(req)
}
u := req.URL.String()
log.Printf("BlackRequest.Do(GET(%v))", u)
br.RLock()
r, ok := br.badUrls[u]
br.RUnlock()
if ok {
log.Printf("%s was found in 500 blacklist, return it directly", u)
r.Body = bytesp.NewPSlice(nil)
return &r, nil
}
resp, err := br.client.Do(req)
if err != nil {
return resp, err
}
if resp.StatusCode == 500 {
log.Printf("Put %s into 500 blacklist", u)
r := *resp
r.Body = nil
br.Lock()
br.badUrls[u] = r
br.Unlock()
}
return resp, nil
}
func GenHttpClient(proxy string) doc.HttpClient {
tp := &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
}
if proxy != "" {
proxyURL, err := url.Parse(proxy)
if err == nil {
tp.Proxy = http.ProxyURL(proxyURL)
}
}
return &BlackRequest{
badUrls: make(map[string]http.Response),
client: &http.Client{
Transport: tp,
},
}
}
func HostOfPackage(pkg string) string {
u, err := url.Parse("http://" + pkg)
if err != nil {
return ""
}
return u.Host
}
func FullProjectOfPackage(pkg string) string {
parts := strings.Split(pkg, "/")
if len(parts) == 0 {
return ""
}
switch parts[0] {
case "llamaslayers.net", "bazil.org":
if len(parts) > 2 {
parts = parts[:2]
}
case "github.com", "code.google.com", "bitbucket.org", "labix.org":
if len(parts) > 3 {
parts = parts[:3]
}
case "golanger.com":
return "golanger.com/golangers"
case "launchpad.net":
if len(parts) > 2 && strings.HasPrefix(parts[1], "~") {
parts = parts[:2]
}
if len(parts) > 1 {
parts = parts[:2]
}
case "cgl.tideland.biz":
return "cgl.tideland.biz/tcgl"
default:
if len(parts) > 3 {
parts = parts[:3]
}
}
return strings.Join(parts, "/")
}
// Package stores information from crawler
type Package struct {
Package string
Name string
Synopsis string
Doc string
ProjectURL string
StarCount int
ReadmeFn string
ReadmeData string
Imports []string
TestImports []string
Exported []string // exported tokens(funcs/types)
References []string
Etag string
}
var (
ErrPackageNotModifed = errors.New("package not modified")
ErrInvalidPackage = errors.New("invalid package")
)
var patSingleReturn = regexp.MustCompile(`\b\n\b`)
func ReadmeToText(fn, data string) string {
fn = strings.ToLower(fn)
if strings.HasSuffix(fn, ".md") || strings.HasSuffix(fn, ".markdown") ||
strings.HasSuffix(fn, ".mkd") {
defer func() {
if r := recover(); r != nil {
return
}
}()
md := index.ParseMarkdown([]byte(data))
return string(md.Text)
}
return data
}
func Plusone(httpClient doc.HttpClient, url string) (int, error) {
req, err := http.NewRequest("POST",
"https://clients6.google.com/rpc?key=AIzaSyCKSbrvQasunBoV16zDH9R33D88CeLr9gQ",
bytesp.NewPSlice([]byte(
`[{"method":"pos.plusones.get","id":"p","params":{"nolog":true,"id": "`+
url+`","source":"widget","userId":"@viewer","groupId":"@self"},"jsonrpc":"2.0","key":"p","apiVersion":"v1"}]`)))
if err != nil {
return 0, errorsp.WithStacksAndMessage(err, "new request for crawling g+ of %v failed", url)
}
req.Header.Set("Content-Type", "application/json")
resp, err := httpClient.Do(req)
if err != nil {
return 0, errorsp.WithStacksAndMessage(err, "crawling g+ of %v failed", url)
}
defer resp.Body.Close()
dec := json.NewDecoder(resp.Body)
var v [1]struct {
Result struct {
Metadata struct {
GlobalCounts struct {
Count float64
}
}
}
}
if err := dec.Decode(&v); err != nil {
return 0, errorsp.WithStacksAndMessage(err, "decoding g+ of %v failed", url)
}
return int(0.5 + v[0].Result.Metadata.GlobalCounts.Count), nil
}
func LikeButton(httpClient doc.HttpClient, Url string) (int, error) {
req, err := http.NewRequest("GET", "http://graph.facebook.com/?"+
url.Values{"ids": {Url}}.Encode(), nil)
if err != nil {
return 0, err
}
resp, err := httpClient.Do(req)
if err != nil {
return 0, err
}
defer resp.Body.Close()
dec := json.NewDecoder(resp.Body)
var v map[string]struct {
Shares int
}
if err := dec.Decode(&v); err != nil {
return 0, err
}
return v[Url].Shares, nil
}
func fuseStars(a, b int) int {
if a < 0 {
return b
}
if b < 0 {
return a
}
if a > b {
a, b = b, a
}
/*
Now, a <= b
Supposing half of the stargzers are shared ones. The numbers could
be a/2, or b/2. The mean is (a + b) / 4. Exclude this from a + b,
and assure it greater than b.
*/
if a <= b/3 {
return b
}
return (a + b) * 3 / 4
}
func newDocGet(ctx context.Context, httpClient doc.HttpClient, pkg string, etag string) (p *doc.Package, err error) {
gp, err := glgddo.Get(ctx, httpClient.(*BlackRequest).client.(*http.Client), pkg, etag)
if err != nil {
if _, ok := err.(gosrc.NotModifiedError); ok {
err = doc.ErrNotModified
}
return nil, err
}
return &doc.Package{
ImportPath: gp.ImportPath,
ProjectRoot: gp.ProjectRoot,
ProjectName: gp.ProjectName,
ProjectURL: gp.ProjectURL,
Errors: gp.Errors,
References: gp.References,
VCS: gp.VCS,
Updated: gp.Updated,
Etag: gp.Etag,
Name: gp.Name,
Synopsis: gp.Synopsis,
Doc: gp.Doc,
IsCmd: gp.IsCmd,
Truncated: gp.Truncated,
GOOS: gp.GOOS,
GOARCH: gp.GOARCH,
LineFmt: gp.LineFmt,
BrowseURL: gp.BrowseURL,
SourceSize: gp.SourceSize,
TestSourceSize: gp.TestSourceSize,
Imports: gp.Imports,
TestImports: gp.TestImports,
XTestImports: gp.XTestImports,
StarCount: -1,
}, nil
}
var GithubSpider *github.Spider
const maxRepoInfoAge = 2 * timep.Day
func CrawlRepoInfo(ctx context.Context, site, user, name string) *gpb.RepoInfo {
// Check cache in store.
path := user + "/" + name
p, err := store.ReadPackage(site, path)
if err != nil {
log.Printf("ReadPackage %v %v failed: %v", site, path, err)
} else {
if p.RepoInfo != nil && store.RepoInfoAge(p.RepoInfo) < maxRepoInfoAge {
log.Printf("Repo cache of %s/%s hit", site, path)
bi.Inc("crawler.repocache.hit")
return p.RepoInfo
}
}
bi.Inc("crawler.repocache.miss")
ri, err := GithubSpider.ReadRepository(ctx, user, name)
if err != nil {
if errorsp.Cause(err) == github.ErrInvalidRepository {
if err := store.DeletePackage(site, path); err != nil {
log.Printf("DeleteRepoInfo %v %v failed: %v", site, path, err)
}
}
return nil
}
if err := store.UpdatePackage(site, path, func(info *gpb.PackageInfo) error {
info.RepoInfo = ri
return nil
}); err != nil {
log.Printf("UpdatePackage %v %v failed: %v", site, path, err)
} else {
log.Printf("UpdatePackage %s %s success", site, path)
}
return ri
}
func getGithubStars(ctx context.Context, user, name string) int {
r := CrawlRepoInfo(ctx, "github.com", user, name)
if r != nil {
return int(r.Stars)
}
return -1
}
func getGithub(ctx context.Context, pkg string) (*doc.Package, []*gpb.FolderInfo, error) {
parts := strings.SplitN(pkg, "/", 4)
for len(parts) < 4 {
parts = append(parts, "")
}
if parts[1] == "" || parts[2] == "" {
return nil, nil, errorsp.WithStacks(ErrInvalidPackage)
}
p, folders, err := GithubSpider.ReadPackage(ctx, parts[1], parts[2], parts[3])
if err != nil {
return nil, folders, err
}
return &doc.Package{
ImportPath: pkg,
ProjectRoot: strings.Join(parts[:3], "/"),
ProjectName: parts[2],
ProjectURL: "https://" + strings.Join(parts[:3], "/"),
Updated: time.Now(),
Name: p.Name,
Doc: p.Description,
Imports: p.Imports,
TestImports: p.TestImports,
StarCount: getGithubStars(ctx, parts[1], parts[2]),
ReadmeFiles: map[string][]byte{p.ReadmeFn: []byte(p.ReadmeData)},
}, folders, nil
}
func CrawlPackage(ctx context.Context, httpClient doc.HttpClient, pkg string, etag string) (p *Package, folders []*gpb.FolderInfo, err error) {
defer func() {
if perr := recover(); perr != nil {
p, folders, err = nil, nil, errorsp.NewWithStacks("Panic when crawling package %s: %v", pkg, perr)
}
}()
var pdoc *doc.Package
if strings.Contains(pkg, "/vendor/") || strings.HasPrefix(pkg, "thezombie.net") {
return nil, folders, ErrInvalidPackage
}
if strings.HasPrefix(pkg, "github.com/") {
if GithubSpider != nil {
pdoc, folders, err = getGithub(ctx, pkg)
} else {
pdoc, err = doc.Get(httpClient, pkg, etag)
}
} else {
pdoc, err = newDocGet(ctx, httpClient, pkg, etag)
}
if err == doc.ErrNotModified {
return nil, folders, ErrPackageNotModifed
}
if err != nil {
return nil, folders, errorsp.WithStacks(err)
}
if pdoc.StarCount < 0 {
// if starcount is not fetched, choose fusion of Plusone and
// Like Button
plus, like := -1, -1
if starCount, err := Plusone(httpClient, pdoc.ProjectURL); err == nil {
plus = starCount
}
if starCount, err := LikeButton(httpClient, pdoc.ProjectURL); err == nil {
like = starCount
}
pdoc.StarCount = fuseStars(plus, like)
}
readmeFn, readmeData := "", ""
for fn, data := range pdoc.ReadmeFiles {
readmeFn, readmeData = strings.TrimSpace(fn),
strings.TrimSpace(string(data))
if len(readmeData) > 1 && utf8.ValidString(readmeData) {
break
} else {
readmeFn, readmeData = "", ""
}
}
// try find synopsis from readme
if pdoc.Doc == "" && pdoc.Synopsis == "" {
pdoc.Synopsis = godoc.Synopsis(ReadmeToText(readmeFn, readmeData))
}
if len(readmeData) > 100*1024 {
readmeData = readmeData[:100*1024]
}
importsSet := stringsp.NewSet(pdoc.Imports...)
importsSet.Delete(pdoc.ImportPath)
imports := importsSet.Elements()
testImports := stringsp.NewSet(pdoc.TestImports...)
testImports.Add(pdoc.XTestImports...)
testImports.Delete(imports...)
testImports.Delete(pdoc.ImportPath)
var exported stringsp.Set
for _, f := range pdoc.Funcs {
exported.Add(f.Name)
}
for _, t := range pdoc.Types {
exported.Add(t.Name)
}
return &Package{
Package: pdoc.ImportPath,
Name: pdoc.Name,
Synopsis: pdoc.Synopsis,
Doc: pdoc.Doc,
ProjectURL: pdoc.ProjectURL,
StarCount: pdoc.StarCount,
ReadmeFn: readmeFn,
ReadmeData: readmeData,
Imports: imports,
TestImports: testImports.Elements(),
Exported: exported.Elements(),
References: pdoc.References,
Etag: pdoc.Etag,
}, folders, nil
}
func IdOfPerson(site, username string) string {
return fmt.Sprintf("%s:%s", site, username)
}
func ParsePersonId(id string) (site, username string) {
parts := strings.Split(id, ":")
return parts[0], parts[1]
}
type Person struct {
Id string
Packages []string
}
func CrawlPerson(ctx context.Context, httpClient doc.HttpClient, id string) (*Person, error) {
site, user := ParsePersonId(id)
switch site {
case "github.com":
u, err := GithubSpider.ReadUser(ctx, user)
if err != nil {
return nil, errorsp.WithStacksAndMessage(err, "ReadUser %s failed", id)
}
p := &Person{Id: id}
for name, ri := range u.Repos {
path := user + "/" + name
p.Packages = append(p.Packages, "github.com/"+path)
if err := store.UpdatePackage(site, path, func(info *gpb.PackageInfo) error {
info.RepoInfo = ri
return nil
}); err != nil {
log.Printf("UpdatePackage %v %v failed: %v", site, path, err)
} else {
log.Printf("UpdatePackage %v %v success", site, path)
}
}
return p, nil
case "bitbucket.org":
p, err := doc.GetBitbucketPerson(httpClient, map[string]string{"owner": user})
if err != nil {
return nil, errorsp.WithStacks(err)
}
return &Person{
Id: id,
Packages: p.Projects,
}, nil
}
return nil, nil
}
func IsBadPackage(err error) bool {
err = villa.DeepestNested(errorsp.Cause(err))
return doc.IsNotFound(err) || err == ErrInvalidPackage || err == github.ErrInvalidPackage
}
type DocDB interface {
Sync() error
Export(root villa.Path, kind string) error
Get(key string, data interface{}) bool
Put(key string, data interface{})
Delete(key string)
Iterate(output func(key string, val interface{}) error) error
}
type PackedDocDB struct {
*MemDB
}
func (db PackedDocDB) Get(key string, data interface{}) bool {
var bs bytesp.Slice
if ok := db.MemDB.Get(key, (*[]byte)(&bs)); !ok {
return false
}
dec := gob.NewDecoder(&bs)
if err := dec.Decode(data); err != nil {
log.Printf("Get %s failed: %v", key, err)
return false
}
return true
}
func (db PackedDocDB) Put(key string, data interface{}) {
var bs bytesp.Slice
enc := gob.NewEncoder(&bs)
if err := enc.Encode(data); err != nil {
log.Printf("Put %s failed: %v", key, err)
return
}
db.MemDB.Put(key, []byte(bs))
}
func (db PackedDocDB) Iterate(
output func(key string, val interface{}) error) error {
return db.MemDB.Iterate(func(key string, val interface{}) error {
dec := gob.NewDecoder(bytesp.NewPSlice(val.([]byte)))
var info DocInfo
if err := dec.Decode(&info); err != nil {
log.Printf("Decode %s failed: %v", key, err)
db.Get(key, &info)
return err
}
return output(key, info)
})
}
type CrawlingEntry struct {
ScheduleTime time.Time
// if gcse.CrawlerVersion is different from this value, etag is ignored
Version int
Etag string
}
func (c *CrawlingEntry) WriteTo(w sophie.Writer) error {
if err := sophie.Time(c.ScheduleTime).WriteTo(w); err != nil {
return err
}
if err := sophie.VInt(c.Version).WriteTo(w); err != nil {
return err
}
if err := sophie.String(c.Etag).WriteTo(w); err != nil {
return err
}
return nil
}
func (c *CrawlingEntry) ReadFrom(r sophie.Reader, l int) error {
if err := (*sophie.Time)(&c.ScheduleTime).ReadFrom(r, -1); err != nil {
return err
}
if err := (*sophie.VInt)(&c.Version).ReadFrom(r, -1); err != nil {
return err
}
if err := (*sophie.String)(&c.Etag).ReadFrom(r, -1); err != nil {
return err
}
return nil
}
const (
// whole document updated
NDA_UPDATE = iota
// only stars updated
NDA_STARS
// deleted
NDA_DEL
// Original document
NDA_ORIGINAL
)
/*
* If Action equals NDA_DEL, DocInfo is undefined.
*/
type NewDocAction struct {
Action sophie.VInt
DocInfo
}
// Returns a new instance of *NewDocAction as a Sophier
func NewNewDocAction() sophie.Sophier {
return new(NewDocAction)
}
func (nda *NewDocAction) WriteTo(w sophie.Writer) error {
if err := nda.Action.WriteTo(w); err != nil {
return err
}
if nda.Action == NDA_DEL {
return nil
}
return nda.DocInfo.WriteTo(w)
}
func (nda *NewDocAction) ReadFrom(r sophie.Reader, l int) error {
if err := nda.Action.ReadFrom(r, -1); err != nil {
return errorsp.WithStacks(err)
}
if nda.Action == NDA_DEL {
return nil
}
return errorsp.WithStacks(nda.DocInfo.ReadFrom(r, -1))
}
func init() {
gob.RegisterName("main.CrawlingEntry", CrawlingEntry{})
}