-
-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathmain.go
More file actions
1787 lines (1590 loc) · 61.5 KB
/
main.go
File metadata and controls
1787 lines (1590 loc) · 61.5 KB
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
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2023 Paolo Fabio Zaino
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package main (TheCROWler) is the application.
// It's responsible for starting the crawler and kickstart the configuration
// reading and the database connection.
// Actual crawling is performed by the pkg/crawler package.
// The database connection is handled by the pkg/database package.
// The configuration is handled by the pkg/config package.
// Page info extraction is handled by the pkg/scrapper package.
package main
import (
"encoding/json"
"flag"
"fmt"
"math"
"net/http"
"os"
"os/signal"
"runtime"
"runtime/debug"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/push"
cmn "github.com/pzaino/thecrowler/pkg/common"
cfg "github.com/pzaino/thecrowler/pkg/config"
crowler "github.com/pzaino/thecrowler/pkg/crawler"
cdb "github.com/pzaino/thecrowler/pkg/database"
rules "github.com/pzaino/thecrowler/pkg/ruleset"
vdi "github.com/pzaino/thecrowler/pkg/vdi"
"golang.org/x/time/rate"
_ "github.com/lib/pq"
)
// PipelineStatusReport is a struct that holds the status report of a crawling pipeline.
type PipelineStatusReport struct {
PipelineID uint64 `json:"pipeline_id"`
Source string `json:"source"`
SourceID uint64 `json:"source_id"`
VDIID string `json:"vdi_id"`
ContextID string `json:"context_id"`
PipelineStatus string `json:"pipeline_status"`
CrawlingStatus string `json:"crawling_status"`
NetInfoStatus string `json:"netinfo_status"`
HTTPInfoStatus string `json:"httpinfo_status"`
RunningTime string `json:"running_time"`
TotalPages int64 `json:"total_pages"`
TotalErrors int64 `json:"total_errors"`
TotalLinks int64 `json:"total_links"`
TotalSkipped int64 `json:"total_skipped"`
TotalDuplicates int64 `json:"total_duplicates"`
TotalLinksToGo int64 `json:"total_links_to_go"`
TotalScrapes int64 `json:"total_scrapes"`
TotalActions int64 `json:"total_actions"`
LastRetry int64 `json:"last_retry"`
LastWait float64 `json:"last_wait"`
LastDelay float64 `json:"last_delay"`
CollectionState string `json:"collection_state"`
}
var (
limiter *rate.Limiter // Rate limiter
configFile *string // Configuration file path
config cfg.Config // Configuration "object"
configMutex sync.RWMutex // Mutex to protect the configuration
sysReadyMtx sync.RWMutex // Mutex to protect the SysReady variable
sysReady int // System readiness status variable 0 = not ready, 1 = starting up, 2 = ready
// GRulesEngine Global rules engine
GRulesEngine rules.RuleEngine // GRulesEngine Global rules engine
// Global DB handler
dbHandler cdb.Handler
// Global Pipeline Status (read only!!!!!)
sysPipelineStatus *[]crowler.Status
)
// WorkBlock is a struct that holds all the necessary information to instantiate a new
// crawling job on the pipeline. It's used to pass the information to the goroutines
// that will perform the actual crawling.
type WorkBlock struct {
db cdb.Handler
//sel *chan vdi.SeleniumInstance
sel *vdi.Pool
sources *[]cdb.Source
RulesEngine *rules.RuleEngine
PipelineStatus *[]crowler.Status
Config *cfg.Config
}
// HealthCheck is a struct that holds the health status of the application.
type HealthCheck struct {
Status string `json:"status"`
}
// ReadyCheck is a struct that holds the system readiness status.
type ReadyCheck struct {
Status string `json:"ready"`
}
func setSysReady(newStatus int) {
if newStatus < 0 || newStatus > 2 {
return
}
sysReadyMtx.Lock()
defer sysReadyMtx.Unlock()
sysReady = newStatus
}
func getSysReady() int {
sysReadyMtx.RLock()
defer sysReadyMtx.RUnlock()
return sysReady
}
// NewVDIPool is a function that creates a new VDI pool with the given configurations.
func NewVDIPool(p *vdi.Pool, configs []cfg.Selenium) error {
p.Init(len(configs))
if p == nil {
return fmt.Errorf("creating VDI pool")
}
// Initialize the pool with the Selenium instances
for i, seleniumConfig := range configs {
selService, err := vdi.NewVDIService(seleniumConfig)
if err != nil {
return fmt.Errorf("creating VDI Instances: %s", err)
}
cmn.DebugMsg(cmn.DbgLvlDebug2, "VDI instance %s:%d:%d created", seleniumConfig.Host, seleniumConfig.Port, i)
selInstance := vdi.SeleniumInstance{
Service: selService,
Config: seleniumConfig,
}
err = p.Add(selInstance)
if err != nil {
return fmt.Errorf("adding VDI instance to pool: %s", err)
}
cmn.DebugMsg(cmn.DbgLvlDebug2, "VDI instance added to the pool")
}
return nil
}
// This function is responsible for performing database maintenance
// to keep it lean and fast. Note: it's specific for PostgreSQL.
func performDBMaintenance(db cdb.Handler) error {
if db.DBMS() == cdb.DBSQLiteStr {
return nil
}
// Define the maintenance commands
var maintenanceCommands []string
if db.DBMS() == cdb.DBPostgresStr {
maintenanceCommands = []string{
"VACUUM Keywords",
"VACUUM MetaTags",
"VACUUM WebObjects",
"VACUUM SearchIndex",
"VACUUM KeywordIndex",
"VACUUM MetaTagsIndex",
"VACUUM WebObjectsIndex",
"REINDEX TABLE WebObjects",
"REINDEX TABLE SearchIndex",
"REINDEX TABLE KeywordIndex",
"REINDEX TABLE WebObjectsIndex",
"REINDEX TABLE MetaTagsIndex",
"REINDEX TABLE NetInfoIndex",
"REINDEX TABLE HTTPInfoIndex",
"REINDEX TABLE SourceInformationSeedIndex",
"REINDEX TABLE SourceOwnerIndex",
"REINDEX TABLE SourceSearchIndex",
}
}
for _, cmd := range maintenanceCommands {
_, err := db.Exec(cmd)
if err != nil {
return fmt.Errorf("error executing maintenance command (%s): %w", cmd, err)
}
}
return nil
}
// This function simply query the database for URLs that need to be crawled
func retrieveAvailableSources(db cdb.Handler, maxSources int) ([]cdb.Source, error) {
// Check DB connection:
if err := db.CheckConnection(config); err != nil {
return nil, fmt.Errorf("error pinging the database: %w", err)
}
// Start a transaction
tx, err := db.Begin()
if err != nil {
return nil, err
}
// Update the SQL query to fetch all necessary fields
query := `
SELECT
l.source_id,
l.url,
l.restricted,
l.flags,
l.config
FROM
update_sources($1,$2,$3,$4,$5,$6,$7) AS l
ORDER BY l.last_updated_at ASC;`
// Execute the query within the transaction
if maxSources <= 0 {
maxSources = config.Crawler.MaxSources
}
rows, err := tx.Query(query, maxSources, config.Crawler.SourcePriority, cmn.GetEngineID(), config.Crawler.CrawlingIfOk, config.Crawler.CrawlingIfError, config.Crawler.CrawlingInterval, config.Crawler.ProcessingTimeout)
if err != nil {
err2 := tx.Rollback()
if err2 != nil {
cmn.DebugMsg(cmn.DbgLvlError, "rolling back transaction: %v", err2)
}
return nil, err
}
// Iterate over the results and store them in a slice
var sourcesToCrawl []cdb.Source
for rows.Next() {
var src cdb.Source
if err := rows.Scan(&src.ID, &src.URL, &src.Restricted, &src.Flags, &src.Config); err != nil {
cmn.DebugMsg(cmn.DbgLvlError, "scanning rows: %v", err)
err2 := rows.Close()
if err2 != nil {
cmn.DebugMsg(cmn.DbgLvlError, "closing rows iterator: %v", err2)
}
err2 = tx.Rollback()
if err2 != nil {
cmn.DebugMsg(cmn.DbgLvlError, "rolling back transaction: %v", err2)
}
return nil, err
}
// Check if Config is nil and assign a default configuration if so
if src.Config == nil {
src.Config = new(json.RawMessage)
*src.Config = cdb.DefaultSourceCfgJSON
}
// Append the source to the slice
sourcesToCrawl = append(sourcesToCrawl, src)
src = cdb.Source{} // Reset the source
}
err = rows.Close() // Close the rows iterator
if err != nil {
cmn.DebugMsg(cmn.DbgLvlError, "closing rows iterator: %v", err)
}
// Commit the transaction if everything is successful
if err := tx.Commit(); err != nil {
return nil, err
}
return sourcesToCrawl, nil
}
/*sel *chan vdi.SeleniumInstance */
// This function is responsible for checking the database for URLs that need to be crawled
// and kickstart the crawling process for each of them
func checkSources(db *cdb.Handler, sel *vdi.Pool, RulesEngine *rules.RuleEngine) {
cmn.DebugMsg(cmn.DbgLvlInfo, "Checking sources...")
// Initialize the pipeline status slice
PipelineStatus := make([]crowler.Status, 0, len(config.Selenium))
// Assign the global pipeline status pointer
sysPipelineStatus = &PipelineStatus
now := time.Now()
// Set the maintenance time
maintenanceTime := now.Add(time.Duration(config.Crawler.Maintenance) * time.Minute)
// Set the resource release time
resourceReleaseTime := now.Add(time.Duration(5) * time.Minute)
// Flag used to avoid repeating 0 sources found constantly
gotSources := true // set to true by default for first source check (so it will log the first time)
// Start the main loop
defer configMutex.RUnlock()
for {
configMutex.RLock()
if !config.Crawler.Schedule.IsActive(time.Now()) {
// We are not active right now, so we can handle signals for reloading the configuration
configMutex.RUnlock()
time.Sleep(time.Duration(config.Crawler.QueryTimer) * time.Second)
continue
}
// Retrieve the sources to crawl
sourcesToCrawl, err := retrieveAvailableSources(*db, 0)
if err != nil {
cmn.DebugMsg(cmn.DbgLvlError, "retrieving sources: %v", err)
// We are about to go to sleep, so we can handle signals for reloading the configuration
configMutex.RUnlock()
time.Sleep(time.Duration(config.Crawler.QueryTimer) * time.Second)
continue
}
// Check if there are sources to crawl
if len(sourcesToCrawl) == 0 {
if gotSources {
cmn.DebugMsg(cmn.DbgLvlDebug2, "No sources to crawl, sleeping...")
gotSources = false
}
// Perform database maintenance if it's time
now := time.Now()
if now.After(maintenanceTime) {
performDatabaseMaintenance(*db)
maintenanceTime = now.Add(time.Duration(config.Crawler.Maintenance) * time.Minute)
cmn.DebugMsg(cmn.DbgLvlDebug2, "Database maintenance every: %d", config.Crawler.Maintenance)
}
// We are about to go to sleep, so we can handle signals for reloading the configuration
configMutex.RUnlock()
if now.After(resourceReleaseTime) {
// Release unneeded resources:
runtime.GC() // Run the garbage collector
debug.FreeOSMemory() // Force release of unused memory to the OS
resourceReleaseTime = now.Add(time.Duration(5) * time.Minute)
}
time.Sleep(time.Duration(config.Crawler.QueryTimer) * time.Second)
continue
}
cmn.DebugMsg(cmn.DbgLvlDebug2, "Sources to crawl: %d", len(sourcesToCrawl))
gotSources = true
// Crawl each source
workBlock := WorkBlock{
db: *db,
sel: sel,
sources: &sourcesToCrawl,
RulesEngine: RulesEngine,
PipelineStatus: &PipelineStatus,
Config: &config,
}
// Create a new WorkBlock for the crawling job
batchUID := cmn.GenerateUID()
event := cdb.Event{
Action: "new",
Type: "started_batch_crawling",
SourceID: 0,
Severity: config.Crawler.SourcePriority,
ExpiresAt: time.Now().Add(2 * time.Minute).Format(time.RFC3339),
Details: map[string]interface{}{
"uid": batchUID,
"node": cmn.GetMicroServiceName(),
"time": time.Now(),
"initial_batch_size": len(sourcesToCrawl),
},
}
createEvent(*db, event, 0)
totSrc := crawlSources(&workBlock) // Start the crawling of this batch of sources
event = cdb.Event{
Action: "new",
Type: "completed_batch_crawling",
SourceID: 0,
Severity: config.Crawler.SourcePriority,
ExpiresAt: time.Now().Add(2 * time.Minute).Format(time.RFC3339),
Details: map[string]interface{}{
"uid": batchUID,
"node": cmn.GetMicroServiceName(),
"time": time.Now(),
"final_batch_size": totSrc,
},
}
createEvent(*db, event, 0)
cmn.DebugMsg(cmn.DbgLvlInfo, "Crawled '%d' sources in this batch", totSrc)
// We have completed all jobs, so we can handle signals for reloading the configuration
configMutex.RUnlock()
sourcesToCrawl = []cdb.Source{} // Reset the sources
}
}
func performDatabaseMaintenance(db cdb.Handler) {
cmn.DebugMsg(cmn.DbgLvlInfo, "Performing database maintenance...")
if err := performDBMaintenance(db); err != nil {
cmn.DebugMsg(cmn.DbgLvlError, "performing database maintenance: %v", err)
} else {
cmn.DebugMsg(cmn.DbgLvlInfo, "Database maintenance completed successfully.")
}
}
func createEvent(db cdb.Handler, event cdb.Event, flags int) {
event.Action = strings.ToLower(strings.TrimSpace(event.Action))
if (event.Action == "") && (flags&1 == 0) {
cmn.DebugMsg(cmn.DbgLvlError, "Action field is empty, ignoring event")
return
}
if event.Action == "new" { // nolint:goconst // it's ok here to have a duplicate "new"
_, err := cdb.CreateEventWithRetries(&db, event)
if err == nil {
return // success!
}
// Final failure
cmn.DebugMsg(cmn.DbgLvlError, "Failed to create event on the DB after retries: %v", err)
}
}
func getEngineID() int {
engineName := cmn.GetMicroServiceName()
engineMultiplier := 1
// The engine ID is usually preceded by either a - or a _
// So check if it contains either of them, if yes try to use them to extract the last part, otherwise use the last two chars
if strings.Contains(engineName, "-") {
parts := strings.Split(engineName, "-")
lastPart := parts[len(parts)-1]
if id, err := strconv.Atoi(lastPart); err == nil {
engineMultiplier = id
}
} else if strings.Contains(engineName, "_") {
parts := strings.Split(engineName, "_")
lastPart := parts[len(parts)-1]
if id, err := strconv.Atoi(lastPart); err == nil {
engineMultiplier = id
}
} else if len(engineName) > 2 {
lastPart := engineName[len(engineName)-2:]
if id, err := strconv.Atoi(lastPart); err == nil {
engineMultiplier = id
}
}
return engineMultiplier
}
func crawlSources(wb *WorkBlock) uint64 {
var (
batchWg sync.WaitGroup
refillLock cmn.SafeMutex // Mutex to protect the refill operation
closeChanOnce sync.Once
statusLock sync.Mutex // Mutex to protect the PipelineStatus slice
TotalSources atomic.Uint64 // Total Crawled Sources Counter
BatchCompleted atomic.Bool // Entire Batch Completed (included Refills)
LastActivity atomic.Value // Last Activity Timestamp
PipelinesRunning atomic.Bool // Pipelines are currently running
RampUpRunning atomic.Bool // Ramp Up is currently running
BusyInstances atomic.Int32 // Number of busy pipelines
)
TotalSources.Store(0)
BatchCompleted.Store(false)
LastActivity.Store(time.Now())
PipelinesRunning.Store(true)
RampUpRunning.Store(true)
BusyInstances.Store(0)
// Create the sources' queue (channel)
sourceChan := make(chan cdb.Source, wb.Config.Crawler.MaxSources*2)
maxPipelines := len(config.Selenium) //nolint:gosec
cmn.DebugMsg(cmn.DbgLvlDebug, "[DEBUG-Pipeline] Max pipelines: %d", maxPipelines)
cmn.DebugMsg(cmn.DbgLvlDebug, "[DEBUG-Pipeline] Max sources: %d", wb.Config.Crawler.MaxSources*2)
// "Reports" go routine, used to produce periodic reports on the pipelines status (during crawling):
go func(plStatus *[]crowler.Status) {
interval := time.Duration(wb.Config.Crawler.ReportInterval) * time.Minute
now := time.Now()
next := now.Add(interval)
for {
anyPipelineStillRunning := false
for idx := range *plStatus {
status := &(*plStatus)[idx]
if status.PipelineRunning.Load() > 0 {
anyPipelineStillRunning = true
break
}
}
// Run the log
logStatus(plStatus)
// Exit condition
if !anyPipelineStillRunning && !RampUpRunning.Load() {
PipelinesRunning.Store(false)
break
}
// Sleep until the exact next interval boundary
time.Sleep(time.Until(next))
next = next.Add(interval)
}
}(wb.PipelineStatus)
// "Refill" go routine: (used to avoid pipeline starvation during crawling)
go func() {
inactivityTimeout := 60 * time.Second
timer := time.NewTimer(inactivityTimeout)
// Determine the target queue capacity for refilling decisions
targetCap := cap(sourceChan)
if targetCap == 0 {
// Unbuffered or unknown: fall back to VDIs count so we don’t block forever
targetCap = len(wb.Config.Selenium)
}
// Optional: low/high water marks to smooth bursts
lowWater := targetCap / 2 // start refilling when queue drops below this
highWater := targetCap // never exceed channel cap
// helper to reset timer
resetTimer := func() {
if !timer.Stop() {
select {
case <-timer.C:
default:
}
}
timer.Reset(inactivityTimeout)
}
defer func() {
// make sure timer is stopped/drained to avoid leaks
if !timer.Stop() {
select {
case <-timer.C:
default:
}
}
defer func() {
recover() //nolint:errcheck // avoid panic if somehow closed elsewhere
}()
closeChanOnce.Do(func() {
close(sourceChan)
BatchCompleted.Store(true)
cmn.DebugMsg(cmn.DbgLvlInfo, "No new sources received in the last %v — closing pipeline.", inactivityTimeout)
refillLock.Unlock() // this is a special lock which is self-aware, so we can safely try to unlock it here to ensure that if is locked we'll unlock and if it isn't we won't panic
})
}()
// ensure LastActivity sane
if v := LastActivity.Load(); v == nil {
LastActivity.Store(time.Now())
}
for {
select {
case <-timer.C:
// Timeout expired → no new sources, close pipeline
if PipelinesRunning.Load() || RampUpRunning.Load() {
last := LastActivity.Load().(time.Time)
if time.Since(last) < (1 * time.Minute) {
// Yes, so reset the timer anyway
resetTimer()
continue
}
PipelinesRunning.Store(false)
RampUpRunning.Store(false)
BatchCompleted.Store(true)
time.Sleep(15 * time.Second) // Give some time to the pipelines to complete
} else {
cmn.DebugMsg(cmn.DbgLvlInfo, "No new sources received in the last %v — closing pipeline.", inactivityTimeout)
return
}
default:
refillLock.Lock()
// First let's check if we are still in an active schedule:
configMutex.RLock()
if !wb.Config.Crawler.Schedule.IsActive(time.Now()) {
// Not active, so we can close the channel and exit
configMutex.RUnlock()
BatchCompleted.Store(true)
closeChanOnce.Do(func() {
close(sourceChan)
cmn.DebugMsg(cmn.DbgLvlInfo, "Crawling schedule is no longer active — closing pipeline.")
})
refillLock.Unlock()
return
}
configMutex.RUnlock()
// We are in active schedule, so check if we need to refill the source channel
if (wb.sel.Available() > 0) && (len(sourceChan) < lowWater) {
// We need to refill the source channel
need := highWater - len(sourceChan)
newSources := []cdb.Source{}
var err error
if !BatchCompleted.Load() {
newSources, err = monitorBatchAndRefill(wb, need)
}
if err != nil {
cmn.DebugMsg(cmn.DbgLvlWarn, "monitorBatchAndRefill error: %v", err)
} else if len(newSources) > 0 {
LastActivity.Store(time.Now()) // Reset activity
cmn.DebugMsg(cmn.DbgLvlDebug, "[DEBUG-Refill] Refilling batch with %d new sources", len(newSources))
if !BatchCompleted.Load() {
for _, src := range newSources {
sourceChan <- src
}
// Reset the timer because we received new sources
resetTimer()
}
} else {
// no data returned, but are we still collecting from sources?
last := LastActivity.Load().(time.Time)
if time.Since(last) < (1 * time.Minute) {
// Yes, so reset the timer anyway
resetTimer()
}
}
} else if (wb.sel.Available() == 0) || (len(sourceChan) >= highWater) {
// Reset the timer, we are busy
resetTimer()
}
refillLock.Unlock()
time.Sleep(2 * time.Second) // Avoid tight loop
}
}
}()
// "Inactivity Watchdog" (used to clean up pipelines that may be gone stale):
go func() {
ticker := time.NewTicker(30 * time.Second) // check every 30 seconds
defer ticker.Stop()
for { //nolint:gosimple // infinite loop is intentional
select {
case <-ticker.C:
last := LastActivity.Load().(time.Time)
if (time.Since(last) > (5 * time.Minute)) && !PipelinesRunning.Load() && !RampUpRunning.Load() {
cmn.DebugMsg(cmn.DbgLvlInfo, "No crawling activity for 5 minutes, closing sourceChan.")
closeChanOnce.Do(func() {
BatchCompleted.Store(true) // Set the batch as completed
close(sourceChan)
cmn.DebugMsg(cmn.DbgLvlInfo, "Closed sourceChan")
})
return
} // else, reset the timer
ticker.Reset(30 * time.Second) // Reset the ticker to avoid tight loop
}
}
}()
// Function to refresh the last activity timestamp (from external functions)
RefreshLastActivity := func() {
LastActivity.Store(time.Now())
}
// Get engine name and if it has an ID at the end use it as a multiplier
engineMultiplier := getEngineID()
ramp := config.Crawler.InitialRampUp
if ramp < 0 {
// Calculate the ramp-up factor based on the number of sources and the number of Selenium instances
if len(config.Selenium) > 0 {
ramp = config.Crawler.MaxSources / len(config.Selenium)
} else {
ramp = 1 // fallback: minimal ramping
}
}
cmn.DebugMsg(cmn.DbgLvlDebug, "[DEBUG-Pipeline] Ramp-up factor: %d (engine multiplier: %d)", ramp, engineMultiplier)
// First batch load into the queue: (initial load)
LastActivity.Store(time.Now()) // Reset activity
for _, source := range *wb.sources {
sourceChan <- source
}
LastActivity.Store(time.Now()) // Reset activity
for vdiID := 0; vdiID < maxPipelines; vdiID++ {
RefreshLastActivity() // Reset activity
if ramp > 0 {
PipelinesRunning.Store(true)
if vdiID > 0 {
// Sleep for a ramp-up time based on the VDI ID and the ramp factor
_, _ = waitSomeTime(float64(ramp), RefreshLastActivity)
}
}
batchWg.Add(1)
go func(vdiSlot int) {
defer batchWg.Done()
var (
currentStatusIdx *int
starves int // Counter for starvation
)
RefreshLastActivity() // Reset activity
for {
var source cdb.Source
if !BatchCompleted.Load() {
var ok bool
// Fetch next available source in the queue:
select {
case source, ok = <-sourceChan:
if !ok {
// Channel is closed, let's check if we need to quit or not:
cmn.DebugMsg(cmn.DbgLvlDebug2, "[DEBUG-Pipeline] Batch completed, exiting goroutine for VDI slot %d", vdiSlot)
return
}
default:
// No source available right now
starves++
if starves > 5 {
cmn.DebugMsg(cmn.DbgLvlDebug2, "[DEBUG-Pipeline] No sources available for 5 iterations for VDI slot %d", vdiSlot)
starves = 0 // Reset starvation counter
// sleep 2 seconds and continue
time.Sleep(2 * time.Second)
} else {
// short sleep to avoid tight loop
time.Sleep(200 * time.Millisecond)
}
continue
}
} else {
// Batch is completed, exit the goroutine
cmn.DebugMsg(cmn.DbgLvlDebug2, "[DEBUG-Pipeline] Batch completed, exiting goroutine for VDI slot %d", vdiSlot)
return
}
starves = 0 // Reset starvation counter
RefreshLastActivity() // Reset activity
TotalSources.Add(1) // Increment the total sources counter
BusyInstances.Add(1) // Increment busy instances counter
// This makes sur we reuse always the same PipelineStatus index
// for this goroutine instance:
var statusIdx int
// Getting a new status index must be protected by a lock
statusLock.Lock()
if currentStatusIdx == nil {
// Get a new or available pipeline status index
// (at startup or when extra data collections are ongoing and we need to move on to the next web collection)
statusIdx = getAvailableOrNewPipelineStatus(wb)
} else {
// reuse current status index (we completed all types of collections)
statusIdx = *currentStatusIdx
}
if statusIdx >= len(*wb.PipelineStatus) {
// Safety check, if we are out of bounds, we need to append a new status
*wb.PipelineStatus = append(*wb.PipelineStatus, crowler.Status{})
if len(*wb.PipelineStatus) > maxPipelines {
maxPipelines = len(*wb.PipelineStatus)
}
}
now := time.Now()
(*wb.PipelineStatus)[statusIdx] = crowler.Status{
PipelineID: uint64(statusIdx), //nolint:gosec // it's safe here.
Source: source.URL,
SourceID: source.ID,
VDIID: "",
StartTime: now,
EndTime: time.Time{},
PipelineRunning: atomic.Int32{},
}
(*wb.PipelineStatus)[statusIdx].PipelineRunning.Store(1) // Set the pipeline running status
statusLock.Unlock()
cmn.DebugMsg(cmn.DbgLvlDebug2, "[DEBUG-Pipeline] Received source: %s (ID: %d) for VDI slot %d on Pipeline: %d", source.URL, source.ID, vdiSlot, statusIdx)
// Start crawling the website
// startCrawling will spawn a crawling thread and return, so we need to wait for
// that thread to complete:
var crawlWG sync.WaitGroup
startCrawling(wb, &crawlWG, source, statusIdx, RefreshLastActivity)
crawlWG.Wait()
status := &(*wb.PipelineStatus)[statusIdx]
if status.NetInfoRunning.Load() == 1 || status.HTTPInfoRunning.Load() == 1 {
currentStatusIdx = nil
} else {
currentStatusIdx = &statusIdx
}
RefreshLastActivity() // Reset activity
BusyInstances.Add(-1) // Decrement busy instances counter
if BusyInstances.Load() < 0 {
BusyInstances.Store(0)
}
}
}(vdiID)
// Log the VDI instance started
cmn.DebugMsg(cmn.DbgLvlDebug2, "[DEBUG-Pipeline] Started VDI slot %d", vdiID)
}
RampUpRunning.Store(false) // Ramp-up phase is over
batchWg.Wait()
cmn.DebugMsg(cmn.DbgLvlInfo, "All sources in this batch have been crawled.")
for idx := 0; idx < maxPipelines; idx++ {
if idx < len(*wb.PipelineStatus) {
(*wb.PipelineStatus)[idx].PipelineRunning.Store(0)
}
}
return TotalSources.Load() // Return the total number of sources crawled
}
func waitSomeTime(delay float64, SessionRefresh func()) (time.Duration, error) {
if delay < 1 {
delay = 1
}
divider := math.Log10(delay+1) * 10 // Adjust multiplier as needed
waitDuration := time.Duration(delay) * time.Second
pollInterval := time.Duration(delay/divider) * time.Second // Check every pollInterval seconds to keep alive
cmn.DebugMsg(cmn.DbgLvlDebug3, "[DEBUG-RampUp] Waiting for %v seconds...", delay)
startTime := time.Now()
for time.Since(startTime) < waitDuration {
// Perform a controlled sleep so we can refresh the session timeout if needed
time.Sleep(pollInterval)
// refresh session timeout
if SessionRefresh != nil {
SessionRefresh()
}
}
// Get the total delay
totalDelay := time.Since(startTime)
cmn.DebugMsg(cmn.DbgLvlDebug3, "[DEBUG-RampUp] Waited for %v seconds", totalDelay.Seconds())
return totalDelay, nil
}
func monitorBatchAndRefill(wb *WorkBlock, need int) ([]cdb.Source, error) {
if wb.sel.Available() <= 0 {
return nil, nil
}
if need <= 0 {
need = wb.sel.Available()
}
newSources, err := retrieveAvailableSources(wb.db, need)
if err != nil {
return nil, err
}
return newSources, nil
}
func getAvailableOrNewPipelineStatus(wb *WorkBlock) int {
for idx := range *wb.PipelineStatus {
status := &(*wb.PipelineStatus)[idx]
if status.PipelineRunning.Load() != 1 && status.CrawlingRunning.Load() != 1 &&
status.NetInfoRunning.Load() != 1 && status.HTTPInfoRunning.Load() != 1 {
return idx //nolint:gosec // it's safe here.
}
}
// All are busy or reserved → add a new one
newIdx := len(*wb.PipelineStatus)
*wb.PipelineStatus = append(*wb.PipelineStatus, crowler.Status{
PipelineID: uint64(newIdx),
})
return newIdx
}
func startCrawling(wb *WorkBlock, wg *sync.WaitGroup, source cdb.Source, idx int, refresh func()) {
if wg != nil {
wg.Add(1)
}
// Prepare the go routine parameters
args := crowler.Pars{
WG: wg,
DB: wb.db,
Src: source,
Sel: wb.sel,
SelIdx: 0,
RE: wb.RulesEngine,
Sources: wb.sources,
Index: uint64(idx), //nolint:gosec // it's safe here.
Status: &((*wb.PipelineStatus)[idx]), // Pointer to a single status element
Refresh: refresh,
}
// Start a goroutine to crawl the website
go func(args *crowler.Pars, c *cfg.Config) {
cmn.DebugMsg(cmn.DbgLvlDebug, "[DEBUG-startCrawling] Waiting for available VDI instance...")
// Fetch the next available Selenium instance (VDI)
vdiPool := args.Sel
index, vdiInstance, err := vdiPool.Acquire(c.Crawler.VDIName)
if err != nil {
// There are no available VDI instances right now, log and return an error
cmn.DebugMsg(cmn.DbgLvlWarn, "No VDI available right now: %v", err)
return
}
cmn.DebugMsg(cmn.DbgLvlDebug2, "[DEBUG-startCrawling] Acquired VDI instance '%s' at index %d and host %v", vdiInstance.Config.Name, index, vdiInstance.Config.Host)
args.SelIdx = index // Update the index in the args
// Assign VDI ID to the pipeline status
(*args.Status).VDIID = vdiInstance.Config.Name
// Create a channel that will signal when the VDI is no longer needed
releaseVDI := make(chan vdi.SeleniumInstance, 1) // Make it buffered
// Start the crawling in a separate goroutine
go func() {
crowler.CrawlWebsite(args, vdiInstance, releaseVDI)
}()
cmn.DebugMsg(cmn.DbgLvlDebug, "[DEBUG-startCrawling] Waiting for VDI release (after any crawling activities are completed)...")
// Wait for `CrawlWebsite()` to release the VDI
for {
select {
case recoveredVDI := <-releaseVDI:
cmn.DebugMsg(cmn.DbgLvlDebug, "[DEBUG-startCrawling] VDI instance '%s' with Address %v released for reuse", recoveredVDI.Config.Name, recoveredVDI.Config.Host)
// Return the VDI instance to the pool
vdiPool := args.Sel
vdiPool.Release(index, c.Crawler.VDIName)
cmn.DebugMsg(cmn.DbgLvlDebug, "[DEBUG-startCrawling] quitting startCrawling() goroutine")
return // Exit the loop once VDI is returned
case <-time.After(10 * time.Minute): // Instead of quitting, just log
cmn.DebugMsg(cmn.DbgLvlWarn, "[DEBUG-startCrawling] VDI instance '%s' with Address %v is still in use after 10 minutes, continuing to wait...", vdiInstance.Config.Name, vdiInstance.Config.Host)
}
}
}(&args, wb.Config)
}
func logStatus(PipelineStatus *[]crowler.Status) {
// Log the status of the pipelines
const (
sepRLine = "====================================="
sepPLine = "-------------------------------------"
)
report := "Pipelines status report\n"
report += sepRLine + "\n"
runningPipelines := 0
for idx := 0; idx < len(*PipelineStatus); idx++ {
status := &(*PipelineStatus)[idx]
if status.PipelineRunning.Load() == 0 {
continue
}
runningPipelines++
var totalRunningTime time.Duration
if status.EndTime.IsZero() {
totalRunningTime = time.Since(status.StartTime)
} else {
totalRunningTime = status.EndTime.Sub(status.StartTime)
}
totalLinksToGo := status.TotalLinks.Load() - (status.TotalPages.Load() + status.TotalSkipped.Load() + status.TotalDuplicates.Load())
if totalLinksToGo < 0 {
totalLinksToGo = 0
}
// Detect if we are stale-processing
if (status.PipelineRunning.Load() == 1) && (totalRunningTime > time.Duration(2*time.Minute)) &&
(status.CrawlingRunning.Load() == 0) && (status.NetInfoRunning.Load() == 0) &&
(status.HTTPInfoRunning.Load() == 0) {
// We are in a stale-processing state
status.DetectedState.Store(1)
} else {
if (status.DetectedState.Load() & 0x01) != 0 {
tmp := status.DetectedState.Load() & 0xfffe
status.DetectedState.Store(tmp) // Reset the stale-processing state bit
}
}
/*
if (status.PipelineRunning == 1) && (status.CrawlingRunning > 1) &&
(status.NetInfoRunning > 1) && (status.HTTPInfoRunning > 1) {
status.PipelineRunning = status.CrawlingRunning | status.NetInfoRunning | status.HTTPInfoRunning
}
*/
// Prepare the report (pipelineID + 1 is to avoid the pipeline 0 which seems to confuse many people)
report += fmt.Sprintf(" Pipeline: %d of %d\n", status.PipelineID+1, len(*PipelineStatus))
report += fmt.Sprintf(" Source: %s\n", status.Source)
report += fmt.Sprintf(" Source ID: %d\n", status.SourceID)
report += fmt.Sprintf(" VDI ID: %s\n", status.VDIID)
report += fmt.Sprintf(" VDI Session ID: %s\n", status.VDISID)
report += fmt.Sprintf(" ContextID: %s\n", status.ContextID)
report += fmt.Sprintf(" Pipeline status: %s\n", StatusStr(int(status.PipelineRunning.Load())))
report += fmt.Sprintf(" Crawling status: %s\n", StatusStr(int(status.CrawlingRunning.Load())))
report += fmt.Sprintf(" NetInfo status: %s\n", StatusStr(int(status.NetInfoRunning.Load())))
report += fmt.Sprintf(" HTTPInfo status: %s\n", StatusStr(int(status.HTTPInfoRunning.Load())))
report += fmt.Sprintf(" Running Time: %s\n", totalRunningTime)
report += fmt.Sprintf(" Total Crawled Pages: %d\n", status.TotalPages.Load())
report += fmt.Sprintf(" Total Errors: %d\n", status.TotalErrors.Load())