[ONOS-3203] End-to-end demo of Fault Management via SNMP.
This adds SNMP device-discovery, and a Fault Management app which makes alarms available to users via REST/GUI/CLI interfaces.
There is still code cleanup that could be done, but aim of this commit is an end-to-end proof of concept.
To demonstrate :
1) /opt/onos/bin/onos-service
onos> app activate org.onosproject.snmp
onos> app activate org.onosproject.faultmanagement
2) SNMP devices are seeded via config file. The default seed file contains connection details for devices (SNMP agents) available via internet e.g. demo.snmplabs.com
cp /opt/onos/apache-karaf-3.0.3/etc/samples/org.onosproject.provider.snmp.device.impl.SnmpDeviceProvider.cfg /opt/onos/apache-karaf-3.0.3/etc/
3) ONOS will poll these SNMP devices and store their alarms.
4) You can now manipulate the alarms via REST e.g. http://<onos>:8181/onos/v1/fm/alarms , via CLI via various "alarm-*” commands or in UI with an Alarms Overlay.
More info at https://wiki.onosproject.org/display/ONOS/Fault+Management
15/Dec/15: Updated regarding review comments from Thomas Vachuska.
17/Dec/15: Updated coreService.registerApplication(name) as per https://gerrit.onosproject.org/#/c/6878/
Change-Id: I886f8511f178dc4600ab96e5ff10cc90329cabec
diff --git a/providers/snmp/alarm/pom.xml b/providers/snmp/alarm/pom.xml
index f147d29..2b13e14 100644
--- a/providers/snmp/alarm/pom.xml
+++ b/providers/snmp/alarm/pom.xml
@@ -1,19 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
- ~ Copyright 2014 Open Networking Laboratory
- ~
- ~ Licensed under the Apache License, Version 2.0 (the "License");
- ~ you may not use this file except in compliance with the License.
- ~ You may obtain a copy of the License at
- ~
- ~ http://www.apache.org/licenses/LICENSE-2.0
- ~
- ~ Unless required by applicable law or agreed to in writing, software
- ~ distributed under the License is distributed on an "AS IS" BASIS,
- ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- ~ See the License for the specific language governing permissions and
- ~ limitations under the License.
- -->
+~ Copyright 2015 Open Networking Laboratory
+~
+~ Licensed under the Apache License, Version 2.0 (the "License");
+~ you may not use this file except in compliance with the License.
+~ You may obtain a copy of the License at
+~
+~ http://www.apache.org/licenses/LICENSE-2.0
+~
+~ Unless required by applicable law or agreed to in writing, software
+~ distributed under the License is distributed on an "AS IS" BASIS,
+~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+~ See the License for the specific language governing permissions and
+~ limitations under the License.
+-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
@@ -31,4 +31,136 @@
<description>ONOS SNMP protocol alarm provider</description>
-</project>
\ No newline at end of file
+ <dependencies>
+ <dependency>
+ <groupId>com.btisystems</groupId>
+ <artifactId>snmp-core</artifactId>
+ <version>1.3-SNAPSHOT</version>
+ </dependency>
+
+ <dependency>
+ <groupId>com.btisystems.mibbler.mibs</groupId>
+ <artifactId>bti7000</artifactId>
+ <version>1.0-SNAPSHOT</version>
+ </dependency>
+
+ <dependency>
+ <groupId>com.btisystems.mibbler.mibs</groupId>
+ <artifactId>net-snmp</artifactId>
+ <version>1.0-SNAPSHOT</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>org.osgi.compendium</artifactId>
+ <version>5.0.0</version>
+ <type>jar</type>
+ </dependency>
+
+ <dependency>
+ <groupId>org.onosproject</groupId>
+ <artifactId>onos-api</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+
+
+
+ <dependency>
+ <groupId>org.onosproject</groupId>
+ <artifactId>onlab-junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.onosproject</groupId>
+ <artifactId>onlab-osgi</artifactId>
+ <version>${project.version}</version>
+ <classifier>tests</classifier>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.onosproject</groupId>
+ <artifactId>onos-api</artifactId>
+ <version>${project.version}</version>
+ <classifier>tests</classifier>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>4.11</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-core</artifactId>
+ <version>1.3</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-library</artifactId>
+ <version>1.3</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.easymock</groupId>
+ <artifactId>easymock</artifactId>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-shade-plugin</artifactId>
+ <version>2.3</version>
+ <configuration>
+ <filters>
+ <filter>
+ <artifact>com.btisystems:snmp-core</artifact>
+ <excludes>
+ <exclude>**</exclude>
+ </excludes>
+ </filter>
+ <filter>
+ <artifact>com.btisystems.mibbler.mibs:bti7000</artifact>
+ <excludes>
+ <exclude>**</exclude>
+ </excludes>
+ </filter>
+ <filter>
+ <artifact>com.btisystems.mibbler.mibs:net-snmp</artifact>
+ <excludes>
+ <exclude>**</exclude>
+ </excludes>
+ </filter>
+ </filters>
+ </configuration>
+ <executions>
+ <execution>
+ <phase>package</phase>
+ <goals>
+ <goal>shade</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>maven-scr-plugin</artifactId>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>maven-bundle-plugin</artifactId>
+ </plugin>
+ <plugin>
+ <groupId>org.onosproject</groupId>
+ <artifactId>onos-maven-plugin</artifactId>
+ </plugin>
+ </plugins>
+ </build>
+</project>
diff --git a/providers/snmp/alarm/src/main/java/org/onosproject/provider/snmp/alarm/impl/Bti7000SnmpAlarmProvider.java b/providers/snmp/alarm/src/main/java/org/onosproject/provider/snmp/alarm/impl/Bti7000SnmpAlarmProvider.java
new file mode 100644
index 0000000..9b74334
--- /dev/null
+++ b/providers/snmp/alarm/src/main/java/org/onosproject/provider/snmp/alarm/impl/Bti7000SnmpAlarmProvider.java
@@ -0,0 +1,179 @@
+/*
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.provider.snmp.alarm.impl;
+
+import com.btisystems.mibbler.mibs.bti7000.bti7000_13_2_0.I_Device;
+import com.btisystems.mibbler.mibs.bti7000.bti7000_13_2_0._OidRegistry;
+import com.btisystems.mibbler.mibs.bti7000.bti7000_13_2_0.btisystems.btiproducts.bti7000.objects.conditions.ActAlarmTable;
+import com.btisystems.mibbler.mibs.bti7000.interfaces.btisystems.btiproducts.bti7000.objects.conditions.IActAlarmTable;
+import com.btisystems.pronx.ems.core.model.ClassRegistry;
+import com.btisystems.pronx.ems.core.model.IClassRegistry;
+import com.btisystems.pronx.ems.core.model.NetworkDevice;
+import com.btisystems.pronx.ems.core.snmp.ISnmpSession;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Calendar;
+import java.util.Collection;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.TimeZone;
+import org.apache.commons.lang.StringUtils;
+import org.onosproject.incubator.net.faultmanagement.alarm.Alarm;
+import org.onosproject.incubator.net.faultmanagement.alarm.AlarmEntityId;
+import org.onosproject.incubator.net.faultmanagement.alarm.DefaultAlarm;
+import org.onosproject.net.DeviceId;
+import org.slf4j.Logger;
+import static org.slf4j.LoggerFactory.getLogger;
+import org.snmp4j.smi.OID;
+import org.snmp4j.smi.OctetString;
+
+/**
+ * BTI 7000 specific implementation to provide a list of current alarms.
+ */
+public class Bti7000SnmpAlarmProvider implements SnmpDeviceAlarmProvider {
+ private final Logger log = getLogger(getClass());
+ protected static final IClassRegistry CLASS_REGISTRY = new ClassRegistry(_OidRegistry.oidRegistry, I_Device.class);
+
+ static final int ALARM_SEVERITY_MINOR = 2;
+ static final int ALARM_SEVERITY_MAJOR = 3;
+ static final int ALARM_SEVERITY_CRITICAL = 4;
+
+ @Override
+ public Collection<Alarm> getAlarms(ISnmpSession session, DeviceId deviceID) {
+ log.info("Getting alarms for BTI 7000 device at {}", deviceID);
+ Set<Alarm> alarms = new HashSet<>();
+ NetworkDevice networkDevice = new NetworkDevice(CLASS_REGISTRY,
+ session.getAddress().getHostAddress());
+
+ try {
+ session.walkDevice(networkDevice, Arrays.asList(
+ new OID[]{CLASS_REGISTRY.getClassToOidMap().get(ActAlarmTable.class)}));
+
+ IActAlarmTable deviceAlarms = (IActAlarmTable) networkDevice.getRootObject()
+ .getEntity(CLASS_REGISTRY.getClassToOidMap().get(ActAlarmTable.class));
+ if ((deviceAlarms != null) && (deviceAlarms.getActAlarmEntry() != null)
+ && (!deviceAlarms.getActAlarmEntry().isEmpty())) {
+
+ deviceAlarms.getActAlarmEntry().values().stream().forEach((alarm) -> {
+ DefaultAlarm.Builder alarmBuilder = new DefaultAlarm.Builder(
+ deviceID, alarm.getActAlarmDescription(),
+ mapAlarmSeverity(alarm.getActAlarmSeverity()),
+ getLocalDateAndTime(alarm.getActAlarmDateAndTime(), null, null).getTime())
+ .forSource(AlarmEntityId.alarmEntityId("other:" + alarm.getActAlarmInstanceIdx()));
+ alarms.add(alarmBuilder.build());
+ });
+
+ }
+ log.info("Conditions retrieved: {}", deviceAlarms);
+
+ } catch (IOException ex) {
+ log.error("Error reading alarms for device {}.", deviceID, ex);
+ }
+
+ return alarms;
+ }
+
+ private Alarm.SeverityLevel mapAlarmSeverity(int intAlarmSeverity) {
+ Alarm.SeverityLevel mappedSeverity;
+ switch (intAlarmSeverity) {
+ case ALARM_SEVERITY_MINOR:
+ mappedSeverity = Alarm.SeverityLevel.MINOR;
+ break;
+ case ALARM_SEVERITY_MAJOR:
+ mappedSeverity = Alarm.SeverityLevel.MAJOR;
+ break;
+ case ALARM_SEVERITY_CRITICAL:
+ mappedSeverity = Alarm.SeverityLevel.CRITICAL;
+ break;
+ default:
+ mappedSeverity = Alarm.SeverityLevel.MINOR;
+ log.warn("Unexpected alarm severity: {}", intAlarmSeverity);
+ }
+ return mappedSeverity;
+ }
+ /**
+ * Converts an SNMP string representation into a {@link Date} object,
+ * and applies time zone conversion to provide the time on the local machine, ie PSM server.
+ *
+ * @param actAlarmDateAndTime MIB-II DateAndTime formatted. May optionally contain
+ * a timezone offset in 3 extra bytes
+ * @param sysInfoTimeZone Must be supplied if actAlarmDateAndTime is just local time (with no timezone)
+ * @param swVersion Must be supplied if actAlarmDateAndTime is just local time (with no timezone)
+ * @return adjusted {@link Date} or a simple conversion if other fields are null.
+ */
+ public static Date getLocalDateAndTime(String actAlarmDateAndTime, String sysInfoTimeZone,
+ String swVersion) {
+ if (StringUtils.isBlank(actAlarmDateAndTime)) {
+ return null;
+ }
+
+ GregorianCalendar decodedDateAndTimeCal = btiMakeCalendar(OctetString.fromHexString(actAlarmDateAndTime));
+ if ((sysInfoTimeZone == null) || (swVersion == null)) {
+ return decodedDateAndTimeCal.getTime();
+ }
+
+ TimeZone javaTimeZone = getTimeZone();
+ decodedDateAndTimeCal.setTimeZone(javaTimeZone);
+
+ GregorianCalendar localTime = new GregorianCalendar();
+ localTime.setTimeInMillis(decodedDateAndTimeCal.getTimeInMillis());
+
+ return localTime.getTime();
+ }
+
+ /**
+ * This method is similar to SNMP4J approach with some fixes for the 11-bytes version (ie the one with timezone
+ * offset).
+ *
+ * For original makeCalendar refer @see http://www.snmp4j.org/agent/doc/org/snmp4j/agent/mo/snmp/DateAndTime.html
+ *
+ * Creates a <code>GregorianCalendar</code> from a properly formatted SNMP4J DateAndTime <code>OctetString</code>.
+ *
+ * @param dateAndTimeValue an OctetString conforming to the DateAndTime TC.
+ * @return the corresponding <code>GregorianCalendar</code> instance.
+ *
+ */
+ public static GregorianCalendar btiMakeCalendar(OctetString dateAndTimeValue) {
+ int year = (dateAndTimeValue.get(0) & 0xFF) * 256
+ + (dateAndTimeValue.get(1) & 0xFF);
+ int month = (dateAndTimeValue.get(2) & 0xFF);
+ int date = (dateAndTimeValue.get(3) & 0xFF);
+ int hour = (dateAndTimeValue.get(4) & 0xFF);
+ int minute = (dateAndTimeValue.get(5) & 0xFF);
+ int second = (dateAndTimeValue.get(6) & 0xFF);
+ int deci = (dateAndTimeValue.get(7) & 0xFF);
+ GregorianCalendar gc =
+ new GregorianCalendar(year, month - 1, date, hour, minute, second);
+ gc.set(Calendar.MILLISECOND, deci * 100);
+
+ if (dateAndTimeValue.length() == 11) {
+ char directionOfOffset = (char) dateAndTimeValue.get(8);
+ int hoursOffset = directionOfOffset == '+'
+ ? dateAndTimeValue.get(9) : -dateAndTimeValue.get(9);
+ org.joda.time.DateTimeZone offset =
+ org.joda.time.DateTimeZone.forOffsetHoursMinutes(hoursOffset, dateAndTimeValue.get(10));
+ org.joda.time.DateTime dt =
+ new org.joda.time.DateTime(year, month, date, hour, minute, second, offset);
+ return dt.toGregorianCalendar();
+ }
+ return gc;
+ }
+
+ private static TimeZone getTimeZone() {
+ return Calendar.getInstance().getTimeZone();
+ }
+}
diff --git a/providers/snmp/alarm/src/main/java/org/onosproject/provider/snmp/alarm/impl/NetSnmpAlarmProvider.java b/providers/snmp/alarm/src/main/java/org/onosproject/provider/snmp/alarm/impl/NetSnmpAlarmProvider.java
new file mode 100644
index 0000000..9940d6e
--- /dev/null
+++ b/providers/snmp/alarm/src/main/java/org/onosproject/provider/snmp/alarm/impl/NetSnmpAlarmProvider.java
@@ -0,0 +1,72 @@
+/*
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.provider.snmp.alarm.impl;
+
+import com.btisystems.mibbler.mibs.netsnmp.netsnmp.I_Device;
+import com.btisystems.mibbler.mibs.netsnmp.netsnmp._OidRegistry;
+import com.btisystems.mibbler.mibs.netsnmp.netsnmp.mib_2.interfaces.IfTable;
+import com.btisystems.pronx.ems.core.model.ClassRegistry;
+import com.btisystems.pronx.ems.core.model.IClassRegistry;
+import com.btisystems.pronx.ems.core.model.NetworkDevice;
+import com.btisystems.pronx.ems.core.snmp.ISnmpSession;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Set;
+import org.onosproject.incubator.net.faultmanagement.alarm.Alarm;
+import org.onosproject.incubator.net.faultmanagement.alarm.AlarmEntityId;
+import org.onosproject.incubator.net.faultmanagement.alarm.DefaultAlarm;
+import org.onosproject.net.DeviceId;
+import org.slf4j.Logger;
+import static org.slf4j.LoggerFactory.getLogger;
+import org.snmp4j.smi.OID;
+
+/**
+ * Net SNMP specific implementation to provide a list of current alarms.
+ */
+public class NetSnmpAlarmProvider implements SnmpDeviceAlarmProvider {
+ private final Logger log = getLogger(getClass());
+ protected static final IClassRegistry CLASS_REGISTRY =
+ new ClassRegistry(_OidRegistry.oidRegistry, I_Device.class);
+ @Override
+ public Collection<Alarm> getAlarms(ISnmpSession session, DeviceId deviceId) {
+ Set<Alarm> alarms = new HashSet<>();
+
+ NetworkDevice networkDevice = new NetworkDevice(CLASS_REGISTRY,
+ session.getAddress().getHostAddress());
+ try {
+ session.walkDevice(networkDevice, Arrays.asList(new OID[]{
+ CLASS_REGISTRY.getClassToOidMap().get(IfTable.class)}));
+
+ IfTable interfaceTable = (IfTable) networkDevice.getRootObject()
+ .getEntity(CLASS_REGISTRY.getClassToOidMap().get(IfTable.class));
+ if (interfaceTable != null) {
+ interfaceTable.getEntries().values().stream().forEach((ifEntry) -> {
+ //TODO will raise alarm for each interface as a demo.
+ // if (ifEntry.getIfAdminStatus() == 1 && ifEntry.getIfOperStatus() == 2){
+ alarms.add(new DefaultAlarm.Builder(deviceId, "Link Down.",
+ Alarm.SeverityLevel.CRITICAL, System.currentTimeMillis())
+ .forSource(AlarmEntityId.alarmEntityId("port:" + ifEntry.getIfDescr())).build());
+ // }
+ log.info("Interface: " + ifEntry);
+ });
+ }
+ } catch (IOException ex) {
+ log.error("Error reading alarms for device {}.", deviceId, ex);
+ }
+ return alarms;
+ }
+}
diff --git a/providers/snmp/alarm/src/main/java/org/onosproject/provider/snmp/alarm/impl/SNMPAlarmProvider.java b/providers/snmp/alarm/src/main/java/org/onosproject/provider/snmp/alarm/impl/SNMPAlarmProvider.java
deleted file mode 100644
index 4d96a99..0000000
--- a/providers/snmp/alarm/src/main/java/org/onosproject/provider/snmp/alarm/impl/SNMPAlarmProvider.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright 2014-2015 Open Networking Laboratory
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.onosproject.provider.snmp.alarm.impl;
-
-import org.apache.felix.scr.annotations.Component;
-import org.onosproject.net.DeviceId;
-import org.onosproject.incubator.net.faultmanagement.alarm.AlarmProvider;
-import org.onosproject.net.provider.AbstractProvider;
-import org.onosproject.net.provider.ProviderId;
-import org.slf4j.Logger;
-
-import static org.slf4j.LoggerFactory.getLogger;
-
-/**
- * Provider which uses an SNMP controller to detect network device alarms. The class leverages functionality from
- *
- * @see <a href="https://github.com/btisystems/snmp-core">https://github.com/btisystems/snmp-core</a>
- * @see <a href="https://github.com/btisystems/mibbler">https://github.com/btisystems/mibbler</a>
- */
-@Component(immediate = true)
-public class SNMPAlarmProvider extends AbstractProvider implements AlarmProvider {
-
- private static final Logger LOG = getLogger(SNMPAlarmProvider.class);
-
- /**
- * Creates a SNMP alarm provider, dummy class provided as template, tbd later.
- */
- public SNMPAlarmProvider() {
- super(new ProviderId("snmp", "org.onosproject.provider.alarm"));
- }
-
- @Override
- public void triggerProbe(DeviceId deviceId) {
-
- // TODO in shout term should this just be synchronous and return result?
- LOG.info("Run a SNMP discovery for device at {} when done invoke on AlarmProviderService", deviceId);
-
- // TODO Look up AlarmProviderService
- // TODO Decide threading
- // TODO Decide shouldn't it be generic not alarm-specific ? Its user responsible for passing in OID list ?
- // Same for its callack AlarmProviderService ?
- }
-
-}
diff --git a/providers/snmp/alarm/src/main/java/org/onosproject/provider/snmp/alarm/impl/SnmpAlarmProviderService.java b/providers/snmp/alarm/src/main/java/org/onosproject/provider/snmp/alarm/impl/SnmpAlarmProviderService.java
new file mode 100644
index 0000000..4d2c658
--- /dev/null
+++ b/providers/snmp/alarm/src/main/java/org/onosproject/provider/snmp/alarm/impl/SnmpAlarmProviderService.java
@@ -0,0 +1,236 @@
+/*
+ * Copyright 2015 Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.provider.snmp.alarm.impl;
+
+import com.btisystems.pronx.ems.core.snmp.DefaultSnmpConfigurationFactory;
+import com.btisystems.pronx.ems.core.snmp.ISnmpConfiguration;
+import com.btisystems.pronx.ems.core.snmp.ISnmpSession;
+import com.btisystems.pronx.ems.core.snmp.ISnmpSessionFactory;
+import com.btisystems.pronx.ems.core.snmp.SnmpSessionFactory;
+import com.btisystems.pronx.ems.core.snmp.V2cSnmpConfiguration;
+import static com.google.common.base.Preconditions.checkNotNull;
+import com.google.common.collect.Sets;
+import java.io.IOException;
+import static org.slf4j.LoggerFactory.getLogger;
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+import org.apache.felix.scr.annotations.Activate;
+import org.apache.felix.scr.annotations.Component;
+import org.apache.felix.scr.annotations.Deactivate;
+import org.apache.felix.scr.annotations.Modified;
+import org.onosproject.incubator.net.faultmanagement.alarm.Alarm;
+import org.onosproject.incubator.net.faultmanagement.alarm.AlarmEvent;
+import org.onosproject.incubator.net.faultmanagement.alarm.AlarmListener;
+import org.onosproject.incubator.net.faultmanagement.alarm.AlarmProvider;
+
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.provider.AbstractProvider;
+import org.onosproject.net.provider.ProviderId;
+import org.osgi.service.component.ComponentContext;
+import org.slf4j.Logger;
+import org.apache.felix.scr.annotations.Reference;
+import org.apache.felix.scr.annotations.ReferenceCardinality;
+import static org.onlab.util.Tools.groupedThreads;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreService;
+import org.onosproject.incubator.net.faultmanagement.alarm.DefaultAlarm;
+import org.onosproject.net.device.DeviceEvent;
+import static org.onosproject.net.device.DeviceEvent.Type.DEVICE_ADDED;
+import static org.onosproject.net.device.DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED;
+import org.onosproject.net.device.DeviceListener;
+import org.onosproject.net.device.DeviceService;
+
+/**
+ * SNMP alarms provider.
+ */
+@Component(immediate = true)
+public class SnmpAlarmProviderService extends AbstractProvider implements AlarmProvider {
+
+ private final Logger log = getLogger(getClass());
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+ protected CoreService coreService;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+ protected DeviceService deviceService;
+
+ private ApplicationId appId;
+
+ private final ISnmpSessionFactory sessionFactory;
+
+ // TODO convert to standard ONOS listener service approach ?
+ protected Set<AlarmListener> alarmEventListener = Sets.newHashSet();
+
+ private ExecutorService eventHandlingExecutor;
+
+ // TODO Could be replaced with a service lookup, and bundles per device variant.
+ Map<String, SnmpDeviceAlarmProvider> providers = new HashMap<>();
+
+ public SnmpAlarmProviderService() {
+ super(new ProviderId("snmp", "org.onosproject.provider.alarm"));
+ sessionFactory = new SnmpSessionFactory(
+ new DefaultSnmpConfigurationFactory(new V2cSnmpConfiguration()));
+ providers.put("1.3.6.1.4.1.18070.2.2", new Bti7000SnmpAlarmProvider());
+ providers.put("1.3.6.1.4.1.20408", new NetSnmpAlarmProvider());
+ }
+
+ @Activate
+ public void activate(ComponentContext context) {
+ appId = coreService.registerApplication("org.onosproject.snmp");
+ eventHandlingExecutor = Executors.newSingleThreadExecutor(
+ groupedThreads("onos/alarms", "event-handler"));
+ deviceService.addListener(new InternalDeviceListener());
+ log.info("activated SNMP provider with appId = {} and context props {}", appId, context.getProperties());
+ modified(context);
+
+ log.info("Started");
+ }
+
+ @Deactivate
+ public void deactivate() {
+ log.info("deactivate SNMP provider {}", appId);
+ }
+
+ @Modified
+ public void modified(ComponentContext context) {
+ log.info("modified {}", context);
+
+ if (context == null) {
+ log.info("No configuration file");
+ }
+
+ }
+
+ @Override
+ public void triggerProbe(DeviceId deviceId) {
+ log.info("SNMP walk request for alarms at deviceId={}", deviceId);
+ if (!isSnmpDevice(deviceId)) {
+ log.info("Ignore non-snmp device!");
+ return;
+ }
+ String[] deviceComponents = deviceId.toString().split(":");
+ Set<Alarm> alarms = new HashSet<>(Sets.newHashSet());
+
+ if (deviceComponents.length > 1) {
+ String ipAddress = deviceComponents[1];
+ String port = deviceComponents[2];
+ ISnmpConfiguration config = new V2cSnmpConfiguration();
+ config.setPort(Integer.parseInt(port));
+
+ try (ISnmpSession session = getSessionFactory().createSession(config, ipAddress)) {
+ // Each session will be auto-closed.
+ String deviceOID = session.identifyDevice();
+ alarms.addAll(getAlarmsForDevice(deviceOID, session, deviceId));
+ log.info("SNMP walk completed ok for deviceId={}", deviceId);
+ } catch (IOException | RuntimeException ex) {
+ log.error("Failed to walk device.", ex.getMessage());
+ log.debug("Detailed problem was ", ex);
+ alarms.add(
+ buildWalkFailedAlarm(deviceId)
+ );
+ }
+ }
+
+ AlarmEvent alarmEvent = new AlarmEvent(alarms, deviceId);
+
+ alarmEventListener.stream().forEach((listener) -> {
+ listener.event(alarmEvent);
+ log.info("Successfully event with discovered alarms for deviceId={} to {}", deviceId, listener);
+ });
+
+ }
+
+ private static DefaultAlarm buildWalkFailedAlarm(DeviceId deviceId) {
+ return new DefaultAlarm.Builder(
+ deviceId, "SNMP alarm retrieval failed",
+ Alarm.SeverityLevel.CRITICAL,
+ System.currentTimeMillis()).build();
+ }
+
+ protected ISnmpSessionFactory getSessionFactory() {
+ return sessionFactory;
+ }
+
+ private Collection<Alarm> getAlarmsForDevice(String deviceOID, ISnmpSession session,
+ DeviceId deviceID) throws IOException {
+ Collection<Alarm> alarms = new HashSet<>();
+ if (providers.containsKey(deviceOID)) {
+ alarms.addAll(providers.get(deviceOID).getAlarms(session, deviceID));
+ }
+ return alarms;
+ }
+
+ @Override
+ public void addAlarmListener(AlarmListener listener) {
+ alarmEventListener.add(checkNotNull(listener, "Listener cannot be null"));
+ }
+
+ @Override
+ public void removeAlarmListener(AlarmListener listener) {
+ alarmEventListener.remove(checkNotNull(listener, "Listener cannot be null"));
+ }
+
+ /**
+ * Internal listener for device service events.
+ */
+ private class InternalDeviceListener implements DeviceListener {
+
+ @Override
+ public void event(DeviceEvent event) {
+ log.info("InternalDeviceListener has got event from device-service{} with ", event);
+ eventHandlingExecutor.execute(() -> {
+ try {
+ DeviceId deviceId = event.subject().id();
+ log.info("From device {}", deviceId);
+ if (!isSnmpDevice(deviceId)) {
+ log.info("Ignore non-snmp device event for {}", deviceId);
+ return;
+ }
+
+ switch (event.type()) {
+ case DEVICE_ADDED:
+ case DEVICE_UPDATED:
+ case DEVICE_AVAILABILITY_CHANGED:
+ if (deviceService.isAvailable(event.subject().id())) {
+ triggerProbe(deviceId);
+ }
+ break;
+ case DEVICE_REMOVED:
+ case DEVICE_SUSPENDED:
+ default:
+ // Could potentially remove all alarms when eg DEVICE_REMOVED or DEVICE_SUSPENDED
+ // however for now ignore and fall through
+ break;
+ }
+ } catch (Exception e) {
+ log.warn("Failed to process {}", event, e);
+ }
+ });
+ }
+
+ }
+
+ private static boolean isSnmpDevice(DeviceId deviceId) {
+ return deviceId.uri().getScheme().equalsIgnoreCase("snmp");
+ }
+}
diff --git a/providers/snmp/alarm/src/main/java/org/onosproject/provider/snmp/alarm/impl/SnmpDeviceAlarmProvider.java b/providers/snmp/alarm/src/main/java/org/onosproject/provider/snmp/alarm/impl/SnmpDeviceAlarmProvider.java
new file mode 100644
index 0000000..ef6678a
--- /dev/null
+++ b/providers/snmp/alarm/src/main/java/org/onosproject/provider/snmp/alarm/impl/SnmpDeviceAlarmProvider.java
@@ -0,0 +1,30 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.provider.snmp.alarm.impl;
+
+import com.btisystems.pronx.ems.core.snmp.ISnmpSession;
+import java.util.Collection;
+import org.onosproject.incubator.net.faultmanagement.alarm.Alarm;
+import org.onosproject.net.DeviceId;
+
+public interface SnmpDeviceAlarmProvider {
+ /**
+ * Implemented by device specific implementations which query the current
+ * alarms from a device.
+ * @param snmpSession SNMP Session
+ * @param deviceId device identifier
+ * @return device alarms
+ */
+ Collection<Alarm> getAlarms(ISnmpSession snmpSession, DeviceId deviceId);
+}
diff --git a/providers/snmp/alarm/src/main/java/org/onosproject/provider/snmp/alarm/impl/package-info.java b/providers/snmp/alarm/src/main/java/org/onosproject/provider/snmp/alarm/impl/package-info.java
index 2c138cb..3ec926c 100644
--- a/providers/snmp/alarm/src/main/java/org/onosproject/provider/snmp/alarm/impl/package-info.java
+++ b/providers/snmp/alarm/src/main/java/org/onosproject/provider/snmp/alarm/impl/package-info.java
@@ -1,5 +1,9 @@
/*
+<<<<<<< HEAD
+ * Copyright 2015 Open Networking Laboratory
+=======
* Copyright 2014 Open Networking Laboratory
+>>>>>>> master
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,6 +19,6 @@
*/
/**
- * Provider that uses SNMP as a means of discovering alarms on devices.
+ * Provider that will support SNMP alarm discoveries.
*/
package org.onosproject.provider.snmp.alarm.impl;
diff --git a/providers/snmp/alarm/src/test/java/org/onosproject/provider/snmp/alarm/impl/Bti7000SnmpAlarmProviderTest.java b/providers/snmp/alarm/src/test/java/org/onosproject/provider/snmp/alarm/impl/Bti7000SnmpAlarmProviderTest.java
new file mode 100644
index 0000000..f26100c
--- /dev/null
+++ b/providers/snmp/alarm/src/test/java/org/onosproject/provider/snmp/alarm/impl/Bti7000SnmpAlarmProviderTest.java
@@ -0,0 +1,115 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.provider.snmp.alarm.impl;
+
+import com.btisystems.mibbler.mibs.bti7000.bti7000_13_2_0.btisystems.btiproducts.bti7000.objects.conditions.ActAlarmTable;
+import com.btisystems.mibbler.mibs.bti7000.interfaces.btisystems.btiproducts.bti7000.objects.conditions.actalarmtable.IActAlarmEntry;
+import com.btisystems.pronx.ems.core.model.NetworkDevice;
+import com.btisystems.pronx.ems.core.snmp.ISnmpSession;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.Arrays;
+import java.util.Collection;
+import org.easymock.Capture;
+import static org.easymock.EasyMock.capture;
+import static org.easymock.EasyMock.createMock;
+import static org.easymock.EasyMock.eq;
+import static org.easymock.EasyMock.expect;
+import static org.easymock.EasyMock.isA;
+import static org.easymock.EasyMock.replay;
+import static org.easymock.EasyMock.verify;
+import org.junit.Before;
+import org.junit.Test;
+import static org.junit.Assert.*;
+import org.onosproject.incubator.net.faultmanagement.alarm.Alarm;
+import org.onosproject.net.DeviceId;
+import org.snmp4j.smi.OID;
+
+
+public class Bti7000SnmpAlarmProviderTest {
+ private Bti7000SnmpAlarmProvider alarmProvider;
+ private ISnmpSession mockSession;
+ private ActAlarmTable alarmsTable;
+
+ public Bti7000SnmpAlarmProviderTest() {
+ }
+
+ @Before
+ public void setUp() {
+ mockSession = createMock(ISnmpSession.class);
+
+ alarmProvider = new Bti7000SnmpAlarmProvider();
+ }
+
+ @Test
+ public void shouldWalkDevice() throws UnknownHostException, IOException {
+ expect(mockSession.getAddress()).andReturn(InetAddress.getLoopbackAddress());
+ expect(mockSession.walkDevice(isA(NetworkDevice.class),
+ eq(Arrays.asList(new OID[]{
+ Bti7000SnmpAlarmProvider.CLASS_REGISTRY.getClassToOidMap().get(ActAlarmTable.class)}))))
+ .andReturn(null);
+
+ replay(mockSession);
+
+ assertNotNull(alarmProvider.getAlarms(mockSession, DeviceId.deviceId("snmp:1.1.1.1")));
+
+ verify(mockSession);
+ }
+
+ @Test
+ public void shouldFindAlarms() throws UnknownHostException, IOException {
+ alarmsTable = new ActAlarmTable();
+ alarmsTable.createEntry("14.1.3.6.1.4.1.18070.2.2.2.2.20.0.1.13.1.3.6.1.4.1."
+ + "18070.2.2.1.4.14.1.7.49.46.55.46.50.46.53");
+ IActAlarmEntry entry = alarmsTable.getEntries().values().iterator().next();
+ entry.setActAlarmDescription("XFP Missing.");
+ entry.setActAlarmDateAndTime("07:df:0c:01:03:0d:30:00");
+ entry.setActAlarmSeverity(1);
+
+ Capture<NetworkDevice> networkDeviceCapture = new Capture<>();
+
+ expect(mockSession.getAddress()).andReturn(InetAddress.getLoopbackAddress());
+ expect(mockSession.walkDevice(capture(networkDeviceCapture),
+ eq(Arrays.asList(new OID[]{
+ Bti7000SnmpAlarmProvider.CLASS_REGISTRY.getClassToOidMap().get(ActAlarmTable.class)}))))
+ .andAnswer(() -> {
+ networkDeviceCapture.getValue().getRootObject().setObject(alarmsTable);
+ return null;
+ });
+
+ replay(mockSession);
+
+ Collection<Alarm> alarms = alarmProvider.getAlarms(mockSession, DeviceId.deviceId("snmp:1.1.1.1"));
+ assertEquals(1, alarms.size());
+ assertEquals("XFP Missing.", alarms.iterator().next().description());
+ verify(mockSession);
+ }
+
+ @Test
+ public void shouldHandleException() throws UnknownHostException, IOException {
+ expect(mockSession.getAddress()).andReturn(InetAddress.getLoopbackAddress());
+ expect(mockSession.walkDevice(isA(NetworkDevice.class),
+ eq(Arrays.asList(new OID[]{
+ Bti7000SnmpAlarmProvider.CLASS_REGISTRY.getClassToOidMap().get(ActAlarmTable.class)}))))
+ .andThrow(new IOException());
+
+ replay(mockSession);
+
+ assertNotNull(alarmProvider.getAlarms(mockSession, DeviceId.deviceId("snmp:1.1.1.1")));
+
+ verify(mockSession);
+ }
+
+}
diff --git a/providers/snmp/alarm/src/test/java/org/onosproject/provider/snmp/alarm/impl/NetSnmpSnmpAlarmProviderTest.java b/providers/snmp/alarm/src/test/java/org/onosproject/provider/snmp/alarm/impl/NetSnmpSnmpAlarmProviderTest.java
new file mode 100644
index 0000000..1442e8d
--- /dev/null
+++ b/providers/snmp/alarm/src/test/java/org/onosproject/provider/snmp/alarm/impl/NetSnmpSnmpAlarmProviderTest.java
@@ -0,0 +1,114 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.provider.snmp.alarm.impl;
+
+import com.btisystems.mibbler.mibs.netsnmp.interfaces.mib_2.interfaces.iftable.IIfEntry;
+import com.btisystems.mibbler.mibs.netsnmp.netsnmp.mib_2.interfaces.IfTable;
+import com.btisystems.pronx.ems.core.model.NetworkDevice;
+import com.btisystems.pronx.ems.core.snmp.ISnmpSession;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.Arrays;
+import java.util.Collection;
+import org.easymock.Capture;
+import static org.easymock.EasyMock.capture;
+import static org.easymock.EasyMock.createMock;
+import static org.easymock.EasyMock.eq;
+import static org.easymock.EasyMock.expect;
+import static org.easymock.EasyMock.isA;
+import static org.easymock.EasyMock.replay;
+import static org.easymock.EasyMock.verify;
+import org.junit.Before;
+import org.junit.Test;
+import static org.junit.Assert.*;
+import org.onosproject.incubator.net.faultmanagement.alarm.Alarm;
+import org.onosproject.net.DeviceId;
+import org.snmp4j.smi.OID;
+
+
+public class NetSnmpSnmpAlarmProviderTest {
+ private NetSnmpAlarmProvider alarmProvider;
+ private ISnmpSession mockSession;
+ private IfTable interfaceTable;
+
+ public NetSnmpSnmpAlarmProviderTest() {
+ }
+
+ @Before
+ public void setUp() {
+ mockSession = createMock(ISnmpSession.class);
+
+ alarmProvider = new NetSnmpAlarmProvider();
+ }
+
+ @Test
+ public void shouldWalkDevice() throws UnknownHostException, IOException {
+ expect(mockSession.getAddress()).andReturn(InetAddress.getLoopbackAddress());
+ expect(mockSession.walkDevice(isA(NetworkDevice.class),
+ eq(Arrays.asList(new OID[]{
+ NetSnmpAlarmProvider.CLASS_REGISTRY.getClassToOidMap().get(IfTable.class)}))))
+ .andReturn(null);
+
+ replay(mockSession);
+
+ assertNotNull(alarmProvider.getAlarms(mockSession, DeviceId.deviceId("snmp:1.1.1.1")));
+
+ verify(mockSession);
+ }
+
+ @Test
+ public void shouldFindAlarms() throws UnknownHostException, IOException {
+ interfaceTable = new IfTable();
+ interfaceTable.createEntry("1");
+ IIfEntry entry = interfaceTable.getEntry("1");
+ entry.setIfDescr("eth1");
+ entry.setIfAdminStatus(1);
+ entry.setIfOperStatus(2);
+
+ Capture<NetworkDevice> networkDeviceCapture = new Capture<>();
+
+ expect(mockSession.getAddress()).andReturn(InetAddress.getLoopbackAddress());
+ expect(mockSession.walkDevice(capture(networkDeviceCapture),
+ eq(Arrays.asList(new OID[]{
+ NetSnmpAlarmProvider.CLASS_REGISTRY.getClassToOidMap().get(IfTable.class)}))))
+ .andAnswer(() -> {
+ networkDeviceCapture.getValue().getRootObject().setObject(interfaceTable);
+ return null;
+ });
+
+ replay(mockSession);
+
+ Collection<Alarm> alarms = alarmProvider.getAlarms(mockSession, DeviceId.deviceId("snmp:1.1.1.1"));
+ assertEquals(1, alarms.size());
+ assertEquals("Link Down.", alarms.iterator().next().description());
+ verify(mockSession);
+ }
+
+ @Test
+ public void shouldHandleException() throws UnknownHostException, IOException {
+ expect(mockSession.getAddress()).andReturn(InetAddress.getLoopbackAddress());
+ expect(mockSession.walkDevice(isA(NetworkDevice.class),
+ eq(Arrays.asList(new OID[]{
+ NetSnmpAlarmProvider.CLASS_REGISTRY.getClassToOidMap().get(IfTable.class)}))))
+ .andThrow(new IOException());
+
+ replay(mockSession);
+
+ assertNotNull(alarmProvider.getAlarms(mockSession, DeviceId.deviceId("snmp:1.1.1.1")));
+
+ verify(mockSession);
+ }
+
+}
diff --git a/providers/snmp/alarm/src/test/java/org/onosproject/provider/snmp/alarm/impl/SnmpDeviceAlarmProviderTest.java b/providers/snmp/alarm/src/test/java/org/onosproject/provider/snmp/alarm/impl/SnmpDeviceAlarmProviderTest.java
new file mode 100644
index 0000000..f443831
--- /dev/null
+++ b/providers/snmp/alarm/src/test/java/org/onosproject/provider/snmp/alarm/impl/SnmpDeviceAlarmProviderTest.java
@@ -0,0 +1,78 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.provider.snmp.alarm.impl;
+
+import com.btisystems.pronx.ems.core.snmp.ISnmpConfiguration;
+import com.btisystems.pronx.ems.core.snmp.ISnmpSession;
+import com.btisystems.pronx.ems.core.snmp.ISnmpSessionFactory;
+import java.io.IOException;
+import java.util.HashSet;
+import org.easymock.EasyMock;
+import static org.easymock.EasyMock.expect;
+import static org.easymock.EasyMock.replay;
+import static org.easymock.EasyMock.verify;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.onosproject.incubator.net.faultmanagement.alarm.AlarmEvent;
+import org.onosproject.net.DeviceId;
+
+public class SnmpDeviceAlarmProviderTest {
+ private SnmpAlarmProviderService alarmProvider;
+ private ISnmpSessionFactory mockSessionFactory;
+ private ISnmpSession mockSession;
+ private SnmpDeviceAlarmProvider mockProvider;
+ private AlarmEvent alarmEvent;
+
+ public SnmpDeviceAlarmProviderTest() {}
+
+ @Before
+ public void setUp() {
+ mockSessionFactory = EasyMock.createMock(ISnmpSessionFactory.class);
+ mockSession = EasyMock.createMock(ISnmpSession.class);
+ mockProvider = EasyMock.createMock(SnmpDeviceAlarmProvider.class);
+
+ alarmProvider = new SnmpAlarmProviderService() {
+ @Override
+ protected ISnmpSessionFactory getSessionFactory() {
+ return mockSessionFactory;
+ }
+ };
+
+ alarmProvider.addAlarmListener((AlarmEvent event) -> {
+ alarmEvent = event;
+ });
+ }
+
+ @Test
+ public void shouldPopulateAlarmsForNetSnmp() throws IOException {
+ alarmProvider.providers.put("1.2.3.4", mockProvider);
+ expect(mockSessionFactory.createSession(EasyMock.isA(ISnmpConfiguration.class),
+ EasyMock.eq("1.1.1.1"))).andReturn(mockSession);
+ expect(mockSession.identifyDevice()).andReturn("1.2.3.4");
+ expect(mockProvider.getAlarms(mockSession, DeviceId.deviceId("snmp:1.1.1.1:161")))
+ .andReturn(new HashSet<>());
+
+ mockSession.close();
+ EasyMock.expectLastCall().once();
+
+ replay(mockSessionFactory, mockSession, mockProvider);
+
+ alarmProvider.triggerProbe(DeviceId.deviceId("snmp:1.1.1.1:161"));
+
+ verify(mockSessionFactory, mockSession, mockProvider);
+ Assert.assertNotNull(alarmEvent);
+ }
+
+}
diff --git a/providers/snmp/app/app.xml b/providers/snmp/app/app.xml
new file mode 100644
index 0000000..758cce2
--- /dev/null
+++ b/providers/snmp/app/app.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ ~ Copyright 2015 Open Networking Laboratory
+ ~
+ ~ Licensed under the Apache License, Version 2.0 (the "License");
+ ~ you may not use this file except in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~ http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+ -->
+<app name="org.onosproject.snmp" origin="BTI Systems" version="${project.version}"
+ featuresRepo="mvn:${project.groupId}/${project.artifactId}/${project.version}/xml/features"
+ features="${project.artifactId}">
+ <description>${project.description}</description>
+ <artifact>mvn:${project.groupId}/onos-snmp-provider-device/${project.version}</artifact>
+ <artifact>mvn:${project.groupId}/onos-snmp-provider-alarm/${project.version}</artifact>
+</app>
diff --git a/providers/snmp/app/features.xml b/providers/snmp/app/features.xml
new file mode 100644
index 0000000..0874f54
--- /dev/null
+++ b/providers/snmp/app/features.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<!--
+ ~ Copyright 2015 Open Networking Laboratory
+ ~
+ ~ Licensed under the Apache License, Version 2.0 (the "License");
+ ~ you may not use this file except in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~ http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+ -->
+<features xmlns="http://karaf.apache.org/xmlns/features/v1.2.0" name="${project.artifactId}-${project.version}">
+ <feature name="${project.artifactId}" version="${project.version}"
+ description="${project.description}">
+ <feature>onos-api</feature>
+ <bundle>mvn:io.netty/netty/3.9.2.Final</bundle>
+ <bundle>mvn:org.apache.servicemix.bundles/org.apache.servicemix.bundles.snmp4j/2.3.4_1</bundle>
+ <bundle>mvn:${project.groupId}/onos-snmp-provider-device/${project.version}</bundle>
+ <bundle>mvn:com.btisystems/snmp-core/1.3-SNAPSHOT</bundle>
+ <bundle>mvn:com.btisystems.mibbler.mibs/bti7000/1.0-SNAPSHOT</bundle>
+ <bundle>mvn:com.btisystems.mibbler.mibs/net-snmp/1.0-SNAPSHOT</bundle>
+ </feature>
+</features>
+
diff --git a/providers/snmp/app/pom.xml b/providers/snmp/app/pom.xml
new file mode 100644
index 0000000..4f6c90a
--- /dev/null
+++ b/providers/snmp/app/pom.xml
@@ -0,0 +1,47 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ ~ Copyright 2015 Open Networking Laboratory
+ ~
+ ~ Licensed under the Apache License, Version 2.0 (the "License");
+ ~ you may not use this file except in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~ http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+ -->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>org.onosproject</groupId>
+ <artifactId>onos-snmp-providers</artifactId>
+ <version>1.4.0-SNAPSHOT</version>
+ <relativePath>../pom.xml</relativePath>
+ </parent>
+
+ <artifactId>onos-snmp-app</artifactId>
+ <packaging>pom</packaging>
+
+ <description>SNMP protocol southbound providers</description>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.onosproject</groupId>
+ <artifactId>onos-snmp-provider-device</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.onosproject</groupId>
+ <artifactId>onos-snmp-provider-alarm</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ </dependencies>
+
+</project>
diff --git a/providers/snmp/device/pom.xml b/providers/snmp/device/pom.xml
new file mode 100644
index 0000000..cf39fe4
--- /dev/null
+++ b/providers/snmp/device/pom.xml
@@ -0,0 +1,64 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ ~ Copyright 2015 Open Networking Laboratory
+ ~
+ ~ Licensed under the Apache License, Version 2.0 (the "License");
+ ~ you may not use this file except in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~ http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>org.onosproject</groupId>
+ <artifactId>onos-snmp-providers</artifactId>
+ <version>1.4.0-SNAPSHOT</version>
+ <relativePath>../pom.xml</relativePath>
+ </parent>
+
+ <artifactId>onos-snmp-provider-device</artifactId>
+ <packaging>bundle</packaging>
+
+ <description>ONOS SNMP protocol device provider</description>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>org.osgi.compendium</artifactId>
+ </dependency>
+ <!-- <dependency>
+ <groupId>javax.ws.rs</groupId>
+ <artifactId>jsr311-api</artifactId>
+ <version>1.1.1</version>
+ </dependency>
+ <dependency>
+ <groupId>org.onosproject</groupId>
+ <artifactId>onos-incubator-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.onosproject</groupId>
+ <artifactId>onos-core-serializers</artifactId>
+ <version>${project.version}</version>
+ </dependency>-->
+ </dependencies>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>maven-scr-plugin</artifactId>
+ </plugin>
+ </plugins>
+ </build>
+
+</project>
+
\ No newline at end of file
diff --git a/providers/snmp/device/src/main/java/org/onosproject/provider/snmp/device/impl/Bti7000DeviceDescriptionProvider.java b/providers/snmp/device/src/main/java/org/onosproject/provider/snmp/device/impl/Bti7000DeviceDescriptionProvider.java
new file mode 100644
index 0000000..d779e0a
--- /dev/null
+++ b/providers/snmp/device/src/main/java/org/onosproject/provider/snmp/device/impl/Bti7000DeviceDescriptionProvider.java
@@ -0,0 +1,64 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.provider.snmp.device.impl;
+
+import com.btisystems.mibbler.mibs.bti7000.bti7000_13_2_0.I_Device;
+import com.btisystems.mibbler.mibs.bti7000.bti7000_13_2_0._OidRegistry;
+import com.btisystems.pronx.ems.core.model.ClassRegistry;
+import com.btisystems.pronx.ems.core.model.IClassRegistry;
+import com.btisystems.pronx.ems.core.model.NetworkDevice;
+import com.btisystems.pronx.ems.core.snmp.ISnmpSession;
+import java.io.IOException;
+import java.util.Arrays;
+import org.onosproject.net.device.DefaultDeviceDescription;
+import org.onosproject.net.device.DeviceDescription;
+import org.slf4j.Logger;
+import static org.slf4j.LoggerFactory.getLogger;
+import org.snmp4j.smi.OID;
+
+/**
+ * A vendor-specific implementation supporting BTI Systems BTI-7000 equipment.
+ */
+public class Bti7000DeviceDescriptionProvider implements SnmpDeviceDescriptionProvider {
+ private final Logger log = getLogger(getClass());
+ protected static final IClassRegistry CLASS_REGISTRY =
+ new ClassRegistry(_OidRegistry.oidRegistry, I_Device.class);
+ private static final String UNKNOWN = "unknown";
+
+ @Override
+ public DeviceDescription populateDescription(ISnmpSession session, DeviceDescription description) {
+ NetworkDevice networkDevice = new NetworkDevice(CLASS_REGISTRY,
+ session.getAddress().getHostAddress());
+ try {
+ session.walkDevice(networkDevice, Arrays.asList(new OID[]{
+ CLASS_REGISTRY.getClassToOidMap().get(
+ com.btisystems.mibbler.mibs.bti7000.bti7000_13_2_0.mib_2.System.class)}));
+
+ com.btisystems.mibbler.mibs.bti7000.bti7000_13_2_0.mib_2.System systemTree =
+ (com.btisystems.mibbler.mibs.bti7000.bti7000_13_2_0.mib_2.System)
+ networkDevice.getRootObject().getEntity(CLASS_REGISTRY.getClassToOidMap().get(
+ com.btisystems.mibbler.mibs.bti7000.bti7000_13_2_0.mib_2.System.class));
+ if (systemTree != null) {
+ String[] systemComponents = systemTree.getSysDescr().split(";");
+ return new DefaultDeviceDescription(description.deviceUri(), description.type(),
+ systemComponents[0], systemComponents[2], systemComponents[3],
+ UNKNOWN, description.chassisId());
+ }
+ } catch (IOException ex) {
+ log.error("Error reading details for device {}.", session.getAddress(), ex);
+ }
+ return description;
+ }
+
+}
diff --git a/providers/snmp/device/src/main/java/org/onosproject/provider/snmp/device/impl/DeviceState.java b/providers/snmp/device/src/main/java/org/onosproject/provider/snmp/device/impl/DeviceState.java
new file mode 100644
index 0000000..e358927
--- /dev/null
+++ b/providers/snmp/device/src/main/java/org/onosproject/provider/snmp/device/impl/DeviceState.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright 2015 Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.provider.snmp.device.impl;
+ /**
+ * The Device State is used to determine whether the device is active or inactive. This state information will help
+ * Device Creator to add or delete the device from the core.
+ */
+ public enum DeviceState {
+ /* Used to specify Active state of the device */
+
+ ACTIVE,
+ /* Used to specify inactive state of the device */
+ INACTIVE,
+ /* Used to specify invalid state of the device */
+ INVALID
+ }
diff --git a/providers/snmp/device/src/main/java/org/onosproject/provider/snmp/device/impl/NetSnmpDeviceDescriptionProvider.java b/providers/snmp/device/src/main/java/org/onosproject/provider/snmp/device/impl/NetSnmpDeviceDescriptionProvider.java
new file mode 100644
index 0000000..5e6689a
--- /dev/null
+++ b/providers/snmp/device/src/main/java/org/onosproject/provider/snmp/device/impl/NetSnmpDeviceDescriptionProvider.java
@@ -0,0 +1,66 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.provider.snmp.device.impl;
+
+import com.btisystems.mibbler.mibs.netsnmp.netsnmp.I_Device;
+import com.btisystems.mibbler.mibs.netsnmp.netsnmp._OidRegistry;
+import com.btisystems.pronx.ems.core.model.ClassRegistry;
+import com.btisystems.pronx.ems.core.model.IClassRegistry;
+import com.btisystems.pronx.ems.core.model.NetworkDevice;
+import com.btisystems.pronx.ems.core.snmp.ISnmpSession;
+import java.io.IOException;
+import java.util.Arrays;
+import org.apache.commons.lang.StringUtils;
+import org.onosproject.net.device.DefaultDeviceDescription;
+import org.onosproject.net.device.DeviceDescription;
+import org.slf4j.Logger;
+import static org.slf4j.LoggerFactory.getLogger;
+import org.snmp4j.smi.OID;
+
+/**
+ * A agent-specific implementation supporting NET-SNMP agents.
+ */
+public class NetSnmpDeviceDescriptionProvider implements SnmpDeviceDescriptionProvider {
+ private final Logger log = getLogger(getClass());
+ protected static final IClassRegistry CLASS_REGISTRY =
+ new ClassRegistry(_OidRegistry.oidRegistry, I_Device.class);
+ private static final String UNKNOWN = "unknown";
+
+ @Override
+ public DeviceDescription populateDescription(ISnmpSession session, DeviceDescription description) {
+ NetworkDevice networkDevice = new NetworkDevice(CLASS_REGISTRY,
+ session.getAddress().getHostAddress());
+ try {
+ session.walkDevice(networkDevice, Arrays.asList(new OID[]{
+ CLASS_REGISTRY.getClassToOidMap().get(
+ com.btisystems.mibbler.mibs.netsnmp.netsnmp.mib_2.System.class)}));
+
+ com.btisystems.mibbler.mibs.netsnmp.netsnmp.mib_2.System systemTree =
+ (com.btisystems.mibbler.mibs.netsnmp.netsnmp.mib_2.System)
+ networkDevice.getRootObject().getEntity(CLASS_REGISTRY.getClassToOidMap().get(
+ com.btisystems.mibbler.mibs.netsnmp.netsnmp.mib_2.System.class));
+ if (systemTree != null) {
+ // TODO SNMP sys-contacts may be verbose; ONOS-GUI doesn't abbreviate fields neatly;
+ // so cut it here until supported in prop displayer
+ String manufacturer = StringUtils.abbreviate(systemTree.getSysContact(), 20);
+ return new DefaultDeviceDescription(description.deviceUri(), description.type(), manufacturer,
+ UNKNOWN, UNKNOWN, UNKNOWN, description.chassisId());
+ }
+ } catch (IOException ex) {
+ log.error("Error reading details for device {}.", session.getAddress(), ex);
+ }
+ return description;
+ }
+
+}
diff --git a/providers/snmp/device/src/main/java/org/onosproject/provider/snmp/device/impl/SnmpDevice.java b/providers/snmp/device/src/main/java/org/onosproject/provider/snmp/device/impl/SnmpDevice.java
new file mode 100644
index 0000000..8b385dc
--- /dev/null
+++ b/providers/snmp/device/src/main/java/org/onosproject/provider/snmp/device/impl/SnmpDevice.java
@@ -0,0 +1,134 @@
+/*
+ * Copyright 2015 Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.provider.snmp.device.impl;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+import static org.slf4j.LoggerFactory.getLogger;
+
+
+import org.slf4j.Logger;
+
+/**
+ * This is a logical representation of actual SNMP device, carrying all the necessary information to connect and execute
+ * SNMP operations.
+ */
+public class SnmpDevice {
+
+ private final Logger log = getLogger(SnmpDevice.class);
+
+
+ private static final int DEFAULT_SNMP_PORT = 161;
+
+ private final String snmpHost;
+ private int snmpPort = DEFAULT_SNMP_PORT;
+ private final String community;
+ private boolean reachable = false;
+
+ private DeviceState deviceState = DeviceState.INVALID;
+
+ protected SnmpDevice(String snmpHost, int snmpPort, String community) {
+
+ this.snmpHost = checkNotNull(snmpHost, "SNMP Device IP cannot be null");
+ this.snmpPort = checkNotNull(snmpPort, "SNMP Device snmp port cannot be null");
+ this.community = community;
+ }
+
+ /**
+ * This will try to connect to SNMP device.
+ *
+ */
+ public void init() {
+
+ reachable = true;
+ }
+
+ /**
+ * This would return host IP and host Port, used by this particular SNMP Device.
+ *
+ * @return Device Information.
+ */
+ public String deviceInfo() {
+ return new StringBuilder("host: ").append(snmpHost).append(". port: ")
+ .append(snmpPort).toString();
+ }
+
+ /**
+ * This will terminate the device connection.
+ */
+ public void disconnect() {
+ log.info("disconnect");
+ reachable = false;
+ }
+
+ /**
+ * This api is intended to know whether the device is connected or not.
+ *
+ * @return true if connected
+ */
+ public boolean isReachable() {
+ return reachable;
+ }
+
+ /**
+ * This will return the IP used connect ssh on the device.
+ *
+ * @return SNMP Device IP
+ */
+ public String getSnmpHost() {
+ return snmpHost;
+ }
+
+ /**
+ * This will return the SSH Port used connect the device.
+ *
+ * @return SSH Port number
+ */
+ public int getSnmpPort() {
+ return snmpPort;
+ }
+
+ public String getCommunity() {
+ return community;
+ }
+
+ /**
+ * Retrieve current state of the device.
+ *
+ * @return Current Device State
+ */
+ public DeviceState getDeviceState() {
+ return deviceState;
+ }
+
+ /**
+ * This is set the state information for the device.
+ *
+ * @param deviceState Next Device State
+ */
+ public void setDeviceState(DeviceState deviceState) {
+ this.deviceState = deviceState;
+ }
+
+ /**
+ * Check whether the device is in Active state.
+ *
+ * @return true if the device is Active
+ */
+ public boolean isActive() {
+ return deviceState == DeviceState.ACTIVE;
+ }
+
+}
diff --git a/providers/snmp/device/src/main/java/org/onosproject/provider/snmp/device/impl/SnmpDeviceDescriptionProvider.java b/providers/snmp/device/src/main/java/org/onosproject/provider/snmp/device/impl/SnmpDeviceDescriptionProvider.java
new file mode 100644
index 0000000..4be3a35
--- /dev/null
+++ b/providers/snmp/device/src/main/java/org/onosproject/provider/snmp/device/impl/SnmpDeviceDescriptionProvider.java
@@ -0,0 +1,33 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.provider.snmp.device.impl;
+
+import com.btisystems.pronx.ems.core.snmp.ISnmpSession;
+import org.onosproject.net.device.DeviceDescription;
+
+/**
+ * Abstraction of an entity which updates a device description with information retrieved via SNMP.
+ */
+public interface SnmpDeviceDescriptionProvider {
+
+ /**
+ * Generated an updated device description.
+ *
+ * @param session SNMP session
+ * @param description old device description
+ * @return new updated description
+ */
+ DeviceDescription populateDescription(ISnmpSession session, DeviceDescription description);
+
+}
diff --git a/providers/snmp/device/src/main/java/org/onosproject/provider/snmp/device/impl/SnmpDeviceProvider.java b/providers/snmp/device/src/main/java/org/onosproject/provider/snmp/device/impl/SnmpDeviceProvider.java
new file mode 100644
index 0000000..f18ae72
--- /dev/null
+++ b/providers/snmp/device/src/main/java/org/onosproject/provider/snmp/device/impl/SnmpDeviceProvider.java
@@ -0,0 +1,406 @@
+/*
+ * Copyright 2015 Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.provider.snmp.device.impl;
+
+import com.btisystems.pronx.ems.core.snmp.DefaultSnmpConfigurationFactory;
+import com.btisystems.pronx.ems.core.snmp.ISnmpConfiguration;
+import com.btisystems.pronx.ems.core.snmp.ISnmpConfigurationFactory;
+import com.btisystems.pronx.ems.core.snmp.ISnmpSession;
+import com.btisystems.pronx.ems.core.snmp.ISnmpSessionFactory;
+import com.btisystems.pronx.ems.core.snmp.SnmpSessionFactory;
+import com.btisystems.pronx.ems.core.snmp.V2cSnmpConfiguration;
+import static com.google.common.base.Strings.isNullOrEmpty;
+import java.io.IOException;
+import static org.onlab.util.Tools.delay;
+import static org.onlab.util.Tools.get;
+import static org.onlab.util.Tools.groupedThreads;
+import static org.slf4j.LoggerFactory.getLogger;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.Dictionary;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.felix.scr.annotations.Activate;
+import org.apache.felix.scr.annotations.Component;
+import org.apache.felix.scr.annotations.Deactivate;
+import org.apache.felix.scr.annotations.Modified;
+import org.apache.felix.scr.annotations.Property;
+import org.apache.felix.scr.annotations.Reference;
+import org.apache.felix.scr.annotations.ReferenceCardinality;
+import org.onlab.packet.ChassisId;
+import org.onosproject.cfg.ComponentConfigService;
+import org.onosproject.cluster.ClusterService;
+import org.onosproject.net.Device;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.MastershipRole;
+import org.onosproject.net.device.DefaultDeviceDescription;
+import org.onosproject.net.device.DeviceDescription;
+import org.onosproject.net.device.DeviceProvider;
+import org.onosproject.net.device.DeviceProviderRegistry;
+import org.onosproject.net.device.DeviceProviderService;
+import org.onosproject.net.device.DeviceService;
+import org.onosproject.net.provider.AbstractProvider;
+import org.onosproject.net.provider.ProviderId;
+import org.osgi.service.component.ComponentContext;
+import org.slf4j.Logger;
+
+/**
+ * Provider which will try to fetch the details of SNMP devices from the core and run a capability discovery on each of
+ * the device.
+ */
+@Component(immediate = true)
+public class SnmpDeviceProvider extends AbstractProvider
+ implements DeviceProvider {
+
+ private final Logger log = getLogger(SnmpDeviceProvider.class);
+
+ private static final String UNKNOWN = "unknown";
+
+ protected Map<DeviceId, SnmpDevice> snmpDeviceMap = new ConcurrentHashMap<>();
+
+ private DeviceProviderService providerService;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+ protected DeviceProviderRegistry providerRegistry;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+ protected DeviceService deviceService;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+ protected ClusterService clusterService;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+ protected ComponentConfigService cfgService;
+
+ private final ExecutorService deviceBuilder = Executors
+ .newFixedThreadPool(1, groupedThreads("onos/snmp", "device-creator"));
+
+ // Delay between events in ms.
+ private static final int EVENTINTERVAL = 5;
+
+ private static final String SCHEME = "snmp";
+
+ @Property(name = "devConfigs", value = "", label = "Instance-specific configurations")
+ private String devConfigs = null;
+
+ @Property(name = "devPasswords", value = "", label = "Instance-specific password")
+ private String devPasswords = null;
+
+ //TODO Could be replaced with a service lookup, and bundles per device variant.
+ Map<String, SnmpDeviceDescriptionProvider> providers = new HashMap<>();
+
+ private final ISnmpSessionFactory sessionFactory;
+
+ /**
+ * Creates a provider with the supplier identifier.
+ */
+ public SnmpDeviceProvider() {
+ super(new ProviderId("snmp", "org.onosproject.provider.device"));
+ sessionFactory = new SnmpSessionFactory(
+ new DefaultSnmpConfigurationFactory(new V2cSnmpConfiguration()));
+ providers.put("1.3.6.1.4.1.18070.2.2", new Bti7000DeviceDescriptionProvider());
+ providers.put("1.3.6.1.4.1.20408", new NetSnmpDeviceDescriptionProvider());
+ }
+
+ @Activate
+ public void activate(ComponentContext context) {
+ log.info("activating for snmp devices ...");
+ cfgService.registerProperties(getClass());
+ providerService = providerRegistry.register(this);
+ modified(context);
+ log.info("activated ok");
+ }
+
+ @Deactivate
+ public void deactivate(ComponentContext context) {
+
+ log.info("deactivating for snmp devices ...");
+
+ cfgService.unregisterProperties(getClass(), false);
+ try {
+ snmpDeviceMap
+ .entrySet().stream().forEach((deviceEntry) -> {
+ deviceBuilder.submit(new DeviceCreator(deviceEntry.getValue(), false));
+ });
+ deviceBuilder.awaitTermination(1000, TimeUnit.MILLISECONDS);
+ } catch (InterruptedException e) {
+ log.error("Device builder did not terminate");
+ }
+ deviceBuilder.shutdownNow();
+ snmpDeviceMap.clear();
+ providerRegistry.unregister(this);
+ providerService = null;
+ log.info("Stopped");
+ }
+
+ @Modified
+ public void modified(ComponentContext context) {
+ log.info("modified ...");
+
+ if (context == null) {
+ log.info("No configuration file");
+ return;
+ }
+ Dictionary<?, ?> properties = context.getProperties();
+
+ log.info("properties={}", context.getProperties());
+
+ String deviceCfgValue = get(properties, "devConfigs");
+ log.info("Settings: devConfigs={}", deviceCfgValue);
+ if (!isNullOrEmpty(deviceCfgValue)) {
+ addOrRemoveDevicesConfig(deviceCfgValue);
+ }
+ log.info("... modified");
+
+ }
+
+ private void addOrRemoveDevicesConfig(String deviceConfig) {
+ for (String deviceEntry : deviceConfig.split(",")) {
+ SnmpDevice device = processDeviceEntry(deviceEntry);
+ if (device != null) {
+ log.info("Device Detail:host={}, port={}, state={}",
+ new Object[]{device.getSnmpHost(),
+ device.getSnmpPort(),
+ device.getDeviceState().name()}
+ );
+ if (device.isActive()) {
+ deviceBuilder.submit(new DeviceCreator(device, true));
+ } else {
+ deviceBuilder.submit(new DeviceCreator(device, false));
+ }
+ }
+ }
+ }
+
+ private SnmpDevice processDeviceEntry(String deviceEntry) {
+ if (deviceEntry == null) {
+ log.info("No content for Device Entry, so cannot proceed further.");
+ return null;
+ }
+ log.info("Trying to convert {} to a SNMP Device Object", deviceEntry);
+ SnmpDevice device = null;
+ try {
+ String userInfo = deviceEntry.substring(0, deviceEntry
+ .lastIndexOf('@'));
+ String hostInfo = deviceEntry.substring(deviceEntry
+ .lastIndexOf('@') + 1);
+ String[] infoSplit = userInfo.split(":");
+ String username = infoSplit[0];
+ String password = infoSplit[1];
+ infoSplit = hostInfo.split(":");
+ String hostIp = infoSplit[0];
+ Integer hostPort;
+ try {
+ hostPort = Integer.parseInt(infoSplit[1]);
+ } catch (NumberFormatException nfe) {
+ log.error("Bad Configuration Data: Failed to parse host port number string: "
+ + infoSplit[1]);
+ throw nfe;
+ }
+ String deviceState = infoSplit[2];
+ if (isNullOrEmpty(username) || isNullOrEmpty(password)
+ || isNullOrEmpty(hostIp) || hostPort == 0) {
+ log.warn("Bad Configuration Data: both user and device information parts of Configuration "
+ + deviceEntry + " should be non-nullable");
+ } else {
+ device = new SnmpDevice(hostIp, hostPort, password);
+ if (!isNullOrEmpty(deviceState)) {
+ if (deviceState.toUpperCase().equals(DeviceState.ACTIVE.name())) {
+ device.setDeviceState(DeviceState.ACTIVE);
+ } else if (deviceState.toUpperCase()
+ .equals(DeviceState.INACTIVE.name())) {
+ device.setDeviceState(DeviceState.INACTIVE);
+ } else {
+ log.warn("Device State Information can not be empty, so marking the state as INVALID");
+ device.setDeviceState(DeviceState.INVALID);
+ }
+ } else {
+ log.warn("The device entry do not specify state information, so marking the state as INVALID");
+ device.setDeviceState(DeviceState.INVALID);
+ }
+ }
+ } catch (ArrayIndexOutOfBoundsException aie) {
+ log.error("Error while reading config infromation from the config file: "
+ + "The user, host and device state infomation should be "
+ + "in the order 'userInfo@hostInfo:deviceState'"
+ + deviceEntry, aie);
+ } catch (Exception e) {
+ log.error("Error while parsing config information for the device entry: "
+ + deviceEntry, e);
+ }
+ return device;
+ }
+
+ @Override
+ public void triggerProbe(DeviceId deviceId) {
+ // TODO SNMP devices should be polled at scheduled intervals to retrieve their
+ // reachability status and other details e.g.swVersion, serialNumber,chassis,
+ }
+
+ @Override
+ public void roleChanged(DeviceId deviceId, MastershipRole newRole) {
+
+ }
+
+ @Override
+ public boolean isReachable(DeviceId deviceId) {
+ SnmpDevice snmpDevice = snmpDeviceMap.get(deviceId);
+ if (snmpDevice == null) {
+ log.warn("BAD REQUEST: the requested device id: "
+ + deviceId.toString()
+ + " is not associated to any SNMP Device");
+ return false;
+ }
+ return snmpDevice.isReachable();
+ }
+
+ /**
+ * This class is intended to add or remove Configured SNMP Devices. Functionality relies on 'createFlag' and
+ * 'SnmpDevice' content. The functionality runs as a thread and depending on the 'createFlag' value it will create
+ * or remove Device entry from the core.
+ */
+ private class DeviceCreator implements Runnable {
+
+ private SnmpDevice device;
+ private boolean createFlag;
+
+ public DeviceCreator(SnmpDevice device, boolean createFlag) {
+ this.device = device;
+ this.createFlag = createFlag;
+ }
+
+ @Override
+ public void run() {
+ if (createFlag) {
+ log.info("Trying to create Device Info on ONOS core");
+ advertiseDevices();
+ } else {
+ log.info("Trying to remove Device Info on ONOS core");
+ removeDevices();
+ }
+ }
+
+ /**
+ * For each SNMP Device, remove the entry from the device store.
+ */
+ private void removeDevices() {
+ if (device == null) {
+ log.warn("The Request SNMP Device is null, cannot proceed further");
+ return;
+ }
+ try {
+ DeviceId did = getDeviceId();
+ if (!snmpDeviceMap.containsKey(did)) {
+ log.error("BAD Request: 'Currently device is not discovered, "
+ + "so cannot remove/disconnect the device: "
+ + device.deviceInfo() + "'");
+ return;
+ }
+ providerService.deviceDisconnected(did);
+ device.disconnect();
+ snmpDeviceMap.remove(did);
+ delay(EVENTINTERVAL);
+ } catch (URISyntaxException uriSyntaxExcpetion) {
+ log.error("Syntax Error while creating URI for the device: "
+ + device.deviceInfo()
+ + " couldn't remove the device from the store",
+ uriSyntaxExcpetion);
+ }
+ }
+
+ /**
+ * Initialize SNMP Device object, and notify core saying device connected.
+ */
+ private void advertiseDevices() {
+ try {
+ if (device == null) {
+ log.warn("The Request SNMP Device is null, cannot proceed further");
+ return;
+ }
+ device.init();
+ DeviceId did = getDeviceId();
+ ChassisId cid = new ChassisId();
+
+
+ DeviceDescription desc = new DefaultDeviceDescription(
+ did.uri(), Device.Type.OTHER, UNKNOWN, UNKNOWN, UNKNOWN, UNKNOWN, cid);
+
+ desc = populateDescriptionFromDevice(did, desc);
+
+ log.info("Persisting Device " + did.uri().toString());
+
+ snmpDeviceMap.put(did, device);
+ providerService.deviceConnected(did, desc);
+ log.info("Done with Device Info Creation on ONOS core. Device Info: "
+ + device.deviceInfo() + " " + did.uri().toString());
+ delay(EVENTINTERVAL);
+ } catch (URISyntaxException e) {
+ log.error("Syntax Error while creating URI for the device: "
+ + device.deviceInfo()
+ + " couldn't persist the device onto the store", e);
+ } catch (Exception e) {
+ log.error("Error while initializing session for the device: "
+ + (device != null ? device.deviceInfo() : null), e);
+ }
+ }
+
+ private DeviceDescription populateDescriptionFromDevice(DeviceId did, DeviceDescription desc) {
+ String[] deviceComponents = did.toString().split(":");
+ if (deviceComponents.length > 1) {
+ String ipAddress = deviceComponents[1];
+ String port = deviceComponents[2];
+
+ ISnmpConfiguration config = new V2cSnmpConfiguration();
+ config.setPort(Integer.parseInt(port));
+
+ try (ISnmpSession session = sessionFactory.createSession(config, ipAddress)) {
+ // Each session will be auto-closed.
+ String deviceOID = session.identifyDevice();
+
+ if (providers.containsKey(deviceOID)) {
+ desc = providers.get(deviceOID).populateDescription(session, desc);
+ }
+
+ } catch (IOException | RuntimeException ex) {
+ log.error("Failed to walk device.", ex.getMessage());
+ log.debug("Detailed problem was ", ex);
+ }
+ }
+ return desc;
+ }
+
+ /**
+ * This will build a device id for the device.
+ */
+ private DeviceId getDeviceId() throws URISyntaxException {
+ String additionalSSP = new StringBuilder(
+ device.getSnmpHost()).append(":")
+ .append(device.getSnmpPort()).toString();
+ return DeviceId.deviceId(new URI(SCHEME, additionalSSP,
+ null));
+ }
+ }
+
+ protected ISnmpSessionFactory getSessionFactory(ISnmpConfigurationFactory configurationFactory) {
+ return new SnmpSessionFactory(configurationFactory);
+ }
+}
diff --git a/providers/snmp/device/src/main/java/org/onosproject/provider/snmp/device/impl/package-info.java b/providers/snmp/device/src/main/java/org/onosproject/provider/snmp/device/impl/package-info.java
new file mode 100644
index 0000000..5c888f5
--- /dev/null
+++ b/providers/snmp/device/src/main/java/org/onosproject/provider/snmp/device/impl/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2015 Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Provider that uses SNMP capability request as a means of infrastructure device discovery.
+ */
+package org.onosproject.provider.snmp.device.impl;
\ No newline at end of file
diff --git a/providers/snmp/pom.xml b/providers/snmp/pom.xml
index 34a4d97..83cd8b9 100644
--- a/providers/snmp/pom.xml
+++ b/providers/snmp/pom.xml
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
- ~ Copyright 2014 Open Networking Laboratory
+ ~ Copyright 2015 Open Networking Laboratory
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
@@ -29,10 +29,55 @@
<artifactId>onos-snmp-providers</artifactId>
<packaging>pom</packaging>
- <description>ONOS SNMP Protocol Adapters</description>
+ <description>ONOS SNMP protocol adapters</description>
<modules>
+ <module>device</module>
+ <module>app</module>
<module>alarm</module>
</modules>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.servicemix.bundles</groupId>
+ <artifactId>org.apache.servicemix.bundles.snmp4j</artifactId>
+ <version>2.3.4_1</version>
+ <exclusions>
+ <exclusion>
+ <artifactId>log4j</artifactId>
+ <groupId>log4j</groupId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+
+ <dependency>
+ <groupId>com.btisystems</groupId>
+ <artifactId>snmp-core</artifactId>
+ <version>1.3-SNAPSHOT</version>
+ </dependency>
+
+ <dependency>
+ <groupId>com.btisystems.mibbler.mibs</groupId>
+ <artifactId>bti7000</artifactId>
+ <version>1.0-SNAPSHOT</version>
+ </dependency>
+
+ <dependency>
+ <groupId>com.btisystems.mibbler.mibs</groupId>
+ <artifactId>net-snmp</artifactId>
+ <version>1.0-SNAPSHOT</version>
+ </dependency>
+ </dependencies>
+ <repositories>
+ <repository>
+ <!-- TODO move over to release snmp-core when it becomes available.-->
+ <id>oss.sonatype.org-snapshot</id>
+ <url>http://oss.sonatype.org/content/repositories/snapshots</url>
+ <snapshots>
+ <enabled>true</enabled>
+ </snapshots>
+ </repository>
+ </repositories>
+
-</project>
\ No newline at end of file
+</project>