KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > fenyo > gnetwatch > SNMPQuerier


1
2 /*
3  * GNetWatch
4  * Copyright 2006, 2007 Alexandre Fenyo
5  * gnetwatch@fenyo.net
6  *
7  * This file is part of GNetWatch.
8  *
9  * GNetWatch is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * GNetWatch is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with GNetWatch; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
22  */

23
24 package net.fenyo.gnetwatch;
25
26 import org.apache.commons.logging.Log;
27 import org.apache.commons.logging.LogFactory;
28
29 import java.net.*;
30 import java.io.*;
31
32 import org.snmp4j.*;
33 import org.snmp4j.smi.*;
34 import org.snmp4j.mp.*;
35 import org.snmp4j.transport.*;
36 import org.snmp4j.util.*;
37 import org.snmp4j.event.*;
38 import org.snmp4j.security.*;
39
40 /**
41  * An SNMP querier maintains SNMP parameters needed for the manager to talk to an agent.
42  * @author Alexandre Fenyo
43  * @version $Id: SNMPQuerier.java,v 1.17 2007/03/12 05:04:15 fenyo Exp $
44  */

45
46 // grosse limitation en V3 : si 2 targets ont le même username mais pas le même pass ni valeur de sec, ca marchera pas
47
// car on n'a pas géré les engines
48
public class SNMPQuerier {
49   private static Log log = LogFactory.getLog(SNMPQuerier.class);
50
51   private final SNMPManager snmp_manager;
52   private Target snmp_target;
53
54   private final InetAddress address;
55
56   private int version = 0; // SNMPv1
57
private int sec = SecurityLevel.AUTH_PRIV;
58   private int retries = 3;
59   private int timeout = 1500; // microsec
60
private int port = 161;
61   private String JavaDoc community = "public";
62   private String JavaDoc username = "";
63   private String JavaDoc password_auth = "";
64   private String JavaDoc password_priv = "";
65   private int pdu_max_size = 1000;
66
67   private boolean snmp_capable = false;
68   private String JavaDoc last_sysdescr = null;
69
70   /**
71    * Interface used to manage asynchronous SNMP answers.
72    */

73   public interface QuerierListener {
74     /**
75      * Called for each ansynchronous answer.
76      * @param event response event recived.
77      * @return void.
78      */

79     public void onResponse(final ResponseEvent event);
80
81     /**
82      * Called after a timeout occured.
83      * @param event timeout event.
84      * @return void.
85      */

86     public void onTimeout(final ResponseEvent event);
87   }
88
89   /**
90    * Constructor.
91    * @param address target address.
92    * @param snmp_manager SNMPManager instance.
93    */

94   protected SNMPQuerier(final InetAddress address, final SNMPManager snmp_manager) {
95     this.snmp_manager = snmp_manager;
96     this.address = address;
97     parametersHaveChanged();
98   }
99
100   /**
101    * Returns the target address.
102    * @param none.
103    * @return InetAddress target address.
104    */

105   public InetAddress getAddress() {
106     return address;
107   }
108
109   /**
110    * Checks that the associated target has already answered a SNMP query.
111    * @param none.
112    * @return boolean true if the target has already answered a SNMP query.
113    */

114   public boolean isSNMPCapable() {
115     return snmp_capable;
116   }
117
118   /**
119    * Returns the last sysdescr returned.
120    * @param none.
121    * @return String system description.
122    */

123   public String JavaDoc getLastSysdescr() {
124     return last_sysdescr;
125   }
126
127   /**
128    * Must be called after some setters have been called.
129    * @param none.
130    * @return void.
131    */

132   public void update() {
133     parametersHaveChanged();
134   }
135
136   /**
137    * Must be called after some setters have been called.
138    * @param none.
139    * @return void.
140    */

141   // final since it is invoked from the constructor
142
private final void parametersHaveChanged() {
143     if (version == 0 || version == 1) {
144       snmp_target = new CommunityTarget();
145       snmp_target.setAddress(new UdpAddress(address, port));
146       snmp_target.setVersion((version == 0) ? SnmpConstants.version1 : SnmpConstants.version2c);
147       ((CommunityTarget) snmp_target).setCommunity(new OctetString(community));
148
149     } else {
150       try {
151         UsmUserEntry entry = snmp_manager.getSNMP().getUSM().getUserTable().getUser(new OctetString(username));
152         if (entry != null && snmp_manager.getSNMP().getUSM().removeUser(entry.getEngineID(), entry.getUserName()) == null)
153             log.error("USM user not found");
154         snmp_manager.getSNMP().getUSM().addUser(new OctetString(username),
155             new UsmUser(new OctetString(username),
156                 sec != SecurityLevel.NOAUTH_NOPRIV ? AuthMD5.ID : null,
157                 sec != SecurityLevel.NOAUTH_NOPRIV ? new OctetString(password_auth) : null,
158                 sec == SecurityLevel.AUTH_PRIV ? PrivDES.ID : null,
159                 sec == SecurityLevel.AUTH_PRIV ? new OctetString(password_priv) : null));
160         snmp_target = new UserTarget(new UdpAddress(address, port), new OctetString(username),
161             new byte [] {}, sec);
162         snmp_target.setVersion(SnmpConstants.version3);
163       } catch (final IllegalArgumentException JavaDoc ex) {
164         log.error("Exception", ex);
165       }
166     }
167
168     snmp_target.setRetries(retries);
169     snmp_target.setTimeout(timeout);
170     snmp_target.setMaxSizeRequestPDU(pdu_max_size);
171   }
172
173   /**
174    * Returns the version attribute.
175    * @param none.
176    * @return int version attribute.
177    */

178   public int getVersion() {
179     return version;
180   }
181
182   /**
183    * Returns the security attribute.
184    * @param none.
185    * @return int security attribute.
186    */

187   public int getSec() {
188     return sec;
189   }
190
191   /**
192    * Returns the retries attribute.
193    * @param none.
194    * @return int retries attribute.
195    */

196   public int getRetries() {
197     return retries;
198   }
199
200   /**
201    * Returns the timeout attribute.
202    * @param none.
203    * @return int timeout attribute.
204    */

205   public int getTimeout() {
206     return timeout;
207   }
208
209   /**
210    * Returns the agent UDP port attribute.
211    * @param none.
212    * @return int agent UDP port.
213    */

214   public int getPort() {
215     return port;
216   }
217
218   /**
219    * Returns the community string.
220    * @param none.
221    * @return String community string.
222    */

223   public String JavaDoc getCommunity() {
224     return community;
225   }
226
227   /**
228    * Returns the username attribute.
229    * @param none.
230    * @return String username attribute.
231    */

232   public String JavaDoc getUsername() {
233     return username;
234   }
235
236   /**
237    * Returns the password authentication attribute.
238    * @param none.
239    * @return String password authentication attribute.
240    */

241   public String JavaDoc getPasswordAuth() {
242     return password_auth;
243   }
244
245   /**
246    * Returns the password privacy attribute.
247    * @param none.
248    * @return String password privacy attribute.
249    */

250   public String JavaDoc getPasswordPriv() {
251     return password_priv;
252   }
253
254   /**
255    * Returns the PDU maximum size attribute.
256    * @param none.
257    * @return int PDU maximum size attribute.
258    */

259   public int getPDUMaxSize() {
260     return pdu_max_size;
261   }
262
263   /**
264    * Sets the version attribute.
265    * @param version version.
266    * @return void.
267    */

268   public void setVersion(final int version) {
269     this.version = version;
270   }
271
272   /**
273    * Sets the security attribute.
274    * @param sec security attribute.
275    * @return void.
276    */

277   public void setSec(final int sec) {
278     this.sec = sec;
279   }
280
281   /**
282    * Sets the retries attribute.
283    * @param retries retries attribute.
284    * @return void.
285    */

286   public void setRetries(final int retries) {
287     this.retries = retries;
288   }
289
290   /**
291    * Sets the timeout attribute.
292    * @param timeout timeout attribute.
293    * @return void.
294    */

295   public void setTimeout(final int timeout) {
296     this.timeout = timeout;
297   }
298
299   /**
300    * Sets the agent UDP port attribute.
301    * @param port agent UDP port attribute.
302    * @return void.
303    */

304   public void setPort(final int port) {
305     this.port = port;
306   }
307
308   /**
309    * Sets the community string attribute.
310    * @param community community string attribute.
311    * @return void.
312    */

313   public void setCommunity(final String JavaDoc community) {
314     this.community = community;
315   }
316
317   /**
318    * Sets the username attribute.
319    * @param username username attribute.
320    * @return void.
321    */

322   public void setUsername(final String JavaDoc username) {
323     this.username = username;
324   }
325
326   /**
327    * Sets the password authentication attribute.
328    * @param password_auth password authentication attribute.
329    * @return void.
330    */

331   public void setPasswordAuth(final String JavaDoc password_auth) {
332     this.password_auth = password_auth;
333   }
334
335   /**
336    * Sets the password privacy attribute.
337    * @param password_priv password_privacy attribute.
338    * @return void.
339    */

340   public void setPasswordPriv(final String JavaDoc password_priv) {
341     this.password_priv = password_priv;
342   }
343
344   /**
345    * Sets the PDU maximum size attribute.
346    * @param pdu_max_size PDU maximum size attribute.
347    * @return void.
348    */

349   public void setPDUMaxSize(final int pdu_max_size) {
350     this.pdu_max_size = pdu_max_size;
351   }
352
353   /**
354    * Returns the SNMP4J Snmp instance used to perform further SNMP queries.
355    * @param none.
356    * @return Snmp Snmp instance.
357    */

358   private Snmp getSNMP() {
359     return snmp_manager.getSNMP();
360   }
361
362   /**
363    * Creates a new empty PDU.
364    * @param none.
365    * @return PDU new PDU.
366    */

367   private PDU getPDU() {
368     if (version == 0) return new PDUv1();
369     if (version == 1) return new PDU();
370     return new ScopedPDU();
371   }
372
373   /**
374    * Gets the system description OID content synchronously.
375    * @param none.
376    * @return String system description.
377    */

378   // snmptranslate -Td IF-MIB::ifName.1
379
// récupérer une table : http://lists.agentpp.org/pipermail/snmp4j/2005-October/000786.html
380
public String JavaDoc getSysDescr() {
381     final PDU pdu = getPDU();
382     pdu.add(new VariableBinding(new OID("1.3.6.1.2.1.1.1")));
383     pdu.setType(PDU.GETNEXT);
384     try {
385       final ResponseEvent response = getSNMP().send(pdu, snmp_target);
386
387       if (response.getResponse() != null) {
388
389         if (response.getResponse().get(0) != null &&
390             response.getResponse().get(0).getVariable() != null) {
391           snmp_capable = true;
392           last_sysdescr = response.getResponse().get(0).getVariable().toString();
393         }
394
395         return response.getResponse().toString();
396       }
397     } catch (final IOException ex) {
398       log.error("Exception", ex);
399     }
400     return null;
401   }
402
403   /**
404    * Gets the system description OID content asynchronously.
405    * @param listener listener instance that will be called asynchronously.
406    * @return void.
407    */

408   public void getSysDescr(final QuerierListener listener) {
409     final PDU pdu = getPDU();
410     pdu.add(new VariableBinding(new OID("1.3.6.1.2.1.1.1")));
411     pdu.setType(PDU.GETNEXT);
412     try {
413       getSNMP().send(pdu, snmp_target, null, new ResponseListener() {
414         private Boolean JavaDoc invoked = false;
415
416         public void onResponse(final ResponseEvent event) {
417           if (event.getResponse() == null) {
418             synchronized(invoked) {
419               if (invoked == true) return;
420               invoked = true;
421             }
422             listener.onTimeout(event);
423           }
424           else {
425             synchronized(invoked) {
426               if (invoked == true) return;
427               invoked = true;
428             }
429             ((Snmp) event.getSource()).cancel(event.getRequest(), this);
430
431             snmp_capable = true;
432             if (event.getResponse() != null && event.getResponse().get(0) != null &&
433                 event.getResponse().get(0).getVariable() != null)
434               last_sysdescr = event.getResponse().get(0).getVariable().toString();
435             
436             listener.onResponse(event);
437           }
438         }
439       });
440     } catch (final IOException ex) {
441       log.error("Exception", ex);
442     }
443   }
444
445   /**
446    * Gets some columns of the interface list table synchronously.
447    * @param none.
448    * @return java.util.List<TableEvent> list of rows.
449    */

450   public java.util.List JavaDoc<TableEvent> getInterfaces() {
451     final PDUFactory pdu_factory = new DefaultPDUFactory(PDU.GETNEXT);
452
453     TableUtils table_utils = new TableUtils(getSNMP(), pdu_factory);
454     /* regarder IF-MIB::ifName */
455     final OID[] cols = new OID[] {
456         new OID("1.3.6.1.2.1.2.2.1.1"), // IF-MIB::ifIndex
457
new OID("1.3.6.1.2.1.2.2.1.2"), // IF-MIB::ifDescr
458
new OID("1.3.6.1.2.1.2.2.1.3"), // IF-MIB::ifType
459
new OID("1.3.6.1.2.1.2.2.1.4"), // IF-MIB::ifMtu
460
new OID("1.3.6.1.2.1.2.2.1.5"), // IF-MIB::ifSpeed
461
new OID("1.3.6.1.2.1.2.2.1.6"), // IF-MIB::ifPhysAddress
462
new OID("1.3.6.1.2.1.2.2.1.7"), // IF-MIB::ifAdminStatus
463
new OID("1.3.6.1.2.1.2.2.1.8"), // IF-MIB::ifOperStatus
464
new OID("1.3.6.1.2.1.2.2.1.10"), // IF-MIB::ifInOctets
465
new OID("1.3.6.1.2.1.2.2.1.16"), // IF-MIB::ifOutOctets
466
};
467
468     java.util.List JavaDoc<TableEvent> table = table_utils.getTable(snmp_target, cols, null, null);
469     if (table != null && table.get(0) != null && table.get(0).getColumns() != null) snmp_capable = true;
470     return table;
471   }
472 }
473
Popular Tags