KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > snmp4j > agent > test > TestAgent


1 /*_############################################################################
2   _##
3   _## SNMP4J-Agent - TestAgent.java
4   _##
5   _## Copyright (C) 2005-2007 Frank Fock (SNMP4J.org)
6   _##
7   _## Licensed under the Apache License, Version 2.0 (the "License");
8   _## you may not use this file except in compliance with the License.
9   _## You may obtain a copy of the License at
10   _##
11   _## http://www.apache.org/licenses/LICENSE-2.0
12   _##
13   _## Unless required by applicable law or agreed to in writing, software
14   _## distributed under the License is distributed on an "AS IS" BASIS,
15   _## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   _## See the License for the specific language governing permissions and
17   _## limitations under the License.
18   _##
19   _##########################################################################*/

20
21
22 package org.snmp4j.agent.test;
23
24 import java.io.*;
25
26 import org.apache.log4j.*;
27 import org.snmp4j.*;
28 import org.snmp4j.agent.*;
29 import org.snmp4j.agent.mo.*;
30 import org.snmp4j.agent.mo.snmp.*;
31 import org.snmp4j.mp.*;
32 import org.snmp4j.security.*;
33 import org.snmp4j.smi.*;
34 import org.snmp4j.transport.*;
35 import org.snmp4j.agent.io.ImportModes;
36 import org.snmp4j.util.ThreadPool;
37 import org.snmp4j.log.Log4jLogFactory;
38 import org.snmp4j.log.LogFactory;
39 import org.snmp4j.agent.mo.snmp4j.example.Snmp4jHeartbeatMib;
40 import org.snmp4j.agent.security.MutableVACM;
41 import org.snmp4j.agent.mo.ext.AgentppSimulationMib;
42
43 /**
44  * The <code>TestAgent</code> is a sample SNMP agent implementation of all
45  * features (MIB implementations) provided by the SNMP4J-Agent framework.
46  * The <code>TestAgent</code> extends the <code>BaseAgent</code> which provides
47  * a framework for custom agent implementations through hook methods. Those
48  * abstract hook methods need to be implemented by extending the
49  * <code>BaseAgent</code>.
50  * <p>
51  * This IF-MIB implementation part of this test agent, is instrumentation as
52  * a simulation MIB. Thus, by changing the agentppSimMode
53  * (1.3.6.1.4.1.4976.2.1.1.0) from 'oper(1)' to 'config(2)' any object of the
54  * IF-MIB is writable and even creatable (columnar objects) via SNMP. Check it
55  * out!
56  *
57  * @author Frank Fock
58  * @version 1.0
59  */

