summaryrefslogtreecommitdiff
path: root/main.go
blob: 567344113227b1e76f002557cd7c4245ca840771 (plain)
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
// URLs implements a breadth-first search webcrawler based on the
// example given in section 8.6 of The Go Programming Language.
package main

import (
	"flag"
	"fmt"
	"log"
	"net/url"
	"runtime/pprof"
	"strings"
	"time"
)

func main() {
	maxConcurrency := flag.Int("c", 0, "Maximum number of concurrent queue pushes")
	startRawURL := flag.String("url", "", "Entry-point URL")
	maxURLs := flag.Int("max", 0, "Maximum number of URLs to collect (omitted or 0 means no limit)")

	flag.Parse()

	if *maxConcurrency == 0 {
		log.Fatal("Missing -c argument")
	}

	if *maxConcurrency < 1 {
		log.Fatalf("Invalid -c argument: %d", *maxConcurrency)
	}

	if *startRawURL == "" {
		log.Fatal("Missing -url argument")
	}

	if *maxURLs < 0 {
		log.Fatalf("Invalid -max argument: %d", *maxURLs)
	}

	startURL, err := url.Parse(*startRawURL)
	if err != nil {
		log.Fatal(err)
	}

	getLeakProfile(func() {
		classic(*startURL, *maxConcurrency, *maxURLs, 1)
	})
}

// getLeakProfile runs a leaky program snippet, extracts the goroutine leak profile,
// and writes it to stdout.
func getLeakProfile(leakySnippet func()) {
	prof := pprof.Lookup("goroutineleak")
	defer func() {
		time.Sleep(2 * time.Second)
		var content strings.Builder

		prof.WriteTo(&content, 2)
		// Ignore non leaked goroutines
		leaks := strings.SplitSeq(content.String(), "\n\n")
		for leak := range leaks {
			if strings.Contains(leak, "(leaked)") {
				fmt.Println(leak + "\n")
			}
		}
	}()

	leakySnippet()
}