Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
5827 amar.kumar 1
/*
2
 *	Copyright 2005 stat4j.org
3
 *
4
 *   Licensed under the Apache License, Version 2.0 (the "License");
5
 *   you may not use this file except in compliance with the License.
6
 *	You may obtain a copy of the License at
7
 *
8
 *       http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 *   Unless required by applicable law or agreed to in writing, software
11
 *   distributed under the License is distributed on an "AS IS" BASIS,
12
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 *   See the License for the specific language governing permissions and
14
 *   limitations under the License.
15
 */
16
 
17
package net.sourceforge.stat4j.filter;
18
 
19
import java.io.PrintStream;
20
import java.util.ArrayList;
21
import java.util.Date;
22
import java.util.HashMap;
23
import java.util.Iterator;
24
import java.util.Map;
25
import java.util.Properties;
26
 
27
import net.sourceforge.stat4j.Alert;
28
import net.sourceforge.stat4j.Calculator;
29
import net.sourceforge.stat4j.Filter;
30
import net.sourceforge.stat4j.Metric;
31
import net.sourceforge.stat4j.Reading;
32
import net.sourceforge.stat4j.Statistic;
33
import net.sourceforge.stat4j.Unit;
34
import net.sourceforge.stat4j.config.StatisticsFactory;
35
import net.sourceforge.stat4j.util.Util;
36
 
37
 
38
 
39
/**
40
 * Name:		MetricCollector.java
41
 * Date:		Sep 1, 2004
42
 * Description:
43
 * 
44
 * 
45
 * @author Lara D'Abreo
46
 */
