crawler.go 7.01 KB
Newer Older
ale's avatar
ale committed
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
package crawl

import (
	"bytes"
	"encoding/gob"
	"errors"
	"fmt"
	"log"
	"net/http"
	"net/url"
	"sync"
	"time"

	"github.com/PuerkitoBio/purell"
	"github.com/jmhodges/levigo"
)

type gobDB struct {
	*levigo.DB
}

func newGobDB(path string) (*gobDB, error) {
	opts := levigo.NewOptions()
	opts.SetCreateIfMissing(true)
	opts.SetCache(levigo.NewLRUCache(2 << 20))
	opts.SetFilterPolicy(levigo.NewBloomFilter(10))
	db, err := levigo.Open(path, opts)
	if err != nil {
		return nil, err
	}
	return &gobDB{db}, nil
}

func (db *gobDB) PutObj(wo *levigo.WriteOptions, key []byte, obj interface{}) error {
	var b bytes.Buffer
	if err := gob.NewEncoder(&b).Encode(obj); err != nil {
		return err
	}
	return db.Put(wo, key, b.Bytes())
}

func (db *gobDB) GetObj(ro *levigo.ReadOptions, key []byte, obj interface{}) error {
	data, err := db.Get(ro, key)
	if err != nil {
		return err
	}
	if err := gob.NewDecoder(bytes.NewBuffer(data)).Decode(obj); err != nil {
		return err
	}
	return nil
}

ale's avatar
ale committed
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
func (db *gobDB) NewPrefixIterator(ro *levigo.ReadOptions, prefix []byte) *gobIterator {
	i := db.NewIterator(ro)
	i.Seek(prefix)
	return &gobIterator{Iterator: i, prefix: prefix}
}

type gobIterator struct {
	*levigo.Iterator
	prefix []byte
}

func (i *gobIterator) Valid() bool {
	return i.Iterator.Valid() && bytes.HasPrefix(i.Key(), i.prefix)
}

func (i *gobIterator) Value(obj interface{}) error {
	return gob.NewDecoder(bytes.NewBuffer(i.Iterator.Value())).Decode(obj)
}

ale's avatar
ale committed
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
type URLInfo struct {
	URL        string
	StatusCode int
	CrawledAt  time.Time
	Error      error
}

type Fetcher interface {
	Fetch(string) (*http.Response, error)
}

type FetcherFunc func(string) (*http.Response, error)

func (f FetcherFunc) Fetch(u string) (*http.Response, error) {
	return f(u)
}

type Handler interface {
	Handle(*Crawler, string, int, *http.Response, error) error
}

type HandlerFunc func(*Crawler, string, int, *http.Response, error) error

func (f HandlerFunc) Handle(db *Crawler, u string, depth int, resp *http.Response, err error) error {
	return f(db, u, depth, resp, err)
}

ale's avatar
ale committed
99
// UrlDb is the database of crawled URLs (either pending or done).
ale's avatar
ale committed
100 101 102
type Crawler struct {
	db      *gobDB
	seeds   []*url.URL
ale's avatar
ale committed
103
	scopes  []Scope
ale's avatar
ale committed
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
	fetcher Fetcher
	handler Handler

	enqueueMx sync.Mutex
}

type QueuePair struct {
	Key   []byte
	URL   string
	Depth int
}

// Update this URLInfo entry in the crawl database.
func (c *Crawler) UpdateURL(info *URLInfo) error {
	wo := levigo.NewWriteOptions()
	defer wo.Close()
	return c.db.PutObj(wo, []byte(fmt.Sprintf("url/%s", info.URL)), info)
}

// Enqueue a (possibly new) URL for processing.
func (c *Crawler) Enqueue(u *url.URL, depth int) {
	// Normalize the URL.
	urlStr := purell.NormalizeURL(u, purell.FlagsSafe|purell.FlagRemoveDotSegments|purell.FlagRemoveDuplicateSlashes|purell.FlagRemoveFragment|purell.FlagRemoveDirectoryIndex|purell.FlagSortQuery)

ale's avatar
ale committed
128 129 130 131 132
	// See if it's in scope. Checks are ANDed.
	for _, sc := range c.scopes {
		if !sc.Check(u, depth) {
			return
		}
ale's avatar
ale committed
133 134
	}

ale's avatar
ale committed
135
	// Protect the read-modify-update below with a mutex.
ale's avatar
ale committed
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
	c.enqueueMx.Lock()
	defer c.enqueueMx.Unlock()

	// Check if we've already seen it.
	var info URLInfo
	ro := levigo.NewReadOptions()
	defer ro.Close()
	ukey := []byte(fmt.Sprintf("url/%s", urlStr))
	if err := c.db.GetObj(ro, ukey, &info); err == nil {
		return
	}

	// Create a unique key using the URL and the current timestamp.
	qkey := []byte(fmt.Sprintf("queue/%d/%s", time.Now().Unix(), urlStr))

	// Store the URL in the queue, and store an empty URLInfo to
	// make sure that subsequent calls to Enqueue with the same
	// URL will fail.
	wo := levigo.NewWriteOptions()
	defer wo.Close()
	c.db.PutObj(wo, qkey, &QueuePair{Key: qkey, URL: urlStr, Depth: depth})
	c.db.PutObj(wo, ukey, &info)
}