60 public class TestAgent extends BaseAgent {
61
62   // initialize Log4J logging
63
static {
64     LogFactory.setLogFactory(new Log4jLogFactory());
65   }
66
67   protected String JavaDoc address;
68   private Snmp4jHeartbeatMib heartbeatMIB;
69   private IfMib ifMIB;
70   private AgentppSimulationMib agentppSimulationMIB;
71
72   /**
73    * Creates the test agent with a file to read and store the boot counter and
74    * a file to read and store its configuration.
75    *
76    * @param bootCounterFile
77    * a file containing the boot counter in serialized form (as expected by
78    * BaseAgent).
79    * @param configFile
80    * a configuration file with serialized management information.
81    * @throws IOException
82    * if the boot counter or config file cannot be read properly.
83    */

84   public TestAgent(File bootCounterFile, File configFile) throws IOException {
85     super(bootCounterFile, configFile,
86           new CommandProcessor(new OctetString(MPv3.createLocalEngineID())));
87 // Alternatively: OctetString.fromHexString("00:00:00:00:00:00:02", ':');
88
agent.setThreadPool(ThreadPool.create("RequestPool", 4));
89   }
90
91   protected void registerManagedObjects() {
92     try {
93 // server.register(createStaticIfTable(), null);
94
agentppSimulationMIB.registerMOs(server, null);
95       ifMIB.registerMOs(server, new OctetString("public"));
96       heartbeatMIB.registerMOs(server, null);
97     }
98     catch (DuplicateRegistrationException ex) {
99       ex.printStackTrace();
100     }
101   }
102
103   protected void addNotificationTargets(SnmpTargetMIB targetMIB,
104                                         SnmpNotificationMIB notificationMIB) {
105     targetMIB.addDefaultTDomains();
106
107     targetMIB.addTargetAddress(new OctetString("notification"),
108                                TransportDomains.transportDomainUdpIpv4,
109                                new OctetString(new UdpAddress("127.0.0.1/162").getValue()),
110                                200, 1,
111                                new OctetString("notify"),
112                                new OctetString("v2c"),
113                                StorageType.permanent);
114     targetMIB.addTargetParams(new OctetString("v2c"),
115                               MessageProcessingModel.MPv3,
116                               SecurityModel.SECURITY_MODEL_USM,
117                               new OctetString("SHADES"),
118                               SecurityLevel.AUTH_PRIV,
119                               StorageType.permanent);
120     notificationMIB.addNotifyEntry(new OctetString("default"),
121                                    new OctetString("notify"),
122                                    SnmpNotificationMIB.SnmpNotifyTypeEnum.inform,
123                                    StorageType.permanent);
124   }
125
126   protected void addViews(VacmMIB vacm) {
127     vacm.addGroup(SecurityModel.SECURITY_MODEL_SNMPv1,
128                   new OctetString("cpublic"),
129                   new OctetString("v1v2group"),
130                   StorageType.nonVolatile);
131     vacm.addGroup(SecurityModel.SECURITY_MODEL_SNMPv2c,
132                   new OctetString("cpublic"),
133                   new OctetString("v1v2group"),
134                   StorageType.nonVolatile);
135     vacm.addGroup(SecurityModel.SECURITY_MODEL_USM,
136                   new OctetString("SHADES"),
137                   new OctetString("v3group"),
138                   StorageType.nonVolatile);
139     vacm.addGroup(SecurityModel.SECURITY_MODEL_USM,
140                   new OctetString("TEST"),
141                   new OctetString("v3test"),
142                   StorageType.nonVolatile);
143     vacm.addGroup(SecurityModel.SECURITY_MODEL_USM,
144                   new OctetString("SHA"),
145                   new OctetString("v3restricted"),
146                   StorageType.nonVolatile);
147
148     vacm.addAccess(new OctetString("v1v2group"), new OctetString("public"),
149                    SecurityModel.SECURITY_MODEL_ANY,
150                    SecurityLevel.NOAUTH_NOPRIV,
151                    MutableVACM.VACM_MATCH_EXACT,
152                    new OctetString("fullReadView"),
153                    new OctetString("fullWriteView"),
154                    new OctetString("fullNotifyView"),
155                    StorageType.nonVolatile);
156     vacm.addAccess(new OctetString("v3group"), new OctetString(),
157                    SecurityModel.SECURITY_MODEL_USM,
158                    SecurityLevel.AUTH_PRIV,
159                    MutableVACM.VACM_MATCH_EXACT,
160                    new OctetString("fullReadView"),
161                    new OctetString("fullWriteView"),
162                    new OctetString("fullNotifyView"),
163                    StorageType.nonVolatile);
164     vacm.addAccess(new OctetString("v3restricted"), new OctetString(),
165                    SecurityModel.SECURITY_MODEL_USM,
166                    SecurityLevel.AUTH_NOPRIV,
167                    MutableVACM.VACM_MATCH_EXACT,
168                    new OctetString("restrictedReadView"),
169                    new OctetString("restrictedWriteView"),
170                    new OctetString("restrictedNotifyView"),
171                    StorageType.nonVolatile);
172     vacm.addAccess(new OctetString("v3test"), new OctetString(),
173                    SecurityModel.SECURITY_MODEL_USM,
174                    SecurityLevel.AUTH_PRIV,
175                    MutableVACM.VACM_MATCH_EXACT,
176                    new OctetString("testReadView"),
177                    new OctetString("testWriteView"),
178                    new OctetString("testNotifyView"),
179                    StorageType.nonVolatile);
180
181     vacm.addViewTreeFamily(new OctetString("fullReadView"), new OID("1.3"),
182                            new OctetString(), VacmMIB.vacmViewIncluded,
183                            StorageType.nonVolatile);
184     vacm.addViewTreeFamily(new OctetString("fullWriteView"), new OID("1.3"),
185                            new OctetString(), VacmMIB.vacmViewIncluded,
186                            StorageType.nonVolatile);
187     vacm.addViewTreeFamily(new OctetString("fullNotifyView"), new OID("1.3"),
188                            new OctetString(), VacmMIB.vacmViewIncluded,
189                            StorageType.nonVolatile);
190
191     vacm.addViewTreeFamily(new OctetString("restrictedReadView"),
192                            new OID("1.3.6.1.2"),
193                            new OctetString(), VacmMIB.vacmViewIncluded,
194                            StorageType.nonVolatile);
195     vacm.addViewTreeFamily(new OctetString("restrictedWriteView"),
196                            new OID("1.3.6.1.2.1"),
197                            new OctetString(),
198                            VacmMIB.vacmViewIncluded,
199                            StorageType.nonVolatile);
200     vacm.addViewTreeFamily(new OctetString("restrictedNotifyView"),
201                            new OID("1.3.6.1.2"),
202                            new OctetString(), VacmMIB.vacmViewIncluded,
203                            StorageType.nonVolatile);
204
205     vacm.addViewTreeFamily(new OctetString("testReadView"),
206                            new OID("1.3.6.1.2"),
207                            new OctetString(), VacmMIB.vacmViewIncluded,
208                            StorageType.nonVolatile);
209     vacm.addViewTreeFamily(new OctetString("testReadView"),
210                            new OID("1.3.6.1.2.1.1"),
211                            new OctetString(), VacmMIB.vacmViewExcluded,
212                            StorageType.nonVolatile);
213     vacm.addViewTreeFamily(new OctetString("testWriteView"),
214                            new OID("1.3.6.1.2.1"),
215                            new OctetString(),
216                            VacmMIB.vacmViewIncluded,
217                            StorageType.nonVolatile);
218     vacm.addViewTreeFamily(new OctetString("testNotifyView"),
219                            new OID("1.3.6.1.2"),
220                            new OctetString(), VacmMIB.vacmViewIncluded,
221                            StorageType.nonVolatile);
222
223   }
224
225   protected void addUsmUser(USM usm) {
226     UsmUser user = new UsmUser(new OctetString("SHADES"),
227                                AuthSHA.ID,
228                                new OctetString("SHADESAuthPassword"),
229                                PrivDES.ID,
230                                new OctetString("SHADESPrivPassword"));
231 // usm.addUser(user.getSecurityName(), usm.getLocalEngineID(), user);
232
usm.addUser(user.getSecurityName(), null, user);
233     user = new UsmUser(new OctetString("TEST"),
234                                AuthSHA.ID,
235                                new OctetString("maplesyrup"),
236                                PrivDES.ID,
237                                new OctetString("maplesyrup"));
238     usm.addUser(user.getSecurityName(), usm.getLocalEngineID(), user);
239     user = new UsmUser(new OctetString("SHA"),
240                                AuthSHA.ID,
241                                new OctetString("SHAAuthPassword"),
242                                null,
243                                null);
244     usm.addUser(user.getSecurityName(), usm.getLocalEngineID(), user);
245   }
246
247 /* This code illustrates how a table can be created and filled with static
248 data:
249
250   private static DefaultMOTable createStaticIfTable() {
251     MOTableSubIndex[] subIndexes =
252         new MOTableSubIndex[] { new MOTableSubIndex(SMIConstants.SYNTAX_INTEGER) };
253     MOTableIndex indexDef = new MOTableIndex(subIndexes, false);
254     MOColumn[] columns = new MOColumn[8];
255     int c = 0;
256     columns[c++] =
257         new MOColumn(c, SMIConstants.SYNTAX_INTEGER,
258                      MOAccessImpl.ACCESS_READ_ONLY); // ifIndex
259     columns[c++] =
260         new MOColumn(c, SMIConstants.SYNTAX_OCTET_STRING,
261                      MOAccessImpl.ACCESS_READ_ONLY);// ifDescr
262     columns[c++] =
263         new MOColumn(c, SMIConstants.SYNTAX_INTEGER,
264                      MOAccessImpl.ACCESS_READ_ONLY); // ifType
265     columns[c++] =
266         new MOColumn(c, SMIConstants.SYNTAX_INTEGER,
267                      MOAccessImpl.ACCESS_READ_ONLY); // ifMtu
268     columns[c++] =
269         new MOColumn(c, SMIConstants.SYNTAX_GAUGE32,
270                      MOAccessImpl.ACCESS_READ_ONLY); // ifSpeed
271     columns[c++] =
272         new MOColumn(c, SMIConstants.SYNTAX_OCTET_STRING,
273                      MOAccessImpl.ACCESS_READ_ONLY);// ifPhysAddress
274     columns[c++] =
275         new MOMutableColumn(c, SMIConstants.SYNTAX_INTEGER, // ifAdminStatus
276                             MOAccessImpl.ACCESS_READ_WRITE, null);
277     columns[c++] =
278         new MOColumn(c, SMIConstants.SYNTAX_INTEGER,
279                      MOAccessImpl.ACCESS_READ_ONLY); // ifOperStatus
280
281     DefaultMOTable ifTable =
282         new DefaultMOTable(new OID("1.3.6.1.2.1.2.2.1"), indexDef, columns);
283     MOMutableTableModel model = (MOMutableTableModel) ifTable.getModel();
284     Variable[] rowValues1 = new Variable[] {
285         new Integer32(1),
286         new OctetString("eth0"),
287         new Integer32(6),
288         new Integer32(1500),
289         new Gauge32(100000000),
290         new OctetString("00:00:00:00:01"),
291         new Integer32(1),
292         new Integer32(1)
293     };
294     Variable[] rowValues2 = new Variable[] {
295         new Integer32(2),
296         new OctetString("loopback"),
297         new Integer32(24),
298         new Integer32(1500),
299         new Gauge32(10000000),
300         new OctetString("00:00:00:00:02"),
301         new Integer32(1),
302         new Integer32(1)
303     };
304     model.addRow(new DefaultMOMutableRow2PC(new OID("1"), rowValues1));
305     model.addRow(new DefaultMOMutableRow2PC(new OID("2"), rowValues2));
306     ifTable.setVolatile(true);
307     return ifTable;
308   }
309 */

310   protected void initTransportMappings() throws IOException {
311     transportMappings = new TransportMapping[1];
312     Address addr = GenericAddress.parse(address);
313     TransportMapping tm =
314         TransportMappings.getInstance().createTransportMapping(addr);
315     transportMappings[0] = tm;
316   }
317
318   public static void main(String JavaDoc[] args) {
319     String JavaDoc address;
320     if (args.length > 0) {
321       address = args[0];
322     }
323     else {
324       address = "0.0.0.0/161";
325     }
326     BasicConfigurator.configure();
327     try {
328       TestAgent testAgent1 = new TestAgent(new File("SNMP4JTestAgentBC.cfg"),
329                                            new File("SNMP4JTestAgentConfig.cfg"));
330       testAgent1.address = address;
331       testAgent1.init();
332       testAgent1.loadConfig(ImportModes.REPLACE_CREATE);
333       testAgent1.addShutdownHook();
334       testAgent1.getServer().addContext(new OctetString("public"));
335       testAgent1.finishInit();
336       testAgent1.run();
337       testAgent1.sendColdStartNotification();
338       while (true) {
339         try {
340           Thread.sleep(1000);
341         }
342         catch (InterruptedException JavaDoc ex1) {
343           break;
344         }
345       }
346     }
347     catch (IOException ex) {
348       ex.printStackTrace();
349     }
350
351   }
352
353   protected void unregisterManagedObjects() {
354     // here we should unregister those objects previously registered...
355
}
356
357   protected void addCommunities(SnmpCommunityMIB communityMIB) {
358     Variable[] com2sec = new Variable[] {
359         new OctetString("public"), // community name
360
new OctetString("cpublic"), // security name
361
getAgent().getContextEngineID(), // local engine ID
362
new OctetString("public"), // default context name
363
new OctetString(), // transport tag
364
new Integer32(StorageType.nonVolatile), // storage type
365
new Integer32(RowStatus.active) // row status
366
};
367     MOTableRow row =
368         communityMIB.getSnmpCommunityEntry().createRow(
369           new OctetString("public2public").toSubIndex(true), com2sec);
370     communityMIB.getSnmpCommunityEntry().addRow(row);
371 // snmpCommunityMIB.setSourceAddressFiltering(true);
372
}
373
374   protected void registerSnmpMIBs() {
375     heartbeatMIB = new Snmp4jHeartbeatMib(super.getNotificationOriginator(),
376                                           new OctetString(),
377                                           super.snmpv2MIB.getSysUpTime());
378     ifMIB = new IfMib();
379     agentppSimulationMIB = new AgentppSimulationMib();
380     super.registerSnmpMIBs();
381   }
382 }
383
Popular Tags