initial artemis application commit
Change-Id: I01967b1e8e8df08cf95a2865566423a4aeb34ea9
diff --git a/apps/artemis/BUCK b/apps/artemis/BUCK
new file mode 100755
index 0000000..ebde4fc
--- /dev/null
+++ b/apps/artemis/BUCK
@@ -0,0 +1,79 @@
+COMPILE_DEPS = [
+ '//lib:CORE_DEPS',
+ '//lib:org.apache.karaf.shell.console',
+ '//cli:onos-cli',
+ '//apps/routing-api:onos-apps-routing-api',
+ '//apps/routing/common:onos-apps-routing-common',
+ '//lib:okhttp',
+ '//lib:okio',
+ ':commons-net',
+ ':io.socket-client',
+ ':json',
+ ':engine.io-client'
+ ]
+
+BUNDLES = [
+ '//apps/artemis:onos-apps-artemis',
+ '//apps/routing-api:onos-apps-routing-api',
+ '//apps/routing/common:onos-apps-routing-common',
+]
+
+EXCLUDED_BUNDLES = [
+ '//lib:okhttp',
+ '//lib:okio',
+ ':commons-net',
+ ':io.socket-client',
+ ':json',
+ ':engine.io-client'
+]
+
+osgi_jar (
+ deps = COMPILE_DEPS,
+)
+
+onos_app (
+ app_name = 'org.onosproject.artemis',
+ title = 'Artemis',
+ category = 'Monitoring',
+ url = 'http://onosproject.org',
+ description = 'Artemis',
+ included_bundles = BUNDLES,
+ excluded_bundles = EXCLUDED_BUNDLES,
+ required_apps = [ 'org.onosproject.sdnip' ],
+)
+
+remote_jar (
+ name = 'commons-net',
+ out = 'commons-net-3.5.jar',
+ url = 'mvn:commons-net:commons-net:jar:3.5',
+ sha1 = '342fc284019f590e1308056990fdb24a08f06318',
+ maven_coords = 'commons-net:commons-net:3.5',
+ visibility = [ 'PUBLIC' ],
+)
+
+remote_jar (
+ name = 'io.socket-client',
+ out = 'socket.io-client-0.8.3.jar',
+ url = 'mvn:io.socket:socket.io-client:jar:0.8.3',
+ sha1 = 'b30500232ff0668a47c9f91f02e6935457a52fb5',
+ maven_coords = 'io.socket:socket.io-client:jar:NON-OSGI:0.8.3',
+ visibility = [ 'PUBLIC' ],
+)
+
+remote_jar (
+ name = 'json',
+ out = 'json-20090211.jar',
+ url = 'mvn:org.json:json:jar:20090211',
+ sha1 = 'c183aa3a2a6250293808bba12262c8920ce5a51c',
+ maven_coords = 'org.json:json:jar:NON-OSGI:20090211',
+ visibility = [ 'PUBLIC' ],
+)
+
+remote_jar (
+ name = 'engine.io-client',
+ out = 'engine.io-client-0.8.3.jar',
+ url = 'mvn:io.socket:engine.io-client:jar:0.8.3',
+ sha1 = '854b49396e1e9f9bb0ab025062ddb49c4ed65ca1',
+ maven_coords = 'io.socket:engine.io-client:jar:NON-OSGI:0.8.3',
+ visibility = [ 'PUBLIC' ],
+)
\ No newline at end of file
diff --git a/apps/artemis/src/main/java/org/onosproject/artemis/cli/LogOptionsCommand.java b/apps/artemis/src/main/java/org/onosproject/artemis/cli/LogOptionsCommand.java
new file mode 100644
index 0000000..1812e91
--- /dev/null
+++ b/apps/artemis/src/main/java/org/onosproject/artemis/cli/LogOptionsCommand.java
@@ -0,0 +1,48 @@
+/*
+ * 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.artemis.cli;
+
+import org.apache.karaf.shell.commands.Command;
+import org.apache.karaf.shell.commands.Option;
+import org.onosproject.artemis.impl.ArtemisService;
+import org.onosproject.cli.AbstractShellCommand;
+
+/**
+ * CLI to enable or disable BGP Update message logging.
+ */
+@Command(scope = "artemis", name = "log-messages",
+ description = "Show RIS messages in logger.")
+public class LogOptionsCommand extends AbstractShellCommand {
+
+ @Option(name = "--enable", aliases = "-e", description = "Enable RIS message logging",
+ required = false, multiValued = false)
+ private boolean enable = false;
+
+ @Option(name = "--disable", aliases = "-d", description = "Disable RIS message logging",
+ required = false, multiValued = false)
+ private boolean disable = false;
+
+ @Override
+ protected void execute() {
+ ArtemisService artemisService = get(ArtemisService.class);
+ if (enable) {
+ artemisService.setLogger(true);
+ } else if (disable) {
+ artemisService.setLogger(false);
+ }
+ }
+}
\ No newline at end of file
diff --git a/apps/artemis/src/main/java/org/onosproject/artemis/cli/package-info.java b/apps/artemis/src/main/java/org/onosproject/artemis/cli/package-info.java
new file mode 100755
index 0000000..09a3e14
--- /dev/null
+++ b/apps/artemis/src/main/java/org/onosproject/artemis/cli/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2016-present 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.
+ */
+
+/**
+ * Artemis CLI commands.
+ */
+package org.onosproject.artemis.cli;
\ No newline at end of file
diff --git a/apps/artemis/src/main/java/org/onosproject/artemis/impl/ArtemisConfig.java b/apps/artemis/src/main/java/org/onosproject/artemis/impl/ArtemisConfig.java
new file mode 100644
index 0000000..741a4fe
--- /dev/null
+++ b/apps/artemis/src/main/java/org/onosproject/artemis/impl/ArtemisConfig.java
@@ -0,0 +1,308 @@
+/*
+ * Copyright 2015-present 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.artemis.impl;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.onlab.packet.IpPrefix;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.net.config.Config;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+/**
+ * Artemis Configuration Class.
+ */
+class ArtemisConfig extends Config<ApplicationId> {
+
+ private static final String PREFIXES = "prefixes";
+ /* */
+ private static final String PREFIX = "prefix";
+ private static final String PATHS = "paths";
+ private static final String MOAS = "moas";
+ /* */
+ private static final String ORIGIN = "origin";
+ private static final String NEIGHBOR = "neighbor";
+ private static final String ASN = "asn";
+ /* */
+
+ private static final String MONITORS = "monitors";
+ /* */
+ private static final String RIPE = "ripe";
+ private static final String EXABGP = "exabgp";
+ /* */
+
+ private static final String FREQUENCY = "frequency";
+
+
+ private final Logger log = LoggerFactory.getLogger(getClass());
+
+ /**
+ * Gets the set of monitored prefixes with the details (prefix, paths and MOAS).
+ *
+ * @return artemis class prefixes
+ */
+ Set<ArtemisPrefixes> monitoredPrefixes() {
+ Set<ArtemisPrefixes> prefixes = Sets.newHashSet();
+
+ JsonNode prefixesNode = object.get(PREFIXES);
+ if (prefixesNode == null) {
+ log.warn("prefixes field is null!");
+ return prefixes;
+ }
+
+ prefixesNode.forEach(jsonNode -> {
+ IpPrefix prefix = IpPrefix.valueOf(jsonNode.get(PREFIX).asText());
+
+ Set<Integer> moasNumbers = Sets.newHashSet();
+ JsonNode moasNode = jsonNode.get(MOAS);
+ moasNode.forEach(asn ->
+ moasNumbers.add(asn.asInt())
+ );
+
+ /*
+ "paths" : [{
+ "origin" : 65004,
+ "neighbor" : [{
+ "asn" : 65002,
+ "neighbor": [{
+ "asn" : 65001,
+ }]
+ }]
+ }]
+ */
+
+ Map<Integer, Map<Integer, Set<Integer>>> paths = Maps.newHashMap();
+ JsonNode pathsNode = jsonNode.get(PATHS);
+ pathsNode.forEach(path -> {
+ addPath(paths, path);
+ });
+
+ // printPaths(paths);
+
+ prefixes.add(new ArtemisPrefixes(prefix, moasNumbers, paths));
+ });
+
+ return prefixes;
+ }
+
+ /**
+ * Appends an ASN path on the ASN paths list of the Artemis application.
+ *
+ * @param paths active ASN paths list
+ * @param path ASN path to be added
+ */
+ private void addPath(Map<Integer, Map<Integer, Set<Integer>>> paths, JsonNode path) {
+ Integer origin = path.path(ORIGIN).asInt();
+
+ JsonNode firstNeighborNode = path.path(NEIGHBOR);
+ // Check if neighbor exists in the configuration
+ if (!firstNeighborNode.isMissingNode()) {
+ firstNeighborNode.forEach(firstNeighbor -> {
+ Integer firstNeighborAsn = firstNeighbor.get(ASN).asInt();
+
+ JsonNode secondNeighborNode = firstNeighbor.path(NEIGHBOR);
+ // check if second neighbor exists in configuration
+ if (!secondNeighborNode.isMissingNode()) {
+ secondNeighborNode.forEach(secondNeighbor -> {
+ Integer secondNeighborAsn = secondNeighbor.asInt();
+
+ if (paths.containsKey(origin)) {
+ // paths already contain origin ASN.
+ Map<Integer, Set<Integer>> integerSetMap = paths.get(origin);
+ if (integerSetMap.containsKey(firstNeighborAsn)) {
+ integerSetMap.get(firstNeighborAsn).add(secondNeighborAsn);
+ } else {
+ paths.get(origin).put(firstNeighborAsn, Sets.newHashSet(secondNeighborAsn));
+ }
+ } else {
+ // origin ASN does not exist in Map.
+ Map<Integer, Set<Integer>> first2second = Maps.newHashMap();
+ first2second.put(firstNeighborAsn, Sets.newHashSet(secondNeighborAsn));
+ paths.put(origin, first2second);
+ }
+ });
+ // else append to paths without second neighbor
+ } else {
+ if (!paths.containsKey(origin)) {
+ Map<Integer, Set<Integer>> first2second = Maps.newHashMap();
+ first2second.put(firstNeighborAsn, Sets.newHashSet());
+ paths.put(origin, first2second);
+ } else {
+ // paths already contain origin ASN.
+ Map<Integer, Set<Integer>> integerSetMap = paths.get(origin);
+ if (!integerSetMap.containsKey(firstNeighborAsn)) {
+ paths.get(origin).put(firstNeighborAsn, Sets.newHashSet());
+ }
+ }
+ }
+ });
+ // else append to paths only the origin
+ } else {
+ if (!paths.containsKey(origin)) {
+ paths.put(origin, Maps.newHashMap());
+ }
+ }
+ }
+
+ /**
+ * Helper function to print the loaded ASN paths.
+ *
+ * @param paths ASN paths to print
+ */
+ private void printPaths(Map<Integer, Map<Integer, Set<Integer>>> paths) {
+ log.warn("------------------------------------");
+ paths.forEach((k, v) -> v.forEach((l, n) -> {
+ n.forEach(p -> log.warn("Origin: " + k + ", 1st: " + l + ", 2nd: " + p));
+ }));
+ }
+
+ /**
+ * Gets the frequency of the detection module in milliseconds.
+ *
+ * @return frequency (ms)
+ */
+ int detectionFrequency() {
+ JsonNode thresholdNode = object.get(FREQUENCY);
+ int threshold = 0;
+
+ if (thresholdNode == null) {
+ log.warn("threshold field is null!");
+ return threshold;
+ }
+
+ return thresholdNode.asInt();
+ }
+
+ /**
+ * Gets the active route collectors.
+ *
+ * @return map with type as a key and host as a value.
+ */
+ Map<String, Set<String>> activeMonitors() {
+ Map<String, Set<String>> monitors = Maps.newHashMap();
+
+ JsonNode monitorsNode = object.get(MONITORS);
+
+ JsonNode ripeNode = monitorsNode.path(RIPE);
+ if (!ripeNode.isMissingNode()) {
+ Set<String> hosts = Sets.newHashSet();
+ ripeNode.forEach(host -> hosts.add(host.asText()));
+ monitors.put(RIPE, hosts);
+ }
+
+ JsonNode exabgpNode = monitorsNode.path(EXABGP);
+ if (!exabgpNode.isMissingNode()) {
+ Set<String> hosts = Sets.newHashSet();
+ exabgpNode.forEach(host -> hosts.add(host.asText()));
+ monitors.put(EXABGP, hosts);
+ }
+
+ return monitors;
+ }
+
+ /**
+ * Configuration for a specific prefix.
+ */
+ static class ArtemisPrefixes {
+ private IpPrefix prefix;
+ private Set<Integer> moas;
+ private Map<Integer, Map<Integer, Set<Integer>>> paths;
+
+ private final Logger log = LoggerFactory.getLogger(getClass());
+
+ ArtemisPrefixes(IpPrefix prefix, Set<Integer> moas, Map<Integer, Map<Integer, Set<Integer>>> paths) {
+ this.prefix = checkNotNull(prefix);
+ this.moas = checkNotNull(moas);
+ this.paths = checkNotNull(paths);
+ }
+
+ protected IpPrefix prefix() {
+ return prefix;
+ }
+
+ protected Set<Integer> moas() {
+ return moas;
+ }
+
+ protected Map<Integer, Map<Integer, Set<Integer>>> paths() {
+ return paths;
+ }
+
+ /**
+ * Given a path we check if the origin is a friendly MOAS or our ASN.
+ * If the origin ASN is not ours the we have a hijack of type 0. Next, in case that the first neighbor is
+ * not a legit neighbor from our configuration we detect a hijack of type 1 and lastly, if the second
+ * neighbor is not a legit neighbor we detect a type 2 hijack.
+ *
+ * @param path as-path that announces our prefix and found from monitors
+ * @return <code>0</code> no bgp hijack detected
+ * <code>50</code> friendly anycaster announcing our prefix
+ * <code>100+i</code> BGP hijack type i (0 <= i <=2)
+ */
+ int checkPath(JSONArray path) {
+ // TODO add MOAS check
+ ArrayList<Integer> asnPath = new ArrayList<>();
+ for (int i = 0; i < path.length(); i++) {
+ try {
+ asnPath.add(path.getInt(i));
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+ }
+ // reverse the list to get path starting from origin
+ Collections.reverse(asnPath);
+
+ if (asnPath.size() > 0 && !paths.containsKey(asnPath.get(0))) {
+ return 100;
+ } else if (asnPath.size() > 1 && !paths.get(asnPath.get(0)).containsKey(asnPath.get(1))) {
+ return 101;
+ } else if (asnPath.size() > 2 && !paths.get(asnPath.get(0)).get(asnPath.get(1)).contains(asnPath.get(2))) {
+ return 102;
+ }
+ return 0;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hashCode(prefix);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj instanceof PrefixHandler) {
+ final PrefixHandler that = (PrefixHandler) obj;
+ return Objects.equals(this.prefix, that.getPrefix());
+ }
+ return false;
+ }
+ }
+
+}
diff --git a/apps/artemis/src/main/java/org/onosproject/artemis/impl/ArtemisManager.java b/apps/artemis/src/main/java/org/onosproject/artemis/impl/ArtemisManager.java
new file mode 100755
index 0000000..0bf5eb5
--- /dev/null
+++ b/apps/artemis/src/main/java/org/onosproject/artemis/impl/ArtemisManager.java
@@ -0,0 +1,178 @@
+/*
+ * Copyright 2016-present 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.artemis.impl;
+
+import com.google.common.collect.Sets;
+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.apache.felix.scr.annotations.Service;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreService;
+import org.onosproject.net.config.ConfigFactory;
+import org.onosproject.net.config.NetworkConfigEvent;
+import org.onosproject.net.config.NetworkConfigListener;
+import org.onosproject.net.config.NetworkConfigRegistry;
+import org.onosproject.net.config.NetworkConfigService;
+import org.onosproject.net.config.basics.SubjectFactories;
+import org.onosproject.routing.bgp.BgpInfoService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.Timer;
+
+/**
+ * Artemis Component.
+ */
+@Component(immediate = true)
+@Service
+public class ArtemisManager implements ArtemisService {
+ private static final String ARTEMIS_APP_ID = "org.onosproject.artemis";
+ private static final Class<ArtemisConfig> CONFIG_CLASS = ArtemisConfig.class;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+ private NetworkConfigRegistry registry;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+ private NetworkConfigService configService;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+ private CoreService coreService;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+ private BgpInfoService bgpInfoService;
+
+ private final Logger log = LoggerFactory.getLogger(getClass());
+
+ private ApplicationId appId;
+ public static boolean logging = false;
+
+ private Set<PrefixHandler> prefixHandlers = Sets.newHashSet();
+ private Deaggregator deaggr;
+ private Timer timer;
+
+ private final InternalNetworkConfigListener configListener =
+ new InternalNetworkConfigListener();
+
+ private ConfigFactory<ApplicationId, ArtemisConfig> artemisConfigFactory =
+ new ConfigFactory<ApplicationId, ArtemisConfig>(
+ SubjectFactories.APP_SUBJECT_FACTORY, ArtemisConfig.class, "artemis") {
+ @Override
+ public ArtemisConfig createConfig() {
+ return new ArtemisConfig();
+ }
+ };
+
+ @Activate
+ protected void activate() {
+ appId = coreService.registerApplication(ARTEMIS_APP_ID);
+ configService.addListener(configListener);
+ registry.registerConfigFactory(artemisConfigFactory);
+ log.info("Artemis Started");
+ }
+
+ @Deactivate
+ protected void deactivate() {
+ configService.removeListener(configListener);
+ registry.unregisterConfigFactory(artemisConfigFactory);
+ prefixHandlers.forEach(PrefixHandler::stopPrefixMonitors);
+ log.info("Artemis Stopped");
+ }
+
+ /**
+ * Helper function to start and stop monitors on configuration changes.
+ */
+ private void setUpConfiguration() {
+ ArtemisConfig config = configService.getConfig(appId, CONFIG_CLASS);
+
+ if (config == null) {
+ log.warn("No artemis config available!");
+ return;
+ }
+
+ final Set<ArtemisConfig.ArtemisPrefixes> prefixes = config.monitoredPrefixes();
+ final Integer frequency = config.detectionFrequency();
+ final Map<String, Set<String>> monitors = config.activeMonitors();
+
+ Set<PrefixHandler> toRemove = Sets.newHashSet(prefixHandlers);
+
+ for (ArtemisConfig.ArtemisPrefixes curr : prefixes) {
+ final Optional<PrefixHandler> handler = prefixHandlers
+ .stream()
+ .filter(prefixHandler -> prefixHandler.getPrefix().equals(curr.prefix()))
+ .findFirst();
+
+ if (handler.isPresent()) {
+ PrefixHandler oldHandler = handler.get();
+ oldHandler.changeMonitors(monitors);
+
+ // remove the ones we are going to keep from toRemove list
+ toRemove.remove(oldHandler);
+ } else {
+ // Add new handler
+ PrefixHandler newHandler = new PrefixHandler(curr.prefix(), monitors);
+ newHandler.startPrefixMonitors();
+ prefixHandlers.add(newHandler);
+ }
+ }
+
+ // stop and remove old monitors that do not exist on new configuration
+ toRemove.forEach(PrefixHandler::stopPrefixMonitors);
+ prefixHandlers.removeAll(toRemove);
+
+ // new timer task with updated bgp speakers
+ deaggr = new Deaggregator(bgpInfoService);
+ deaggr.setPrefixes(prefixes);
+
+ if (timer != null) {
+ timer.cancel();
+ }
+ timer = new Timer();
+ timer.scheduleAtFixedRate(deaggr, frequency, frequency);
+ }
+
+ @Override
+ public void setLogger(boolean value) {
+ logging = value;
+ }
+
+ private class InternalNetworkConfigListener implements NetworkConfigListener {
+
+ @Override
+ public void event(NetworkConfigEvent event) {
+ switch (event.type()) {
+ case CONFIG_REGISTERED:
+ break;
+ case CONFIG_UNREGISTERED:
+ break;
+ case CONFIG_ADDED:
+ case CONFIG_UPDATED:
+ case CONFIG_REMOVED:
+ if (event.configClass() == CONFIG_CLASS) {
+ setUpConfiguration();
+ }
+ break;
+ default:
+ break;
+ }
+ }
+ }
+}
diff --git a/apps/artemis/src/main/java/org/onosproject/artemis/impl/ArtemisService.java b/apps/artemis/src/main/java/org/onosproject/artemis/impl/ArtemisService.java
new file mode 100755
index 0000000..4fc73b4
--- /dev/null
+++ b/apps/artemis/src/main/java/org/onosproject/artemis/impl/ArtemisService.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright 2016-present 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.artemis.impl;
+
+/**
+ * Artemis Service.
+ */
+public interface ArtemisService {
+
+ /**
+ * Set logger to print incoming packets or not.
+ *
+ * @param value true to print incoming BGP messages
+ */
+ void setLogger(boolean value);
+
+}
diff --git a/apps/artemis/src/main/java/org/onosproject/artemis/impl/DataHandler.java b/apps/artemis/src/main/java/org/onosproject/artemis/impl/DataHandler.java
new file mode 100644
index 0000000..c0257a6
--- /dev/null
+++ b/apps/artemis/src/main/java/org/onosproject/artemis/impl/DataHandler.java
@@ -0,0 +1,134 @@
+/*
+ * Copyright 2016-present 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.artemis.impl;
+
+import org.json.JSONObject;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.util.ArrayList;
+import java.util.concurrent.atomic.AtomicReference;
+
+/**
+ * Helper class that handles BGP Update messages.
+ */
+public final class DataHandler {
+ private static final File DATA_FILE = new File("data.json");
+ private static final File HIJACKS_FILE = new File("hijack.json");
+
+ private final AtomicReference<ArrayList<JSONObject>> data = new AtomicReference<ArrayList<JSONObject>>();
+
+ private static DataHandler instance = new DataHandler();
+
+ private DataHandler() {
+ data.set(new ArrayList<>());
+ }
+
+ /**
+ * Singleton for data handler class.
+ *
+ * @return instance of class
+ */
+ public static synchronized DataHandler getInstance() {
+ if (instance == null) {
+ instance = new DataHandler();
+ }
+ return instance;
+ }
+
+ /**
+ * Atomic append a BGP update message to a list.
+ *
+ * @param obj BGP update message
+ */
+ public synchronized void appendData(JSONObject obj) {
+ data.get().add(obj);
+ }
+
+ /**
+ * Atomic read and clear a list of BGP updates.
+ *
+ * @return list of messages that received in 'threshold' period
+ */
+ synchronized ArrayList<JSONObject> getData() {
+ ArrayList<JSONObject> tmp = (ArrayList<JSONObject>) data.get().clone();
+ data.get().clear();
+ return tmp;
+ }
+
+ /**
+ * A serializer to write incoming BGP updates and hijack attempts to json files.
+ */
+ public static class Serializer {
+ private static RandomAccessFile fwData, fwHijack;
+ private static long lengthData, lengthHijack;
+
+ static {
+ try {
+ if (DATA_FILE.exists()) {
+ fwData = new RandomAccessFile(DATA_FILE, "rw");
+ } else {
+ fwData = new RandomAccessFile(DATA_FILE, "rw");
+ fwData.writeBytes("[\n]");
+ }
+ lengthData = fwData.length() - 1;
+
+ if (HIJACKS_FILE.exists()) {
+ fwHijack = new RandomAccessFile(HIJACKS_FILE, "rw");
+ } else {
+ fwHijack = new RandomAccessFile(HIJACKS_FILE, "rw");
+ fwHijack.writeBytes("[\n]");
+ }
+ lengthHijack = fwHijack.length() - 1;
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * Writes BGP update to json file.
+ *
+ * @param data BGP update
+ */
+ public static synchronized void writeData(Object data) {
+ try {
+ String entry = data.toString() + ",\n]";
+ fwData.seek(lengthData);
+ fwData.writeBytes(entry);
+ lengthData += entry.length() - 1;
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * Writes detected BGP hijack to json file.
+ *
+ * @param data BGP update of hijack
+ */
+ static synchronized void writeHijack(Object data) {
+ try {
+ String entry = data.toString() + ",\n]";
+ fwHijack.seek(lengthHijack);
+ fwHijack.writeBytes(entry);
+ lengthHijack += entry.length() - 1;
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+}
diff --git a/apps/artemis/src/main/java/org/onosproject/artemis/impl/Deaggregator.java b/apps/artemis/src/main/java/org/onosproject/artemis/impl/Deaggregator.java
new file mode 100644
index 0000000..d0cb96c
--- /dev/null
+++ b/apps/artemis/src/main/java/org/onosproject/artemis/impl/Deaggregator.java
@@ -0,0 +1,124 @@
+/*
+ * Copyright 2016-present 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.artemis.impl;
+
+import com.google.common.collect.Sets;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+import org.onlab.packet.IpAddress;
+import org.onlab.packet.IpPrefix;
+import org.onosproject.artemis.impl.bgpspeakers.BgpSpeakers;
+import org.onosproject.artemis.impl.bgpspeakers.QuaggaBgpSpeakers;
+import org.onosproject.routing.bgp.BgpInfoService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.Set;
+
+/**
+ * Timertask class which detects and mitigates BGP hijacks.
+ */
+class Deaggregator extends java.util.TimerTask {
+
+ private final Logger log = LoggerFactory.getLogger(getClass());
+ private Set<ArtemisConfig.ArtemisPrefixes> prefixes = Sets.newHashSet();
+ private Set<BgpSpeakers> bgpSpeakers = Sets.newHashSet();
+
+ Deaggregator(BgpInfoService bgpInfoService) {
+ super();
+ // deaggregator must know the type of the connected BGP speakers and the BGP info.
+ // for this example we only have one Quagga BGP speaker.
+ bgpSpeakers.add(new QuaggaBgpSpeakers(bgpInfoService));
+ }
+
+ @Override
+ public void run() {
+ ArrayList<JSONObject> messagesArray = DataHandler.getInstance().getData();
+// log.info("Messages size: " + messagesArray.size());
+
+ // Example of BGP Update message:
+ // {
+ // "path":[65001, 65002, 65004], (origin being last)
+ // "prefix":"12.0.0.0/8",
+ // }
+
+ prefixes.forEach(prefix -> {
+ IpPrefix monitoredPrefix = prefix.prefix();
+
+ // for each update message in memory check for hijack
+ for (JSONObject tmp : messagesArray) {
+ IpPrefix receivedPrefix = null;
+ try {
+ receivedPrefix = IpPrefix.valueOf(tmp.getString("prefix"));
+ } catch (JSONException e) {
+ log.warn("JSONException: " + e.getMessage());
+ e.printStackTrace();
+ }
+ if (receivedPrefix == null) {
+ continue;
+ }
+
+ // check if the announced network address is inside our subnet
+ if (monitoredPrefix.contains(receivedPrefix)) {
+ JSONArray path = null;
+ try {
+ path = tmp.getJSONArray("path");
+ } catch (JSONException e) {
+ log.warn("JSONException: " + e.getMessage());
+ e.printStackTrace();
+ }
+ if (path == null) {
+ continue;
+ }
+
+ int state = prefix.checkPath(path);
+ if (state >= 100) {
+ log.warn("BGP Hijack detected of type " +
+ (state - 100) + "\n" + tmp.toString());
+ DataHandler.Serializer.writeHijack(tmp);
+ // can only de-aggregate /23 subnets and higher
+ int cidr = receivedPrefix.prefixLength();
+ if (receivedPrefix.prefixLength() < 24) {
+ byte[] octets = receivedPrefix.address().toOctets();
+ int byteGroup = (cidr + 1) / 8,
+ bitPos = 8 - (cidr + 1) % 8;
+
+ octets[byteGroup] = (byte) (octets[byteGroup] & ~(1 << bitPos));
+ String low = IpPrefix.valueOf(IpAddress.Version.INET, octets, cidr + 1).toString();
+ octets[byteGroup] = (byte) (octets[byteGroup] | (1 << bitPos));
+ String high = IpPrefix.valueOf(IpAddress.Version.INET, octets, cidr + 1).toString();
+
+ String[] prefixes = {low, high};
+ bgpSpeakers.forEach(bgpSpeakers -> bgpSpeakers.announceSubPrefixes(prefixes));
+ } else {
+ log.warn("Cannot announce smaller prefix than /24");
+ }
+ }
+ }
+ }
+ });
+ }
+
+ public Set<ArtemisConfig.ArtemisPrefixes> getPrefixes() {
+ return prefixes;
+ }
+
+ public void setPrefixes(Set<ArtemisConfig.ArtemisPrefixes> prefixes) {
+ this.prefixes = prefixes;
+ }
+}
\ No newline at end of file
diff --git a/apps/artemis/src/main/java/org/onosproject/artemis/impl/PrefixHandler.java b/apps/artemis/src/main/java/org/onosproject/artemis/impl/PrefixHandler.java
new file mode 100644
index 0000000..a334e4e
--- /dev/null
+++ b/apps/artemis/src/main/java/org/onosproject/artemis/impl/PrefixHandler.java
@@ -0,0 +1,136 @@
+/*
+ * Copyright 2016-present 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.artemis.impl;
+
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
+import org.onlab.packet.IpPrefix;
+import org.onosproject.artemis.impl.monitors.ExaBgpMonitor;
+import org.onosproject.artemis.impl.monitors.Monitor;
+import org.onosproject.artemis.impl.monitors.RipeMonitor;
+
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+
+/**
+ * Handler of monitoring step for each different prefix.
+ * This class contains all the running monitors of the specified prefix.
+ */
+class PrefixHandler {
+
+ private IpPrefix prefix;
+ private Set<Monitor> prefixMonitors = Sets.newHashSet();
+
+ /**
+ * Constructor that takes a CIDR-notation string and a list of monitors.
+ *
+ * @param prefix A CIDR-notation string, e.g. "192.168.0.1/24"
+ * @param monitors A map of strings to a set of string for monitors, e.g. "ripe", ["host1","host2",..]
+ */
+ PrefixHandler(IpPrefix prefix, Map<String, Set<String>> monitors) {
+ this.prefix = prefix;
+
+ monitors.forEach((type, values) -> {
+ if (type.equals(Monitor.Types.RIPE.toString())) {
+ values.forEach(host -> prefixMonitors.add(new RipeMonitor(prefix, host)));
+ } else if (type.equals(Monitor.Types.EXABGP.toString())) {
+ values.forEach(host -> prefixMonitors.add(new ExaBgpMonitor(prefix, host)));
+ }
+ });
+ }
+
+ /**
+ * Start all monitors for this prefix.
+ */
+ void startPrefixMonitors() {
+ prefixMonitors.forEach(Monitor::startMonitor);
+ }
+
+ /**
+ * Stop all monitors for this prefix.
+ */
+ void stopPrefixMonitors() {
+ prefixMonitors.forEach(Monitor::stopMonitor);
+ }
+
+ /**
+ * Return a CIDR-notation string of prefix.
+ *
+ * @return the prefix in CIDR-notation
+ */
+ IpPrefix getPrefix() {
+ return prefix;
+ }
+
+ /**
+ * Changes the monitors based on the new list given.
+ *
+ * @param newMonitors monitors to be added
+ */
+ void changeMonitors(Map<String, Set<String>> newMonitors) {
+ Set<String> newTypes = newMonitors.keySet();
+ Set<Monitor> monToRemove = Sets.newHashSet();
+ Map<String, Set<String>> monToAdd = Maps.newHashMap(newMonitors);
+
+ prefixMonitors.forEach(monitor -> {
+ String oldType = monitor.getType().toString();
+ if (newTypes.contains(oldType)) {
+ Set<String> newHosts = newMonitors.get(oldType);
+ String oldHost = monitor.getHost();
+ if (newHosts.contains(oldHost)) {
+ monToAdd.remove(oldHost, oldHost);
+ } else {
+ monToRemove.add(monitor);
+ }
+ } else {
+ monToRemove.add(monitor);
+ }
+ });
+
+ monToRemove.forEach(Monitor::stopMonitor);
+ prefixMonitors.removeAll(monToRemove);
+
+ //TODO
+ monToAdd.forEach((type, values) -> {
+ if (type.equals(Monitor.Types.RIPE.toString())) {
+ values.forEach(host -> prefixMonitors.add(new RipeMonitor(prefix, host)));
+ } else if (type.equals(Monitor.Types.EXABGP.toString())) {
+ values.forEach(host -> prefixMonitors.add(new ExaBgpMonitor(prefix, host)));
+ }
+ });
+
+ startPrefixMonitors();
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hashCode(prefix);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj instanceof PrefixHandler) {
+ final PrefixHandler that = (PrefixHandler) obj;
+ return Objects.equals(this.prefix, that.prefix);
+ }
+ return false;
+ }
+
+}
diff --git a/apps/artemis/src/main/java/org/onosproject/artemis/impl/bgpspeakers/BgpSpeakers.java b/apps/artemis/src/main/java/org/onosproject/artemis/impl/bgpspeakers/BgpSpeakers.java
new file mode 100644
index 0000000..0677b08
--- /dev/null
+++ b/apps/artemis/src/main/java/org/onosproject/artemis/impl/bgpspeakers/BgpSpeakers.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright 2016-present 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.artemis.impl.bgpspeakers;
+
+import org.onosproject.routing.bgp.BgpInfoService;
+import org.onosproject.routing.bgp.BgpSession;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Collection;
+
+/**
+ * Abstract class for all the types of BGP Speakers.
+ */
+public abstract class BgpSpeakers {
+
+ final Logger log = LoggerFactory.getLogger(getClass());
+ Collection<BgpSession> bgpSessions;
+
+ BgpSpeakers(BgpInfoService bgpInfoService) {
+ this.bgpSessions = bgpInfoService.getBgpSessions();
+ }
+
+ /**
+ * Abstract function which announces the two new subprefixes on the BGP Speaker.
+ * @param prefixes list of two prefixes
+ */
+ public abstract void announceSubPrefixes(String[] prefixes);
+}
diff --git a/apps/artemis/src/main/java/org/onosproject/artemis/impl/bgpspeakers/QuaggaBgpSpeakers.java b/apps/artemis/src/main/java/org/onosproject/artemis/impl/bgpspeakers/QuaggaBgpSpeakers.java
new file mode 100644
index 0000000..30a0022
--- /dev/null
+++ b/apps/artemis/src/main/java/org/onosproject/artemis/impl/bgpspeakers/QuaggaBgpSpeakers.java
@@ -0,0 +1,137 @@
+/*
+ * Copyright 2016-present 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.artemis.impl.bgpspeakers;
+
+import org.apache.commons.net.telnet.TelnetClient;
+import org.onosproject.routing.bgp.BgpInfoService;
+
+import java.io.InputStream;
+import java.io.PrintStream;
+import java.util.Arrays;
+
+/**
+ * Quagga interface to connect and announce prefixes.
+ */
+public class QuaggaBgpSpeakers extends BgpSpeakers {
+ private static final String PASSWORD = "sdnip";
+
+ private TelnetClient telnet = new TelnetClient();
+ private InputStream in;
+ private PrintStream out;
+
+ public QuaggaBgpSpeakers(BgpInfoService bgpInfoService) {
+ super(bgpInfoService);
+ }
+
+ @Override
+ public void announceSubPrefixes(String[] prefixes) {
+ bgpSessions.forEach((session) -> {
+ String peerIp = session.remoteInfo().ip4Address().toString(),
+ localAs = String.valueOf(session.remoteInfo().as4Number());
+ assert peerIp != null;
+
+ try {
+ telnet.connect(peerIp, 2605);
+ in = telnet.getInputStream();
+ out = new PrintStream(telnet.getOutputStream());
+
+ readUntil("Password: ");
+ write(PASSWORD);
+ readUntil("> ");
+
+ // we user remote AS as local because he is iBGP neighbor.
+ announcePrefix(prefixes, localAs);
+
+ disconnect();
+
+ log.info("Announced " + prefixes[0] + " and " + prefixes[1] + " at " + peerIp);
+ } catch (Exception e) {
+ log.warn(e.getMessage());
+ }
+ });
+ }
+
+ /**
+ * Read telnet buffer until a pattern is met.
+ *
+ * @param pattern string pattern to match in terminal
+ * @return matched string
+ */
+ private String readUntil(String pattern) {
+ try {
+ char lastChar = pattern.charAt(pattern.length() - 1);
+ StringBuffer sb = new StringBuffer();
+ char ch = (char) in.read();
+ while (true) {
+ sb.append(ch);
+ if (ch == lastChar) {
+ if (sb.toString().endsWith(pattern)) {
+ return sb.toString();
+ }
+ }
+ ch = (char) in.read();
+ }
+ } catch (Exception e) {
+ log.warn(e.getMessage());
+ }
+ return null;
+ }
+
+ /**
+ * Write to the telnet client.
+ *
+ * @param value string to write
+ */
+ private void write(String value) {
+ try {
+ out.println(value);
+ out.flush();
+ } catch (Exception e) {
+ log.warn(e.getMessage());
+ }
+ }
+
+ /**
+ * Configure terminal and announce prefix inside the Quagga router.
+ *
+ * @param prefixes prefixes to announce
+ * @param localAs ASN of BGP Speaker
+ */
+ private void announcePrefix(String[] prefixes, String localAs) {
+ write("en");
+ readUntil("# ");
+ write("configure terminal");
+ readUntil("(config)# ");
+ write("router bgp " + localAs);
+ readUntil("(config-router)# ");
+ Arrays.stream(prefixes).forEach((prefix) -> {
+ write("network " + prefix);
+ readUntil("(config-router)# ");
+ });
+ write("end");
+ }
+
+ /**
+ * Disconnect from the telnet session.
+ */
+ private void disconnect() {
+ try {
+ telnet.disconnect();
+ } catch (Exception e) {
+ log.warn(e.getMessage());
+ }
+ }
+}
diff --git a/apps/artemis/src/main/java/org/onosproject/artemis/impl/bgpspeakers/package-info.java b/apps/artemis/src/main/java/org/onosproject/artemis/impl/bgpspeakers/package-info.java
new file mode 100644
index 0000000..bd12a31
--- /dev/null
+++ b/apps/artemis/src/main/java/org/onosproject/artemis/impl/bgpspeakers/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2016-present 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.
+ */
+
+/**
+ * BGP Speakers.
+ */
+package org.onosproject.artemis.impl.bgpspeakers;
\ No newline at end of file
diff --git a/apps/artemis/src/main/java/org/onosproject/artemis/impl/monitors/ExaBgpMonitor.java b/apps/artemis/src/main/java/org/onosproject/artemis/impl/monitors/ExaBgpMonitor.java
new file mode 100644
index 0000000..fbf5d27
--- /dev/null
+++ b/apps/artemis/src/main/java/org/onosproject/artemis/impl/monitors/ExaBgpMonitor.java
@@ -0,0 +1,160 @@
+/*
+ * Copyright 2016-present 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.artemis.impl.monitors;
+
+import io.socket.client.IO;
+import io.socket.client.Socket;
+import org.json.JSONException;
+import org.json.JSONObject;
+import org.onlab.packet.IpPrefix;
+import org.onosproject.artemis.impl.ArtemisManager;
+import org.onosproject.artemis.impl.DataHandler;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.net.URISyntaxException;
+import java.util.Objects;
+
+/**
+ * Implementation of ExaBGP Route Collector Monitor.
+ */
+public class ExaBgpMonitor extends Monitor {
+ private String host;
+ private Socket socket;
+
+ private final Logger log = LoggerFactory.getLogger(getClass());
+
+ public ExaBgpMonitor(IpPrefix prefix, String host) {
+ super(prefix);
+ this.host = host;
+ }
+
+ /**
+ * socket.io onConnect event handler.
+ */
+ private void onConnect() {
+ try {
+ JSONObject parameters = new JSONObject();
+ parameters.put("prefix", this.prefix);
+
+ socket.emit("exa_subscribe", parameters);
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+ }
+
+ private void onExaMessage(Object[] args) {
+ JSONObject message = (JSONObject) args[0];
+
+ try {
+ if (message.getString("type").equals("A")) {
+ // Write BGP message to a json database
+ DataHandler.Serializer.writeData(args[0]);
+
+ if (ArtemisManager.logging) {
+ log.info(message.toString());
+ }
+
+ // Example of BGP Update message:
+ // {
+ // "path":[65001],
+ // "peer":"1.1.1.1",
+ // "prefix":"12.0.0.0/8",
+ // "host":"exabgp", <-- Can put IP here
+ // "type":"A",
+ // "timestamp":1488120484
+ // }
+
+ // We want to keep only prefix and path in memory.
+ message.remove("peer");
+ message.remove("host");
+ message.remove("type");
+ message.remove("timestamp");
+
+ // Append synchronized message to message list in memory.
+ DataHandler.getInstance().appendData(message);
+ }
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Override
+ public void startMonitor() {
+ if (!isRunning()) {
+ log.info("Starting EXA monitor for " + prefix + " / " + host);
+ try {
+ this.socket = IO.socket("http://" + this.host + "/onos");
+ this.socket.on(Socket.EVENT_CONNECT, args -> onConnect());
+ this.socket.on(Socket.EVENT_PING, args -> socket.emit("pong"));
+ this.socket.on("exa_message", this::onExaMessage);
+ } catch (URISyntaxException e) {
+ e.printStackTrace();
+ }
+ this.socket.connect();
+ }
+ }
+
+ @Override
+ public void stopMonitor() {
+ if (isRunning()) {
+ log.info("Stopping EXA monitor for " + prefix + " / " + host);
+ this.socket.off();
+ this.socket.disconnect();
+ this.socket.close();
+ this.socket = null;
+ }
+ }
+
+ @Override
+ public Types getType() {
+ return Types.EXABGP;
+ }
+
+ @Override
+ public boolean isRunning() {
+ return this.socket != null;
+ }
+
+ @Override
+ public String getHost() {
+ return host;
+ }
+
+ @Override
+ public void setHost(String host) {
+ this.host = host;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(prefix, host);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj instanceof ExaBgpMonitor) {
+ final ExaBgpMonitor that = (ExaBgpMonitor) obj;
+ return Objects.equals(this.prefix, that.prefix) &&
+ Objects.equals(this.host, that.host);
+ }
+ return false;
+ }
+
+}
diff --git a/apps/artemis/src/main/java/org/onosproject/artemis/impl/monitors/Monitor.java b/apps/artemis/src/main/java/org/onosproject/artemis/impl/monitors/Monitor.java
new file mode 100644
index 0000000..f93de3c
--- /dev/null
+++ b/apps/artemis/src/main/java/org/onosproject/artemis/impl/monitors/Monitor.java
@@ -0,0 +1,102 @@
+/*
+ * Copyright 2016-present 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.artemis.impl.monitors;
+
+import org.onlab.packet.IpPrefix;
+
+/**
+ * Abstract class for Monitors.
+ */
+public abstract class Monitor {
+ /**
+ * Match enum type with monitor type inside configuration to map them.
+ */
+ public enum Types {
+ RIPE {
+ @Override
+ public String toString() {
+ return "ripe";
+ }
+ },
+ EXABGP {
+ @Override
+ public String toString() {
+ return "exabgp";
+ }
+ }
+ }
+
+ IpPrefix prefix;
+ Monitor(IpPrefix prefix) {
+ this.prefix = prefix;
+ }
+
+ /**
+ * Get prefix of the specific monitor.
+ *
+ * @return prefix
+ */
+ public IpPrefix getPrefix() {
+ return prefix;
+ }
+
+ /**
+ * Set prefix for monitor.
+ *
+ * @param prefix prefix
+ */
+ public void setPrefix(IpPrefix prefix) {
+ this.prefix = prefix;
+ }
+
+ /**
+ * Start monitor to begin capturing incoming BGP packets.
+ */
+ public abstract void startMonitor();
+
+ /**
+ * Stop monitor from capturing incoming BGP packets.
+ */
+ public abstract void stopMonitor();
+
+ /**
+ * Get type of monitor.
+ *
+ * @return enum type
+ */
+ public abstract Types getType();
+
+ /**
+ * Check if monitor is running.
+ *
+ * @return true if running
+ */
+ public abstract boolean isRunning();
+
+ /**
+ * Get host alias e.g. IP address, name.
+ *
+ * @return host alias
+ */
+ public abstract String getHost();
+
+ /**
+ * Set alias of host.
+ *
+ * @param host alias
+ */
+ public abstract void setHost(String host);
+}
diff --git a/apps/artemis/src/main/java/org/onosproject/artemis/impl/monitors/RipeMonitor.java b/apps/artemis/src/main/java/org/onosproject/artemis/impl/monitors/RipeMonitor.java
new file mode 100644
index 0000000..e121c10
--- /dev/null
+++ b/apps/artemis/src/main/java/org/onosproject/artemis/impl/monitors/RipeMonitor.java
@@ -0,0 +1,181 @@
+/*
+ * Copyright 2016-present 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.artemis.impl.monitors;
+
+import io.socket.client.IO;
+import io.socket.client.Socket;
+import org.json.JSONException;
+import org.json.JSONObject;
+import org.onlab.packet.IpPrefix;
+import org.onosproject.artemis.impl.ArtemisManager;
+import org.onosproject.artemis.impl.DataHandler;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.net.URISyntaxException;
+import java.util.Objects;
+
+/**
+ * Implementation of RIPE Route Collector Monitor.
+ */
+public class RipeMonitor extends Monitor {
+ private String host;
+ private Socket socket;
+
+ private final Logger log = LoggerFactory.getLogger(getClass());
+
+ public RipeMonitor(IpPrefix prefix, String host) {
+ super(prefix);
+ this.host = host;
+ }
+
+ /**
+ * socket.io onConnect event handler.
+ */
+ private void onConnect() {
+ try {
+ socket.emit("ping");
+
+ JSONObject parameters = new JSONObject();
+ parameters.put("origin", (Object) null);
+ parameters.put("type", (Object) null);
+ parameters.put("moreSpecific", true);
+ parameters.put("lessSpecific", false);
+ parameters.put("peer", (Object) null);
+ parameters.put("host", this.host);
+ parameters.put("prefix", this.prefix);
+
+ socket.emit("ris_subscribe", parameters);
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * socket.io onRisMessage event handler.
+ * This event is custom made that triggers when it receives an BGP update/withdraw for our prefix.
+ *
+ * @param args RIS message
+ */
+ private void onRisMessage(Object[] args) {
+ try {
+ JSONObject message = (JSONObject) args[0];
+ if (message.getString("type").equals("A")) {
+ // Write BGP message to a json database
+ DataHandler.Serializer.writeData(args[0]);
+
+ if (ArtemisManager.logging) {
+ log.info(message.toString());
+ }
+
+ // Example of BGP Update message:
+ // {
+ // "timestamp":1488044022.97,
+ // "prefix":"101.1.46.0/24",
+ // "host":"rrc21",
+ // "next_hop":"37.49.236.246",
+ // "peer":"37.49.236.246",
+ // "path":[2613,25091,9318,9524],
+ // "type":"A"
+ // }
+
+ // We want to keep only prefix and path in memory.
+ message.remove("community");
+ message.remove("timestamp");
+ message.remove("next_hop");
+ message.remove("peer");
+ message.remove("type");
+ message.remove("host");
+
+ // Append synchronized message to message list in memory.
+ DataHandler.getInstance().appendData(message);
+ }
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+ socket.emit("ping");
+ }
+
+ @Override
+ public void startMonitor() {
+ if (!isRunning()) {
+ log.info("Starting RIPE monitor for " + prefix + " / " + host);
+ IO.Options opts = new IO.Options();
+ opts.path = "/stream/socket.io/";
+
+ try {
+ this.socket = IO.socket("http://stream-dev.ris.ripe.net/", opts);
+ this.socket.on(Socket.EVENT_CONNECT, args -> onConnect());
+ this.socket.on(Socket.EVENT_PONG, args -> socket.emit("ping"));
+ this.socket.on("ris_message", this::onRisMessage);
+ } catch (URISyntaxException e) {
+ e.printStackTrace();
+ }
+
+ this.socket.connect();
+ }
+ }
+
+ @Override
+ public void stopMonitor() {
+ if (isRunning()) {
+ log.info("Stopping RIPE monitor for " + prefix + " / " + host);
+ this.socket.off();
+ this.socket.disconnect();
+ this.socket.close();
+ this.socket = null;
+ }
+ }
+
+ @Override
+ public Types getType() {
+ return Types.RIPE;
+ }
+
+ @Override
+ public boolean isRunning() {
+ return this.socket != null;
+ }
+
+ @Override
+ public String getHost() {
+ return host;
+ }
+
+ @Override
+ public void setHost(String host) {
+ this.host = host;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(prefix, host);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj instanceof RipeMonitor) {
+ final RipeMonitor that = (RipeMonitor) obj;
+ return Objects.equals(this.prefix, that.prefix) &&
+ Objects.equals(this.host, that.host);
+ }
+ return false;
+ }
+
+}
diff --git a/apps/artemis/src/main/java/org/onosproject/artemis/impl/monitors/package-info.java b/apps/artemis/src/main/java/org/onosproject/artemis/impl/monitors/package-info.java
new file mode 100644
index 0000000..aa8ded7
--- /dev/null
+++ b/apps/artemis/src/main/java/org/onosproject/artemis/impl/monitors/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2016-present 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.
+ */
+
+/**
+ * Route Collector Monitors.
+ */
+package org.onosproject.artemis.impl.monitors;
\ No newline at end of file
diff --git a/apps/artemis/src/main/java/org/onosproject/artemis/impl/package-info.java b/apps/artemis/src/main/java/org/onosproject/artemis/impl/package-info.java
new file mode 100755
index 0000000..6445f38
--- /dev/null
+++ b/apps/artemis/src/main/java/org/onosproject/artemis/impl/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2016-present 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.
+ */
+
+/**
+ * Artemis component.
+ */
+package org.onosproject.artemis.impl;
\ No newline at end of file
diff --git a/apps/artemis/src/main/resources/OSGI-INF/blueprint/shell-config.xml b/apps/artemis/src/main/resources/OSGI-INF/blueprint/shell-config.xml
new file mode 100755
index 0000000..9f9666a
--- /dev/null
+++ b/apps/artemis/src/main/resources/OSGI-INF/blueprint/shell-config.xml
@@ -0,0 +1,24 @@
+<!--
+ ~ 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.artemis.cli.LogOptionsCommand"/>
+ </command>
+ </command-bundle>
+
+</blueprint>