Implemented control plane redirect for control traffic.

Modified SoftRouterPipeline to support new flow objectives.

Change-Id: Ia93bc927832444ba1f7cf20b276e4866789c9d30
diff --git a/apps/routing/src/main/java/org/onosproject/routing/impl/ControlPlaneRedirectManager.java b/apps/routing/src/main/java/org/onosproject/routing/impl/ControlPlaneRedirectManager.java
new file mode 100644
index 0000000..c5e7142
--- /dev/null
+++ b/apps/routing/src/main/java/org/onosproject/routing/impl/ControlPlaneRedirectManager.java
@@ -0,0 +1,265 @@
+/*
+ * Copyright 2016 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.routing.impl;
+
+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.onlab.packet.EthType;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreService;
+import org.onosproject.incubator.net.intf.Interface;
+import org.onosproject.incubator.net.intf.InterfaceService;
+import org.onosproject.net.ConnectPoint;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.PortNumber;
+import org.onosproject.net.config.NetworkConfigEvent;
+import org.onosproject.net.config.NetworkConfigListener;
+import org.onosproject.net.config.NetworkConfigService;
+import org.onosproject.net.device.DeviceEvent;
+import org.onosproject.net.device.DeviceListener;
+import org.onosproject.net.device.DeviceService;
+import org.onosproject.net.flow.DefaultTrafficSelector;
+import org.onosproject.net.flow.DefaultTrafficTreatment;
+import org.onosproject.net.flow.TrafficSelector;
+import org.onosproject.net.flow.TrafficTreatment;
+import org.onosproject.net.flowobjective.DefaultForwardingObjective;
+import org.onosproject.net.flowobjective.FlowObjectiveService;
+import org.onosproject.net.flowobjective.ForwardingObjective;
+import org.onosproject.net.host.InterfaceIpAddress;
+import org.onosproject.routing.RoutingService;
+import org.onosproject.routing.config.RouterConfig;
+import org.slf4j.Logger;
+
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * Manages connectivity between peers redirecting control traffic to a routing
+ * control plane available on the dataplane.
+ */
+@Component(immediate = true, enabled = false)
+public class ControlPlaneRedirectManager {
+
+    private final Logger log = getLogger(getClass());
+
+    private static final int PRIORITY = 40001;
+
+    private static final String APP_NAME = "org.onosproject.cpredirect";
+    private ApplicationId appId;
+
+    private ConnectPoint controlPlaneConnectPoint;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected CoreService coreService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected DeviceService deviceService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected InterfaceService interfaceService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected FlowObjectiveService flowObjectiveService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected NetworkConfigService networkConfigService;
+
+    private final InternalDeviceListener deviceListener = new InternalDeviceListener();
+    private final InternalNetworkConfigListener networkConfigListener =
+            new InternalNetworkConfigListener();
+
+    @Activate
+    public void activate() {
+        this.appId = coreService.registerApplication(APP_NAME);
+
+        deviceService.addListener(deviceListener);
+        networkConfigService.addListener(networkConfigListener);
+
+        updateConfig();
+    }
+
+    @Deactivate
+    public void deactivate() {
+        deviceService.removeListener(deviceListener);
+        networkConfigService.removeListener(networkConfigListener);
+    }
+
+    private void updateConfig() {
+        ApplicationId routingAppId =
+                coreService.registerApplication(RoutingService.ROUTER_APP_ID);
+
+        RouterConfig config = networkConfigService.getConfig(
+                routingAppId, RoutingService.ROUTER_CONFIG_CLASS);
+
+        if (config == null) {
+            log.info("Router config not available");
+            return;
+        }
+
+        if (!config.getControlPlaneConnectPoint().equals(controlPlaneConnectPoint)) {
+            this.controlPlaneConnectPoint = config.getControlPlaneConnectPoint();
+        }
+
+        if (controlPlaneConnectPoint != null &&
+                deviceService.isAvailable(controlPlaneConnectPoint.deviceId())) {
+            notifySwitchAvailable();
+        }
+    }
+
+    private void notifySwitchAvailable() {
+        DeviceId deviceId = controlPlaneConnectPoint.deviceId();
+
+        interfaceService.getInterfaces().stream()
+                .filter(intf -> intf.connectPoint().deviceId().equals(deviceId))
+                .forEach(this::addInterfaceForwarding);
+
+        log.info("Sent interface objectives to {}", controlPlaneConnectPoint.deviceId());
+    }
+
+    private void addInterfaceForwarding(Interface intf) {
+        log.debug("Adding interface objectives for {}", intf);
+
+        DeviceId deviceId = controlPlaneConnectPoint.deviceId();
+        PortNumber controlPlanePort = controlPlaneConnectPoint.port();
+
+        for (InterfaceIpAddress ip : intf.ipAddresses()) {
+            // IPv4 to router
+            TrafficSelector toSelector = DefaultTrafficSelector.builder()
+                    .matchInPort(intf.connectPoint().port())
+                    .matchEthDst(intf.mac())
+                    .matchEthType(EthType.EtherType.IPV4.ethType().toShort())
+                    .matchVlanId(intf.vlan())
+                    .matchIPDst(ip.ipAddress().toIpPrefix())
+                    .build();
+
+            TrafficTreatment toTreatment = DefaultTrafficTreatment.builder()
+                    .setOutput(controlPlanePort)
+                    .build();
+
+            flowObjectiveService.forward(deviceId,
+                    buildForwardingObjective(toSelector, toTreatment));
+
+            // IPv4 from router
+            TrafficSelector fromSelector = DefaultTrafficSelector.builder()
+                    .matchInPort(controlPlanePort)
+                    .matchEthSrc(intf.mac())
+                    .matchVlanId(intf.vlan())
+                    .matchEthType(EthType.EtherType.IPV4.ethType().toShort())
+                    .matchIPSrc(ip.ipAddress().toIpPrefix())
+                    .build();
+
+            TrafficTreatment intfTreatment = DefaultTrafficTreatment.builder()
+                    .setOutput(intf.connectPoint().port())
+                    .build();
+
+            flowObjectiveService.forward(deviceId,
+                    buildForwardingObjective(fromSelector, intfTreatment));
+
+
+            // ARP to router
+            toSelector = DefaultTrafficSelector.builder()
+                    .matchInPort(intf.connectPoint().port())
+                    .matchEthType(EthType.EtherType.ARP.ethType().toShort())
+                    .matchVlanId(intf.vlan())
+                    .build();
+
+            toTreatment = DefaultTrafficTreatment.builder()
+                    .setOutput(controlPlanePort)
+                    .punt()
+                    .build();
+
+            flowObjectiveService.forward(deviceId,
+                    buildForwardingObjective(toSelector, toTreatment));
+
+            // ARP from router
+            fromSelector = DefaultTrafficSelector.builder()
+                    .matchInPort(controlPlanePort)
+                    .matchEthSrc(intf.mac())
+                    .matchVlanId(intf.vlan())
+                    .matchEthType(EthType.EtherType.ARP.ethType().toShort())
+                    .build();
+
+            intfTreatment = DefaultTrafficTreatment.builder()
+                    .setOutput(intf.connectPoint().port())
+                    .punt()
+                    .build();
+
+            flowObjectiveService.forward(deviceId,
+                    buildForwardingObjective(fromSelector, intfTreatment));
+        }
+    }
+
+    private ForwardingObjective buildForwardingObjective(TrafficSelector selector,
+                                                         TrafficTreatment treatment) {
+
+        return DefaultForwardingObjective.builder()
+                .withSelector(selector)
+                .withTreatment(treatment)
+                .fromApp(appId)
+                .withPriority(PRIORITY)
+                .withFlag(ForwardingObjective.Flag.VERSATILE)
+                .add();
+    }
+
+    private class InternalDeviceListener implements DeviceListener {
+        @Override
+        public void event(DeviceEvent event) {
+            if (controlPlaneConnectPoint != null &&
+                    event.subject().id().equals(controlPlaneConnectPoint.deviceId())) {
+                switch (event.type()) {
+                case DEVICE_ADDED:
+                case DEVICE_AVAILABILITY_CHANGED:
+                    if (deviceService.isAvailable(event.subject().id())) {
+                        log.info("Device connected {}", event.subject().id());
+                        notifySwitchAvailable();
+                    }
+
+                    break;
+                case DEVICE_UPDATED:
+                case DEVICE_REMOVED:
+                case DEVICE_SUSPENDED:
+                case PORT_ADDED:
+                case PORT_UPDATED:
+                case PORT_REMOVED:
+                default:
+                    break;
+                }
+            }
+        }
+    }
+
+    private class InternalNetworkConfigListener implements NetworkConfigListener {
+        @Override
+        public void event(NetworkConfigEvent event) {
+            if (event.subject().equals(RoutingService.ROUTER_CONFIG_CLASS)) {
+                switch (event.type()) {
+                case CONFIG_ADDED:
+                case CONFIG_UPDATED:
+                    updateConfig();
+                    break;
+                case CONFIG_REGISTERED:
+                case CONFIG_UNREGISTERED:
+                case CONFIG_REMOVED:
+                default:
+                    break;
+                }
+            }
+        }
+    }
+}