[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/apps/faultmanagement/app/app.xml b/apps/faultmanagement/app/app.xml
index 288ccc4..5c2db0c 100644
--- a/apps/faultmanagement/app/app.xml
+++ b/apps/faultmanagement/app/app.xml
@@ -21,4 +21,6 @@
<artifact>mvn:${project.groupId}/onos-app-fm-mgr/${project.version}</artifact>
<artifact>mvn:${project.groupId}/onos-app-fm-web/${project.version}</artifact>
+ <artifact>mvn:${project.groupId}/onos-app-fm-gui/${project.version}</artifact>
+ <artifact>mvn:${project.groupId}/onos-app-fm-cli/${project.version}</artifact>
</app>
diff --git a/apps/faultmanagement/app/features.xml b/apps/faultmanagement/app/features.xml
index 86aab91..0f9c192 100644
--- a/apps/faultmanagement/app/features.xml
+++ b/apps/faultmanagement/app/features.xml
@@ -21,5 +21,7 @@
<feature>onos-drivers</feature>
<bundle>mvn:${project.groupId}/onos-app-fm-mgr/${project.version}</bundle>
<bundle>mvn:${project.groupId}/onos-app-fm-web/${project.version}</bundle>
+ <bundle>mvn:${project.groupId}/onos-app-fm-gui/${project.version}</bundle>
+ <bundle>mvn:${project.groupId}/onos-app-fm-cli/${project.version}</bundle>
</feature>
</features>
diff --git a/apps/faultmanagement/app/pom.xml b/apps/faultmanagement/app/pom.xml
index ef32be6..41c6d8c 100644
--- a/apps/faultmanagement/app/pom.xml
+++ b/apps/faultmanagement/app/pom.xml
@@ -1,21 +1,21 @@
<?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.
- -->
+~ 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">
+ 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>
@@ -28,7 +28,7 @@
<artifactId>onos-app-fm-onosfw</artifactId>
<packaging>pom</packaging>
- <description>ONOS framework applications</description>
+ <description>ONOS fault management application</description>
<dependencies>
<dependency>
@@ -41,6 +41,15 @@
<artifactId>onos-app-fm-mgr</artifactId>
<version>${project.version}</version>
</dependency>
+ <dependency>
+ <groupId>org.onosproject</groupId>
+ <artifactId>onos-app-fm-gui</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.onosproject</groupId>
+ <artifactId>onos-app-fm-cli</artifactId>
+ <version>${project.version}</version>
+ </dependency>
</dependencies>
-
</project>
diff --git a/apps/faultmanagement/fmcli/pom.xml b/apps/faultmanagement/fmcli/pom.xml
new file mode 100644
index 0000000..753ed73
--- /dev/null
+++ b/apps/faultmanagement/fmcli/pom.xml
@@ -0,0 +1,61 @@
+<?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
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
+ xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>org.onosproject</groupId>
+ <artifactId>onos-app-fm</artifactId>
+ <version>1.4.0-SNAPSHOT</version>
+ <relativePath>../pom.xml</relativePath>
+ </parent>
+
+ <artifactId>onos-app-fm-cli</artifactId>
+ <packaging>bundle</packaging>
+ <dependencies>
+ <dependency>
+ <groupId>org.onosproject</groupId>
+ <artifactId>onlab-osgi</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.onosproject</groupId>
+ <artifactId>onlab-junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>org.apache.felix.scr.annotations</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.onosproject</groupId>
+ <artifactId>onos-cli</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.karaf.shell</groupId>
+ <artifactId>org.apache.karaf.shell.console</artifactId>
+ </dependency>
+ </dependencies>
+</project>
diff --git a/apps/faultmanagement/fmcli/src/main/java/org/onosproject/faultmanagement/alarms/cli/GetAllActiveAlarms.java b/apps/faultmanagement/fmcli/src/main/java/org/onosproject/faultmanagement/alarms/cli/GetAllActiveAlarms.java
new file mode 100644
index 0000000..f1900fa
--- /dev/null
+++ b/apps/faultmanagement/fmcli/src/main/java/org/onosproject/faultmanagement/alarms/cli/GetAllActiveAlarms.java
@@ -0,0 +1,44 @@
+/*
+ * 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.faultmanagement.alarms.cli;
+
+import java.util.Set;
+import org.apache.commons.lang3.builder.ToStringBuilder;
+import org.apache.commons.lang3.builder.ToStringStyle;
+import org.apache.karaf.shell.commands.Command;
+import org.onosproject.cli.AbstractShellCommand;
+import org.onosproject.incubator.net.faultmanagement.alarm.Alarm;
+import org.onosproject.incubator.net.faultmanagement.alarm.AlarmService;
+
+/**
+ * Lists active alarms across all devices.
+ */
+@Command(scope = "onos", name = "alarm-list-active",
+ description = "Lists all the ACTIVE alarms across all devices.")
+public class GetAllActiveAlarms extends AbstractShellCommand {
+
+
+ @Override
+ protected void execute() {
+ printAlarms(AbstractShellCommand.get(AlarmService.class).getActiveAlarms());
+ }
+
+ void printAlarms(Set<Alarm> alarms) {
+ alarms.stream().forEach((alarm) -> {
+ print(ToStringBuilder.reflectionToString(alarm, ToStringStyle.SHORT_PREFIX_STYLE));
+ });
+ }
+}
diff --git a/apps/faultmanagement/fmcli/src/main/java/org/onosproject/faultmanagement/alarms/cli/GetAllAlarms.java b/apps/faultmanagement/fmcli/src/main/java/org/onosproject/faultmanagement/alarms/cli/GetAllAlarms.java
new file mode 100644
index 0000000..8cc54e2
--- /dev/null
+++ b/apps/faultmanagement/fmcli/src/main/java/org/onosproject/faultmanagement/alarms/cli/GetAllAlarms.java
@@ -0,0 +1,43 @@
+/*
+ * 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.faultmanagement.alarms.cli;
+
+import java.util.Set;
+import org.apache.commons.lang3.builder.ToStringBuilder;
+import org.apache.commons.lang3.builder.ToStringStyle;
+import org.apache.karaf.shell.commands.Command;
+import org.onosproject.cli.AbstractShellCommand;
+import org.onosproject.incubator.net.faultmanagement.alarm.Alarm;
+import org.onosproject.incubator.net.faultmanagement.alarm.AlarmService;
+
+/**
+ * Lists alarms across all devices.
+ */
+@Command(scope = "onos", name = "alarm-list",
+ description = "Lists active alarms across all devices.")
+public class GetAllAlarms extends AbstractShellCommand {
+
+ @Override
+ protected void execute() {
+ printAlarms(AbstractShellCommand.get(AlarmService.class).getAlarms());
+ }
+
+ void printAlarms(Set<Alarm> alarms) {
+ alarms.stream().forEach((alarm) -> {
+ print(ToStringBuilder.reflectionToString(alarm, ToStringStyle.SHORT_PREFIX_STYLE));
+ });
+ }
+}
diff --git a/apps/faultmanagement/fmcli/src/main/java/org/onosproject/faultmanagement/alarms/cli/GetAllAlarmsCounts.java b/apps/faultmanagement/fmcli/src/main/java/org/onosproject/faultmanagement/alarms/cli/GetAllAlarmsCounts.java
new file mode 100644
index 0000000..c90546a
--- /dev/null
+++ b/apps/faultmanagement/fmcli/src/main/java/org/onosproject/faultmanagement/alarms/cli/GetAllAlarmsCounts.java
@@ -0,0 +1,45 @@
+/*
+ * 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.faultmanagement.alarms.cli;
+
+import java.util.Map;
+import org.apache.karaf.shell.commands.Command;
+import org.onosproject.cli.AbstractShellCommand;
+import org.onosproject.incubator.net.faultmanagement.alarm.Alarm;
+import org.onosproject.incubator.net.faultmanagement.alarm.AlarmService;
+
+/**
+ * Lists alarm counts across all devices.
+ */
+@Command(scope = "onos", name = "alarm-counts",
+ description = "Lists alarm counts across all devices.")
+public class GetAllAlarmsCounts extends AbstractShellCommand {
+
+ @Override
+ protected void execute() {
+ Map<Alarm.SeverityLevel, Long> alarmCounts
+ = AbstractShellCommand.get(AlarmService.class).getAlarmCounts();
+ printCounts(alarmCounts);
+ }
+
+ static void printCounts(Map<Alarm.SeverityLevel, Long> alarmCounts) {
+ alarmCounts.entrySet().stream().forEach((countEntry) -> {
+ System.out.println(String.format("%s, %d",
+ countEntry.getKey(), countEntry.getValue()));
+
+ });
+ }
+}
diff --git a/apps/faultmanagement/fmcli/src/main/java/org/onosproject/faultmanagement/alarms/cli/GetDeviceAlarmsCounts.java b/apps/faultmanagement/fmcli/src/main/java/org/onosproject/faultmanagement/alarms/cli/GetDeviceAlarmsCounts.java
new file mode 100644
index 0000000..2954f9c
--- /dev/null
+++ b/apps/faultmanagement/fmcli/src/main/java/org/onosproject/faultmanagement/alarms/cli/GetDeviceAlarmsCounts.java
@@ -0,0 +1,44 @@
+/*
+ * 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.faultmanagement.alarms.cli;
+
+import java.util.Map;
+import org.apache.karaf.shell.commands.Argument;
+import org.apache.karaf.shell.commands.Command;
+import org.onosproject.cli.AbstractShellCommand;
+import org.onosproject.incubator.net.faultmanagement.alarm.Alarm;
+import org.onosproject.incubator.net.faultmanagement.alarm.AlarmService;
+import org.onosproject.net.DeviceId;
+
+/**
+ * Lists alarm counts across specified device.
+ */
+@Command(scope = "onos", name = "alarm-counts-device",
+ description = "Lists alarm counts across specified device.")
+public class GetDeviceAlarmsCounts extends AbstractShellCommand {
+
+ @Argument(index = 0, name = "deviceId", description = "Device identity", required = true, multiValued = false)
+ String deviceId = null;
+
+ @Override
+ protected void execute() {
+ Map<Alarm.SeverityLevel, Long> alarmCounts = AbstractShellCommand.get(AlarmService.class).
+ getAlarmCounts(DeviceId.deviceId(deviceId));
+ // Deliberately using same formatting for both ...
+ GetAllAlarmsCounts.printCounts(alarmCounts);
+ }
+
+}
diff --git a/apps/faultmanagement/fmcli/src/main/java/org/onosproject/faultmanagement/alarms/cli/package-info.java b/apps/faultmanagement/fmcli/src/main/java/org/onosproject/faultmanagement/alarms/cli/package-info.java
new file mode 100644
index 0000000..f830a55
--- /dev/null
+++ b/apps/faultmanagement/fmcli/src/main/java/org/onosproject/faultmanagement/alarms/cli/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.
+ */
+
+/**
+ * CLI implementation for alarms.
+ */
+package org.onosproject.faultmanagement.alarms.cli;
diff --git a/apps/faultmanagement/fmcli/src/main/resources/OSGI-INF/blueprint/shell-config.xml b/apps/faultmanagement/fmcli/src/main/resources/OSGI-INF/blueprint/shell-config.xml
new file mode 100644
index 0000000..0807e9e
--- /dev/null
+++ b/apps/faultmanagement/fmcli/src/main/resources/OSGI-INF/blueprint/shell-config.xml
@@ -0,0 +1,40 @@
+<!--
+~ 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.
+-->
+<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0">
+
+ <command-bundle xmlns="http://karaf.apache.org/xmlns/shell/v1.1.0">
+
+ <command>
+ <action class="org.onosproject.faultmanagement.alarms.cli.GetAllActiveAlarms"/>
+ </command>
+ <command>
+ <action class="org.onosproject.faultmanagement.alarms.cli.GetAllAlarms"/>
+ </command>
+ <command>
+ <action class="org.onosproject.faultmanagement.alarms.cli.GetAllAlarmsCounts"/>
+ </command>
+ <command>
+ <action class="org.onosproject.faultmanagement.alarms.cli.GetDeviceAlarmsCounts"/>
+ <completers>
+ <ref component-id="deviceIdCompleter"/>
+ </completers>
+ </command>
+ </command-bundle>
+
+
+ <bean id="deviceIdCompleter" class="org.onosproject.cli.net.DeviceIdCompleter"/>
+
+</blueprint>
diff --git a/apps/faultmanagement/fmcli/src/test/java/org/onosproject/faultmanagement/alarms/cli/README.txt b/apps/faultmanagement/fmcli/src/test/java/org/onosproject/faultmanagement/alarms/cli/README.txt
new file mode 100644
index 0000000..4f4037f
--- /dev/null
+++ b/apps/faultmanagement/fmcli/src/test/java/org/onosproject/faultmanagement/alarms/cli/README.txt
@@ -0,0 +1 @@
+# Need to write unit tests but do so after there are other CLI tests to use as a template.
diff --git a/apps/faultmanagement/fmgui/pom.xml b/apps/faultmanagement/fmgui/pom.xml
new file mode 100644
index 0000000..85ab309
--- /dev/null
+++ b/apps/faultmanagement/fmgui/pom.xml
@@ -0,0 +1,65 @@
+<?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/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+
+ <parent>
+ <groupId>org.onosproject</groupId>
+ <artifactId>onos-app-fm</artifactId>
+ <version>1.4.0-SNAPSHOT</version>
+ <relativePath>../pom.xml</relativePath>
+ </parent>
+
+ <artifactId>onos-app-fm-gui</artifactId>
+ <packaging>bundle</packaging>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.karaf.shell</groupId>
+ <artifactId>org.apache.karaf.shell.console</artifactId>
+ <scope>compile</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.onosproject</groupId>
+ <artifactId>onlab-osgi</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>org.onosproject</groupId>
+ <artifactId>onlab-junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+
+
+ <dependency>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>org.apache.felix.scr.annotations</artifactId>
+ <scope>provided</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.onosproject</groupId>
+ <artifactId>onos-cli</artifactId>
+ <version>${project.version}</version>
+ <type>jar</type>
+ </dependency>
+ </dependencies>
+
+</project>
diff --git a/apps/faultmanagement/fmgui/src/main/java/org/onosproject/faultmanagement/alarms/gui/AlarmServiceUtil.java b/apps/faultmanagement/fmgui/src/main/java/org/onosproject/faultmanagement/alarms/gui/AlarmServiceUtil.java
new file mode 100644
index 0000000..fca8bbd
--- /dev/null
+++ b/apps/faultmanagement/fmgui/src/main/java/org/onosproject/faultmanagement/alarms/gui/AlarmServiceUtil.java
@@ -0,0 +1,58 @@
+/*
+ * 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.faultmanagement.alarms.gui;
+
+import java.util.Map;
+import java.util.Set;
+import org.onosproject.cli.AbstractShellCommand;
+import org.onosproject.incubator.net.faultmanagement.alarm.Alarm;
+import org.onosproject.incubator.net.faultmanagement.alarm.AlarmId;
+import org.onosproject.incubator.net.faultmanagement.alarm.AlarmService;
+import org.onosproject.net.DeviceId;
+
+/**
+ *
+ * Utility for invoking on alarm service.
+ */
+public final class AlarmServiceUtil {
+
+ static Alarm lookupAlarm(AlarmId alarmId) {
+ return alarmService().getAlarm(alarmId);
+ }
+
+ static Set<Alarm> lookUpAlarms() {
+ return alarmService().getAlarms();
+ }
+
+ static Set<Alarm> lookUpAlarms(DeviceId deviceId) {
+ return alarmService().getAlarms(deviceId);
+ }
+
+ static Map<Alarm.SeverityLevel, Long> lookUpAlarmCounts(DeviceId deviceId) {
+ return alarmService().getAlarmCounts(deviceId);
+ }
+
+ static Map<Alarm.SeverityLevel, Long> lookUpAlarmCounts() {
+ return alarmService().getAlarmCounts();
+ }
+
+ private static AlarmService alarmService() {
+ return AbstractShellCommand.get(AlarmService.class);
+ }
+
+ private AlarmServiceUtil() {
+ }
+}
diff --git a/apps/faultmanagement/fmgui/src/main/java/org/onosproject/faultmanagement/alarms/gui/AlarmTableComponent.java b/apps/faultmanagement/fmgui/src/main/java/org/onosproject/faultmanagement/alarms/gui/AlarmTableComponent.java
new file mode 100644
index 0000000..bf9eb94
--- /dev/null
+++ b/apps/faultmanagement/fmgui/src/main/java/org/onosproject/faultmanagement/alarms/gui/AlarmTableComponent.java
@@ -0,0 +1,77 @@
+/*
+ * 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.faultmanagement.alarms.gui;
+
+import com.google.common.collect.ImmutableList;
+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.Reference;
+import org.apache.felix.scr.annotations.ReferenceCardinality;
+import org.onosproject.ui.UiExtension;
+import org.onosproject.ui.UiExtensionService;
+import org.onosproject.ui.UiMessageHandlerFactory;
+import org.onosproject.ui.UiView;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.List;
+
+/**
+ * Skeletal ONOS UI Table-View application component.
+ */
+@Component(immediate = true)
+public class AlarmTableComponent {
+
+ private static final String VIEW_ID = "alarmTable";
+ private static final String VIEW_TEXT = "Alarms";
+
+ private final Logger log = LoggerFactory.getLogger(getClass());
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+ protected UiExtensionService uiExtensionService;
+
+ // List of application views
+ private final List<UiView> uiViews = ImmutableList.of(
+ new UiView(UiView.Category.OTHER, VIEW_ID, VIEW_TEXT)
+ );
+
+ // Factory for UI message handlers
+ private final UiMessageHandlerFactory messageHandlerFactory =
+ () -> ImmutableList.of(
+ new AlarmTableMessageHandler()
+ );
+
+ // Application UI extension
+ protected UiExtension extension =
+ new UiExtension.Builder(getClass().getClassLoader(), uiViews)
+ .resourcePath(VIEW_ID)
+ .messageHandlerFactory(messageHandlerFactory)
+ .build();
+
+ @Activate
+ protected void activate() {
+ uiExtensionService.register(extension);
+ log.info("Started");
+ }
+
+ @Deactivate
+ protected void deactivate() {
+ uiExtensionService.unregister(extension);
+ log.info("Stopped");
+ }
+
+}
diff --git a/apps/faultmanagement/fmgui/src/main/java/org/onosproject/faultmanagement/alarms/gui/AlarmTableMessageHandler.java b/apps/faultmanagement/fmgui/src/main/java/org/onosproject/faultmanagement/alarms/gui/AlarmTableMessageHandler.java
new file mode 100644
index 0000000..df475e2
--- /dev/null
+++ b/apps/faultmanagement/fmgui/src/main/java/org/onosproject/faultmanagement/alarms/gui/AlarmTableMessageHandler.java
@@ -0,0 +1,177 @@
+/*
+ * 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.faultmanagement.alarms.gui;
+
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.google.common.base.Strings;
+import com.google.common.collect.ImmutableSet;
+import org.onosproject.ui.RequestHandler;
+import org.onosproject.ui.UiMessageHandler;
+import org.onosproject.ui.table.TableModel;
+import org.onosproject.ui.table.TableRequestHandler;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Collection;
+import java.util.Set;
+import org.joda.time.DateTime;
+import org.onosproject.incubator.net.faultmanagement.alarm.Alarm;
+import org.onosproject.incubator.net.faultmanagement.alarm.AlarmId;
+import org.onosproject.net.DeviceId;
+import org.onosproject.ui.table.cell.TimeFormatter;
+
+/**
+ * Skeletal ONOS UI Table-View message handler.
+ */
+public class AlarmTableMessageHandler extends UiMessageHandler {
+
+ private static final String ALARM_TABLE_DATA_REQ = "alarmTableDataRequest";
+ private static final String ALARM_TABLE_DATA_RESP = "alarmTableDataResponse";
+ private static final String ALARM_TABLES = "alarmTables";
+
+ private static final String ALARM_TABLE_DETAIL_REQ = "alarmTableDetailsRequest";
+ private static final String ALARM_TABLE_DETAIL_RESP = "alarmTableDetailsResponse";
+ private static final String DETAILS = "details";
+
+ private static final String ID = "id";
+ private static final String DEVICE_ID_STR = "alarmDeviceId";
+ private static final String DESCRIPTION = "alarmDesc";
+ private static final String SOURCE = "alarmSource";
+ private static final String TIME_RAISED = "alarmTimeRaised";
+ private static final String TIME_UPDATED = "alarmTimeUpdated";
+ private static final String TIME_CLEARED = "alarmTimeCleared";
+ private static final String SEVERITY = "alarmSeverity";
+ private static final String RESULT = "result";
+
+ // TODO No need to show id column in ONOS-GUI
+
+ // TODO Replace SEVERITY column by color-coding of row depending on severity ie. red=critical, green=cleared etc
+ private static final String[] COLUMN_IDS = {ID, DEVICE_ID_STR, DESCRIPTION, SOURCE, TIME_RAISED, SEVERITY};
+
+ private final Logger log = LoggerFactory.getLogger(getClass());
+
+ @Override
+ protected Collection<RequestHandler> createRequestHandlers() {
+ return ImmutableSet.of(
+ new AlarmTableDataRequestHandler(),
+ new AlarmTableDetailRequestHandler()
+ );
+ }
+
+ // handler for alarm table requests
+ private final class AlarmTableDataRequestHandler extends TableRequestHandler {
+
+ private AlarmTableDataRequestHandler() {
+ super(ALARM_TABLE_DATA_REQ, ALARM_TABLE_DATA_RESP, ALARM_TABLES);
+ }
+
+ @Override
+ protected String defaultColumnId() {
+ // if necessary, override defaultColumnId() -- if it isn't "id"
+ return ID;
+ }
+
+ @Override
+ protected String[] getColumnIds() {
+ return COLUMN_IDS;
+ }
+
+ @Override
+ protected TableModel createTableModel() {
+ // if required, override createTableModel() to set column formatters / comparators
+ TableModel tm = super.createTableModel();
+ tm.setFormatter(TIME_RAISED, new TimeFormatter());
+ return tm;
+ }
+
+ @Override
+ protected void populateTable(TableModel tm, ObjectNode payload) {
+ log.debug(" populateTable tm={} payload ={}", tm, payload);
+ String devId = string(payload, "devId");
+
+ Set<Alarm> alarms = Strings.isNullOrEmpty(devId) ?
+ AlarmServiceUtil.lookUpAlarms() :
+ AlarmServiceUtil.lookUpAlarms(DeviceId.deviceId(devId));
+
+ alarms.stream().forEach((alarm) -> {
+ populateRow(tm.addRow(), alarm);
+ });
+
+ }
+
+ private void populateRow(TableModel.Row row, Alarm alarm) {
+ log.debug("populate table Row row={} item ={}", row, alarm);
+
+ row.cell(ID, alarm.id().fingerprint())
+ .cell(DEVICE_ID_STR, alarm.deviceId())
+ .cell(DESCRIPTION, alarm.description())
+ .cell(SOURCE, alarm.source())
+ .cell(TIME_RAISED, new DateTime(alarm.timeRaised()))
+ .cell(SEVERITY, alarm.severity());
+ }
+ }
+
+ // handler for alarm details requests
+ private final class AlarmTableDetailRequestHandler extends RequestHandler {
+
+ private AlarmTableDetailRequestHandler() {
+ super(ALARM_TABLE_DETAIL_REQ);
+ }
+
+ @Override
+ public void process(long sid, ObjectNode payload) {
+ log.debug("sid={}, payload ={}", sid, payload);
+
+ String id = string(payload, ID, "(none)");
+ Alarm alarm = AlarmServiceUtil.lookupAlarm(AlarmId.alarmId(Long.parseLong(id)));
+ ObjectNode rootNode = objectNode();
+ ObjectNode data = objectNode();
+ rootNode.set(DETAILS, data);
+
+ if (alarm == null) {
+ rootNode.put(RESULT, "Item with id '" + id + "' not found");
+ log.warn("attempted to get item detail for id '{}'", id);
+
+ } else {
+ rootNode.put(RESULT, "Found item with id '" + id + "'");
+
+ data.put(ID, alarm.id().fingerprint());
+ data.put(DESCRIPTION, alarm.description());
+ data.put(DEVICE_ID_STR, alarm.deviceId().toString());
+ data.put(SOURCE, alarm.source().toString());
+ long timeRaised = alarm.timeRaised();
+ data.put(TIME_RAISED,
+ formatTime(timeRaised)
+ );
+ data.put(TIME_UPDATED, formatTime(alarm.timeUpdated()));
+ data.put(TIME_CLEARED, formatTime(alarm.timeCleared()));
+ data.put(SEVERITY, alarm.severity().toString());
+ }
+ log.debug("send ={}", rootNode);
+
+ sendMessage(ALARM_TABLE_DETAIL_RESP, 0, rootNode);
+ }
+ }
+
+ private static String formatTime(Long msSinceStartOfEpoch) {
+ if (msSinceStartOfEpoch == null) {
+ return "-";
+ }
+ return new TimeFormatter().format(new DateTime(msSinceStartOfEpoch));
+ }
+
+
+}
diff --git a/apps/faultmanagement/fmgui/src/main/java/org/onosproject/faultmanagement/alarms/gui/AlarmTopovComponent.java b/apps/faultmanagement/fmgui/src/main/java/org/onosproject/faultmanagement/alarms/gui/AlarmTopovComponent.java
new file mode 100644
index 0000000..901d30f
--- /dev/null
+++ b/apps/faultmanagement/fmgui/src/main/java/org/onosproject/faultmanagement/alarms/gui/AlarmTopovComponent.java
@@ -0,0 +1,86 @@
+/*
+ * 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.faultmanagement.alarms.gui;
+
+import com.google.common.collect.ImmutableList;
+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.Reference;
+import org.apache.felix.scr.annotations.ReferenceCardinality;
+import org.onosproject.ui.UiExtension;
+import org.onosproject.ui.UiExtensionService;
+import org.onosproject.ui.UiMessageHandlerFactory;
+import org.onosproject.ui.UiTopoOverlayFactory;
+import org.onosproject.ui.UiView;
+import org.onosproject.ui.UiViewHidden;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.List;
+
+/**
+ * Skeletal ONOS UI Topology-Overlay application component.
+ */
+@Component(immediate = true)
+public class AlarmTopovComponent {
+
+ private static final ClassLoader CL = AlarmTopovComponent.class.getClassLoader();
+ private static final String VIEW_ID = "alarmTopov";
+
+ private final Logger log = LoggerFactory.getLogger(getClass());
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+ protected UiExtensionService uiExtensionService;
+
+ // List of application views
+ private final List<UiView> uiViews = ImmutableList.of(
+ new UiViewHidden(VIEW_ID)
+ );
+
+ // Factory for UI message handlers
+ private final UiMessageHandlerFactory messageHandlerFactory =
+ () -> ImmutableList.of(
+ new AlarmTopovMessageHandler()
+ );
+
+ // Factory for UI topology overlays
+ private final UiTopoOverlayFactory topoOverlayFactory =
+ () -> ImmutableList.of(
+ new AlarmTopovOverlay()
+ );
+
+ // Application UI extension
+ protected UiExtension extension =
+ new UiExtension.Builder(CL, uiViews)
+ .resourcePath(VIEW_ID)
+ .messageHandlerFactory(messageHandlerFactory)
+ .topoOverlayFactory(topoOverlayFactory)
+ .build();
+
+ @Activate
+ protected void activate() {
+ uiExtensionService.register(extension);
+ log.info("Started");
+ }
+
+ @Deactivate
+ protected void deactivate() {
+ uiExtensionService.unregister(extension);
+ log.info("Stopped");
+ }
+
+}
diff --git a/apps/faultmanagement/fmgui/src/main/java/org/onosproject/faultmanagement/alarms/gui/AlarmTopovMessageHandler.java b/apps/faultmanagement/fmgui/src/main/java/org/onosproject/faultmanagement/alarms/gui/AlarmTopovMessageHandler.java
new file mode 100644
index 0000000..adeb9d5
--- /dev/null
+++ b/apps/faultmanagement/fmgui/src/main/java/org/onosproject/faultmanagement/alarms/gui/AlarmTopovMessageHandler.java
@@ -0,0 +1,224 @@
+/*
+ * 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.faultmanagement.alarms.gui;
+
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.google.common.base.Strings;
+import com.google.common.collect.ImmutableSet;
+import org.onlab.osgi.ServiceDirectory;
+import org.onosproject.net.Device;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.Element;
+import org.onosproject.net.HostId;
+import org.onosproject.net.device.DeviceService;
+import org.onosproject.net.host.HostService;
+import org.onosproject.ui.RequestHandler;
+import org.onosproject.ui.UiConnection;
+import org.onosproject.ui.UiMessageHandler;
+import org.onosproject.ui.topo.DeviceHighlight;
+import org.onosproject.ui.topo.Highlights;
+import org.onosproject.ui.topo.NodeBadge;
+import org.onosproject.ui.topo.NodeBadge.Status;
+import org.onosproject.ui.topo.TopoJson;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Collection;
+import java.util.Set;
+import org.onosproject.incubator.net.faultmanagement.alarm.Alarm;
+import org.onosproject.incubator.net.faultmanagement.alarm.AlarmService;
+
+/**
+ * Skeletal ONOS UI Topology-Overlay message handler.
+ */
+public class AlarmTopovMessageHandler extends UiMessageHandler {
+
+ private static final String ALARM_TOPOV_DISPLAY_START = "alarmTopovDisplayStart";
+ private static final String ALARM_TOPOV_DISPLAY_UPDATE = "alarmTopovDisplayUpdate";
+ private static final String ALARM_TOPOV_DISPLAY_STOP = "alarmTopovDisplayStop";
+
+ private static final String ID = "id";
+ private static final String MODE = "mode";
+
+ private enum Mode {
+
+ IDLE, MOUSE
+ }
+
+ private final Logger log = LoggerFactory.getLogger(getClass());
+
+ private DeviceService deviceService;
+ private HostService hostService;
+ private AlarmService alarmService;
+
+ private Mode currentMode = Mode.IDLE;
+ private Element elementOfNote;
+
+ // ===============-=-=-=-=-=-======================-=-=-=-=-=-=-================================
+ @Override
+ public void init(UiConnection connection, ServiceDirectory directory) {
+ super.init(connection, directory);
+ deviceService = directory.get(DeviceService.class);
+ hostService = directory.get(HostService.class);
+ alarmService = directory.get(AlarmService.class);
+ }
+
+ @Override
+ protected Collection<RequestHandler> createRequestHandlers() {
+ return ImmutableSet.of(
+ new DisplayStartHandler(),
+ new DisplayUpdateHandler(),
+ new DisplayStopHandler()
+ );
+ }
+
+ // === -------------------------
+ // === Handler classes
+ private final class DisplayStartHandler extends RequestHandler {
+
+ public DisplayStartHandler() {
+ super(ALARM_TOPOV_DISPLAY_START);
+ }
+
+ @Override
+ public void process(long sid, ObjectNode payload) {
+ String mode = string(payload, MODE);
+
+ log.debug("Start Display: mode [{}]", mode);
+ clearState();
+ clearForMode();
+
+ switch (mode) {
+ case "mouse":
+ currentMode = Mode.MOUSE;
+
+ sendMouseData();
+ break;
+
+ default:
+ currentMode = Mode.IDLE;
+
+ break;
+ }
+ }
+ }
+
+ private final class DisplayUpdateHandler extends RequestHandler {
+
+ public DisplayUpdateHandler() {
+ super(ALARM_TOPOV_DISPLAY_UPDATE);
+ }
+
+ @Override
+ public void process(long sid, ObjectNode payload) {
+ String id = string(payload, ID);
+ log.debug("Update Display: id [{}]", id);
+ if (!Strings.isNullOrEmpty(id)) {
+ updateForMode(id);
+ } else {
+ clearForMode();
+ }
+ }
+ }
+
+ private final class DisplayStopHandler extends RequestHandler {
+
+ public DisplayStopHandler() {
+ super(ALARM_TOPOV_DISPLAY_STOP);
+ }
+
+ @Override
+ public void process(long sid, ObjectNode payload) {
+ log.debug("Stop Display");
+ clearState();
+ clearForMode();
+ }
+ }
+
+ // === ------------
+ private void clearState() {
+ currentMode = Mode.IDLE;
+ elementOfNote = null;
+ }
+
+ private void updateForMode(String id) {
+ log.debug("host service: {}", hostService);
+ log.debug("device service: {}", deviceService);
+
+ try {
+ HostId hid = HostId.hostId(id);
+ log.debug("host id {}", hid);
+ elementOfNote = hostService.getHost(hid);
+ log.debug("host element {}", elementOfNote);
+
+ } catch (RuntimeException e) {
+ try {
+ DeviceId did = DeviceId.deviceId(id);
+ log.debug("device id {}", did);
+ elementOfNote = deviceService.getDevice(did);
+ log.debug("device element {}", elementOfNote);
+
+ } catch (RuntimeException e2) {
+ log.debug("Unable to process ID [{}]", id);
+ elementOfNote = null;
+ }
+ }
+
+ switch (currentMode) {
+ case MOUSE:
+ sendMouseData();
+ break;
+
+ default:
+ break;
+ }
+
+ }
+
+ private void clearForMode() {
+ sendHighlights(new Highlights());
+ }
+
+ private void sendHighlights(Highlights highlights) {
+ sendMessage(TopoJson.highlightsMessage(highlights));
+ }
+
+ private void sendMouseData() {
+ if (elementOfNote != null && elementOfNote instanceof Device) {
+ DeviceId devId = (DeviceId) elementOfNote.id();
+ Set<Alarm> alarmsOnDevice = alarmService.getAlarms(devId);
+ Highlights highlights = new Highlights();
+
+ addDeviceBadge(highlights, devId, alarmsOnDevice.size());
+ sendHighlights(highlights);
+ }
+ // Note: could also process Host, if available
+ }
+
+ private void addDeviceBadge(Highlights h, DeviceId devId, int n) {
+ DeviceHighlight dh = new DeviceHighlight(devId.toString());
+ dh.setBadge(createBadge(n));
+ h.add(dh);
+ }
+
+ private NodeBadge createBadge(int n) {
+ Status status = n > 0 ? Status.ERROR : Status.INFO;
+ String noun = n > 0 ? "(Alarmed)" : "(Normal)";
+ String msg = "Alarms: " + n + " " + noun;
+ return NodeBadge.number(status, n, msg);
+ }
+
+}
diff --git a/apps/faultmanagement/fmgui/src/main/java/org/onosproject/faultmanagement/alarms/gui/AlarmTopovOverlay.java b/apps/faultmanagement/fmgui/src/main/java/org/onosproject/faultmanagement/alarms/gui/AlarmTopovOverlay.java
new file mode 100644
index 0000000..7fc87db
--- /dev/null
+++ b/apps/faultmanagement/fmgui/src/main/java/org/onosproject/faultmanagement/alarms/gui/AlarmTopovOverlay.java
@@ -0,0 +1,92 @@
+/*
+ * 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.faultmanagement.alarms.gui;
+
+import java.util.Map;
+import org.onosproject.incubator.net.faultmanagement.alarm.Alarm;
+import org.onosproject.net.DeviceId;
+import org.onosproject.ui.UiTopoOverlay;
+import org.onosproject.ui.topo.ButtonId;
+import org.onosproject.ui.topo.PropertyPanel;
+import org.onosproject.ui.topo.TopoConstants.CoreButtons;
+import static org.onosproject.ui.topo.TopoConstants.Properties.*;
+
+/**
+ * Our topology overlay.
+ */
+public class AlarmTopovOverlay extends UiTopoOverlay {
+
+ // NOTE: this must match the ID defined in alarmTopov.js
+ private static final String OVERLAY_ID = "alarmsTopo-overlay";
+
+ private static final ButtonId ALARM1_BUTTON = new ButtonId("alarm1button");
+ private static final ButtonId ALARM2_BUTTON = new ButtonId("alarm2button");
+
+ public AlarmTopovOverlay() {
+ super(OVERLAY_ID);
+ }
+
+ @Override
+ public void modifySummary(PropertyPanel pp) {
+ pp.title("Alarms Overview");
+ // We could just remove some properties here but lets keep it uncluttered, unless
+ // there is feedback other properties are essential.
+ pp.removeAllProps();
+ Map<Alarm.SeverityLevel, Long> countsForAll = AlarmServiceUtil.lookUpAlarmCounts();
+ addAlarmCountsProperties(pp, countsForAll);
+
+ }
+
+ @Override
+ public void modifyDeviceDetails(PropertyPanel pp, DeviceId deviceId) {
+ pp.title("Alarm Details");
+ pp.removeProps(LATITUDE, LONGITUDE, PORTS, FLOWS, TUNNELS, SERIAL_NUMBER, PROTOCOL);
+
+ Map<Alarm.SeverityLevel, Long> countsForDevice = AlarmServiceUtil.lookUpAlarmCounts(deviceId);
+ addAlarmCountsProperties(pp, countsForDevice);
+
+ pp.addButton(ALARM1_BUTTON)
+ .addButton(ALARM2_BUTTON);
+
+ pp.removeButtons(CoreButtons.SHOW_PORT_VIEW)
+ .removeButtons(CoreButtons.SHOW_GROUP_VIEW);
+ }
+
+ private void addAlarmCountsProperties(PropertyPanel pp, Map<Alarm.SeverityLevel, Long> countsForDevice) {
+
+ // TODO we could show these as color-coded squares with a count inside, to save space on the screen.
+
+ long cr = countsForDevice.getOrDefault(Alarm.SeverityLevel.CRITICAL, 0L);
+ long ma = countsForDevice.getOrDefault(Alarm.SeverityLevel.MAJOR, 0L);
+ long mi = countsForDevice.getOrDefault(Alarm.SeverityLevel.MINOR, 0L);
+ long wa = countsForDevice.getOrDefault(Alarm.SeverityLevel.WARNING, 0L);
+ long in = countsForDevice.getOrDefault(Alarm.SeverityLevel.INDETERMINATE, 0L);
+ long cl = countsForDevice.getOrDefault(Alarm.SeverityLevel.CLEARED, 0L);
+
+ // Unfortunately the PropertyPanel does not righ justify numbers even when using longs,
+ // but that not in scope of fault management work
+ pp.addProp("Critical", cr);
+ pp.addProp("Major", ma);
+ pp.addProp("Minor", mi);
+ pp.addProp("Warning", wa);
+ pp.addProp("Indeter.", in);
+ pp.addProp("Cleared", cl);
+ pp.addSeparator();
+ pp.addProp("Total", cr + ma + mi + wa + in + cl);
+
+ }
+
+}
diff --git a/apps/faultmanagement/fmgui/src/main/java/org/onosproject/faultmanagement/alarms/gui/package-info.java b/apps/faultmanagement/fmgui/src/main/java/org/onosproject/faultmanagement/alarms/gui/package-info.java
new file mode 100644
index 0000000..fcb4284
--- /dev/null
+++ b/apps/faultmanagement/fmgui/src/main/java/org/onosproject/faultmanagement/alarms/gui/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.
+ */
+
+/**
+ * Fault Management GUI implementation.
+ */
+package org.onosproject.faultmanagement.alarms.gui;
diff --git a/apps/faultmanagement/fmgui/src/main/resources/alarmTable/css.html b/apps/faultmanagement/fmgui/src/main/resources/alarmTable/css.html
new file mode 100644
index 0000000..436ca0e
--- /dev/null
+++ b/apps/faultmanagement/fmgui/src/main/resources/alarmTable/css.html
@@ -0,0 +1 @@
+<link rel="stylesheet" href="app/view/alarmTable/alarmTable.css">
\ No newline at end of file
diff --git a/apps/faultmanagement/fmgui/src/main/resources/alarmTable/js.html b/apps/faultmanagement/fmgui/src/main/resources/alarmTable/js.html
new file mode 100644
index 0000000..b7bdb61
--- /dev/null
+++ b/apps/faultmanagement/fmgui/src/main/resources/alarmTable/js.html
@@ -0,0 +1 @@
+<script src="app/view/alarmTable/alarmTable.js"></script>
\ No newline at end of file
diff --git a/apps/faultmanagement/fmgui/src/main/resources/alarmTopov/css.html b/apps/faultmanagement/fmgui/src/main/resources/alarmTopov/css.html
new file mode 100644
index 0000000..3294fbd
--- /dev/null
+++ b/apps/faultmanagement/fmgui/src/main/resources/alarmTopov/css.html
@@ -0,0 +1 @@
+<link rel="stylesheet" href="app/view/alarmTopov/alarmTopov.css">
diff --git a/apps/faultmanagement/fmgui/src/main/resources/alarmTopov/js.html b/apps/faultmanagement/fmgui/src/main/resources/alarmTopov/js.html
new file mode 100644
index 0000000..5ca23c2
--- /dev/null
+++ b/apps/faultmanagement/fmgui/src/main/resources/alarmTopov/js.html
@@ -0,0 +1,2 @@
+<script src="app/view/alarmTopov/alarmTopovDemo.js"></script>
+<script src="app/view/alarmTopov/alarmTopovOverlay.js"></script>
diff --git a/apps/faultmanagement/fmgui/src/main/resources/app/view/alarmTable/alarmTable.css b/apps/faultmanagement/fmgui/src/main/resources/app/view/alarmTable/alarmTable.css
new file mode 100644
index 0000000..47dfee4
--- /dev/null
+++ b/apps/faultmanagement/fmgui/src/main/resources/app/view/alarmTable/alarmTable.css
@@ -0,0 +1,35 @@
+/* css for alarm table view */
+
+#ov-alarm-table h2 {
+ display: inline-block;
+}
+
+/* Panel Styling */
+#ov-alarm-table-item-details-panel.floatpanel {
+ position: absolute;
+ top: 115px;
+}
+
+.light #ov-alarm-table-item-details-panel.floatpanel {
+ background-color: rgb(229, 234, 237);
+}
+.dark #ov-alarm-table-item-details-panel.floatpanel {
+ background-color: #3A4042;
+}
+
+#ov-alarm-table-item-details-panel h3 {
+ margin: 0;
+ font-size: large;
+}
+
+#ov-alarm-table-item-details-panel h4 {
+ margin: 0;
+}
+
+#ov-alarm-table-item-details-panel td {
+ padding: 5px;
+}
+#ov-alarm-table-item-details-panel td.label {
+ font-style: italic;
+ opacity: 0.8;
+}
diff --git a/apps/faultmanagement/fmgui/src/main/resources/app/view/alarmTable/alarmTable.html b/apps/faultmanagement/fmgui/src/main/resources/app/view/alarmTable/alarmTable.html
new file mode 100644
index 0000000..b9eacc3
--- /dev/null
+++ b/apps/faultmanagement/fmgui/src/main/resources/app/view/alarmTable/alarmTable.html
@@ -0,0 +1,54 @@
+<!-- partial HTML -->
+<div id="ov-alarm-table">
+ <div class="tabular-header">
+ <h2>Alarms for {{devId || "all devices."}} ({{tableData.length}} total)</h2>
+ <div class="ctrl-btns">
+ <div class="refresh" ng-class="{active: autoRefresh}"
+ icon icon-id="refresh" icon-size="36"
+ tooltip tt-msg="autoRefreshTip"
+ ng-click="toggleRefresh()"></div>
+ </div>
+ </div>
+
+ <div class="summary-list" onos-table-resize>
+
+ <div class="table-header" onos-sortable-header>
+ <table>
+ <tr>
+
+ <td colId="id" sortable>Id </td>
+ <td colId="alarmDeviceId" sortable>Device </td>
+ <td colId="alarmDesc" sortable>Description </td>
+ <td colId="alarmSource" sortable>Source </td>
+ <td colId="alarmTimeRaised" sortable>Time Raised </td>
+ <td colId="alarmSeverity" sortable>Severity </td>
+
+ </tr>
+ </table>
+ </div>
+
+ <div class="table-body">
+ <table>
+ <tr ng-if="!tableData.length" class="no-data">
+ <td colspan="3">
+ No Alarms found
+ </td>
+ </tr>
+
+ <tr ng-repeat="item in tableData track by $index"
+ ng-click="selectCallback($event, item)"
+ ng-class="{selected: item.id === selId}">
+ <td>{{item.id}}</td>
+ <td>{{item.alarmDeviceId}}</td>
+ <td>{{item.alarmDesc}}</td>
+ <td>{{item.alarmSource}}</td>
+ <td>{{item.alarmTimeRaised}}</td>
+ <td>{{item.alarmSeverity}}</td>
+ </tr>
+ </table>
+ </div>
+
+ </div>
+
+ <ov-alarm-table-item-details-panel></ov-alarm-table-item-details-panel>
+</div>
diff --git a/apps/faultmanagement/fmgui/src/main/resources/app/view/alarmTable/alarmTable.js b/apps/faultmanagement/fmgui/src/main/resources/app/view/alarmTable/alarmTable.js
new file mode 100644
index 0000000..82ceeda
--- /dev/null
+++ b/apps/faultmanagement/fmgui/src/main/resources/app/view/alarmTable/alarmTable.js
@@ -0,0 +1,157 @@
+// js for alarm app table view
+(function () {
+ 'use strict';
+
+ // injected refs
+ var $log, $scope, $loc, devId, fs, wss;
+
+ // constants
+ var detailsReq = 'alarmTableDetailsRequest',
+ detailsResp = 'alarmTableDetailsResponse',
+ pName = 'ov-alarm-table-item-details-panel',
+ propOrder = ['id', 'alarmDeviceId', 'alarmDesc', 'alarmSource', 'alarmTimeRaised', 'alarmTimeUpdated', 'alarmTimeCleared', 'alarmSeverity'],
+ friendlyProps = ['Alarm Id', 'Device Id', 'Description', 'Source', 'Time Raised', 'Time Updated', 'Time Cleared', 'Severity'];
+
+
+ function addProp(tbody, index, value) {
+ var tr = tbody.append('tr');
+
+ function addCell(cls, txt) {
+ tr.append('td').attr('class', cls).html(txt);
+ }
+ addCell('label', friendlyProps[index] + ' :');
+ addCell('value', value);
+ }
+
+ function populatePanel(panel) {
+ var title = panel.append('h3'),
+ tbody = panel.append('table').append('tbody');
+
+ title.text('Alarm Details');
+
+ propOrder.forEach(function (prop, i) {
+ addProp(tbody, i, $scope.panelDetails[prop]);
+ });
+
+ panel.append('hr');
+ panel.append('h4').text('Comments');
+ panel.append('p').text($scope.panelDetails.comment);
+ }
+
+ function respDetailsCb(data) {
+ $scope.panelDetails = data.details;
+ $scope.$apply();
+ }
+
+ angular.module('ovAlarmTable', [])
+ .controller('OvAlarmTableCtrl',
+ ['$log', '$scope', '$location', 'TableBuilderService',
+ 'FnService', 'WebSocketService',
+ function (_$log_, _$scope_, _$location_, tbs, _fs_, _wss_) {
+ var params;
+
+ $log = _$log_;
+ $scope = _$scope_;
+ $loc = _$location_;
+
+ fs = _fs_;
+ wss = _wss_;
+
+
+ params = $loc.search();
+ if (params.hasOwnProperty('devId')) {
+ $scope.devId = params['devId'];
+ }
+
+ var handlers = {};
+ $scope.panelDetails = {};
+
+ // details response handler
+ handlers[detailsResp] = respDetailsCb;
+ wss.bindHandlers(handlers);
+
+ // custom selection callback
+ function selCb($event, row) {
+ $log.debug("selCb row=" + JSON.stringify(row, null, 4) +
+ ", $event=" + JSON.stringify($event, null, 4));
+ $log.debug('$scope.selId=', $scope.selId);
+ if ($scope.selId) {
+ $log.debug('send');
+ wss.sendEvent(detailsReq, {id: row.id});
+ } else {
+ $log.debug('hidePanel');
+ $scope.hidePanel();
+ }
+ $log.debug('Got a click on:', row);
+ }
+
+ // TableBuilderService creating a table for us
+ tbs.buildTable({
+ scope: $scope,
+ tag: 'alarmTable',
+ selCb: selCb,
+ query: params
+ });
+
+ // cleanup
+ $scope.$on('$destroy', function () {
+ wss.unbindHandlers(handlers);
+ $log.log('OvAlarmTableCtrl has been destroyed');
+ });
+
+ $log.log('OvAlarmTableCtrl has been created');
+ }])
+
+ .directive('ovAlarmTableItemDetailsPanel', ['PanelService', 'KeyService',
+ function (ps, ks) {
+ return {
+ restrict: 'E',
+ link: function (scope, element, attrs) {
+ // insert details panel with PanelService
+ // create the panel
+ var panel = ps.createPanel(pName, {
+ width: 400,
+ margin: 20,
+ hideMargin: 0
+ });
+ panel.hide();
+ scope.hidePanel = function () {
+ panel.hide();
+ };
+
+ function closePanel() {
+ if (panel.isVisible()) {
+ $scope.selId = null;
+ panel.hide();
+ return true;
+ }
+ return false;
+ }
+
+ // create key bindings to handle panel
+ ks.keyBindings({
+ esc: [closePanel, 'Close the details panel'],
+ _helpFormat: ['esc']
+ });
+ ks.gestureNotes([
+ ['click', 'Select a row to show item details']
+ ]);
+
+ // update the panel's contents when the data is changed
+ scope.$watch('panelDetails', function () {
+ if (!fs.isEmptyObject(scope.panelDetails)) {
+ panel.empty();
+ populatePanel(panel);
+ panel.show();
+ }
+ });
+
+ // cleanup on destroyed scope
+ scope.$on('$destroy', function () {
+ ks.unbindKeys();
+ ps.destroyPanel(pName);
+ });
+ }
+ };
+ }]);
+}());
diff --git a/apps/faultmanagement/fmgui/src/main/resources/app/view/alarmTopov/alarmTopov.css b/apps/faultmanagement/fmgui/src/main/resources/app/view/alarmTopov/alarmTopov.css
new file mode 100644
index 0000000..e657900
--- /dev/null
+++ b/apps/faultmanagement/fmgui/src/main/resources/app/view/alarmTopov/alarmTopov.css
@@ -0,0 +1,2 @@
+/* css for alarm app topology overlay */
+
diff --git a/apps/faultmanagement/fmgui/src/main/resources/app/view/alarmTopov/alarmTopovDemo.js b/apps/faultmanagement/fmgui/src/main/resources/app/view/alarmTopov/alarmTopovDemo.js
new file mode 100644
index 0000000..8c4846e
--- /dev/null
+++ b/apps/faultmanagement/fmgui/src/main/resources/app/view/alarmTopov/alarmTopovDemo.js
@@ -0,0 +1,104 @@
+/*
+ * 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.
+ */
+
+/*
+ Alarm Demo module. This contains the "business logic" for the topology
+ overlay that we are implementing.
+ */
+
+(function () {
+ 'use strict';
+
+ // injected refs
+ var $log, fs, flash, wss;
+
+ // constants
+ var displayStart = 'alarmTopovDisplayStart',
+ displayUpdate = 'alarmTopovDisplayUpdate',
+ displayStop = 'alarmTopovDisplayStop';
+
+ // internal state
+ var currentMode = null;
+
+
+ // === ---------------------------
+ // === Helper functions
+
+ function sendDisplayStart(mode) {
+ wss.sendEvent(displayStart, {
+ mode: mode
+ });
+ }
+
+ function sendDisplayUpdate(what) {
+ wss.sendEvent(displayUpdate, {
+ id: what ? what.id : ''
+ });
+ }
+
+ function sendDisplayStop() {
+ wss.sendEvent(displayStop);
+ }
+
+ // === ---------------------------
+ // === Main API functions
+
+ function startDisplay(mode) {
+ if (currentMode === mode) {
+ $log.debug('(in mode', mode, 'already)');
+ } else {
+ currentMode = mode;
+ sendDisplayStart(mode);
+ flash.flash('Starting display mode: ' + mode);
+ }
+ }
+
+ function updateDisplay(m) {
+ if (currentMode) {
+ sendDisplayUpdate(m);
+ }
+ }
+
+ function stopDisplay() {
+ if (currentMode) {
+ currentMode = null;
+ sendDisplayStop();
+ flash.flash('Canceling display mode');
+ return true;
+ }
+ return false;
+ }
+
+ // === ---------------------------
+ // === Module Factory Definition
+
+ angular.module('ovAlarmTopov', [])
+ .factory('AlarmTopovDemoService',
+ ['$log', 'FnService', 'FlashService', 'WebSocketService',
+
+ function (_$log_, _fs_, _flash_, _wss_) {
+ $log = _$log_;
+ fs = _fs_;
+ flash = _flash_;
+ wss = _wss_;
+
+ return {
+ startDisplay: startDisplay,
+ updateDisplay: updateDisplay,
+ stopDisplay: stopDisplay
+ };
+ }]);
+}());
diff --git a/apps/faultmanagement/fmgui/src/main/resources/app/view/alarmTopov/alarmTopovOverlay.js b/apps/faultmanagement/fmgui/src/main/resources/app/view/alarmTopov/alarmTopovOverlay.js
new file mode 100644
index 0000000..37ebda3
--- /dev/null
+++ b/apps/faultmanagement/fmgui/src/main/resources/app/view/alarmTopov/alarmTopovOverlay.js
@@ -0,0 +1,136 @@
+// alarm topology overlay - client side
+//
+// This is the glue that binds our business logic (in alarmTopovDemo.js)
+// to the overlay framework.
+
+(function () {
+ 'use strict';
+
+ // injected refs
+ var $log, tov, stds, ns;
+
+ // internal state should be kept in the service module (not here)
+
+ // our overlay definition
+ var overlay = {
+ // NOTE: this must match the ID defined in AppUiTopovOverlay
+ overlayId: 'alarmsTopo-overlay',
+ glyphId: '*star4',
+ tooltip: 'Alarms Overlay',
+ // These glyphs get installed using the overlayId as a prefix.
+ // e.g. 'star4' is installed as 'alarmsTopo-overlay-star4'
+ // They can be referenced (from this overlay) as '*star4'
+ // That is, the '*' prefix stands in for 'alarmsTopo-overlay-'
+ glyphs: {
+ star4: {
+ vb: '0 0 8 8',
+ // TODO new icon needed
+ d: 'M1,4l2,-1l1,-2l1,2l2,1l-2,1l-1,2l-1,-2z'
+ },
+ banner: {
+ vb: '0 0 6 6',
+ // TODO new icon needed
+ d: 'M1,1v4l2,-2l2,2v-4z'
+ }
+ },
+ activate: function () {
+ $log.debug("Alarm topology overlay ACTIVATED");
+ },
+ deactivate: function () {
+ stds.stopDisplay();
+ $log.debug("Alarm topology overlay DEACTIVATED");
+ },
+ // detail panel button definitions
+ buttons: {
+ alarm1button: {
+ gid: 'chain',
+ tt: 'Show alarms for this device',
+ cb: function (data) {
+ $log.debug('Show alarms for selected device. data:', data);
+ ns.navTo("alarmTable", {devId: data.id});
+
+ }
+ },
+ alarm2button: {
+ gid: '*banner',
+ tt: 'Show alarms for all devices',
+ cb: function (data) {
+ $log.debug('Show alarms for all devices. data:', data);
+ ns.navTo("alarmTable");
+
+ }
+ }
+ },
+ // Key bindings for traffic overlay buttons
+ // NOTE: fully qual. button ID is derived from overlay-id and key-name
+ keyBindings: {
+ 0: {
+ cb: function () {
+ stds.stopDisplay();
+ },
+ tt: 'Cancel Alarm Count on Device',
+ gid: 'xMark'
+ },
+ V: {
+ cb: function () {
+ stds.startDisplay('mouse');
+ },
+ tt: 'Start Alarm Count on Device',
+ gid: '*banner'
+ },
+ _keyOrder: [
+ '0', 'V'
+ ]
+ },
+ hooks: {
+ // hook for handling escape key
+ // Must return true to consume ESC, false otherwise.
+ escape: function () {
+ // Must return true to consume ESC, false otherwise.
+ return stds.stopDisplay();
+ },
+ // hooks for when the selection changes...
+ empty: function () {
+ selectionCallback('empty');
+ },
+ single: function (data) {
+ selectionCallback('single', data);
+ },
+ multi: function (selectOrder) {
+ selectionCallback('multi', selectOrder);
+ tov.addDetailButton('alarm1button');
+ tov.addDetailButton('alarm2button');
+ },
+ mouseover: function (m) {
+ // m has id, class, and type properties
+ $log.debug('mouseover:', m);
+ stds.updateDisplay(m);
+ },
+ mouseout: function () {
+ $log.debug('mouseout');
+ stds.updateDisplay();
+ }
+ }
+ };
+
+
+ function buttonCallback(x) {
+ $log.debug('Toolbar-button callback', x);
+ }
+
+ function selectionCallback(x, d) {
+ $log.debug('Selection callback', x, d);
+ }
+
+ // invoke code to register with the overlay service
+ angular.module('ovAlarmTopov')
+ .run(['$log', 'TopoOverlayService', 'AlarmTopovDemoService', 'NavService',
+ function (_$log_, _tov_, _stds_, _ns_) {
+ $log = _$log_;
+ tov = _tov_;
+ stds = _stds_;
+ ns = _ns_;
+ tov.register(overlay);
+ }]);
+
+}());
diff --git a/apps/faultmanagement/fmgui/src/main/resources/app/view/alarmTopov/sampleTopov.html b/apps/faultmanagement/fmgui/src/main/resources/app/view/alarmTopov/sampleTopov.html
new file mode 100644
index 0000000..e51c1e0
--- /dev/null
+++ b/apps/faultmanagement/fmgui/src/main/resources/app/view/alarmTopov/sampleTopov.html
@@ -0,0 +1,4 @@
+<!-- partial HTML -->
+<div id="ov-alarm-topov">
+ <p>This is a hidden view .. just a placeholder to house the javascript</p>
+</div>
diff --git a/apps/faultmanagement/fmgui/src/main/resources/css.html b/apps/faultmanagement/fmgui/src/main/resources/css.html
new file mode 100644
index 0000000..860f655
--- /dev/null
+++ b/apps/faultmanagement/fmgui/src/main/resources/css.html
@@ -0,0 +1 @@
+<link rel="stylesheet" href="app/view/alarmCustom/alarmCustom.css">
\ No newline at end of file
diff --git a/apps/faultmanagement/fmgui/src/main/resources/js.html b/apps/faultmanagement/fmgui/src/main/resources/js.html
new file mode 100644
index 0000000..d07cd63
--- /dev/null
+++ b/apps/faultmanagement/fmgui/src/main/resources/js.html
@@ -0,0 +1 @@
+<script src="app/view/alarmCustom/alarmCustom.js"></script>
\ No newline at end of file
diff --git a/apps/faultmanagement/fmgui/src/test/java/org/onosproject/faultmanagement/alarms/gui/README.txt b/apps/faultmanagement/fmgui/src/test/java/org/onosproject/faultmanagement/alarms/gui/README.txt
new file mode 100644
index 0000000..8374808
--- /dev/null
+++ b/apps/faultmanagement/fmgui/src/test/java/org/onosproject/faultmanagement/alarms/gui/README.txt
@@ -0,0 +1 @@
+# Need to write unit tests for the GUI server-side code ; write them after there are examples at web/gui/src/test/java/org/onosproject/ui/impl
\ No newline at end of file
diff --git a/apps/faultmanagement/fmmgr/pom.xml b/apps/faultmanagement/fmmgr/pom.xml
index 7d045f0..d4fb5e6 100644
--- a/apps/faultmanagement/fmmgr/pom.xml
+++ b/apps/faultmanagement/fmmgr/pom.xml
@@ -45,6 +45,11 @@
<version>${project.version}</version>
</dependency>
<dependency>
+ <groupId>org.onosproject</groupId>
+ <artifactId>onos-snmp-provider-alarm</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.compendium</artifactId>
<version>5.0.0</version>
diff --git a/apps/faultmanagement/fmmgr/src/main/java/org/onosproject/faultmanagement/impl/AlarmsManager.java b/apps/faultmanagement/fmmgr/src/main/java/org/onosproject/faultmanagement/impl/AlarmsManager.java
index 1939231..f93dba6 100644
--- a/apps/faultmanagement/fmmgr/src/main/java/org/onosproject/faultmanagement/impl/AlarmsManager.java
+++ b/apps/faultmanagement/fmmgr/src/main/java/org/onosproject/faultmanagement/impl/AlarmsManager.java
@@ -15,13 +15,16 @@
*/
package org.onosproject.faultmanagement.impl;
-import static com.google.common.base.Strings.isNullOrEmpty;
+import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Dictionary;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.atomic.AtomicLong;
+import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.stream.Collectors;
+import org.apache.commons.collections.CollectionUtils;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
@@ -47,8 +50,15 @@
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.onlab.util.ItemNotFoundException;
+import org.onosproject.incubator.net.faultmanagement.alarm.AlarmProvider;
import org.onosproject.incubator.net.faultmanagement.alarm.DefaultAlarm;
+import org.onosproject.net.device.DeviceService;
import org.osgi.service.component.ComponentContext;
+import static java.util.concurrent.TimeUnit.SECONDS;
+
+import java.util.concurrent.atomic.AtomicLong;
+import static org.onlab.util.Tools.groupedThreads;
+import org.onosproject.net.Device;
/**
* Implementation of the Alarm service.
@@ -57,89 +67,133 @@
@Service
public class AlarmsManager implements AlarmService {
+ // For subscribing to device-related events
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected CoreService coreService;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+ protected DeviceService deviceService;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+ protected AlarmProvider alarmProvider;
+
private final Logger log = getLogger(getClass());
private ApplicationId appId;
private IdGenerator idGenerator;
+ private ScheduledExecutorService alarmPollExecutor;
- @Property(name = "fmDevices", value = "127.0.0.1", label = "Instance-specific configurations")
- private String devConfigs;
-
- private final Map<AlarmId, Alarm> alarms = new ConcurrentHashMap<>();
-
-
+ // dummy data
private final AtomicLong alarmIdGenerator = new AtomicLong(0);
- @Override
- public Alarm update(Alarm replacement) {
+ private AlarmId generateAlarmId() {
+ return AlarmId.alarmId(alarmIdGenerator.incrementAndGet());
+ }
- final Alarm found = alarms.get(replacement.id());
+ private static final int DEFAULT_POLL_FREQUENCY_SECONDS = 120;
+ @Property(name = "alarmPollFrequencySeconds", intValue = DEFAULT_POLL_FREQUENCY_SECONDS,
+ label = "Frequency (in seconds) for polling alarm from devices")
+ private int alarmPollFrequencySeconds = DEFAULT_POLL_FREQUENCY_SECONDS;
+
+ // TODO implement purging of old alarms.
+ private static final int DEFAULT_CLEAR_FREQUENCY_SECONDS = 500;
+ @Property(name = "clearedAlarmPurgeSeconds", intValue = DEFAULT_CLEAR_FREQUENCY_SECONDS,
+ label = "Frequency (in seconds) for deleting cleared alarms")
+ private int clearedAlarmPurgeFrequencySeconds = DEFAULT_CLEAR_FREQUENCY_SECONDS;
+
+ // TODO Later should must be persisted to disk or database
+ private final Map<AlarmId, Alarm> alarms = new ConcurrentHashMap<>();
+
+ @Override
+ public Alarm updateBookkeepingFields(AlarmId id, boolean isAcknowledged, String assignedUser) {
+
+ Alarm found = alarms.get(id);
if (found == null) {
- throw new ItemNotFoundException("Alarm with id " + replacement.id() + " found");
+ throw new ItemNotFoundException("Alarm with id " + id + " found");
}
- final Alarm updated = new DefaultAlarm.Builder(found).
- withAcknowledged(replacement.acknowledged()).
- withAssignedUser(replacement.assignedUser()).build();
- alarms.put(replacement.id(), updated);
+
+ Alarm updated = new DefaultAlarm.Builder(found).
+ withAcknowledged(isAcknowledged).
+ withAssignedUser(assignedUser).build();
+ alarms.put(id, updated);
+ return updated;
+ }
+
+ public Alarm clear(AlarmId id) {
+
+ Alarm found = alarms.get(id);
+ if (found == null) {
+ log.warn("id {} cant be cleared as it is already gone.", id);
+ return null;
+ }
+ Alarm updated = new DefaultAlarm.Builder(found).clear().build();
+ alarms.put(id, updated);
return updated;
}
@Override
- public int getActiveAlarmCount(DeviceId deviceId) {
- //TODO
- throw new UnsupportedOperationException(NOT_SUPPORTED_YET);
+ public Map<Alarm.SeverityLevel, Long> getAlarmCounts(DeviceId deviceId) {
+
+ return getAlarms(deviceId).stream().collect(
+ Collectors.groupingBy(Alarm::severity, Collectors.counting()));
+
}
+
+ @Override
+ public Map<Alarm.SeverityLevel, Long> getAlarmCounts() {
+
+ return getAlarms().stream().collect(
+ Collectors.groupingBy(Alarm::severity, Collectors.counting()));
+ }
+
+
private static final String NOT_SUPPORTED_YET = "Not supported yet.";
@Override
public Alarm getAlarm(AlarmId alarmId) {
return nullIsNotFound(
- alarms.get(alarmId),
+ alarms.get(
+ checkNotNull(alarmId, "Alarm Id cannot be null")),
"Alarm is not found");
}
@Override
public Set<Alarm> getAlarms() {
- //TODO
- throw new UnsupportedOperationException(NOT_SUPPORTED_YET);
+ return new HashSet<>(alarms.values());
}
@Override
public Set<Alarm> getActiveAlarms() {
- // Enpty set if no values
- return alarms.isEmpty() ? new HashSet<>() : new HashSet<>(alarms.values());
-
- }
-
- private static DefaultAlarm generateFake(DeviceId deviceId, AlarmId alarmId) {
-
- return new DefaultAlarm.Builder(
- alarmId, deviceId, "NE is not reachable", Alarm.SeverityLevel.MAJOR, System.currentTimeMillis()).
- withTimeUpdated(System.currentTimeMillis()).
- withServiceAffecting(true)
- .withAcknowledged(true).
- withManuallyClearable(true)
- .withAssignedUser("user1").build();
+ return alarms.values().stream().filter(
+ a -> !a.severity().equals(Alarm.SeverityLevel.CLEARED)).
+ collect(Collectors.toSet());
}
@Override
public Set<Alarm> getAlarms(Alarm.SeverityLevel severity) {
- //TODO
- throw new UnsupportedOperationException(NOT_SUPPORTED_YET);
+ return alarms.values().stream().filter(
+ a -> a.severity().equals(severity)).
+ collect(Collectors.toSet());
}
@Override
public Set<Alarm> getAlarms(DeviceId deviceId) {
- //TODO
- throw new UnsupportedOperationException(NOT_SUPPORTED_YET);
+ return alarms.values().stream().filter(
+ a -> deviceId.equals(a.deviceId())).
+ collect(Collectors.toSet());
+ }
+
+ private Set<Alarm> getActiveAlarms(DeviceId deviceId) {
+ return getActiveAlarms().stream().filter(
+ a -> deviceId.equals(a.deviceId())).
+ collect(Collectors.toSet());
}
@Override
public Set<Alarm> getAlarms(DeviceId deviceId, AlarmEntityId source) {
- //TODO
- throw new UnsupportedOperationException(NOT_SUPPORTED_YET);
+ return getAlarms(deviceId).stream().filter(
+ a -> source.equals(a.source())
+ ).collect(Collectors.toSet());
}
@Override
@@ -154,41 +208,92 @@
throw new UnsupportedOperationException(NOT_SUPPORTED_YET);
}
- private void discoverAlarmsForDevice(DeviceId deviceId) {
- final AlarmId alarmId = new AlarmId(alarmIdGenerator.incrementAndGet());
-
- // TODO In a new thread invoke SNMP Provider with DeviceId and device type and when done update our of alarms
- //
- alarms.put(alarmId, generateFake(deviceId, alarmId));
-
- }
+ private final AlarmListener alarmListener = new InternalAlarmListener();
private class InternalAlarmListener implements AlarmListener {
@Override
public void event(AlarmEvent event) {
- // TODO
- throw new UnsupportedOperationException(NOT_SUPPORTED_YET);
+ log.debug("AlarmsManager. InternalAlarmListener received {}", event);
+ try {
+
+ switch (event.type()) {
+ case DEVICE_DISCOVERY:
+ DeviceId deviceId = checkNotNull(event.getDeviceRefreshed(), "Listener cannot be null");
+ log.info("New alarm set for {} received!", deviceId);
+ updateAlarms(event.subject(), deviceId);
+ break;
+
+ case NOTIFICATION:
+ throw new IllegalArgumentException(
+ "Alarm Notifications (Traps) not expected or implemented yet. Received =" + event);
+ default:
+ break;
+ }
+ } catch (Exception e) {
+ log.warn("Failed to process {}", event, e);
+ }
}
}
@Activate
public void activate(ComponentContext context) {
- log.info("Activate ...");
- appId = coreService.registerApplication("org.onos.faultmanagement.alarms");
+ appId = coreService.registerApplication("org.onosproject.faultmanagement.alarms");
idGenerator = coreService.getIdGenerator("alarm-ids");
- log.info("Started with appId={} idGenerator={}", appId, idGenerator);
+ log.info("Started with appId={}", appId);
- final boolean result = modified(context);
+ alarmProvider.addAlarmListener(alarmListener);
+
+ probeActiveDevices();
+
+ boolean result = modified(context);
log.info("modified result = {}", result);
+ alarmPollExecutor = newSingleThreadScheduledExecutor(groupedThreads("onos/fm", "alarms-poll-%d"));
+ alarmPollExecutor.scheduleAtFixedRate(new PollAlarmsTask(),
+ alarmPollFrequencySeconds, alarmPollFrequencySeconds, SECONDS);
+
+ }
+
+ /**
+ * Auxiliary task to keep alarms up to date. IN future release alarm-notifications will be used as an optimization
+ * so we dont have to wait until polling to detect changes. Furthermore with simple polling flapping alarms may be
+ * missed.
+ */
+ private final class PollAlarmsTask implements Runnable {
+
+ @Override
+ public void run() {
+ if (Thread.currentThread().isInterrupted()) {
+ log.info("Interrupted, quitting");
+ return;
+ }
+ try {
+ probeActiveDevices();
+ } catch (RuntimeException e) {
+ log.error("Exception thrown during alarm synchronization process", e);
+ }
+ }
+ }
+
+ private void probeActiveDevices() {
+ Iterable<Device> devices = deviceService.getAvailableDevices();
+ log.info("Refresh alarms for all available devices={} ...", devices);
+ for (Device d : devices) {
+ log.info("Lets tell alarm provider to refresh alarms for {} ...", d.id());
+ alarmProvider.triggerProbe(d.id());
+ }
}
@Deactivate
public void deactivate(ComponentContext context) {
log.info("Deactivate ...");
- // cfgService.unregisterProperties(getClass(), false);
+ alarmProvider.removeAlarmListener(alarmListener);
+ if (alarmPollExecutor != null) {
+ alarmPollExecutor.shutdownNow();
+ }
+ alarms.clear();
log.info("Stopped");
}
@@ -199,24 +304,36 @@
log.info("No configuration file");
return false;
}
- final Dictionary<?, ?> properties = context.getProperties();
- final String ipaddresses = get(properties, "fmDevices");
- log.info("Settings: devConfigs={}", ipaddresses);
- if (!isNullOrEmpty(ipaddresses)) {
- discover(ipaddresses);
+ Dictionary<?, ?> properties = context.getProperties();
+ String clearedAlarmPurgeSeconds = get(properties, "clearedAlarmPurgeSeconds");
- }
+ log.info("Settings: clearedAlarmPurgeSeconds={}", clearedAlarmPurgeSeconds);
+
return true;
}
- private void discover(String ipaddresses) {
- for (String deviceEntry : ipaddresses.split(",")) {
- final DeviceId deviceId = DeviceId.deviceId(deviceEntry);
- if (deviceId != null) {
- log.info("Device {} needs to have its alarms refreshed!", deviceId);
- discoverAlarmsForDevice(deviceId);
- }
+ // Synchronised to prevent duplicate NE alarms being raised
+ synchronized void updateAlarms(Set<Alarm> discoveredSet, DeviceId deviceId) {
+ Set<Alarm> storedSet = getActiveAlarms(deviceId);
+ log.trace("currentNeAlarms={}. discoveredAlarms={}", storedSet, discoveredSet);
+
+ if (CollectionUtils.isEqualCollection(storedSet, discoveredSet)) {
+ log.debug("Alarm lists are equivalent so no update for {}.", deviceId);
+ return;
}
+
+ storedSet.stream().filter(
+ (stored) -> (!discoveredSet.contains(stored))).forEach((stored) -> {
+ log.info("Alarm will be cleared as it is not on the element. Cleared alarm: {}.", stored);
+ clear(stored.id());
+ });
+
+ discoveredSet.stream().filter(
+ (discovered) -> (!storedSet.contains(discovered))).forEach((discovered) -> {
+ log.info("Alarm will be raised as it is missing. New alarm: {}.", discovered);
+ AlarmId id = generateAlarmId();
+ alarms.put(id, new DefaultAlarm.Builder(discovered).withId(id).build());
+ });
}
}
diff --git a/apps/faultmanagement/fmmgr/src/test/java/org/onosproject/faultmanagement/impl/AlarmsManagerTest.java b/apps/faultmanagement/fmmgr/src/test/java/org/onosproject/faultmanagement/impl/AlarmsManagerTest.java
new file mode 100644
index 0000000..586d233
--- /dev/null
+++ b/apps/faultmanagement/fmmgr/src/test/java/org/onosproject/faultmanagement/impl/AlarmsManagerTest.java
@@ -0,0 +1,136 @@
+/*
+ * 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.faultmanagement.impl;
+
+import com.google.common.collect.Sets;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import org.junit.Test;
+import static org.junit.Assert.*;
+import org.onlab.util.ItemNotFoundException;
+import org.onosproject.net.DeviceId;
+import static org.hamcrest.Matchers.containsString;
+import org.onosproject.incubator.net.faultmanagement.alarm.Alarm;
+import static org.onosproject.incubator.net.faultmanagement.alarm.Alarm.SeverityLevel.*;
+import org.onosproject.incubator.net.faultmanagement.alarm.AlarmEntityId;
+import org.onosproject.incubator.net.faultmanagement.alarm.AlarmId;
+import org.onosproject.incubator.net.faultmanagement.alarm.DefaultAlarm;
+
+public class AlarmsManagerTest {
+
+ @Test
+ public void testGettersWhenNoAlarms() {
+ AlarmsManager am = new AlarmsManager();
+ assertTrue("No alarms", am.getAlarms().isEmpty());
+ assertTrue("No active alarms", am.getActiveAlarms().isEmpty());
+ assertTrue("No alarms gives empty map per unknown device", am.getAlarmCounts(DeviceId.NONE).keySet().isEmpty());
+ assertTrue("No alarms gives empty map", am.getAlarmCounts().keySet().isEmpty());
+
+ assertEquals("Zero alarms for that device", 0, am.getAlarms(DeviceId.NONE).size());
+ assertEquals("Zero major alarms", 0, am.getAlarms(Alarm.SeverityLevel.MAJOR).size());
+
+ try {
+ assertEquals("no alarms", 0, am.getAlarm(null));
+ } catch (NullPointerException ex) {
+ assertThat(ex.getMessage(),
+ containsString("cannot be null"));
+ }
+
+ try {
+ assertEquals("no alarms", 0, am.getAlarm(AlarmId.alarmId(1)));
+ } catch (ItemNotFoundException ex) {
+ assertThat(ex.getMessage(),
+ containsString("not found"));
+ }
+ }
+
+ @Test
+ public void testAlarmUpdates() {
+ AlarmsManager am = new AlarmsManager();
+ assertTrue("no alarms", am.getAlarms().isEmpty());
+
+ am.updateAlarms(new HashSet<>(), DEVICE_ID);
+ assertTrue("still no alarms", am.getAlarms().isEmpty());
+ Map<Alarm.SeverityLevel, Long> zeroAlarms = new CountsMapBuilder().create();
+ assertEquals(zeroAlarms, am.getAlarmCounts());
+ assertEquals(zeroAlarms, am.getAlarmCounts(DEVICE_ID));
+
+ am.updateAlarms(Sets.newHashSet(ALARM_B, ALARM_A), DEVICE_ID);
+ verifyGettingSetsOfAlarms(am, 2, 2);
+ Map<Alarm.SeverityLevel, Long> critical2 = new CountsMapBuilder().with(CRITICAL, 2L).create();
+ assertEquals(critical2, am.getAlarmCounts());
+ assertEquals(critical2, am.getAlarmCounts(DEVICE_ID));
+
+ am.updateAlarms(Sets.newHashSet(ALARM_A), DEVICE_ID);
+ verifyGettingSetsOfAlarms(am, 2, 1);
+ Map<Alarm.SeverityLevel, Long> critical1cleared1 =
+ new CountsMapBuilder().with(CRITICAL, 1L).with(CLEARED, 1L).create();
+ assertEquals(critical1cleared1, am.getAlarmCounts());
+ assertEquals(critical1cleared1, am.getAlarmCounts(DEVICE_ID));
+
+ // No change map when same alarms sent
+ am.updateAlarms(Sets.newHashSet(ALARM_A), DEVICE_ID);
+ verifyGettingSetsOfAlarms(am, 2, 1);
+ assertEquals(critical1cleared1, am.getAlarmCounts());
+ assertEquals(critical1cleared1, am.getAlarmCounts(DEVICE_ID));
+
+ am.updateAlarms(Sets.newHashSet(ALARM_A, ALARM_A_WITHSRC), DEVICE_ID);
+ verifyGettingSetsOfAlarms(am, 3, 2);
+ Map<Alarm.SeverityLevel, Long> critical2cleared1 =
+ new CountsMapBuilder().with(CRITICAL, 2L).with(CLEARED, 1L).create();
+ assertEquals(critical2cleared1, am.getAlarmCounts());
+ assertEquals(critical2cleared1, am.getAlarmCounts(DEVICE_ID));
+
+ am.updateAlarms(Sets.newHashSet(), DEVICE_ID);
+ verifyGettingSetsOfAlarms(am, 3, 0);
+ assertEquals(new CountsMapBuilder().with(CLEARED, 3L).create(), am.getAlarmCounts(DEVICE_ID));
+
+ assertEquals("No alarms for unknown devices", zeroAlarms, am.getAlarmCounts(DeviceId.NONE));
+ assertEquals("No alarms for unknown devices", zeroAlarms, am.getAlarmCounts(DeviceId.deviceId("junk:junk")));
+
+ }
+
+ private void verifyGettingSetsOfAlarms(AlarmsManager am, int expectedTotal, int expectedActive) {
+ assertEquals("Wrong total", expectedTotal, am.getAlarms().size());
+ assertEquals("Wrong active count", expectedActive, am.getActiveAlarms().size());
+ }
+ private static final DeviceId DEVICE_ID = DeviceId.deviceId("foo:bar");
+ private static final DefaultAlarm ALARM_A = new DefaultAlarm.Builder(
+ DEVICE_ID, "aaa", Alarm.SeverityLevel.CRITICAL, 0).build();
+
+ private static final DefaultAlarm ALARM_A_WITHSRC = new DefaultAlarm.Builder(
+ ALARM_A).forSource(AlarmEntityId.alarmEntityId("port:foo")).build();
+
+ private static final DefaultAlarm ALARM_B = new DefaultAlarm.Builder(
+ DEVICE_ID, "bbb", Alarm.SeverityLevel.CRITICAL, 0).build();
+
+ private static class CountsMapBuilder {
+
+ private final Map<Alarm.SeverityLevel, Long> map = new HashMap<>();
+
+ public CountsMapBuilder with(Alarm.SeverityLevel sev, Long count) {
+ map.put(sev, count);
+ return this;
+ }
+
+ public Map<Alarm.SeverityLevel, Long> create() {
+ return Collections.unmodifiableMap(map);
+ }
+ }
+
+}
diff --git a/apps/faultmanagement/fmweb/pom.xml b/apps/faultmanagement/fmweb/pom.xml
index a67ad56..daaa09b 100644
--- a/apps/faultmanagement/fmweb/pom.xml
+++ b/apps/faultmanagement/fmweb/pom.xml
@@ -124,6 +124,7 @@
com.fasterxml.jackson.core,
org.apache.karaf.shell.commands,
org.apache.commons.lang.math.*,
+ org.apache.commons.lang.*,
com.google.common.*,
org.onlab.packet.*,
org.onlab.rest.*,
diff --git a/apps/faultmanagement/fmweb/src/main/java/org/onosproject/faultmanagement/web/AlarmCodec.java b/apps/faultmanagement/fmweb/src/main/java/org/onosproject/faultmanagement/web/AlarmCodec.java
index 60587bd..279e6b2 100644
--- a/apps/faultmanagement/fmweb/src/main/java/org/onosproject/faultmanagement/web/AlarmCodec.java
+++ b/apps/faultmanagement/fmweb/src/main/java/org/onosproject/faultmanagement/web/AlarmCodec.java
@@ -66,28 +66,29 @@
}
log.debug("id={}, full json={} ", json.get("id"), json);
- final Long id = json.get("id").asLong();
+ Long id = json.get("id").asLong();
- final DeviceId deviceId = DeviceId.deviceId(json.get("deviceId").asText());
- final String description = json.get("description").asText();
- final Long timeRaised = json.get("timeRaised").asLong();
- final Long timeUpdated = json.get("timeUpdated").asLong();
+ DeviceId deviceId = DeviceId.deviceId(json.get("deviceId").asText());
+ String description = json.get("description").asText();
+ Long timeRaised = json.get("timeRaised").asLong();
+ Long timeUpdated = json.get("timeUpdated").asLong();
- final JsonNode jsonTimeCleared = json.get("timeCleared");
- final Long timeCleared = jsonTimeCleared == null || jsonTimeCleared.isNull() ? null : jsonTimeCleared.asLong();
+ JsonNode jsonTimeCleared = json.get("timeCleared");
+ Long timeCleared = jsonTimeCleared == null || jsonTimeCleared.isNull() ? null : jsonTimeCleared.asLong();
- final Alarm.SeverityLevel severity = Alarm.SeverityLevel.valueOf(json.get("severity").asText().toUpperCase());
+ Alarm.SeverityLevel severity = Alarm.SeverityLevel.valueOf(json.get("severity").asText().toUpperCase());
- final Boolean serviceAffecting = json.get("serviceAffecting").asBoolean();
- final Boolean acknowledged = json.get("acknowledged").asBoolean();
- final Boolean manuallyClearable = json.get("manuallyClearable").asBoolean();
+ Boolean serviceAffecting = json.get("serviceAffecting").asBoolean();
+ Boolean acknowledged = json.get("acknowledged").asBoolean();
+ Boolean manuallyClearable = json.get("manuallyClearable").asBoolean();
- final JsonNode jsonAssignedUser = json.get("assignedUser");
- final String assignedUser
+ JsonNode jsonAssignedUser = json.get("assignedUser");
+ String assignedUser
= jsonAssignedUser == null || jsonAssignedUser.isNull() ? null : jsonAssignedUser.asText();
return new DefaultAlarm.Builder(
- AlarmId.valueOf(id), deviceId, description, severity, timeRaised).forSource(AlarmEntityId.NONE).
+ deviceId, description, severity, timeRaised).forSource(AlarmEntityId.NONE).
+ withId(AlarmId.alarmId(id)).
withTimeUpdated(timeUpdated).
withTimeCleared(timeCleared).
withServiceAffecting(serviceAffecting).
diff --git a/apps/faultmanagement/fmweb/src/main/java/org/onosproject/faultmanagement/web/AlarmsWebResource.java b/apps/faultmanagement/fmweb/src/main/java/org/onosproject/faultmanagement/web/AlarmsWebResource.java
index d62fa76..118cd18 100644
--- a/apps/faultmanagement/fmweb/src/main/java/org/onosproject/faultmanagement/web/AlarmsWebResource.java
+++ b/apps/faultmanagement/fmweb/src/main/java/org/onosproject/faultmanagement/web/AlarmsWebResource.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2014-2015 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.
@@ -34,7 +34,9 @@
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
+import org.apache.commons.lang.StringUtils;
import org.onosproject.incubator.net.faultmanagement.alarm.AlarmService;
+import org.onosproject.net.DeviceId;
import org.slf4j.Logger;
import static org.slf4j.LoggerFactory.getLogger;
@@ -48,31 +50,32 @@
private final Logger log = getLogger(getClass());
- public AlarmsWebResource() {
- }
-
/**
- * Get all alarms. Returns a list of all alarms across all devices.
+ * Get alarms. Returns a list of alarms
*
- * @param includeCleared include recently cleared alarms in response
+ * @param includeCleared (optional) include recently cleared alarms in response
+ * @param devId (optional) include only for specified device
* @return JSON encoded set of alarms
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
- public Response getAlarms(@DefaultValue("false") @QueryParam("includeCleared") boolean includeCleared
+ public Response getAlarms(@DefaultValue("false") @QueryParam("includeCleared") boolean includeCleared,
+ @DefaultValue("") @QueryParam("devId") String devId
) {
log.info("Requesting all alarms, includeCleared={}", includeCleared);
- final AlarmService service = get(AlarmService.class);
+ AlarmService service = get(AlarmService.class);
- final Iterable<Alarm> alarms = includeCleared
- ? service.getAlarms()
- : service.getActiveAlarms();
-
- final ObjectNode result = new ObjectMapper().createObjectNode();
- result.set("alarms",
- codec(Alarm.class).
- encode(alarms, this));
+ Iterable<Alarm> alarms;
+ if (StringUtils.isBlank(devId)) {
+ alarms = includeCleared
+ ? service.getAlarms()
+ : service.getActiveAlarms();
+ } else {
+ alarms = service.getAlarms(DeviceId.deviceId(devId));
+ }
+ ObjectNode result = new ObjectMapper().createObjectNode();
+ result.set("alarms", new AlarmCodec().encode(alarms, this));
return ok(result.toString()).build();
}
@@ -89,11 +92,11 @@
public Response getAlarm(@PathParam("id") String id) {
log.info("HTTP GET alarm for id={}", id);
- final AlarmId alarmId = toAlarmId(id);
- final Alarm alarm = get(AlarmService.class).getAlarm(alarmId);
+ AlarmId alarmId = toAlarmId(id);
+ Alarm alarm = get(AlarmService.class).getAlarm(alarmId);
- final ObjectNode result = mapper().createObjectNode();
- result.set("alarm", codec(Alarm.class).encode(alarm, this));
+ ObjectNode result = new ObjectMapper().createObjectNode();
+ result.set("alarm", new AlarmCodec().encode(alarm, this));
return ok(result.toString()).build();
}
@@ -113,20 +116,22 @@
log.info("PUT NEW ALARM at /{}", alarmIdPath);
try {
- final ObjectNode jsonTree = (ObjectNode) mapper().readTree(stream);
+ ObjectNode jsonTree = (ObjectNode) mapper().readTree(stream);
log.info("jsonTree={}", jsonTree);
- final Alarm alarm = codec(Alarm.class).decode(jsonTree, this);
+ Alarm alarm = new AlarmCodec().decode(jsonTree, this);
- final AlarmService service = get(AlarmService.class);
+ AlarmService service = get(AlarmService.class);
if (Long.parseLong(alarmIdPath) != alarm.id().fingerprint()) {
throw new IllegalArgumentException("id in path is " + Long.parseLong(alarmIdPath)
+ " but payload uses id=" + alarm.id().fingerprint());
}
- final Alarm updated = service.update(alarm);
- final ObjectNode encoded = new AlarmCodec().encode(updated, this);
+ Alarm updated = service.updateBookkeepingFields(
+ alarm.id(), alarm.acknowledged(), alarm.assignedUser()
+ );
+ ObjectNode encoded = new AlarmCodec().encode(updated, this);
return ok(encoded.toString()).build();
} catch (IOException ioe) {
@@ -136,7 +141,7 @@
private static AlarmId toAlarmId(String id) {
try {
- return AlarmId.valueOf(Long.parseLong(id));
+ return AlarmId.alarmId(Long.parseLong(id));
} catch (NumberFormatException ex) {
throw new IllegalArgumentException("Alarm id should be numeric", ex);
}
diff --git a/apps/faultmanagement/fmweb/src/test/java/org/onosproject/faultmanagement/web/AlarmCodecContext.java b/apps/faultmanagement/fmweb/src/test/java/org/onosproject/faultmanagement/web/AlarmCodecContext.java
index 6b80b72..56da337 100644
--- a/apps/faultmanagement/fmweb/src/test/java/org/onosproject/faultmanagement/web/AlarmCodecContext.java
+++ b/apps/faultmanagement/fmweb/src/test/java/org/onosproject/faultmanagement/web/AlarmCodecContext.java
@@ -25,7 +25,7 @@
/**
* Mock codec context for use in codec unit tests.
*/
-public class AlarmCodecContext implements CodecContext {
+public final class AlarmCodecContext implements CodecContext {
private final ObjectMapper mapper = new ObjectMapper();
private final CodecManager codecManager = new CodecManager();
diff --git a/apps/faultmanagement/fmweb/src/test/java/org/onosproject/faultmanagement/web/AlarmCodecTest.java b/apps/faultmanagement/fmweb/src/test/java/org/onosproject/faultmanagement/web/AlarmCodecTest.java
index 012b1ff..6d06b58 100644
--- a/apps/faultmanagement/fmweb/src/test/java/org/onosproject/faultmanagement/web/AlarmCodecTest.java
+++ b/apps/faultmanagement/fmweb/src/test/java/org/onosproject/faultmanagement/web/AlarmCodecTest.java
@@ -36,37 +36,26 @@
public class AlarmCodecTest {
private final AlarmCodecContext context = new AlarmCodecContext();
+ private static final AlarmId ALARM_ID = AlarmId.alarmId(44);
// Use this to check handling for miminal Alarm
private final Alarm alarmMinimumFields = new DefaultAlarm.Builder(
- new AlarmId(44),
- DeviceId.deviceId("of:2222000000000000"),
- "NE unreachable",
- Alarm.SeverityLevel.CLEARED,
- 1).
- build();
+ DeviceId.deviceId("of:2222000000000000"), "NE unreachable", Alarm.SeverityLevel.CLEARED, 1
+ ).withId(ALARM_ID).build();
// Use this to check handling for fully populated Alarm
private final Alarm alarmWithSource = new DefaultAlarm.Builder(
- new AlarmId(44),
- DeviceId.deviceId("of:2222000000000000"),
- "NE unreachable",
- Alarm.SeverityLevel.CLEARED, 1).
- forSource(AlarmEntityId.alarmEntityId("port:1/2/3/4")).
- withTimeUpdated(2).
- withTimeCleared(3L).
- withServiceAffecting(true).
- withAcknowledged(true).
- withManuallyClearable(true).
+ DeviceId.deviceId("of:2222000000000000"), "NE unreachable", Alarm.SeverityLevel.CLEARED, 1
+ ).withId(ALARM_ID).forSource(AlarmEntityId.alarmEntityId("port:1/2/3/4")).withTimeUpdated(2).withTimeCleared(3L).
+ withServiceAffecting(true).withAcknowledged(true).withManuallyClearable(true).
withAssignedUser("the assigned user").build();
@Test
public void alarmCodecTestWithOptionalFieldMissing() {
- //context.registerService(AlarmService.class, new AlarmServiceAdapter());
- final JsonCodec<Alarm> codec = context.codec(Alarm.class);
+ JsonCodec<Alarm> codec = context.codec(Alarm.class);
assertThat(codec, is(notNullValue()));
- final ObjectNode alarmJson = codec.encode(alarmMinimumFields, context);
+ ObjectNode alarmJson = codec.encode(alarmMinimumFields, context);
assertThat(alarmJson, notNullValue());
assertThat(alarmJson, matchesAlarm(alarmMinimumFields));
@@ -74,10 +63,10 @@
@Test
public void alarmCodecTestWithOptionalField() {
- final JsonCodec<Alarm> codec = context.codec(Alarm.class);
+ JsonCodec<Alarm> codec = context.codec(Alarm.class);
assertThat(codec, is(notNullValue()));
- final ObjectNode alarmJson = codec.encode(alarmWithSource, context);
+ ObjectNode alarmJson = codec.encode(alarmWithSource, context);
assertThat(alarmJson, notNullValue());
assertThat(alarmJson, matchesAlarm(alarmWithSource));
@@ -85,9 +74,9 @@
@Test
public void verifyMinimalAlarmIsEncoded() throws Exception {
- final JsonCodec<Alarm> alarmCodec = context.codec(Alarm.class);
+ JsonCodec<Alarm> alarmCodec = context.codec(Alarm.class);
- final Alarm alarm = getDecodedAlarm(alarmCodec, "alarm-minimal.json");
+ Alarm alarm = getDecodedAlarm(alarmCodec, "alarm-minimal.json");
assertCommon(alarm);
assertThat(alarm.timeCleared(), nullValue());
@@ -97,9 +86,9 @@
@Test
public void verifyFullyLoadedAlarmIsEncoded() throws Exception {
- final JsonCodec<Alarm> alarmCodec = context.codec(Alarm.class);
+ JsonCodec<Alarm> alarmCodec = context.codec(Alarm.class);
- final Alarm alarm = getDecodedAlarm(alarmCodec, "alarm-full.json");
+ Alarm alarm = getDecodedAlarm(alarmCodec, "alarm-full.json");
assertCommon(alarm);
assertThat(alarm.timeCleared(), is(2222L));
@@ -108,7 +97,7 @@
}
private void assertCommon(Alarm alarm) {
- assertThat(alarm.id(), is(new AlarmId(10L)));
+ assertThat(alarm.id(), is(AlarmId.alarmId(10L)));
assertThat(alarm.description(), is("NE is not reachable"));
assertThat(alarm.source(), is(AlarmEntityId.NONE));
assertThat(alarm.timeRaised(), is(999L));
@@ -127,14 +116,14 @@
* @throws IOException if processing the resource fails to decode
*/
private Alarm getDecodedAlarm(JsonCodec<Alarm> codec, String resourceName) throws IOException {
- final InputStream jsonStream = AlarmCodecTest.class
- .getResourceAsStream(resourceName);
- final JsonNode json = context.mapper().readTree(jsonStream);
- assertThat(json, notNullValue());
- final Alarm result = codec.decode((ObjectNode) json, context);
- assertThat(result, notNullValue());
- return result;
+ try (InputStream jsonStream = AlarmCodecTest.class
+ .getResourceAsStream(resourceName)) {
+ JsonNode json = context.mapper().readTree(jsonStream);
+ assertThat(json, notNullValue());
+ Alarm result = codec.decode((ObjectNode) json, context);
+ assertThat(result, notNullValue());
+ return result;
+ }
}
-
}
diff --git a/apps/faultmanagement/fmweb/src/test/java/org/onosproject/faultmanagement/web/AlarmJsonMatcher.java b/apps/faultmanagement/fmweb/src/test/java/org/onosproject/faultmanagement/web/AlarmJsonMatcher.java
index 9a295c8..d32383c 100644
--- a/apps/faultmanagement/fmweb/src/test/java/org/onosproject/faultmanagement/web/AlarmJsonMatcher.java
+++ b/apps/faultmanagement/fmweb/src/test/java/org/onosproject/faultmanagement/web/AlarmJsonMatcher.java
@@ -34,48 +34,48 @@
@Override
public boolean matchesSafely(JsonNode jsonAlarm, Description description) {
- final String jsonAlarmId = jsonAlarm.get("id").asText();
- final String alarmId = Long.toString(alarm.id().fingerprint());
+ String jsonAlarmId = jsonAlarm.get("id").asText();
+ String alarmId = Long.toString(alarm.id().fingerprint());
if (!jsonAlarmId.equals(alarmId)) {
description.appendText("alarm id was " + jsonAlarmId);
return false;
}
- final String jsonDeviceId = jsonAlarm.get("deviceId").asText();
- final String alarmDeviceId = alarm.deviceId().toString();
+ String jsonDeviceId = jsonAlarm.get("deviceId").asText();
+ String alarmDeviceId = alarm.deviceId().toString();
if (!jsonDeviceId.equals(alarmDeviceId)) {
description.appendText("DeviceId was " + jsonDeviceId);
return false;
}
- final String jsonDescription = jsonAlarm.get("description").asText();
- final String alarmDesc = alarm.description();
+ String jsonDescription = jsonAlarm.get("description").asText();
+ String alarmDesc = alarm.description();
if (!jsonDescription.equals(alarmDesc)) {
description.appendText("description was " + jsonDescription);
return false;
}
- final long jsonTimeRaised = jsonAlarm.get("timeRaised").asLong();
- final long timeRaised = alarm.timeRaised();
+ long jsonTimeRaised = jsonAlarm.get("timeRaised").asLong();
+ long timeRaised = alarm.timeRaised();
if (timeRaised != jsonTimeRaised) {
description.appendText("timeRaised was " + jsonTimeRaised);
return false;
}
- final long jsonTimeUpdated = jsonAlarm.get("timeUpdated").asLong();
- final long timeUpdated = alarm.timeUpdated();
+ long jsonTimeUpdated = jsonAlarm.get("timeUpdated").asLong();
+ long timeUpdated = alarm.timeUpdated();
if (timeUpdated != jsonTimeUpdated) {
description.appendText("timeUpdated was " + jsonTimeUpdated);
return false;
}
- final JsonNode jsonTimeClearedNode = jsonAlarm.get("timeCleared");
+ JsonNode jsonTimeClearedNode = jsonAlarm.get("timeCleared");
if (alarm.timeCleared() != null) {
- final Long jsonTimeCleared = jsonTimeClearedNode.longValue();
- final Long timeCleared = alarm.timeCleared();
+ Long jsonTimeCleared = jsonTimeClearedNode.longValue();
+ Long timeCleared = alarm.timeCleared();
if (!timeCleared.equals(jsonTimeCleared)) {
description.appendText("Time Cleared was " + jsonTimeCleared);
@@ -89,18 +89,18 @@
}
}
- final String jsonSeverity = jsonAlarm.get("severity").asText();
- final String severity = alarm.severity().toString();
+ String jsonSeverity = jsonAlarm.get("severity").asText();
+ String severity = alarm.severity().toString();
if (!severity.equals(jsonSeverity)) {
description.appendText("severity was " + jsonSeverity);
return false;
}
- final JsonNode jsonAlarmNode = jsonAlarm.get("source");
+ JsonNode jsonAlarmNode = jsonAlarm.get("source");
if (alarm.source() != null) {
- final String jsonSource = jsonAlarmNode.textValue();
- final String source = alarm.source().toString();
+ String jsonSource = jsonAlarmNode.textValue();
+ String source = alarm.source().toString();
if (!source.equals(jsonSource)) {
description.appendText("source was " + jsonSource);
diff --git a/apps/faultmanagement/fmweb/src/test/java/org/onosproject/faultmanagement/web/AlarmsWebResourceTest.java b/apps/faultmanagement/fmweb/src/test/java/org/onosproject/faultmanagement/web/AlarmsWebResourceTest.java
index e07487c..027a548 100644
--- a/apps/faultmanagement/fmweb/src/test/java/org/onosproject/faultmanagement/web/AlarmsWebResourceTest.java
+++ b/apps/faultmanagement/fmweb/src/test/java/org/onosproject/faultmanagement/web/AlarmsWebResourceTest.java
@@ -38,10 +38,10 @@
@Before
public void setUp() {
- final CodecManager codecService = new CodecManager();
+ CodecManager codecService = new CodecManager();
codecService.activate();
- final ServiceDirectory testDirectory = new TestServiceDirectory()
+ ServiceDirectory testDirectory = new TestServiceDirectory()
// Currently no alarms-service implemented
// .add(AlarmsService.class, alarmsService)
.add(CodecService.class, codecService);
@@ -51,8 +51,8 @@
@Test
@Ignore
public void getAllAlarms() {
- final WebResource rs = resource();
- final String response = rs.path("/alarms").get(String.class);
+ WebResource rs = resource();
+ String response = rs.path("/alarms").get(String.class);
// Ensure hard-coded alarms returned okay
assertThat(response, containsString("\"NE is not reachable\","));
assertThat(response, containsString("\"Equipment Missing\","));
@@ -61,8 +61,8 @@
@Test
@Ignore
public void getAlarm() {
- final WebResource rs = resource();
- final String response = rs.path("/alarms/1").get(String.class);
+ WebResource rs = resource();
+ String response = rs.path("/alarms/1").get(String.class);
// Ensure hard-coded alarms returned okay
assertThat(response, containsString("\"NE is not reachable\","));
assertThat(response, not(containsString("\"Equipment Missing\",")));
diff --git a/apps/faultmanagement/pom.xml b/apps/faultmanagement/pom.xml
index 90ba23e..14c1571 100644
--- a/apps/faultmanagement/pom.xml
+++ b/apps/faultmanagement/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">
@@ -34,10 +34,12 @@
<modules>
<module>fmmgr</module>
<module>fmweb</module>
+ <module>fmgui</module>
+ <module>fmcli</module>
<module>app</module>
- </modules>
- <dependencies>
- <dependency>
+ </modules>
+ <dependencies>
+ <dependency>
<groupId>org.onosproject</groupId>
<artifactId>onlab-junit</artifactId>
<scope>test</scope>