-
-
Notifications
You must be signed in to change notification settings - Fork 420
/
Switchboard.java
3612 lines (3305 loc) · 163 KB
/
Switchboard.java
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
// plasmaSwitchboard.java
// (C) 2004-2007 by Michael Peter Christen; mc@yacy.net, Frankfurt a. M., Germany
// first published 2004 on http://yacy.net
//
// This is a part of YaCy, a peer-to-peer based web search engine
//
// $LastChangedDate$
// $LastChangedRevision$
// $LastChangedBy$
//
// LICENSE
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
/*
This class holds the run-time environment of the plasma
Search Engine. It's data forms a blackboard which can be used
to organize running jobs around the indexing algorithm.
The blackboard consist of the following entities:
- storage: one plasmaStore object with the url-based database
- configuration: initialized by properties once, then by external functions
- job queues: for parsing, condensing, indexing
*/
package net.yacy.search;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.net.MalformedURLException;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.apache.solr.common.SolrInputDocument;
import net.yacy.contentcontrol.ContentControlFilterUpdateThread;
import net.yacy.contentcontrol.SMWListSyncThread;
import net.yacy.cora.date.GenericFormatter;
import net.yacy.cora.document.ASCII;
import net.yacy.cora.document.MultiProtocolURI;
import net.yacy.cora.document.RSSFeed;
import net.yacy.cora.document.RSSMessage;
import net.yacy.cora.document.RSSReader;
import net.yacy.cora.document.UTF8;
import net.yacy.cora.document.WordCache;
import net.yacy.cora.document.analysis.Classification;
import net.yacy.cora.federate.solr.YaCySchema;
import net.yacy.cora.federate.solr.connector.ShardSelection;
import net.yacy.cora.federate.solr.connector.ShardSolrConnector;
import net.yacy.cora.federate.solr.connector.SolrConnector;
import net.yacy.cora.federate.yacy.CacheStrategy;
import net.yacy.cora.federate.yacy.ConfigurationSet;
import net.yacy.cora.lod.JenaTripleStore;
import net.yacy.cora.order.Base64Order;
import net.yacy.cora.order.Digest;
import net.yacy.cora.order.NaturalOrder;
import net.yacy.cora.protocol.ClientIdentification;
import net.yacy.cora.protocol.ConnectionInfo;
import net.yacy.cora.protocol.Domains;
import net.yacy.cora.protocol.HeaderFramework;
import net.yacy.cora.protocol.RequestHeader;
import net.yacy.cora.protocol.ResponseHeader;
import net.yacy.cora.protocol.TimeoutRequest;
import net.yacy.cora.protocol.http.HTTPClient;
import net.yacy.cora.protocol.http.ProxySettings;
import net.yacy.cora.storage.HandleSet;
import net.yacy.cora.util.SpaceExceededException;
import net.yacy.crawler.CrawlStacker;
import net.yacy.crawler.CrawlSwitchboard;
import net.yacy.crawler.data.Cache;
import net.yacy.crawler.data.CrawlProfile;
import net.yacy.crawler.data.CrawlQueues;
import net.yacy.crawler.data.NoticedURL;
import net.yacy.crawler.data.ResultImages;
import net.yacy.crawler.data.ResultURLs;
import net.yacy.crawler.data.NoticedURL.StackType;
import net.yacy.crawler.data.ResultURLs.EventOrigin;
import net.yacy.crawler.data.ZURL.FailCategory;
import net.yacy.crawler.retrieval.Request;
import net.yacy.crawler.retrieval.Response;
import net.yacy.crawler.robots.RobotsTxt;
import net.yacy.data.BlogBoard;
import net.yacy.data.BlogBoardComments;
import net.yacy.data.BookmarkHelper;
import net.yacy.data.BookmarksDB;
import net.yacy.data.ListManager;
import net.yacy.data.MessageBoard;
import net.yacy.data.URLLicense;
import net.yacy.data.UserDB;
import net.yacy.data.WorkTables;
import net.yacy.data.wiki.WikiBoard;
import net.yacy.data.wiki.WikiCode;
import net.yacy.data.wiki.WikiParser;
import net.yacy.data.ymark.YMarkTables;
import net.yacy.document.Condenser;
import net.yacy.document.Document;
import net.yacy.document.LibraryProvider;
import net.yacy.document.Parser;
import net.yacy.document.TextParser;
import net.yacy.document.Parser.Failure;
import net.yacy.document.content.DCEntry;
import net.yacy.document.content.SurrogateReader;
import net.yacy.document.importer.OAIListFriendsLoader;
import net.yacy.document.parser.audioTagParser;
import net.yacy.document.parser.html.Evaluation;
import net.yacy.gui.Tray;
import net.yacy.kelondro.blob.Tables;
import net.yacy.kelondro.data.meta.DigestURI;
import net.yacy.kelondro.data.meta.URIMetadataNode;
import net.yacy.kelondro.data.word.Word;
import net.yacy.kelondro.logging.Log;
import net.yacy.kelondro.rwi.ReferenceContainer;
import net.yacy.kelondro.util.FileUtils;
import net.yacy.kelondro.util.MemoryControl;
import net.yacy.kelondro.util.OS;
import net.yacy.kelondro.util.SetTools;
import net.yacy.kelondro.workflow.BusyThread;
import net.yacy.kelondro.workflow.InstantBusyThread;
import net.yacy.kelondro.workflow.WorkflowProcessor;
import net.yacy.kelondro.workflow.WorkflowThread;
import net.yacy.peers.Dispatcher;
import net.yacy.peers.EventChannel;
import net.yacy.peers.Network;
import net.yacy.peers.NewsPool;
import net.yacy.peers.DHTSelection;
import net.yacy.peers.Protocol;
import net.yacy.peers.Seed;
import net.yacy.peers.SeedDB;
import net.yacy.peers.graphics.WebStructureGraph;
import net.yacy.peers.operation.yacyBuildProperties;
import net.yacy.peers.operation.yacyRelease;
import net.yacy.peers.operation.yacyUpdateLocation;
import net.yacy.repository.Blacklist;
import net.yacy.repository.Blacklist.BlacklistType;
import net.yacy.repository.FilterEngine;
import net.yacy.repository.LoaderDispatcher;
import net.yacy.search.index.Segment;
import net.yacy.search.index.SolrConfiguration;
import net.yacy.search.query.AccessTracker;
import net.yacy.search.query.SearchEvent;
import net.yacy.search.query.SearchEventCache;
import net.yacy.search.ranking.BlockRank;
import net.yacy.search.ranking.RankingProfile;
import net.yacy.search.snippet.TextSnippet;
import net.yacy.server.serverCore;
import net.yacy.server.serverSwitch;
import net.yacy.server.http.RobotsTxtConfig;
import net.yacy.utils.CryptoLib;
import net.yacy.utils.UPnP;
import net.yacy.utils.crypt;
import com.google.common.io.Files;
public final class Switchboard extends serverSwitch {
// load slots
public static int xstackCrawlSlots = 2000;
public static long lastPPMUpdate = System.currentTimeMillis() - 30000;
private static final int dhtMaxContainerCount = 500;
private int dhtMaxReferenceCount = 1000;
// colored list management
public static SortedSet<String> badwords = new TreeSet<String>(NaturalOrder.naturalComparator);
public static SortedSet<String> stopwords = new TreeSet<String>(NaturalOrder.naturalComparator);
public static SortedSet<String> blueList = null;
public static HandleSet badwordHashes = null;
public static HandleSet blueListHashes = null;
public static HandleSet stopwordHashes = null;
public static Blacklist urlBlacklist = null;
public static WikiParser wikiParser = null;
// storage management
public File htCachePath;
public final File dictionariesPath;
public File listsPath;
public File htDocsPath;
public File workPath;
public File releasePath;
public File networkRoot;
public File queuesRoot;
public File surrogatesInPath;
public File surrogatesOutPath;
public Segment index;
public LoaderDispatcher loader;
public CrawlSwitchboard crawler;
public CrawlQueues crawlQueues;
public CrawlStacker crawlStacker;
public MessageBoard messageDB;
public WikiBoard wikiDB;
public BlogBoard blogDB;
public BlogBoardComments blogCommentDB;
public RobotsTxt robots;
public Map<String, Object[]> outgoingCookies, incomingCookies;
public volatile long proxyLastAccess, localSearchLastAccess, remoteSearchLastAccess;
public Network yc;
public ResourceObserver observer;
public UserDB userDB;
public BookmarksDB bookmarksDB;
public WebStructureGraph webStructure;
public ConcurrentHashMap<String, TreeSet<Long>> localSearchTracker, remoteSearchTracker; // mappings from requesting host to a TreeSet of Long(access time)
public long indexedPages = 0;
public int searchQueriesRobinsonFromLocal = 0; // absolute counter of all local queries submitted on this peer from a local or autheticated used
public int searchQueriesRobinsonFromRemote = 0; // absolute counter of all local queries submitted on this peer from a remote IP without authentication
public float searchQueriesGlobal = 0f; // partial counter of remote queries (1/number-of-requested-peers)
public SortedMap<byte[], String> clusterhashes; // map of peerhash(String)/alternative-local-address as ip:port or only ip (String) or null if address in seed should be used
public URLLicense licensedURLs;
public List<Pattern> networkWhitelist, networkBlacklist;
public FilterEngine domainList;
private Dispatcher dhtDispatcher;
public LinkedBlockingQueue<String> trail;
public SeedDB peers;
public WorkTables tables;
public Tray tray;
public WorkflowProcessor<IndexingQueueEntry> indexingDocumentProcessor;
public WorkflowProcessor<IndexingQueueEntry> indexingCondensementProcessor;
public WorkflowProcessor<IndexingQueueEntry> indexingAnalysisProcessor;
public WorkflowProcessor<IndexingQueueEntry> indexingStorageProcessor;
public RobotsTxtConfig robotstxtConfig = null;
public boolean useTailCache;
public boolean exceed134217727;
private final Semaphore shutdownSync = new Semaphore(0);
private boolean terminate = false;
private static Switchboard sb;
public HashMap<String, Object[]> crawlJobsStatus = new HashMap<String, Object[]>();
public Switchboard(final File dataPath, final File appPath, final String initPath, final String configPath) throws IOException {
super(dataPath, appPath, initPath, configPath);
sb = this;
// check if port is already occupied
final int port = getConfigInt("port", 8090);
try {
if ( TimeoutRequest.ping(Domains.LOCALHOST, port, 500) ) {
throw new RuntimeException(
"a server is already running on the YaCy port "
+ port
+ "; possibly another YaCy process has not terminated yet. Please stop YaCy before running a new instance.");
}
} catch ( final ExecutionException e1 ) {
}
MemoryTracker.startSystemProfiling();
// set loglevel and log
setLog(new Log("SWITCHBOARD"));
AccessTracker.setDumpFile(new File("DATA/LOG/queries.log"));
// set default peer name
Seed.ANON_PREFIX = getConfig("peernameprefix", "_anon");
// UPnP port mapping
if ( getConfigBool(SwitchboardConstants.UPNP_ENABLED, false) ) {
InstantBusyThread.oneTimeJob(UPnP.class, "addPortMapping", 0);
}
// init TrayIcon if possible
this.tray = new Tray(this);
// remote proxy configuration
initRemoteProxy();
// memory configuration
long tableCachingLimit = getConfigLong("tableCachingLimit", 419430400L);
if ( MemoryControl.available() > tableCachingLimit ) {
this.useTailCache = true;
}
this.exceed134217727 = getConfigBool("exceed134217727", true);
if ( MemoryControl.available() > 1024L * 1024L * 1024L * 2L ) {
this.exceed134217727 = true;
}
// load values from configs
final File indexPath =
getDataPath(SwitchboardConstants.INDEX_PRIMARY_PATH, SwitchboardConstants.INDEX_PATH_DEFAULT);
this.log.logConfig("Index Primary Path: " + indexPath.toString());
this.listsPath =
getDataPath(SwitchboardConstants.LISTS_PATH, SwitchboardConstants.LISTS_PATH_DEFAULT);
this.log.logConfig("Lists Path: " + this.listsPath.toString());
this.htDocsPath =
getDataPath(SwitchboardConstants.HTDOCS_PATH, SwitchboardConstants.HTDOCS_PATH_DEFAULT);
this.log.logConfig("HTDOCS Path: " + this.htDocsPath.toString());
this.workPath = getDataPath(SwitchboardConstants.WORK_PATH, SwitchboardConstants.WORK_PATH_DEFAULT);
this.workPath.mkdirs();
this.log.logConfig("Work Path: " + this.workPath.toString());
this.dictionariesPath =
getDataPath(
SwitchboardConstants.DICTIONARY_SOURCE_PATH,
SwitchboardConstants.DICTIONARY_SOURCE_PATH_DEFAULT);
this.log.logConfig("Dictionaries Path:" + this.dictionariesPath.toString());
// init libraries
this.log.logConfig("initializing libraries");
new Thread() {
@Override
public void run() {
Thread.currentThread().setName("LibraryProvider.initialize");
LibraryProvider.initialize(Switchboard.this.dictionariesPath);
}
}.start();
// init global host name cache
Domains.init(new File(this.workPath, "globalhosts.list"));
// init sessionid name file
final String sessionidNamesFile = getConfig("sessionidNamesFile", "defaults/sessionid.names");
this.log.logConfig("Loading sessionid file " + sessionidNamesFile);
MultiProtocolURI.initSessionIDNames(FileUtils.loadList(new File(getAppPath(), sessionidNamesFile)));
// init tables
this.tables = new WorkTables(this.workPath);
// set a high maximum cache size to current size; this is adopted later automatically
final int wordCacheMaxCount = (int) getConfigLong(SwitchboardConstants.WORDCACHE_MAX_COUNT, 20000);
setConfig(SwitchboardConstants.WORDCACHE_MAX_COUNT, Integer.toString(wordCacheMaxCount));
// load the network definition
overwriteNetworkDefinition();
// start indexing management
this.log.logConfig("Starting Indexing Management");
final String networkName = getConfig(SwitchboardConstants.NETWORK_NAME, "");
final long fileSizeMax = (OS.isWindows) ? this.getConfigLong("filesize.max.win", Integer.MAX_VALUE) : this.getConfigLong( "filesize.max.other", Integer.MAX_VALUE);
final int redundancy = (int) this.getConfigLong("network.unit.dhtredundancy.senior", 1);
final int partitionExponent = (int) this.getConfigLong("network.unit.dht.partitionExponent", 0);
this.networkRoot = new File(new File(indexPath, networkName), "NETWORK");
this.queuesRoot = new File(new File(indexPath, networkName), "QUEUES");
this.networkRoot.mkdirs();
this.queuesRoot.mkdirs();
// prepare a solr index profile switch list
final File solrBackupProfile = new File("defaults/solr.keys.list");
final String schemename = getConfig(SwitchboardConstants.FEDERATED_SERVICE_SOLR_INDEXING_SCHEMEFILE, "solr.keys.default.list");
final File solrWorkProfile = new File(getDataPath(), "DATA/SETTINGS/" + schemename);
if ( !solrWorkProfile.exists() ) {
Files.copy(solrBackupProfile, solrWorkProfile);
}
final boolean solrlazy = getConfigBool(SwitchboardConstants.FEDERATED_SERVICE_SOLR_INDEXING_LAZY, true);
final SolrConfiguration backupScheme = new SolrConfiguration(solrBackupProfile, solrlazy);
final SolrConfiguration solrScheme = new SolrConfiguration(solrWorkProfile, solrlazy);
// update the working scheme with the backup scheme. This is necessary to include new features.
// new features are always activated by default (if activated in input-backupScheme)
solrScheme.fill(backupScheme, true);
// switch on some fields which are necessary for ranking and faceting
for (YaCySchema field: new YaCySchema[]{
YaCySchema.host_s, YaCySchema.load_date_dt,
YaCySchema.url_file_ext_s, YaCySchema.last_modified, // needed for media search and /date operator
YaCySchema.url_paths_sxt, YaCySchema.host_organization_s, // needed to search in the url
YaCySchema.inboundlinks_protocol_sxt, YaCySchema.inboundlinks_urlstub_txt, // needed for HostBrowser
YaCySchema.outboundlinks_protocol_sxt, YaCySchema.outboundlinks_urlstub_txt // needed to enhance the crawler
}) {
ConfigurationSet.Entry entry = solrScheme.get(field.name()); entry.setEnable(true); solrScheme.put(field.name(), entry);
}
solrScheme.commit();
// initialize index
ReferenceContainer.maxReferences = getConfigInt("index.maxReferences", 0);
final File segmentsPath = new File(new File(indexPath, networkName), "SEGMENTS");
this.index = new Segment(this.log, new File(segmentsPath, "default"), solrScheme);
final int connectWithinMs = this.getConfigInt(SwitchboardConstants.FEDERATED_SERVICE_SOLR_INDEXING_COMMITWITHINMS, 180000);
if (this.getConfigBool(SwitchboardConstants.CORE_SERVICE_RWI, true)) this.index.connectRWI(wordCacheMaxCount, fileSizeMax);
if (this.getConfigBool(SwitchboardConstants.CORE_SERVICE_CITATION, true)) this.index.connectCitation(wordCacheMaxCount, fileSizeMax);
if (this.getConfigBool(SwitchboardConstants.CORE_SERVICE_FULLTEXT, true)) {
this.index.connectUrlDb(this.useTailCache, this.exceed134217727);
this.index.fulltext().connectLocalSolr(connectWithinMs);
}
// set up the solr interface
final String solrurls = getConfig(SwitchboardConstants.FEDERATED_SERVICE_SOLR_INDEXING_URL, "http://127.0.0.1:8983/solr");
final boolean usesolr = getConfigBool(SwitchboardConstants.FEDERATED_SERVICE_SOLR_INDEXING_ENABLED, false) & solrurls.length() > 0;
if (usesolr && solrurls != null && solrurls.length() > 0) {
try {
SolrConnector solr = new ShardSolrConnector(
solrurls,
ShardSelection.Method.MODULO_HOST_MD5,
10000, true);
solr.setCommitWithinMs(connectWithinMs);
this.index.fulltext().connectRemoteSolr(solr);
} catch ( final IOException e ) {
Log.logException(e);
}
}
// initialize network database
final File mySeedFile = new File(this.networkRoot, SeedDB.DBFILE_OWN_SEED);
this.peers =
new SeedDB(
this.networkRoot,
"seed.new.heap",
"seed.old.heap",
"seed.pot.heap",
mySeedFile,
redundancy,
partitionExponent,
false,
this.exceed134217727);
// load domainList
try {
this.domainList = null;
if ( !getConfig("network.unit.domainlist", "").equals("") ) {
final Reader r =
getConfigFileFromWebOrLocally(getConfig("network.unit.domainlist", ""), getAppPath()
.getAbsolutePath(), new File(this.networkRoot, "domainlist.txt"));
this.domainList = new FilterEngine();
this.domainList.loadList(new BufferedReader(r), null);
}
} catch ( final FileNotFoundException e ) {
this.log.logSevere("CONFIG: domainlist not found: " + e.getMessage());
} catch ( final IOException e ) {
this.log.logSevere("CONFIG: error while retrieving domainlist: " + e.getMessage());
}
// create a crawler
this.crawler = new CrawlSwitchboard(networkName, this.log, this.queuesRoot);
// start yacy core
this.log.logConfig("Starting YaCy Protocol Core");
this.yc = new Network(this);
InstantBusyThread.oneTimeJob(this, "loadSeedLists", 0);
//final long startedSeedListAquisition = System.currentTimeMillis();
// init a DHT transmission dispatcher
this.dhtDispatcher =
(this.peers.sizeConnected() == 0) ? null : new Dispatcher(
this.index,
this.peers,
true,
10000);
// set up local robots.txt
this.robotstxtConfig = RobotsTxtConfig.init(this);
// setting timestamp of last proxy access
this.proxyLastAccess = System.currentTimeMillis() - 10000;
this.localSearchLastAccess = System.currentTimeMillis() - 10000;
this.remoteSearchLastAccess = System.currentTimeMillis() - 10000;
this.webStructure = new WebStructureGraph(new File(this.queuesRoot, "webStructure.map"));
// configuring list path
if ( !(this.listsPath.exists()) ) {
this.listsPath.mkdirs();
}
// load coloured lists
if ( blueList == null ) {
// read only once upon first instantiation of this class
final String f =
getConfig(SwitchboardConstants.LIST_BLUE, SwitchboardConstants.LIST_BLUE_DEFAULT);
final File plasmaBlueListFile = new File(f);
if ( f != null ) {
blueList = SetTools.loadList(plasmaBlueListFile, NaturalOrder.naturalComparator);
} else {
blueList = new TreeSet<String>();
}
blueListHashes = Word.words2hashesHandles(blueList);
this.log.logConfig("loaded blue-list from file "
+ plasmaBlueListFile.getName()
+ ", "
+ blueList.size()
+ " entries, "
+ ppRamString(plasmaBlueListFile.length() / 1024));
}
// load blacklist
this.log.logConfig("Loading blacklist ...");
final File blacklistsPath =
getDataPath(SwitchboardConstants.LISTS_PATH, SwitchboardConstants.LISTS_PATH_DEFAULT);
urlBlacklist = new Blacklist(blacklistsPath);
ListManager.switchboard = this;
ListManager.listsPath = blacklistsPath;
ListManager.reloadBlacklists();
// load badwords (to filter the topwords)
if ( badwords == null || badwords.isEmpty() ) {
final File badwordsFile = new File(appPath, SwitchboardConstants.LIST_BADWORDS_DEFAULT);
badwords = SetTools.loadList(badwordsFile, NaturalOrder.naturalComparator);
badwordHashes = Word.words2hashesHandles(badwords);
this.log.logConfig("loaded badwords from file "
+ badwordsFile.getName()
+ ", "
+ badwords.size()
+ " entries, "
+ ppRamString(badwordsFile.length() / 1024));
}
// load stopwords
if ( stopwords == null || stopwords.isEmpty() ) {
final File stopwordsFile = new File(appPath, SwitchboardConstants.LIST_STOPWORDS_DEFAULT);
stopwords = SetTools.loadList(stopwordsFile, NaturalOrder.naturalComparator);
stopwordHashes = Word.words2hashesHandles(stopwords);
this.log.logConfig("loaded stopwords from file "
+ stopwordsFile.getName()
+ ", "
+ stopwords.size()
+ " entries, "
+ ppRamString(stopwordsFile.length() / 1024));
}
// load ranking from distribution
final File rankingPath = new File(this.appPath, "ranking/YBR".replace('/', File.separatorChar));
BlockRank.loadBlockRankTable(rankingPath, 16);
// load distributed ranking
// very large memory configurations allow to re-compute a ranking table
/*
final File hostIndexFile = new File(this.queuesRoot, "hostIndex.blob");
if (MemoryControl.available() > 1024 * 1024 * 1024) new Thread() {
public void run() {
ReferenceContainerCache<HostReference> hostIndex; // this will get large, more than 0.5 million entries by now
if (!hostIndexFile.exists()) {
hostIndex = BlockRank.collect(Switchboard.this.peers, Switchboard.this.webStructure, Integer.MAX_VALUE);
BlockRank.saveHostIndex(hostIndex, hostIndexFile);
} else {
hostIndex = BlockRank.loadHostIndex(hostIndexFile);
}
// use an index segment to find hosts for given host hashes
final String segmentName = getConfig(SwitchboardConstants.SEGMENT_PUBLIC, "default");
final Segment segment = Switchboard.this.indexSegments.segment(segmentName);
final MetadataRepository metadata = segment.urlMetadata();
Map<String,HostStat> hostHashResolver;
try {
hostHashResolver = metadata.domainHashResolver(metadata.domainSampleCollector());
} catch (final IOException e) {
hostHashResolver = new HashMap<String, HostStat>();
}
// recursively compute a new ranking table
Switchboard.this.log.logInfo("BLOCK RANK: computing new ranking tables...");
BlockRank.ybrTables = BlockRank.evaluate(hostIndex, hostHashResolver, null, 0);
hostIndex = null; // we don't need that here any more, so free the memory
// use the web structure and the hostHash resolver to analyse the ranking table
Switchboard.this.log.logInfo("BLOCK RANK: analysis of " + BlockRank.ybrTables.length + " tables...");
BlockRank.analyse(Switchboard.this.webStructure, hostHashResolver);
// store the new table
Switchboard.this.log.logInfo("BLOCK RANK: storing fresh table...");
BlockRank.storeBlockRankTable(rankingPath);
}
}.start();
*/
// start a cache manager
this.log.logConfig("Starting HT Cache Manager");
// create the cache directory
this.htCachePath =
getDataPath(SwitchboardConstants.HTCACHE_PATH, SwitchboardConstants.HTCACHE_PATH_DEFAULT);
this.log.logInfo("HTCACHE Path = " + this.htCachePath.getAbsolutePath());
final long maxCacheSize =
1024L * 1024L * Long.parseLong(getConfig(SwitchboardConstants.PROXY_CACHE_SIZE, "2")); // this is megabyte
Cache.init(this.htCachePath, this.peers.mySeed().hash, maxCacheSize);
// create the surrogates directories
this.surrogatesInPath =
getDataPath(
SwitchboardConstants.SURROGATES_IN_PATH,
SwitchboardConstants.SURROGATES_IN_PATH_DEFAULT);
this.log.logInfo("surrogates.in Path = " + this.surrogatesInPath.getAbsolutePath());
this.surrogatesInPath.mkdirs();
this.surrogatesOutPath =
getDataPath(
SwitchboardConstants.SURROGATES_OUT_PATH,
SwitchboardConstants.SURROGATES_OUT_PATH_DEFAULT);
this.log.logInfo("surrogates.out Path = " + this.surrogatesOutPath.getAbsolutePath());
this.surrogatesOutPath.mkdirs();
// create the release download directory
this.releasePath =
getDataPath(SwitchboardConstants.RELEASE_PATH, SwitchboardConstants.RELEASE_PATH_DEFAULT);
this.releasePath.mkdirs();
this.log.logInfo("RELEASE Path = " + this.releasePath.getAbsolutePath());
// starting message board
initMessages();
// starting wiki
initWiki();
//starting blog
initBlog();
// init User DB
this.log.logConfig("Loading User DB");
final File userDbFile = new File(getDataPath(), "DATA/SETTINGS/user.heap");
this.userDB = new UserDB(userDbFile);
this.log.logConfig("Loaded User DB from file "
+ userDbFile.getName()
+ ", "
+ this.userDB.size()
+ " entries"
+ ", "
+ ppRamString(userDbFile.length() / 1024));
// init user triplestores
JenaTripleStore.initPrivateStores();
// init html parser evaluation scheme
File parserPropertiesPath = new File("defaults/");
String[] settingsList = parserPropertiesPath.list();
for ( final String l : settingsList ) {
if ( l.startsWith("parser.") && l.endsWith(".properties") ) {
Evaluation.add(new File(parserPropertiesPath, l));
}
}
parserPropertiesPath = new File(getDataPath(), "DATA/SETTINGS/");
settingsList = parserPropertiesPath.list();
for ( final String l : settingsList ) {
if ( l.startsWith("parser.") && l.endsWith(".properties") ) {
Evaluation.add(new File(parserPropertiesPath, l));
}
}
// init bookmarks DB: needs more time since this does a DNS lookup for each Bookmark.
// Can be started concurrently
new Thread() {
@Override
public void run() {
Thread.currentThread().setName("Switchboard.initBookmarks");
try {
initBookmarks();
} catch ( final IOException e ) {
Log.logException(e);
}
}
}.start();
// define a realtime parsable mimetype list
this.log.logConfig("Parser: Initializing Mime Type deny list");
final boolean enableAudioTags = getConfigBool("parser.enableAudioTags", false);
log.logConfig("Parser: parser.enableAudioTags= "+enableAudioTags);
final StringBuilder denyExt = new StringBuilder(256);
final StringBuilder denyMime = new StringBuilder(256);
denyExt.append(getConfig(SwitchboardConstants.PARSER_MIME_DENY, ""));
denyMime.append(getConfig(SwitchboardConstants.PARSER_EXTENSIONS_DENY, ""));
if (!enableAudioTags) {
if(denyExt.length()>0) {
denyExt.append(audioTagParser.SEPERATOR);
}
denyExt.append(audioTagParser.EXTENSIONS);
if(denyMime.length()>0) {
denyMime.append(audioTagParser.SEPERATOR);
}
denyMime.append(audioTagParser.MIME_TYPES);
setConfig(SwitchboardConstants.PARSER_EXTENSIONS_DENY, denyExt.toString());
setConfig(SwitchboardConstants.PARSER_MIME_DENY, denyMime.toString());
setConfig("parser.enableAudioTags", true);
}
TextParser.setDenyMime(getConfig(SwitchboardConstants.PARSER_MIME_DENY, ""));
TextParser.setDenyExtension(getConfig(SwitchboardConstants.PARSER_EXTENSIONS_DENY, ""));
// start a loader
this.log.logConfig("Starting Crawl Loader");
this.loader = new LoaderDispatcher(this);
// load the robots.txt db
this.log.logConfig("Initializing robots.txt DB");
this.robots = new RobotsTxt(this.tables, this.loader);
this.log.logConfig("Loaded robots.txt DB: " + this.robots.size() + " entries");
// load oai tables
final Map<String, File> oaiFriends =
OAIListFriendsLoader.loadListFriendsSources(
new File("defaults/oaiListFriendsSource.xml"),
getDataPath());
OAIListFriendsLoader.init(this.loader, oaiFriends);
this.crawlQueues = new CrawlQueues(this, this.queuesRoot);
this.crawlQueues.noticeURL.setMinimumDelta(
getConfigInt("minimumLocalDelta", this.crawlQueues.noticeURL.getMinimumLocalDelta()),
getConfigInt("minimumGlobalDelta", this.crawlQueues.noticeURL.getMinimumGlobalDelta()));
/*
* Creating sync objects and loading status for the crawl jobs
* a) local crawl
* b) remote triggered crawl
* c) global crawl trigger
*/
this.crawlJobsStatus.put(
SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL,
new Object[] {
new Object(),
Boolean.valueOf(getConfig(SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL + "_isPaused", "false"))
});
this.crawlJobsStatus.put(
SwitchboardConstants.CRAWLJOB_REMOTE_TRIGGERED_CRAWL,
new Object[] {
new Object(),
Boolean.valueOf(getConfig(
SwitchboardConstants.CRAWLJOB_REMOTE_TRIGGERED_CRAWL + "_isPaused",
"false"))
});
this.crawlJobsStatus.put(
SwitchboardConstants.CRAWLJOB_REMOTE_CRAWL_LOADER,
new Object[] {
new Object(),
Boolean.valueOf(getConfig(
SwitchboardConstants.CRAWLJOB_REMOTE_CRAWL_LOADER + "_isPaused",
"false"))
});
// init cookie-Monitor
this.log.logConfig("Starting Cookie Monitor");
this.outgoingCookies = new ConcurrentHashMap<String, Object[]>();
this.incomingCookies = new ConcurrentHashMap<String, Object[]>();
// init search history trackers
this.localSearchTracker = new ConcurrentHashMap<String, TreeSet<Long>>(); // String:TreeSet - IP:set of Long(accessTime)
this.remoteSearchTracker = new ConcurrentHashMap<String, TreeSet<Long>>();
// init messages: clean up message symbol
final File notifierSource =
new File(getAppPath(), getConfig(
SwitchboardConstants.HTROOT_PATH,
SwitchboardConstants.HTROOT_PATH_DEFAULT) + "/env/grafics/empty.gif");
final File notifierDest =
new File(
getDataPath(SwitchboardConstants.HTDOCS_PATH, SwitchboardConstants.HTDOCS_PATH_DEFAULT),
"notifier.gif");
try {
Files.copy(notifierSource, notifierDest);
} catch ( final IOException e ) {
}
// init nameCacheNoCachingList
try {
Domains.setNoCachingPatterns(getConfig(SwitchboardConstants.HTTPC_NAME_CACHE_CACHING_PATTERNS_NO, ""));
} catch (PatternSyntaxException pse) {
Log.logSevere("Switchboard", "Invalid regular expression in "
+ SwitchboardConstants.HTTPC_NAME_CACHE_CACHING_PATTERNS_NO
+ " property: " + pse.getMessage());
System.exit(-1);
}
// generate snippets cache
this.log.logConfig("Initializing Snippet Cache");
// init the wiki
wikiParser = new WikiCode();
// initializing the resourceObserver
InstantBusyThread.oneTimeJob(ResourceObserver.class, "initThread", 0);
// initializing the stackCrawlThread
this.crawlStacker =
new CrawlStacker(
this.robots,
this.crawlQueues,
this.crawler,
this.index,
this.peers,
isIntranetMode(),
isGlobalMode(),
this.domainList); // Intranet and Global mode may be both true!
// possibly switch off localIP check
Domains.setNoLocalCheck(isAllIPMode());
// check status of account configuration: when local url crawling is allowed, it is not allowed
// that an automatic authorization of localhost is done, because in this case crawls from local
// addresses are blocked to prevent attack szenarios where remote pages contain links to localhost
// addresses that can steer a YaCy peer
if ( !getConfigBool("adminAccountForLocalhost", false) ) {
if ( getConfig(SwitchboardConstants.ADMIN_ACCOUNT_B64MD5, "").startsWith("0000") ) {
// the password was set automatically with a random value.
// We must remove that here to prevent that a user cannot log in any more
setConfig(SwitchboardConstants.ADMIN_ACCOUNT_B64MD5, "");
// after this a message must be generated to alert the user to set a new password
this.log.logInfo("RANDOM PASSWORD REMOVED! User must set a new password");
}
}
// initializing dht chunk generation
this.dhtMaxReferenceCount = (int) getConfigLong(SwitchboardConstants.INDEX_DIST_CHUNK_SIZE_START, 50);
// init robinson cluster
// before we do that, we wait some time until the seed list is loaded.
this.clusterhashes = this.peers.clusterHashes(getConfig("cluster.peers.yacydomain", ""));
// deploy blocking threads
this.indexingStorageProcessor =
new WorkflowProcessor<IndexingQueueEntry>(
"storeDocumentIndex",
"This is the sequencing step of the indexing queue. Files are written as streams, too much councurrency would destroy IO performance. In this process the words are written to the RWI cache, which flushes if it is full.",
new String[] {
"RWI/Cache/Collections"
},
this,
"storeDocumentIndex",
2,
null,
1 /*Math.max(1, WorkflowProcessor.availableCPU / 2)*/);
this.indexingAnalysisProcessor =
new WorkflowProcessor<IndexingQueueEntry>(
"webStructureAnalysis",
"This just stores the link structure of the document into a web structure database.",
new String[] {
"storeDocumentIndex"
},
this,
"webStructureAnalysis",
WorkflowProcessor.availableCPU + 1,
this.indexingStorageProcessor,
WorkflowProcessor.availableCPU);
this.indexingCondensementProcessor =
new WorkflowProcessor<IndexingQueueEntry>(
"condenseDocument",
"This does a structural analysis of plain texts: markup of headlines, slicing into phrases (i.e. sentences), markup with position, counting of words, calculation of term frequency.",
new String[] {
"webStructureAnalysis"
},
this,
"condenseDocument",
WorkflowProcessor.availableCPU + 1,
this.indexingAnalysisProcessor,
WorkflowProcessor.availableCPU);
this.indexingDocumentProcessor =
new WorkflowProcessor<IndexingQueueEntry>(
"parseDocument",
"This does the parsing of the newly loaded documents from the web. The result is not only a plain text document, but also a list of URLs that are embedded into the document. The urls are handed over to the CrawlStacker. This process has two child process queues!",
new String[] {
"condenseDocument", "CrawlStacker"
},
this,
"parseDocument",
Math.max(20, WorkflowProcessor.availableCPU * 2), // it may happen that this is filled with new files from the search process. That means there should be enough place for two result pages
this.indexingCondensementProcessor,
WorkflowProcessor.availableCPU);
// deploy busy threads
this.log.logConfig("Starting Threads");
MemoryControl.gc(10000, "plasmaSwitchboard, help for profiler"); // help for profiler - thq
deployThread(
SwitchboardConstants.CLEANUP,
"Cleanup",
"simple cleaning process for monitoring information",
null,
new InstantBusyThread(
this,
SwitchboardConstants.CLEANUP_METHOD_START,
SwitchboardConstants.CLEANUP_METHOD_JOBCOUNT,
SwitchboardConstants.CLEANUP_METHOD_FREEMEM,
60000,
Long.MAX_VALUE,
10000,
Long.MAX_VALUE),
60000); // all 5 Minutes, wait 1 minute until first run
deployThread(
SwitchboardConstants.SURROGATES,
"Surrogates",
"A thread that polls the SURROGATES path and puts all Documents in one surroagte file into the indexing queue.",
null,
new InstantBusyThread(
this,
SwitchboardConstants.SURROGATES_METHOD_START,
SwitchboardConstants.SURROGATES_METHOD_JOBCOUNT,
SwitchboardConstants.SURROGATES_METHOD_FREEMEM,
20000,
Long.MAX_VALUE,
0,
Long.MAX_VALUE),
10000);
deployThread(
SwitchboardConstants.CRAWLJOB_REMOTE_TRIGGERED_CRAWL,
"Remote Crawl Job",
"thread that performes a single crawl/indexing step triggered by a remote peer",
"/IndexCreateWWWRemoteQueue_p.html",
new InstantBusyThread(
this.crawlQueues,
SwitchboardConstants.CRAWLJOB_REMOTE_TRIGGERED_CRAWL_METHOD_START,
SwitchboardConstants.CRAWLJOB_REMOTE_TRIGGERED_CRAWL_METHOD_JOBCOUNT,
SwitchboardConstants.CRAWLJOB_REMOTE_TRIGGERED_CRAWL_METHOD_FREEMEM,
0,
Long.MAX_VALUE,
0,
Long.MAX_VALUE),
10000);
deployThread(
SwitchboardConstants.CRAWLJOB_REMOTE_CRAWL_LOADER,
"Remote Crawl URL Loader",
"thread that loads remote crawl lists from other peers",
null,
new InstantBusyThread(
this.crawlQueues,
SwitchboardConstants.CRAWLJOB_REMOTE_CRAWL_LOADER_METHOD_START,
SwitchboardConstants.CRAWLJOB_REMOTE_CRAWL_LOADER_METHOD_JOBCOUNT,
SwitchboardConstants.CRAWLJOB_REMOTE_CRAWL_LOADER_METHOD_FREEMEM,
10000,
Long.MAX_VALUE,
10000,
Long.MAX_VALUE),
10000); // error here?
deployThread(
SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL,
"Local Crawl",
"thread that performes a single crawl step from the local crawl queue",
"/IndexCreateWWWLocalQueue_p.html",
new InstantBusyThread(
this.crawlQueues,
SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL_METHOD_START,
SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL_METHOD_JOBCOUNT,
SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL_METHOD_FREEMEM,
0,
Long.MAX_VALUE,
0,
Long.MAX_VALUE),
10000);
deployThread(
SwitchboardConstants.SEED_UPLOAD,
"Seed-List Upload",
"task that a principal peer performes to generate and upload a seed-list to a ftp account",
null,
new InstantBusyThread(
this.yc,
SwitchboardConstants.SEED_UPLOAD_METHOD_START,
SwitchboardConstants.SEED_UPLOAD_METHOD_JOBCOUNT,
SwitchboardConstants.SEED_UPLOAD_METHOD_FREEMEM,
600000,
Long.MAX_VALUE,
300000,
Long.MAX_VALUE),
180000);
deployThread(
SwitchboardConstants.PEER_PING,
"YaCy Core",
"this is the p2p-control and peer-ping task",
null,
new InstantBusyThread(
this.yc,
SwitchboardConstants.PEER_PING_METHOD_START,
SwitchboardConstants.PEER_PING_METHOD_JOBCOUNT,
SwitchboardConstants.PEER_PING_METHOD_FREEMEM,
30000,
Long.MAX_VALUE,
30000,
Long.MAX_VALUE),
2000);
deployThread(
SwitchboardConstants.INDEX_DIST,
"DHT Distribution",
"selection, transfer and deletion of index entries that are not searched on your peer, but on others",
null,
new InstantBusyThread(
this,