47
public class MetricCollector {
48
 
49
	private static MetricCollector instance = null;
50
 
51
	// Reading caches - one for within threads
52
	// and the other global
53
	protected ThreadLocal localReadingCache = new ThreadLocal() {
54
		protected synchronized Object initialValue() {
55
			return new HashMap();
56
		}
57
	};
58
	protected Map readingCache;
59
 
60
	// Stats
61
	protected Map statistics;
62
	protected Map calculators;
63
	protected Map alerts;
64
 
65
	// Scraper
66
	protected RegExpScraper scraper;
67
 
68
	// Filters
69
	protected FilterStatisticMap[] filters;
70
 
71
	// Alerts
72
 
73
	public MetricCollector() {
74
		this.scraper = new RegExpScraper();
75
		this.readingCache = new HashMap();
76
		this.calculators = new HashMap();
77
		this.statistics = new HashMap();
78
		this.alerts = new HashMap();
79
	}
80
 
81
	/**
82
	 * Reset all statistic values to 0
83
	 */
84
	public void reset() {
85
		Iterator itr = calculators.keySet().iterator();
86
		while (itr.hasNext()) {
87
			Object key = itr.next();
88
			Calculator c = (Calculator) calculators.get(key);
89
			c.reset();
90
		}
91
	}
92
 
93
	public void init() {
94
		// load factory
95
		String factoryName = Util.getValue("factory.name");
96
		String prefix = "factory." + factoryName + ".";
97
		String className = Util.getValue(prefix + "classname");
98
 
99
		StatisticsFactory factory =
100
			(StatisticsFactory) Util.createObject(className);
101
		Properties p = Util.createProperties(prefix);
102
		factory.init(p);
103
 
104
		// load stats to collect/calculate
105
		Statistic[] stats = factory.loadStatistics();
106
 
107
		// load alerts
108
		Alert[] alerts = factory.loadAlerts();
109
 
110
		for (int i = 0; i < alerts.length; ++i) {
111
			Alert a = alerts[i];
112
 
113
			this.alerts.put(a.getStatisticName(), a);
114
		}
115
 
116
 
117
		HashMap filterMap = new HashMap();
118
 
119
		// Map statistics
120
		for (int i = 0; i < stats.length; ++i) {
121
			Statistic s = stats[i];
122
 
123
			statistics.put(s.getName(), s);
124
 
125
			Calculator c = factory.createCalculator(s.getCalculator(), s);
126
			calculators.put(s.getName(), c);
127
 
128
			// Map filters by regexpression
129
			// to ensure we only match on a given 
130
			// expression once
131
			String matchExp = s.getFirst().getMatch();
132
			FilterStatisticMap f = (FilterStatisticMap) filterMap.get(matchExp);
133
			if (f == null) {
134
				f = new FilterStatisticMap(matchExp);
135
				filterMap.put(matchExp, f);
136
			}
137
			f.getFirsts().add(s);
138
 
139
			if (s.getSecond() != null) {
140
 
141
				matchExp = s.getSecond().getMatch();
142
				f = (FilterStatisticMap) filterMap.get(matchExp);
143
				if (f == null) {
144
					f = new FilterStatisticMap(matchExp);
145
					filterMap.put(matchExp, f);
146
				}
147
				f.getSeconds().add(s);
148
			} //fi
149
		}
150
 
151
		filters =
152
			(FilterStatisticMap[]) filterMap.values().toArray(
153
				new FilterStatisticMap[0]);
154
 
155
	};
156
 
157
	public static synchronized MetricCollector getInstance() {
158
		if (instance == null) {
159
			instance = new MetricCollector();
160
			instance.init();
161
		}
162
		return instance;
163
	}
164
 
165
	public void applyLog(String log, Throwable throwable) {
166
		// Iterate over filters and see if
167
		// a match has occured
168
		System.out.println(log);
169
        String throwableInfo = (throwable == null)? "" : throwable.toString() + " <- ";
170
        System.out.println(throwableInfo);
171
        String fullLog = throwableInfo + log;
172
		for (int i = 0; i < filters.length; ++i) {
173
			if (filters[i].isMatch(fullLog)) {
174
				System.out.println("GenerateMetric called for filter : " +filters[i]);
175
				generateMetrics(filters[i], fullLog);
176
			}
177
		} //rof
178
 
179
	}
180
 
181
	protected void generateMetrics(FilterStatisticMap map, String log) {
182
		processReadingsThatMatchFirstFilters(map, log);
183
		processReadingsThatMatchSecondFilters(map, log);
184
	}
185
 
186
	private void processReadingsThatMatchSecondFilters(
187
		FilterStatisticMap filter,
188
		String log) {
189
 
190
		ArrayList seconds = filter.getSeconds();
191
		for (int i = 0; i < seconds.size(); ++i) {
192
			Statistic statistic = (Statistic) seconds.get(i);
193
 
194
			// Get Calculator
195
			Calculator calculator =
196
				(Calculator) calculators.get(statistic.getName());
197
 
198
			// Generate Reading
199
			Reading reading =
200
				generateReading(statistic, statistic.getSecond(), log);
201
			if (reading == null)
202
				continue;
203
 
204
			if (calculator.isApplyImmediate()) {
205
				Metric metric = new Metric(statistic.getName(), null, reading);
206
				calculateStatistic(calculator, metric);
207
 
208
			} else {
209
				matchReading(statistic, calculator, reading);
210
			}
211
		} // rof
212
 
213
	}
214
 
215
	private void processReadingsThatMatchFirstFilters(
216
		FilterStatisticMap filter,
217
		String log) {
218
		ArrayList firsts = filter.getFirsts();
219
		for (int i = 0; i < firsts.size(); ++i) {
220
			Statistic statistic = (Statistic) firsts.get(i);
221
 
222
			// Get Calculator
223
			Calculator calculator =
224
				(Calculator) calculators.get(statistic.getName());
225
 
226
			// Generate Reading
227
			Reading reading =
228
				generateReading(statistic, statistic.getFirst(), log);
229
			if (reading == null)
230
				continue;
231
 
232
			if (calculator.isApplyImmediate()) {
233
				Metric metric = new Metric(statistic.getName(), reading);
234
				calculateStatistic(calculator, metric);
235
 
236
			} else {
237
				cacheReading(statistic, reading);
238
			}
239
		} // rof
240
	}
241
 
242
	protected Reading generateReading(
243
		Statistic statistic,
244
		Filter filter,
245
		String log) {
246
 
247
		if (statistic.getUnit().equals(Unit.VALUE)) {
248
			double value = 1.0;
249
 
250
			// scrap value if scraping required
251
			if (filter.getScape() != null) {
252
				Double scrapValue =
253
					scraper.scrapUserDefinedValue(log, filter.getScape());
254
 
255
				if (scrapValue != null) {
256
					value = scrapValue.doubleValue();
257
				} else {
258
					// scrape failed
259
					return null;
260
				}
261
			}
262
			return new Reading(value);
263
		} else {
264
			return new Reading();
265
		}
266
	}
267
 
268
	protected Map getReadingCache(Statistic statistic) {
269
		if (statistic.isCaptureInThread()) {
270
			// look for match locally
271
			return (Map) localReadingCache.get();
272
		} else {
273
			return readingCache;
274
		}
275
	}
276
	protected void matchReading(
277
		Statistic statistic,
278
		Calculator calculator,
279
		Reading reading) {
280
		Map map = null;
281
 
282
		Map cache = getReadingCache(statistic);
283
 
284
		Reading first = (Reading) cache.get(statistic.getName());
285
 
286
		// found match to this reading
287
		if (first != null) {
288
			// generate metric
289
			Metric metric = new Metric(statistic.getName(), first, reading);
290
			calculateStatistic(calculator, metric);
291
 
292
			// clear first reading from cache 
293
			// ready to collect again
294
			cache.remove(statistic.getName());
295
		}
296
 
297
	}
298
 
299
	protected void cacheReading(Statistic statistic, Reading reading) {
300
 
301
		Map cache = getReadingCache(statistic);
302
		cache.put(statistic.getName(), reading);
303
	}
304
 
305
	protected void calculateStatistic(Calculator calculator, Metric metric) {
306
		calculator.applyMetric(metric);
307
 
308
		Alert a = (Alert) alerts.get(metric.getStatisticName());
309
 
310
		if (a != null) {
311
			a.evaluateAlert(calculator.getResult());
312
		}
313
 
314
	}
315
 
316
	public void close() {
317
		/*
318
		localReadingCache = null;
319
		readingCache.clear();
320
		statistics.clear();
321
		calculators.clear();
322
		*/
323
	}
324
 
325
	public void report(PrintStream out) {
326
		Calculator[] calcs =
327
			(Calculator[]) calculators.values().toArray(new Calculator[0]);
328
		for (int i = 0; i < calcs.length; ++i) {
329
			Calculator calculator = calcs[i];
330
			double result = calculator.getResult();
331
			long ts = calculator.getTimestamp();
332
 
333
			out.print(
334
				"Statistic("
335
					+ calculator.getStatistic().getDescription()
336
					+ ") value("
337
					+ result
338
					+ ") time ("
339
					+ new Date(ts)
340
					+ ")\n");
341
		}
342
	}
343
 
344
 
345
}