/
serverSwitch.java
744 lines (666 loc) · 23.2 KB
/
serverSwitch.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
// serverSwitch.java
// -------------------------------------
// (C) by Michael Peter Christen; mc@yacy.net
// first published on http://www.anomic.de
// Frankfurt, Germany, 2004, 2005
// last major change: 24.03.2005
//
// 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
package net.yacy.server;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.InetAddress;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import net.yacy.cora.order.Digest;
import net.yacy.cora.protocol.ClientIdentification;
import net.yacy.cora.protocol.Domains;
import net.yacy.cora.protocol.HeaderFramework;
import net.yacy.cora.protocol.RequestHeader;
import net.yacy.cora.protocol.http.HTTPClient;
import net.yacy.cora.util.CommonPattern;
import net.yacy.cora.util.ConcurrentLog;
import net.yacy.http.YaCyHttpServer;
import net.yacy.kelondro.util.FileUtils;
import net.yacy.kelondro.workflow.BusyThread;
import net.yacy.kelondro.workflow.WorkflowThread;
import net.yacy.peers.Seed;
import net.yacy.search.SwitchboardConstants;
public class serverSwitch {
// configuration management
private final File configFile;
private final String configComment;
public final File dataPath;
public final File appPath;
protected boolean firstInit;
public ConcurrentLog log;
protected int serverJobs;
private ConcurrentMap<String, String> configProps;
private final ConcurrentMap<String, String> configRemoved;
private final NavigableMap<String, BusyThread> workerThreads;
private YaCyHttpServer httpserver; // implemented HttpServer
private ConcurrentMap<String, Integer> upnpPortMap = new ConcurrentHashMap<>();
private boolean isConnectedViaUpnp;
public serverSwitch(final File dataPath, final File appPath,
final String initPath, final String configPath) {
// we initialize the switchboard with a property file,
// but maintain these properties then later in a new 'config' file
// to reset all changed configs, the config file must
// be deleted, but not the init file
// the only attribute that will always be read from the init is the
// file name of the config file
this.dataPath = dataPath;
this.appPath = appPath;
this.configComment = "This is an automatically generated file, updated by serverAbstractSwitch and initialized by "
+ initPath;
final File initFile = new File(appPath, initPath);
this.configFile = new File(dataPath, configPath); // propertiesFile(config);
this.firstInit = !this.configFile.exists(); // this is true if the
// application was started
// for the first time
new File(this.configFile.getParent()).mkdir();
// predefine init's
final ConcurrentMap<String, String> initProps;
if (initFile.exists()) {
initProps = FileUtils.loadMap(initFile);
} else {
initProps = new ConcurrentHashMap<String, String>();
}
// load config's from last save
if (this.configFile.exists()) {
this.configProps = FileUtils.loadMap(this.configFile);
} else {
this.configProps = new ConcurrentHashMap<String, String>();
}
// remove all values from config that do not appear in init
this.configRemoved = new ConcurrentHashMap<String, String>();
synchronized (this.configProps) {
Iterator<String> i = this.configProps.keySet().iterator();
String key;
while (i.hasNext()) {
key = i.next();
if (!(initProps.containsKey(key))) {
this.configRemoved.put(key, this.configProps.get(key));
i.remove();
}
}
// merge new props from init to config
// this is necessary for migration, when new properties are attached
initProps.putAll(this.configProps);
this.configProps = initProps;
// save result; this may initially create a config file after
// initialization
saveConfig();
}
// init thread control
this.workerThreads = new TreeMap<String, BusyThread>();
// init busy state control
// this.serverJobs = 0;
// init server tracking
serverAccessTracker.init(
getConfigLong("server.maxTrackingTime", 60 * 60 * 1000),
(int) getConfigLong("server.maxTrackingCount", 1000),
(int) getConfigLong("server.maxTrackingHostCount", 100));
}
/**
* get my public IP, either set statically or figure out dynamic This method
* is deprecated because there may be more than one public IPs of this peer,
* i.e. one IPv4 and one IPv6. Please use myPublicIPs() instead
*
* @return the public IP of this peer, if known
*/
@Deprecated
public String myPublicIP() {
// if a static IP was configured, we have to return it here ...
final String staticIP = getConfig("staticIP", "");
if (staticIP.length() > 0)
return staticIP;
// otherwise we return the real IP address of this host
final InetAddress pLIP = Domains.myPublicLocalIP();
if (pLIP != null)
return pLIP.getHostAddress();
return null;
}
/**
* Get all my public IPs. If there was a static IP assignment, only one,
* that IP is returned.
*
* @return a set of IPs which are supposed to be my own public IPs
*/
public Set<String> myPublicIPs() {
// if a static IP was configured, we have to return it here ...
final String staticIP = getConfig("staticIP", "");
if (staticIP.length() > 0) {
HashSet<String> h = new HashSet<>();
h.add(staticIP);
return h;
}
Set<String> h = new LinkedHashSet<>();
for (InetAddress i : Domains.myPublicIPv6()) {
String s = i.getHostAddress();
if (Seed.isProperIP(s))
h.add(Domains.chopZoneID(s));
}
for (InetAddress i : Domains.myPublicIPv4()) {
String s = i.getHostAddress();
if (Seed.isProperIP(s))
h.add(Domains.chopZoneID(s));
}
return h;
}
/**
* Gets public port. May differ from local port due to NATting. This method
* will eventually removed once nobody used IPv4 anymore, but until then we
* have to live with it.
*
* @param key
* original key from config (for example "port" or "port.ssl")
* @param dflt
* default value which will be used if no value is found
* @return the public port of this system on its IPv4 address
*
* @see #getLocalPort(String, int)
*/
public int getPublicPort(final String key, final int dflt) {
if (isConnectedViaUpnp && upnpPortMap.containsKey(key)) {
return upnpPortMap.get(key).intValue();
}
// TODO: add way of setting and retrieving port for manual NAT
return getConfigInt(key, dflt);
}
/**
* Wrapper for {@link #getConfigInt(String, int)} to have a more consistent
* API.
*
* Default value 8090 will be used if no value is found
*
* @return the local port of this system
* @see #getPublicPort(String, int)
*/
public int getLocalPort() {
/* A system property "http.port" may override configuration
* This is useful when running YaCy inside a container manager such as Heroku which decide which http port to use */
String systemDefinedPort = System.getProperty("http.port");
if(systemDefinedPort != null) {
try {
return Integer.parseInt(systemDefinedPort);
} catch(NumberFormatException e) {
}
}
return getConfigInt("port", 8090);
}
// a logger for this switchboard
public void setLog(final ConcurrentLog log) {
this.log = log;
}
public ConcurrentLog getLog() {
return this.log;
}
/**
* add whole map of key-value pairs to config
*
* @param otherConfigs
*/
public void setConfig(final Map<String, String> otherConfigs) {
final Iterator<Map.Entry<String, String>> i = otherConfigs.entrySet()
.iterator();
Map.Entry<String, String> entry;
while (i.hasNext()) {
entry = i.next();
setConfig(entry.getKey(), entry.getValue());
}
}
public void setConfig(final String key, final boolean value) {
setConfig(key, (value) ? "true" : "false");
}
public void setConfig(final String key, final long value) {
setConfig(key, Long.toString(value));
}
public void setConfig(final String key, final float value) {
setConfig(key, Float.toString(value));
}
public void setConfig(final String key, final double value) {
setConfig(key, Double.toString(value));
}
public void setConfig(final String key, final String value) {
// set the value
final String oldValue = this.configProps.put(key, value);
if (oldValue == null || !value.equals(oldValue)) {
saveConfig();
}
}
public void setConfig(final String key, final String[] value) {
StringBuilder sb = new StringBuilder();
if (value != null) for (String s: value) sb.append(',').append(s);
setConfig(key, sb.length() > 0 ? sb.substring(1) : "");
}
public void setConfig(final String key, Set<String> value) {
String[] a = new String[value.size()];
int c = 0;
for (String s: value) a[c++] = s;
setConfig(key, a);
}
public void removeConfig(final String key) {
this.configProps.remove(key);
}
/**
* Gets a configuration parameter from the properties.
*
* @param key
* name of the configuration parameter
* @param dflt
* default value which will be used in case parameter can not be
* found or if it is invalid
* @return value if the parameter or default value
*/
public String getConfig(final String key, final String dflt) {
// get the value
final String s = this.configProps.get(key);
// return value
if (s == null) {
return dflt;
}
return s;
}
/**
* Gets a configuration parameter from the properties.
*
* @param key
* name of the configuration parameter
* @param dflt
* default value which will be used in case parameter can not be
* found or if it is invalid
* @return value if the parameter or default value
*/
public long getConfigLong(final String key, final long dflt) {
try {
return Long.parseLong(getConfig(key, Long.toString(dflt)));
} catch (final NumberFormatException e) {
return dflt;
}
}
/**
* Gets a configuration parameter from the properties.
*
* @param key
* name of the configuration parameter
* @param dflt
* default value which will be used in case parameter can not be
* found or if it is invalid
* @return value if the parameter or default value
*/
public float getConfigFloat(final String key, final float dflt) {
try {
return Float.parseFloat(getConfig(key, Float.toString(dflt)));
} catch (final NumberFormatException e) {
return dflt;
}
}
public boolean isConnectedViaUpnp() {
return isConnectedViaUpnp;
}
public void setConnectedViaUpnp(final boolean isConnectedViaUpnp) {
this.isConnectedViaUpnp = isConnectedViaUpnp;
if (!isConnectedViaUpnp) {
upnpPortMap.clear();
}
}
public void setUpnpPorts(final String key, final int port) {
upnpPortMap.put(key, Integer.valueOf(port));
}
public void removeUpnpPort(final String key) {
upnpPortMap.remove(key);
}
/**
* Gets a configuration parameter from the properties.
*
* @param key
* name of the configuration parameter
* @param dflt
* default value which will be used in case parameter can not be
* found or if it is invalid
* @return value if the parameter or default value
*/
public int getConfigInt(final String key, final int dflt) {
try {
return Integer.parseInt(getConfig(key, Integer.toString(dflt)));
} catch (final NumberFormatException e) {
return dflt;
}
}
/**
* Gets a configuration parameter from the properties.
*
* @param key
* name of the configuration parameter
* @param dflt
* default value which will be used in case parameter can not be
* found or if it is invalid
* @return value if the parameter or default value
*/
public boolean getConfigBool(final String key, final boolean dflt) {
return Boolean.parseBoolean(getConfig(key, Boolean.toString(dflt)));
}
/**
* get a configuration parameter list
* @param key
* @param dflt a default list
* @return a list of strings which had been separated by comma in the setting
*/
public String[] getConfigArray(final String key, final String dflt) {
return CommonPattern.COMMA.split(this.getConfig(key, dflt));
}
/**
* get a configuration parameter set
* @param key
* @param dflt a default list
* @return a set of strings which had been separated by comma in the setting
*/
public Set<String> getConfigSet(final String key) {
Set<String> h = new LinkedHashSet<>();
for (String s: getConfigArray(key, "")) {s = s.trim(); if (s.length() > 0) h.add(s.trim());}
return h;
}
/**
* Create a File instance for a configuration setting specifying a path.
*
* @param key
* config key
* @param dflt
* default path value, that is used when there is no value
* <code>key</code> in the configuration.
* @return if the value of the setting is an absolute path String, then the
* returned File is derived from this setting only. Otherwise the
* path's file is constructed from the applications root path + the
* relative path setting.
*/
public File getDataPath(final String key, final String dflt) {
return getFileByPath(key, dflt, this.dataPath);
}
/**
* return file at path from config entry "key", or fallback to default dflt
*
* @param key
* @param dflt
* @return
*/
public File getAppPath(final String key, final String dflt) {
return getFileByPath(key, dflt, this.appPath);
}
private File getFileByPath(String key, String dflt, File prefix) {
final String path = getConfig(key, dflt).replace('\\', '/');
final File f = new File(path);
return (f.isAbsolute() ? new File(f.getAbsolutePath()) : new File(
prefix, path));
}
public Iterator<String> configKeys() {
return this.configProps.keySet().iterator();
}
/**
* write the changes to permanent storage (File)
*/
private void saveConfig() {
ConcurrentMap<String, String> configPropsCopy = new ConcurrentHashMap<String, String>();
configPropsCopy.putAll(this.configProps); // avoid concurrency problems
FileUtils.saveMap(this.configFile, configPropsCopy, this.configComment);
}
/**
* Gets configuration parameters which have been removed during
* initialization.
*
* @return contains parameter name as key and parameter value as value
*/
public ConcurrentMap<String, String> getRemoved() {
return this.configRemoved;
}
public void deployThread(final String threadName,
final String threadShortDescription,
final String threadLongDescription, final String threadMonitorURL,
final BusyThread newThread, final long startupDelay) {
deployThread(
threadName,
threadShortDescription,
threadLongDescription,
threadMonitorURL,
newThread,
startupDelay,
Long.parseLong(getConfig(threadName + "_idlesleep", "1000")),
Long.parseLong(getConfig(threadName + "_busysleep", "100")),
Long.parseLong(getConfig(threadName + "_memprereq", "1048576")),
Double.parseDouble(getConfig(threadName + "_loadprereq", "9.0")));
}
public void deployThread(final String threadName,
final String threadShortDescription,
final String threadLongDescription, final String threadMonitorURL,
final BusyThread newThread, final long startupDelay,
final long initialIdleSleep, final long initialBusySleep,
final long initialMemoryPreRequisite,
final double initialLoadPreRequisite) {
if (newThread.isAlive()) {
throw new RuntimeException(
"undeployed threads must not live; they are started as part of the deployment");
}
newThread.setStartupSleep(startupDelay);
long x;
try {
x = Long.parseLong(getConfig(threadName + "_idlesleep", "novalue"));
newThread.setIdleSleep(x);
} catch (final NumberFormatException e) {
newThread.setIdleSleep(initialIdleSleep);
setConfig(threadName + "_idlesleep", initialIdleSleep);
}
try {
x = Long.parseLong(getConfig(threadName + "_busysleep", "novalue"));
newThread.setBusySleep(x);
} catch (final NumberFormatException e) {
newThread.setBusySleep(initialBusySleep);
setConfig(threadName + "_busysleep", initialBusySleep);
}
try {
x = Long.parseLong(getConfig(threadName + "_memprereq", "novalue"));
newThread.setMemPreReqisite(x);
} catch (final NumberFormatException e) {
newThread.setMemPreReqisite(initialMemoryPreRequisite);
setConfig(threadName + "_memprereq", initialMemoryPreRequisite);
}
try {
final double load = Double.parseDouble(getConfig(threadName
+ "_loadprereq", "novalue"));
newThread.setLoadPreReqisite(load);
} catch (final NumberFormatException e) {
newThread.setLoadPreReqisite(initialLoadPreRequisite);
setConfig(threadName + "_loadprereq",
(float) initialLoadPreRequisite);
}
newThread.setDescription(threadShortDescription, threadLongDescription,
threadMonitorURL);
this.workerThreads.put(threadName, newThread);
// start the thread
if (this.workerThreads.containsKey(threadName)) {
newThread.start();
}
}
public BusyThread getThread(final String threadName) {
return this.workerThreads.get(threadName);
}
public void setThreadPerformance(final String threadName,
final long idleMillis, final long busyMillis,
final long memprereqBytes, final double loadprereq) {
final BusyThread thread = this.workerThreads.get(threadName);
if (thread != null) {
setConfig(threadName + "_idlesleep",
thread.setIdleSleep(idleMillis));
setConfig(threadName + "_busysleep",
thread.setBusySleep(busyMillis));
setConfig(threadName + "_memprereq", memprereqBytes);
thread.setMemPreReqisite(memprereqBytes);
setConfig(threadName + "_loadprereq", (float) loadprereq);
thread.setLoadPreReqisite(loadprereq);
}
}
public synchronized void terminateThread(final String threadName,
final boolean waitFor) {
if (this.workerThreads.containsKey(threadName)) {
((WorkflowThread) this.workerThreads.get(threadName))
.terminate(waitFor);
this.workerThreads.remove(threadName);
}
}
public void intermissionAllThreads(final long pause) {
final Iterator<String> e = this.workerThreads.keySet().iterator();
while (e.hasNext()) {
this.workerThreads.get(e.next()).intermission(pause);
}
}
public synchronized void terminateAllThreads(final boolean waitFor) {
Iterator<String> e = this.workerThreads.keySet().iterator();
while (e.hasNext()) {
((WorkflowThread) this.workerThreads.get(e.next()))
.terminate(false);
}
if (waitFor) {
e = this.workerThreads.keySet().iterator();
while (e.hasNext()) {
((WorkflowThread) this.workerThreads.get(e.next()))
.terminate(true);
e.remove();
}
}
}
public Iterator<String> /* of serverThread-Names (String) */threadNames() {
return this.workerThreads.keySet().iterator();
}
public File getDataPath() {
return this.dataPath;
}
public File getAppPath() {
return this.appPath;
}
@Override
public String toString() {
return this.configProps.toString();
}
public void handleBusyState(final int jobs) {
this.serverJobs = jobs;
}
/**
* Retrieve text data (e. g. config file) from file file may be an url or a
* filename with path relative to rootPath parameter
*
* @param file
* url or filename
* @param rootPath
* searchpath for file
* @param file
* file to use when remote fetching fails (null if unused)
*/
public Reader getConfigFileFromWebOrLocally(final String uri,
final String rootPath, final File file) throws IOException,
FileNotFoundException {
if (uri.startsWith("http://") || uri.startsWith("https://")) {
final String[] uris = CommonPattern.COMMA.split(uri);
for (String netdef : uris) {
netdef = netdef.trim();
try {
final RequestHeader reqHeader = new RequestHeader();
reqHeader
.put(HeaderFramework.USER_AGENT,
ClientIdentification.yacyInternetCrawlerAgent.userAgent);
final HTTPClient client = new HTTPClient(
ClientIdentification.yacyInternetCrawlerAgent);
client.setHeader(reqHeader.entrySet());
byte[] data = client
.GETbytes(
uri,
getConfig(
SwitchboardConstants.ADMIN_ACCOUNT_USER_NAME,
"admin"),
getConfig(
SwitchboardConstants.ADMIN_ACCOUNT_B64MD5,
""), false);
if (data == null || data.length == 0) {
continue;
}
// save locally in case next fetch fails
if (file != null) {
FileOutputStream f = new FileOutputStream(file);
f.write(data);
f.close();
}
return new InputStreamReader(new BufferedInputStream(
new ByteArrayInputStream(data)));
} catch (final Exception e) {
continue;
}
}
if (file != null && file.exists()) {
return new FileReader(file);
}
throw new FileNotFoundException();
}
final File f = (uri.length() > 0 && uri.startsWith("/")) ? new File(uri)
: new File(rootPath, uri);
if (f.exists())
return new FileReader(f);
throw new FileNotFoundException(f.toString());
}
private static Random pwGenerator = new Random();
/**
* Generates a random password.
*
* @return random password which is 20 characters long.
*/
public String genRandomPassword() {
return genRandomPassword(20);
}
/**
* Generates a random password of a given length.
*
* @param length
* length o password
* @return password of given length
*/
public String genRandomPassword(final int length) {
byte[] bytes = new byte[length];
pwGenerator.nextBytes(bytes);
return Digest.encodeMD5Hex(bytes);
}
/**
* set/remember jetty server
*
* @param jettyserver
*/
public void setHttpServer(YaCyHttpServer jettyserver) {
this.httpserver = jettyserver;
}
public YaCyHttpServer getHttpServer() {
return httpserver;
}
}