// Scan the queue for URLs until there are no more.
func (c *Crawler) process() <-chan QueuePair {
	ch := make(chan QueuePair)
	go func() {
		queuePrefix := []byte("queue/")
		for range time.Tick(2 * time.Second) {
			n := 0

			// Scan the queue using a snapshot, to ignore
			// new URLs that might be added after this.
			s := c.db.NewSnapshot()
			ro := levigo.NewReadOptions()
			ro.SetSnapshot(s)

ale's avatar
ale committed
174 175
			iter := c.db.NewPrefixIterator(ro, queuePrefix)
			for ; iter.Valid(); iter.Next() {
ale's avatar
ale committed
176
				var p QueuePair
ale's avatar
ale committed
177
				if err := iter.Value(&p); err != nil {
ale's avatar
ale committed
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
					continue
				}
				ch <- p
				n++
			}
			iter.Close()

			ro.Close()
			c.db.ReleaseSnapshot(s)

			if n == 0 {
				break
			}
		}
		close(ch)
	}()
	return ch
}

// Main worker loop.
func (c *Crawler) urlHandler(queue <-chan QueuePair) {
	for p := range queue {
		// Fetch the URL and handle it. Make sure to Close the
		// response body (even if it gets replaced in the
		// Response object).
		fmt.Printf("%s\n", p.URL)
		httpResp, httpErr := c.fetcher.Fetch(p.URL)
		respBody := httpResp.Body
		err := c.handler.Handle(c, p.URL, p.Depth, httpResp, httpErr)
		if httpErr == nil {
			respBody.Close()
		}

		// Remove the URL from the queue if the handler was successful.
		if err == nil {
			wo := levigo.NewWriteOptions()
			c.db.Delete(wo, p.Key)
			wo.Close()
		} else {
			log.Printf("error handling %s: %v", p.URL, err)
		}
	}
}

func MustParseURLs(urls []string) []*url.URL {
	// Parse the seed URLs.
	var parsed []*url.URL
	for _, s := range urls {
		u, err := url.Parse(s)
		if err != nil {
			log.Fatalf("error parsing seed \"%s\": %v", s, err)
		}
		parsed = append(parsed, u)
	}
	return parsed
}

// NewCrawler creates a new Crawler object with the specified behavior.
ale's avatar
ale committed
236
func NewCrawler(path string, seeds []*url.URL, scopes []Scope, f Fetcher, h Handler) (*Crawler, error) {
ale's avatar
ale committed
237 238 239 240 241 242 243 244 245 246
	// Open the crawl database.
	db, err := newGobDB(path)
	if err != nil {
		return nil, err
	}
	c := &Crawler{
		db:      db,
		fetcher: f,
		handler: &standardPageHandler{h},
		seeds:   seeds,
ale's avatar
ale committed
247
		scopes:  scopes,
ale's avatar
ale committed
248 249 250 251
	}
	return c, nil
}

252 253 254
// Run the crawl with the specified number of workers. This function
// does not exit until all work is done (no URLs left in the queue).
func (c *Crawler) Run(concurrency int) {
ale's avatar
ale committed
255 256 257 258 259 260 261 262
	// Load initial seeds into the queue.
	for _, u := range c.seeds {
		c.Enqueue(u, 0)
	}

	// Start some runners and wait until they're done.
	var wg sync.WaitGroup
	ch := c.process()
263
	for i := 0; i < concurrency; i++ {
ale's avatar
ale committed
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
		wg.Add(1)
		go func() {
			c.urlHandler(ch)
			wg.Done()
		}()
	}
	wg.Wait()
}

// Standard page handler, follows redirects and invokes a child
// handler when status == 200.
type standardPageHandler struct {
	h Handler
}

func (wrap *standardPageHandler) Handle(c *Crawler, u string, depth int, resp *http.Response, err error) error {
	info := &URLInfo{URL: u, CrawledAt: time.Now()}
	if err == nil {
		info.StatusCode = resp.StatusCode
		if resp.StatusCode == 200 {
			err = wrap.h.Handle(c, u, depth, resp, err)
		} else if resp.StatusCode > 300 && resp.StatusCode < 400 {
			location := resp.Header.Get("Location")
			if location != "" {
				locationUrl, err := resp.Request.URL.Parse(location)
				if err != nil {
					log.Printf("error parsing Location header: %v", err)
				} else {
					c.Enqueue(locationUrl, depth+1)
				}
			}
		} else {
			err = errors.New(resp.Status)
		}
	}
	info.Error = err

	c.UpdateURL(info)
	return nil
}