/
PropertiesManager.java
587 lines (520 loc) · 22.3 KB
/
PropertiesManager.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
package jrds;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.xml.DOMConfigurator;
import jrds.snmp.MainStarter;
import jrds.starter.Timer;
import jrds.store.RrdDbStoreFactory;
import jrds.store.StoreFactory;
import jrds.webapp.ACL;
import jrds.webapp.RolesACL;
/**
* An less ugly class supposed to manage properties should be reworked
*
* @author Fabrice Bacchella
*/
public class PropertiesManager extends Properties {
private final Logger logger = Logger.getLogger(PropertiesManager.class);
public static final class TimerInfo {
public int step;
public int timeout;
public int numCollectors;
public int slowCollectTime;
}
private final FileFilter filter = new FileFilter() {
public boolean accept(File file) {
return (!file.isHidden()) && (file.isFile() && file.getName().endsWith(".jar"));
}
};
public PropertiesManager() {
}
public PropertiesManager(File propFile) {
join(propFile);
update();
}
private int parseInteger(String s) {
Integer integer;
if (s != null) {
if (s.startsWith("#")) {
integer = Integer.valueOf(s.substring(1), 16);
} else if (s.startsWith("0x")) {
integer = Integer.valueOf(s.substring(2), 16);
} else if (s.startsWith("0") && s.length() > 1) {
integer = Integer.valueOf(s.substring(1), 8);
} else {
integer = Integer.valueOf(s);
}
return integer.intValue();
}
throw new NumberFormatException("Parsing null string");
}
public boolean parseBoolean(String s) {
s = s.toLowerCase().trim();
boolean retValue = false;
if("1".equals(s))
retValue = true;
else if("yes".equals(s))
retValue = true;
else if("y".equals(s))
retValue = true;
else if("true".equals(s))
retValue = true;
else if("enable".equals(s))
retValue = true;
else if("on".equals(s))
retValue = true;
return retValue;
}
public Map<String, String> subKey(String prefix) {
Pattern regex = Pattern.compile("^" + prefix + "\\.");
Map<String, String> props = new HashMap<String, String>();
for(Map.Entry<Object, Object> e: entrySet()) {
String key = (String) e.getKey();
Matcher m = regex.matcher(key);
if(m.find()) {
String value = (String) e.getValue();
props.put(m.replaceFirst(""), value);
}
}
return props;
}
public void join(URL url) {
try {
InputStream inputstream = url.openStream();
load(inputstream);
inputstream.close();
} catch (IOException ex) {
logger.warn("Invalid URL: " + ex.getLocalizedMessage());
}
}
public void join(Properties moreProperties) {
putAll(moreProperties);
}
public void join(File propFile) {
logger.debug("Using propertie file " + propFile.getAbsolutePath());
InputStream inputstream = null;
try {
inputstream = new FileInputStream(propFile);
load(inputstream);
} catch (IOException ex) {
logger.warn("Invalid properties file " + propFile.getAbsolutePath() + ": " + ex.getLocalizedMessage());
} finally {
IOUtils.closeQuietly(inputstream);
}
}
public void join(InputStream propStream) {
try {
load(propStream);
} catch (IOException ex) {
logger.warn("Invalid properties stream " + propStream + ": " + ex);
}
}
private ClassLoader doClassLoader(String extendedclasspath) {
FileFilter filter = new FileFilter() {
public boolean accept(File file) {
return (!file.isHidden()) && file.isFile() && file.getName().endsWith(".jar");
}
};
Collection<URI> urls = new ArrayList<URI>();
if(extendedclasspath != null && !"".equals(extendedclasspath)) {
for(String pathElement: extendedclasspath.split(";")) {
logger.debug("Setting class directories to: " + pathElement);
File path = new File(pathElement);
if(path.isDirectory()) {
for(File f: path.listFiles(filter)) {
urls.add(f.toURI());
}
} else if(filter.accept(path)) {
urls.add(path.toURI());
}
}
}
for(URI u: libspath) {
urls.add(u);
}
URL[] arrayUrl = new URL[urls.size()];
int i = 0;
for(URI u: urls) {
try {
arrayUrl[i++] = u.toURL();
} catch (MalformedURLException e) {
logger.error("Invalid URL in libs path: " + u);
}
}
if(logger.isDebugEnabled())
logger.debug("Internal class loader will look in:" + urls);
return new URLClassLoader(arrayUrl, getClass().getClassLoader()) {
@Override
public String toString() {
return "JRDS' class loader";
}
};
}
private File prepareDir(File dir, boolean autocreate, boolean readOnly) throws IOException {
if(dir == null) {
throw new IOException("path not defined");
}
if(!dir.exists()) {
if(!autocreate) {
throw new IOException(dir + " doesn't exist");
}
if(autocreate && !dir.mkdirs()) {
throw new IOException(dir + " doesn't exist and can't be created");
}
} else if(!dir.isDirectory()) {
throw new IOException(dir + " exists but is not a directory");
} else if(!dir.canWrite() && !readOnly) {
throw new IOException(dir + " exists can't be written");
}
return dir;
}
private File prepareDir(String path, boolean autocreate, boolean readOnly) throws IOException {
if(path == null || path.isEmpty()) {
throw new IOException("path not defined");
}
File dir = new File(path);
return prepareDir(dir, autocreate, readOnly);
}
public void configureStores() {
String defaultStorename = getProperty("defaultstore", StoreFactory.DEFAULTNAME);
Map<String, Properties> storesConfig = new HashMap<String, Properties>(1);
storesConfig.put(defaultStorename, new Properties());
Properties defaultStoreProps = storesConfig.get(defaultStorename);
// Put old values in the default factory properties
for(String oldProps: new String[] { "rrdbackend", "dbPoolSize", "usepool" }) {
if(getProperty(oldProps) != null)
defaultStoreProps.put(oldProps, getProperty(oldProps));
}
// Simple case, just the store factory
if(getProperty("storefactory") != null) {
String defaultstorefactoryclassname = getProperty("storefactory");
defaultStoreProps.put("factory", defaultstorefactoryclassname);
}
String propertiesListStores = getProperty("stores", "");
if(!propertiesListStores.trim().isEmpty()) {
for(String storeName: propertiesListStores.split(",")) {
storeName = storeName.trim();
Map<String, String> storeInfo = subKey("store." + storeName);
Properties props = new Properties();
props.putAll(storeInfo);
storesConfig.put(storeName, props);
}
}
// Ensure that the default store was not forgotten
if(defaultStoreProps.get("factory") == null) {
defaultStoreProps.put("factory", RrdDbStoreFactory.class.getName());
}
logger.trace(Util.delayedFormatString("Stores configuration: %s", storesConfig));
// Ok, now configure and store the factories
for(Map.Entry<String, Properties> e: storesConfig.entrySet()) {
String storeName = e.getKey();
Properties storesInfo = e.getValue();
try {
String storefactoryclassname = storesInfo.getProperty("factory");
if(storefactoryclassname != null && !storefactoryclassname.isEmpty()) {
StoreFactory sf = (StoreFactory) extensionClassLoader.loadClass(storefactoryclassname).getConstructor().newInstance();
sf.configureStore(this, storesInfo);
sf.start();
stores.put(storeName, sf);
} else {
logger.error(Util.delayedFormatString("store factory %s invalid, no factory given", storeName));
}
} catch (Exception e1) {
jrds.Util.log(getClass().getCanonicalName(), logger, Level.ERROR, e1, "store factory %s failed to configure: %s", storeName, e1);
}
}
logger.debug(Util.delayedFormatString("Stores configured: %s", stores));
logger.debug(Util.delayedFormatString("default store: %s", defaultStorename));
defaultStore = stores.remove(defaultStorename);
}
@SuppressWarnings("unchecked")
public void importSystemProps() {
String localPropFile = System.getProperty("jrds.propertiesFile");
if(localPropFile != null)
join(new File(localPropFile));
Pattern jrdsPropPattern = Pattern.compile("jrds\\.(.+)");
Properties p = System.getProperties();
for(String name: Collections.list((Enumeration<String>) p.propertyNames())) {
Matcher m = jrdsPropPattern.matcher(name);
if(m.matches()) {
String prop = System.getProperty(name);
if(prop != null)
setProperty(m.group(1), prop);
}
}
}
public void update() {
Locale.setDefault(new Locale("POSIX"));
// **********************
// The class loader configuration
// First resolve libspath, doClassLoader needs it
try {
Enumeration<URL> descurl = getClass().getClassLoader().getResources("desc");
while (descurl.hasMoreElements()) {
libspath.add(descurl.nextElement().toURI());
}
} catch (URISyntaxException e) {
throw new RuntimeException("URI syntax exception", e);
} catch (IOException e) {
throw new RuntimeException("Can't locate embedded desc", e);
}
String libspathString = getProperty("libspath", "");
if(!"".equals(libspathString.trim())) {
for(String libName: libspathString.split(";")) {
File lib = new File(libName.trim());
boolean noJarDir = true;
if(lib.isDirectory()) {
File[] foundFiles = lib.listFiles(filter);
if(foundFiles == null) {
logger.error("Failed to search in " + lib);
continue;
}
for(File f: foundFiles) {
libspath.add(f.toURI());
noJarDir = false;
}
}
// If a jar was found previously, it's not a source directory,
// don't add it, only the jar in it are interesting
if(lib.isFile() || (lib.isDirectory() && noJarDir))
libspath.add(lib.toURI());
}
}
// The class loader is configured early, it can be used by log4j
extensionClassLoader = doClassLoader(getProperty("classpath", ""));
// **********************
// The log configuration
// log4j uses the contextClassLoader, set it so it can uses fancy appenders
Thread.currentThread().setContextClassLoader(extensionClassLoader);
// Log configuration is done early
boolean nologging = parseBoolean(getProperty("nologging", "false"));
String log4jXmlFile = getProperty("log4jxmlfile", "");
String log4jPropFile = getProperty("log4jpropfile", "");
if(log4jXmlFile != null && !log4jXmlFile.trim().isEmpty()) {
File xmlfile = new File(log4jXmlFile.trim());
if(!xmlfile.canRead()) {
logger.error("log4j xml file " + xmlfile.getPath() + " can't be read, log4j not configured");
} else {
BasicConfigurator.resetConfiguration();
DOMConfigurator.configure(xmlfile.getPath());
nologging = true;
logger.info("configured with " + xmlfile.getPath());
}
} else if(log4jPropFile != null && !log4jPropFile.trim().isEmpty()) {
File propfile = new File(log4jPropFile.trim());
if(!propfile.canRead()) {
logger.error("log4j properties file " + propfile.getPath() + " can't be read, log4j not configured");
} else {
BasicConfigurator.resetConfiguration();
PropertyConfigurator.configure(propfile.getPath());
nologging = true;
logger.info("configured with " + propfile.getPath());
}
}
// the logging setup was not previously captured
if(!nologging) {
for(String ls: new String[] { "trace", "debug", "info", "error", "fatal", "warn" }) {
Level l = Level.toLevel(ls);
String param = getProperty("log." + ls, "");
if(!"".equals(param)) {
String[] loggersName = param.split(",");
List<String> loggerList = new ArrayList<String>(loggersName.length);
for(String logger: loggersName) {
loggerList.add(logger.trim());
}
loglevels.put(l, loggerList);
}
}
loglevel = Level.toLevel(getProperty("loglevel", "info"));
logfile = getProperty("logfile");
try {
JrdsLoggerConfiguration.configure(this);
} catch (IOException e1) {
logger.error("Unable to set log file to " + this.logfile + ": " + e1);
}
} else {
JrdsLoggerConfiguration.setExternal();
}
legacymode = parseBoolean(getProperty("legacymode", "1"));
strictparsing = parseBoolean(getProperty("strictparsing", "false"));
// Directories configuration
autocreate = parseBoolean(getProperty("autocreate", "false"));
try {
configdir = prepareDir(getProperty("configdir"), autocreate, true);
} catch (IOException e) {
throw new IllegalArgumentException("configuration directory invalid: " + e.getMessage(), e);
}
try {
rrddir = prepareDir(getProperty("rrddir"), autocreate, false);
} catch (IOException e) {
// rrddir is mandatory only if default store is rrd
if(RrdDbStoreFactory.class.getName().equals(getProperty("storefactory", RrdDbStoreFactory.class.getName()))) {
throw new IllegalArgumentException("probe storage directory invalid: " + e.getMessage(), e);
}
}
// Different place to find the temp directory
try {
String tmpDirProperty = getProperty("tmpdir", "");
if(tmpDirProperty.isEmpty()) {
tmpDirProperty = System.getProperty("javax.servlet.context.tempdir", "");
}
if(tmpDirProperty.isEmpty()) {
File tempDirPath = new File(System.getProperty("java.io.tmpdir"), "jrds");
tempDirPath.mkdir();
tmpDirProperty = tempDirPath.getCanonicalPath();
}
if(tmpDirProperty == null) {
throw new IllegalArgumentException("No temp directory path found");
}
tmpdir = prepareDir(tmpDirProperty, autocreate, true);
} catch (IOException e) {
throw new IllegalArgumentException("No temp directory defined: " + e.getMessage(), e);
}
// Configure the timers
step = parseInteger(getProperty("step", "300"));
timeout = parseInteger(getProperty("timeout", "10"));
numCollectors = parseInteger(getProperty("collectorThreads", "1"));
slowcollecttime = parseInteger(getProperty("slowcollecttime", Integer.toString(timeout + 1)));
String propertiesList = getProperty("timers", "");
if(timeout * 2 >= step) {
logger.warn("useless default timer, step must be more than twice the timeout");
}
if(!propertiesList.trim().isEmpty()) {
for(String timerName: propertiesList.split(",")) {
timerName = timerName.trim();
TimerInfo ti = new TimerInfo();
ti.step = parseInteger(getProperty("timer." + timerName + ".step", Integer.toString(step)));
ti.timeout = parseInteger(getProperty("timer." + timerName + ".timeout", Integer.toString(timeout)));
ti.numCollectors = parseInteger(getProperty("timer." + timerName + ".collectorThreads", Integer.toString(numCollectors)));
ti.slowCollectTime = parseInteger(getProperty("timer." + timerName + ".slowcollecttime", Integer.toString(ti.timeout + 1)));
if(ti.timeout * 2 >= ti.step) {
logger.warn("useless timer " + timerName + ", step must be more than twice the timeout");
break;
}
timers.put(timerName, ti);
}
}
// Add the default timer
TimerInfo ti = new TimerInfo();
ti.step = step;
ti.timeout = timeout;
ti.numCollectors = numCollectors;
ti.slowCollectTime = slowcollecttime;
timers.put(Timer.DEFAULTNAME, ti);
//
// Tab configuration
//
// We search for the tabs list in the property tab
// spaces are non-significant
String tabsList = getProperty("tabs");
if(tabsList != null && !"".equals(tabsList.trim())) {
this.tabsList = new ArrayList<String>();
for(String tab: tabsList.split(",")) {
this.tabsList.add(tab.trim());
}
}
//
// Security configuration
//
security = parseBoolean(getProperty("security", "false"));
if(security) {
userfile = getProperty("userfile", "users.properties");
adminrole = getProperty("adminrole", adminrole);
adminACL = new ACL.AdminACL(adminrole);
String defaultRolesString = getProperty("defaultroles", "ANONYMOUS");
defaultRoles = new HashSet<String>();
for(String aRole: defaultRolesString.split(",")) {
defaultRoles.add(aRole.trim());
}
defaultACL = new RolesACL(defaultRoles);
defaultACL = defaultACL.join(adminACL);
logger.debug(jrds.Util.delayedFormatString("Admin ACL is %s", adminACL));
logger.debug(jrds.Util.delayedFormatString("Default ACL is %s", defaultACL));
}
readonly = parseBoolean(getProperty("readonly", "0"));
withjmx = parseBoolean(getProperty("jmx", "0"));
if(withjmx) {
jmxprops = subKey("jmx");
if(!jmxprops.containsKey("protocol")) {
jmxprops.put("protocol", "rmi");
}
}
archivesSet = getProperty("archivesset", ArchivesSet.DEFAULT.getName());
//
// SNMP MIB configuration
//
String propertiesmibDirs = getProperty("mibdirs", "");
if(!propertiesmibDirs.trim().isEmpty()) {
try {
MainStarter.configure(propertiesmibDirs);
} catch (NoClassDefFoundError e) {
logger.error("mibdirs configured, but SNMP code not availabe");
}
}
}
public File configdir;
public File rrddir;
public File tmpdir;
public String urlpngroot;
public String logfile;
public int slowcollecttime;
public int step;
public Map<String, TimerInfo> timers = new HashMap<String, TimerInfo>();
public int numCollectors;
public final Set<URI> libspath = new HashSet<URI>();
public boolean strictparsing = false;
public ClassLoader extensionClassLoader;
public final Map<Level, List<String>> loglevels = new HashMap<Level, List<String>>();
public Level loglevel;
public boolean legacymode;
public boolean autocreate;
public int timeout;
public boolean security = false;
public String userfile = "/dev/zero";
public Set<String> defaultRoles = Collections.emptySet();
public String adminrole = "admin";
public ACL defaultACL = ACL.ALLOWEDACL;
public ACL adminACL = ACL.ALLOWEDACL;
public boolean readonly = false;
public boolean withjmx = false;
public Map<String, String> jmxprops = Collections.emptyMap();
public String archivesSet;
public static final String FILTERTAB = "filtertab";
public static final String CUSTOMGRAPHTAB = "customgraph";
public static final String SUMSTAB = "sumstab";
public static final String SERVICESTAB = "servicestab";
public static final String VIEWSTAB = "viewstab";
public static final String HOSTSTAB = "hoststab";
public static final String TAGSTAB = "tagstab";
public static final String ADMINTAB = "adminTab";
public Map<String, StoreFactory> stores = new HashMap<String, StoreFactory>();
public StoreFactory defaultStore;
public List<String> tabsList = Arrays.asList(FILTERTAB, CUSTOMGRAPHTAB, "@", SUMSTAB, SERVICESTAB, VIEWSTAB, HOSTSTAB, TAGSTAB, ADMINTAB);
}