KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mr > core > stats > StatManager


1 /*
2  * Copyright 2002 by
3  * <a HREF="http://www.coridan.com">Coridan</a>
4  * <a HREF="mailto: support@coridan.com ">support@coridan.com</a>
5  *
6  * The contents of this file are subject to the Mozilla Public License Version
7  * 1.1 (the "License"); you may not use this file except in compliance with the
8  * License. You may obtain a copy of the License at
9  * http://www.mozilla.org/MPL/
10  *
11  * Software distributed under the License is distributed on an "AS IS" basis,
12  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
13  * for the specific language governing rights and limitations under the
14  * License.
15  *
16  * The Original Code is "MantaRay" (TM).
17  *
18  * The Initial Developer of the Original Code is Uri Schneider.
19  * Portions created by the Initial Developer are Copyright (C) 2006
20  * Coridan Inc. All Rights Reserved.
21  *
22  * Contributor(s): all the names of the contributors are added in the source
23  * code where applicable.
24  *
25  * Alternatively, the contents of this file may be used under the terms of the
26  * LGPL license (the "GNU LESSER GENERAL PUBLIC LICENSE"), in which case the
27  * provisions of LGPL are applicable instead of those above. If you wish to
28  * allow use of your version of this file only under the terms of the LGPL
29  * License and not to allow others to use your version of this file under
30  * the MPL, indicate your decision by deleting the provisions above and
31  * replace them with the notice and other provisions required by the LGPL.
32  * If you do not delete the provisions above, a recipient may use your version
33  * of this file under either the MPL or the GNU LESSER GENERAL PUBLIC LICENSE.
34  
35  *
36  * This library is free software; you can redistribute it and/or modify it
37  * under the terms of the MPL as stated above or under the terms of the GNU
38  * Lesser General Public License as published by the Free Software Foundation;
39  * either version 2.1 of the License, or any later version.
40  *
41  * This library is distributed in the hope that it will be useful, but WITHOUT
42  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
43  * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
44  * License for more details.
45  */

46 package org.mr.core.stats;
47
48 import javax.jms.Connection JavaDoc;
49 import javax.jms.ConnectionFactory JavaDoc;
50 import javax.jms.JMSException JavaDoc;
51 import javax.jms.MessageProducer JavaDoc;
52 import javax.jms.Session JavaDoc;
53 import javax.jms.TextMessage JavaDoc;
54 import javax.jms.Topic JavaDoc;
55
56 import org.apache.commons.logging.Log;
57 import org.apache.commons.logging.LogFactory;
58 import org.mr.MantaAgent;
59 import org.mr.MantaAgentConstants;
60 import org.mr.api.jms.MantaConnectionFactory;
61 import org.mr.core.configuration.ConfigManager;
62 import org.mr.core.configuration.ConfigurationChangeEvent;
63 import org.mr.core.configuration.ConfigurationChangeListener;
64 import org.mr.core.stats.cmc.CMCAgentStats;
65 import org.mr.core.util.SystemTime;
66 import org.mr.core.util.TimeoutTimer;
67 import org.mr.core.util.Timeoutable;
68
69 /**
70  * StatManager.java
71  *
72  *
73  * Created: Wed Feb 18 16:31:52 2004
74  *
75  * @author Uri Schneider
76  * @version 1.0
77  */

