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
|
type CrawlTask struct {
URL string
Priority int
ScheduledTime time.Time
RetryCount int
}
type MachineStatus struct {
MachineID string
IPAddress string
LastHeartbeat time.Time
IsBlacklisted bool
CrawlRate int
}
type CrawlResult struct {
URL string
Content string
ExtractedLinks []string
Timestamp time.Time
Success bool
IsBlacklisted bool
}
type MasterServer struct {
visitedUrls map[string]bool
taskQueue chan CrawlTask
machines map[string]*MachineStatus
rateLimits map[string]time.Time
mutex sync.RWMutex
}
func NewMasterServer() *MasterServer {
return &MasterServer{
visitedUrls: make(map[string]bool),
taskQueue: make(chan CrawlTask, 1000000),
machines: make(map[string]*MachineStatus),
rateLimits: make(map[string]time.Time),
}
}
func (ms *MasterServer) InitializeCrawl(seedUrls []string) {
for _, url := range seedUrls {
ms.taskQueue <- CrawlTask{
URL: url,
Priority: 1,
ScheduledTime: time.Now(),
RetryCount: 0,
}
}
}
func (ms *MasterServer) AssignTask(machineID string) (CrawlTask, error) {
ms.updateMachineHeartbeat(machineID)
select {
case task := <-ms.taskQueue:
domain := ms.extractDomain(task.URL)
ms.mutex.Lock()
if rateLimit, exists := ms.rateLimits[domain]; exists && time.Now().Before(rateLimit) {
// Re-queue with delay
task.ScheduledTime = rateLimit.Add(time.Second)
ms.taskQueue <- task
ms.mutex.Unlock()
return ms.AssignTask(machineID)
}
ms.visitedUrls[task.URL] = true
ms.rateLimits[domain] = time.Now().Add(time.Second)
ms.mutex.Unlock()
return task, nil
case <-time.After(5 * time.Second):
return CrawlTask{}, fmt.Errorf("no tasks available")
}
}
func (ms *MasterServer) SubmitResults(machineID string, result CrawlResult) {
// Store in database
ms.storePageContent(result)
// Extract and queue new URLs
for _, link := range result.ExtractedLinks {
ms.mutex.RLock()
if !ms.visitedUrls[link] {
ms.taskQueue <- CrawlTask{
URL: link,
Priority: 2,
ScheduledTime: time.Now(),
RetryCount: 0,
}
}
ms.mutex.RUnlock()
}
}
func (ms *MasterServer) HandleMachineFailure(machineID string) {
ms.mutex.Lock()
if machine, exists := ms.machines[machineID]; exists {
machine.IsBlacklisted = true
}
ms.mutex.Unlock()
// Redistribute pending tasks
ms.redistributeTasks(machineID)
}
func (ms *MasterServer) extractDomain(url string) string {
if idx := strings.Index(url, "://"); idx != -1 {
url = url[idx+3:]
}
if idx := strings.Index(url, "/"); idx != -1 {
url = url[:idx]
}
return url
}
func (ms *MasterServer) updateMachineHeartbeat(machineID string) {
ms.mutex.Lock()
if machine, exists := ms.machines[machineID]; exists {
machine.LastHeartbeat = time.Now()
} else {
ms.machines[machineID] = &MachineStatus{
MachineID: machineID,
LastHeartbeat: time.Now(),
IsBlacklisted: false,
}
}
ms.mutex.Unlock()
}
func (ms *MasterServer) storePageContent(result CrawlResult) {
// Database storage implementation
}
func (ms *MasterServer) redistributeTasks(failedMachine string) {
// Implementation for task redistribution
}
type WorkerMachine struct {
machineID string
master *MasterServer
proxyList []string
currentProxyIndex int
client *http.Client
}
func NewWorkerMachine(machineID string, master *MasterServer) *WorkerMachine {
return &WorkerMachine{
machineID: machineID,
master: master,
proxyList: []string{"proxy1.com", "proxy2.com", "proxy3.com"},
client: &http.Client{Timeout: 30 * time.Second},
}
}
func (wm *WorkerMachine) StartCrawling() {
for {
task, err := wm.master.AssignTask(wm.machineID)
if err != nil {
time.Sleep(5 * time.Second)
continue
}
result := wm.crawlPage(task.URL)
if result.Success {
wm.master.SubmitResults(wm.machineID, result)
} else if result.IsBlacklisted {
wm.rotateProxy()
wm.master.HandleMachineFailure(wm.machineID)
}
// Rate limiting
time.Sleep(100 * time.Millisecond)
}
}
func (wm *WorkerMachine) crawlPage(url string) CrawlResult {
result := CrawlResult{
URL: url,
Timestamp: time.Now(),
}
resp, err := wm.client.Get(url)
if err != nil {
result.Success = false
return result
}
defer resp.Body.Close()
if resp.StatusCode == 429 || resp.StatusCode == 403 {
result.IsBlacklisted = true
result.Success = false
return result
}
body, err := io.ReadAll(resp.Body)
if err != nil {
result.Success = false
return result
}
result.Content = string(body)
result.ExtractedLinks = wm.parseLinks(result.Content)
result.Success = true
return result
}
func (wm *WorkerMachine) rotateProxy() {
wm.currentProxyIndex = (wm.currentProxyIndex + 1) % len(wm.proxyList)
// Update HTTP client with new proxy
}
func (wm *WorkerMachine) parseLinks(html string) []string {
var links []string
// HTML parsing implementation using regex or parser
re := regexp.MustCompile(`href="(/wiki/[^"]*)"`)
matches := re.FindAllStringSubmatch(html, -1)
for _, match := range matches {
if len(match) > 1 {
links = append(links, "https://en.wikipedia.org"+match[1])
}
}
return links
}
func RunDistributedCrawl(seedUrls []string, numMachines int) {
master := NewMasterServer()
master.InitializeCrawl(seedUrls)
var wg sync.WaitGroup
for i := 0; i < numMachines; i++ {
wg.Add(1)
go func(machineID string) {
defer wg.Done()
worker := NewWorkerMachine(machineID, master)
worker.StartCrawling()
}(fmt.Sprintf("machine-%d", i))
}
wg.Wait()
}
|