78 public class StatManager {
79     private String JavaDoc serviceName;
80     private long updateInterval; // in milliseconds
81
private boolean sendUpdates;
82     private boolean collectStats;
83     private TimeoutTimer timer;
84     private ConfigManager config;
85     private Log log;
86     private Timeoutable topicPublisher;
87     
88     // counters
89
private AggregateCounter totalBytes;
90     private AggregateCounter totalMessages;
91     private TemporalCounter temporalBytes;
92     private TemporalCounter temporalMessages;
93     private MaxCounter maxMem;
94     private CurrentCounter currentMem;
95     private CurrentCounter freeMem;
96     
97     // JMS resources
98
private ConnectionFactory JavaDoc factory;
99     private Connection JavaDoc con;
100     private Session JavaDoc ses;
101     private MessageProducer JavaDoc prod;
102     private Topic JavaDoc topic;
103     
104     
105     // constructor
106
public StatManager() {
107         // init counters
108
this.totalBytes = new AggregateCounter();
109         this.totalMessages = new AggregateCounter();
110         this.temporalBytes = new TemporalCounter(5000, 60); // 60 * 5 secs
111
this.temporalMessages = new TemporalCounter(5000, 60);
112         this.maxMem = new MaxCounter();
113         this.currentMem = new CurrentCounter();
114         this.freeMem = new CurrentCounter();
115         
116         // configuration stuff
117
this.config = MantaAgent.getInstance().getSingletonRepository().getConfigManager();
118         this.serviceName = config.getStringProperty("statistics.topic", "StatsTopic");
119         if (this.serviceName.equals("")) {
120             this.serviceName = null;
121         }
122         this.updateInterval = config.getLongProperty("statistics.update_interval", 3600L) * 1000;
123         this.sendUpdates = config.getBooleanProperty("statistics.send_updates", false);
124         this.collectStats = config.getBooleanProperty("statistics.collect_stats", false);
125         config.registerAsConfigChangeListener(new ConfigurationChangeListener() {
126             public void refresh(ConfigurationChangeEvent e) {
127                 if (e.getKey().equals("statistics.send_updates")) {
128                     StatManager.this.sendUpdates = StatManager.this.config.
129                             getBooleanProperty("statistics.send_updates", false);
130                 }
131                 if (e.getKey().equals("statistics.collect_stats")) {
132                     StatManager.this.collectStats = StatManager.this.config.
133                             getBooleanProperty("statistics.collect_stats", false);
134                 }
135                 if (StatManager.this.collectStats && StatManager.this.sendUpdates) {
136                     startUpdates();
137                 } else {
138                     stopUpdates();
139                 }
140             }
141         });
142         
143         // timer stuff
144
this.timer = new TimeoutTimer("Stat_Timer");
145         this.topicPublisher = new Timeoutable() {
146             public void timeout(Object JavaDoc o) {
147                 publishUpdate();
148                 timer.addTimeout(this, this, StatManager.this.updateInterval);
149             }
150         };
151         Timeoutable memSampler = new Timeoutable() {
152             public void timeout(Object JavaDoc event) {
153                 long mem = Runtime.getRuntime().totalMemory();
154                 maxMem.addSample(mem);
155                 currentMem.addSample(mem);
156                 freeMem.addSample(Runtime.getRuntime().freeMemory());
157                 timer.addTimeout(this, this, 60000);
158             }
159         };
160         timer.addTimeout(memSampler, memSampler, 1000);
161         
162         this.log = LogFactory.getLog("StatManager");
163         
164         if (this.collectStats && this.sendUpdates) {
165             startUpdates();
166         }
167     } // StatManager constructor
168

169     
170     // initializes the JMS resources
171
private void initJMS() throws JMSException JavaDoc {
172         factory = new MantaConnectionFactory();
173         con = factory.createConnection();
174         ses = con.createSession(false,Session.AUTO_ACKNOWLEDGE);
175         topic = ses.createTopic(serviceName);
176         prod = ses.createProducer(topic);
177     }
178     
179     
180     // disposes the JMS resources
181
private void closeJMS() throws JMSException JavaDoc {
182         con.close();
183         ses = null;
184         topic = null;
185         prod = null;
186         con = null;
187         factory = null;
188     }
189     
190     /**
191      * This is used by a Transport object to report a message had been sent.
192      *
193      * @param byteCount The message's size in bytes
194      */

195     public void addMessageSample(long byteCount) {
196         if (this.collectStats) {
197             totalBytes.addSample(byteCount);
198             totalMessages.addSample(1);
199             temporalBytes.addSample(byteCount);
200             temporalMessages.addSample(1);
201         }
202     }//addMessageSample
203

204     
205 // public boolean isActive() {
206
// return (this.serviceName != null && !this.serviceName.equals(""));
207
// }
208

209     
210     public CMCAgentStats getCurrentCMCStats() {
211         CMCAgentStats stats = new CMCAgentStats();
212         stats.setTotalMem(currentMem.getValue());
213         stats.setFreeMem(freeMem.getValue());
214         stats.setTotalMessages(totalMessages.getValue());
215         stats.setTotalBytes(totalBytes.getValue());
216         stats.setFiveMinMessages(temporalMessages.getValue());
217         stats.setFiveMinBytes(temporalBytes.getValue());
218         return stats;
219     }
220     
221     
222     // starts the updates
223
private void startUpdates() {
224         this.timer.addTimeout(this.topicPublisher, this.topicPublisher,
225                 this.updateInterval);
226     }
227     
228     
229     // stops the updates
230
private void stopUpdates() {
231         this.timer.removeTimeout(this.topicPublisher);
232     }
233     
234     
235     // create the object that contains the statistics information
236
private String JavaDoc getCurrentStats() {
237         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
238         sb.append(Long.toString(this.totalMessages.getValue())).append("|");
239         sb.append(Long.toString(this.totalBytes.getValue())).append("|");
240         sb.append(Long.toString(this.temporalMessages.getValue())).append("|");
241         sb.append(Long.toString(this.temporalBytes.getValue())).append("|");
242         sb.append(Long.toString(this.maxMem.getValue())).append("|");
243         sb.append(Long.toString(this.currentMem.getValue())).append("|");
244         return sb.toString();
245     }
246     
247     // publishes the statistics
248
private void publishUpdate() {
249         if (this.prod == null) {
250             try {
251                 initJMS();
252             } catch (JMSException JavaDoc e) {
253                 if (log.isErrorEnabled()) {
254                     log.error("Failed initializing Statistics topic service.");
255                 }
256                 try {
257                     closeJMS();
258                 } catch (JMSException JavaDoc e1) {}
259                 return;
260             }
261         }
262         if (this.sendUpdates) {
263             try {
264                 TextMessage JavaDoc textMessage = ses.createTextMessage(getCurrentStats());
265                 if(log.isDebugEnabled()){
266                     log.debug("Publishing statistics");
267                 }
268                 prod.send(textMessage,
269                         MantaAgentConstants.NON_PERSISTENT,
270                         MantaAgentConstants.NORMAL,
271                         SystemTime.gmtCurrentTimeMillis()+60000);
272             } catch (JMSException JavaDoc e) {
273                 if(log.isErrorEnabled()){
274                     log.error("Exception during publishing statstics.", e);
275                 }
276             }
277         }
278     }
279 } // StatManager
280
Popular Tags