ONOS-5457 OFAgent - handle FLOW_MOD controller to switch command message

Change-Id: I6c5328f9cb32cf77a4e8dfa7aea6ede518602af6
diff --git a/apps/ofagent/BUCK b/apps/ofagent/BUCK
index e32808e..0d28fca 100644
--- a/apps/ofagent/BUCK
+++ b/apps/ofagent/BUCK
@@ -15,6 +15,12 @@
     '//lib:openflowj',
     '//lib:javax.ws.rs-api',
     '//utils/rest:onlab-rest',
+    '//providers/openflow/flow:onos-providers-openflow-flow',
+]
+
+BUNDLES = [
+    '//apps/ofagent:onos-apps-ofagent',
+    '//providers/openflow/flow:onos-providers-openflow-flow',
 ]
 
 TEST_DEPS = [
@@ -41,5 +47,6 @@
     title = 'OpenFlow Agent',
     category = 'Traffic Steering',
     url = 'http://onosproject.org',
+    included_bundles = BUNDLES,
     description = 'OpenFlow agent application for virtualization subsystem.',
 )
diff --git a/apps/ofagent/pom.xml b/apps/ofagent/pom.xml
index a3590e9..76fb852 100644
--- a/apps/ofagent/pom.xml
+++ b/apps/ofagent/pom.xml
@@ -172,6 +172,13 @@
             <scope>test</scope>
         </dependency>
 
+        <!-- Flow Entry building dependencies -->
+        <dependency>
+            <groupId>org.onosproject</groupId>
+            <artifactId>onos-providers-openflow-flow</artifactId>
+            <version>${project.version}</version>
+        </dependency>
+
     </dependencies>
 
     <build>
@@ -191,6 +198,9 @@
                             *,org.glassfish.jersey.servlet
                         </Import-Package>
                         <Web-ContextPath>${web.context}</Web-ContextPath>
+                        <Private-Package>
+                            org.onosproject.provider.of.flow.util
+                        </Private-Package>
                     </instructions>
                 </configuration>
             </plugin>
diff --git a/apps/ofagent/src/main/java/org/onosproject/ofagent/impl/DefaultOFSwitch.java b/apps/ofagent/src/main/java/org/onosproject/ofagent/impl/DefaultOFSwitch.java
index 3f4f878..f06446a 100644
--- a/apps/ofagent/src/main/java/org/onosproject/ofagent/impl/DefaultOFSwitch.java
+++ b/apps/ofagent/src/main/java/org/onosproject/ofagent/impl/DefaultOFSwitch.java
@@ -20,13 +20,16 @@
 import io.netty.channel.Channel;
 import org.onlab.osgi.ServiceDirectory;
 import org.onosproject.incubator.net.virtual.NetworkId;
+import org.onosproject.incubator.net.virtual.VirtualNetworkService;
 import org.onosproject.net.ConnectPoint;
 import org.onosproject.net.DeviceId;
 import org.onosproject.net.Port;
 import org.onosproject.net.PortNumber;
 import org.onosproject.net.device.PortStatistics;
+import org.onosproject.net.driver.DriverService;
 import org.onosproject.net.flow.FlowEntry;
 import org.onosproject.net.flow.FlowRule;
+import org.onosproject.net.flow.FlowRuleService;
 import org.onosproject.net.flow.TableStatisticsEntry;
 import org.onosproject.net.group.Group;
 import org.onosproject.net.packet.InboundPacket;
@@ -34,6 +37,7 @@
 import org.onosproject.ofagent.api.OFSwitchCapabilities;
 import org.onosproject.ofagent.api.OFSwitchService;
 import org.projectfloodlight.openflow.protocol.OFActionType;
+import org.projectfloodlight.openflow.protocol.OFBadRequestCode;
 import org.projectfloodlight.openflow.protocol.OFBarrierReply;
 import org.projectfloodlight.openflow.protocol.OFBucket;
 import org.projectfloodlight.openflow.protocol.OFBucketCounter;
@@ -43,6 +47,7 @@
 import org.projectfloodlight.openflow.protocol.OFFactories;
 import org.projectfloodlight.openflow.protocol.OFFactory;
 import org.projectfloodlight.openflow.protocol.OFFeaturesReply;
+import org.projectfloodlight.openflow.protocol.OFFlowMod;
 import org.projectfloodlight.openflow.protocol.OFFlowStatsEntry;
 import org.projectfloodlight.openflow.protocol.OFGetConfigReply;
 import org.projectfloodlight.openflow.protocol.OFGroupDescStatsEntry;
@@ -55,6 +60,7 @@
 import org.projectfloodlight.openflow.protocol.OFPacketInReason;
 import org.projectfloodlight.openflow.protocol.OFPacketOut;
 import org.projectfloodlight.openflow.protocol.OFPortDesc;
+import org.projectfloodlight.openflow.protocol.OFPortMod;
 import org.projectfloodlight.openflow.protocol.OFPortReason;
 import org.projectfloodlight.openflow.protocol.OFPortStatsEntry;
 import org.projectfloodlight.openflow.protocol.OFPortStatsRequest;
@@ -69,6 +75,7 @@
 import org.projectfloodlight.openflow.protocol.OFVersion;
 import org.projectfloodlight.openflow.protocol.action.OFAction;
 import org.projectfloodlight.openflow.protocol.action.OFActionOutput;
+import org.projectfloodlight.openflow.protocol.errormsg.OFBadRequestErrorMsg;
 import org.projectfloodlight.openflow.protocol.instruction.OFInstruction;
 import org.projectfloodlight.openflow.protocol.match.Match;
 import org.projectfloodlight.openflow.protocol.match.MatchField;
@@ -103,6 +110,8 @@
     private final Logger log;
 
     private final OFSwitchService ofSwitchService;
+    private final FlowRuleService flowRuleService;
+    private final DriverService driverService;
 
     private final DatapathId dpId;
     private final OFSwitchCapabilities capabilities;
@@ -121,12 +130,15 @@
 
     private DefaultOFSwitch(DatapathId dpid, OFSwitchCapabilities capabilities,
                             NetworkId networkId, DeviceId deviceId,
-                            OFSwitchService ofSwitchService) {
+                            ServiceDirectory serviceDirectory) {
         this.dpId = dpid;
         this.capabilities = capabilities;
         this.networkId = networkId;
         this.deviceId = deviceId;
-        this.ofSwitchService = ofSwitchService;
+        this.ofSwitchService = serviceDirectory.get(OFSwitchService.class);
+        this.driverService = serviceDirectory.get(DriverService.class);
+        VirtualNetworkService virtualNetworkService = serviceDirectory.get(VirtualNetworkService.class);
+        this.flowRuleService = virtualNetworkService.get(networkId, FlowRuleService.class);
         log = LoggerFactory.getLogger(getClass().getName() + " : " + dpid);
     }
 
@@ -135,8 +147,7 @@
                                      ServiceDirectory serviceDirectory) {
         checkNotNull(dpid, "DPID cannot be null");
         checkNotNull(capabilities, "OF capabilities cannot be null");
-        return new DefaultOFSwitch(dpid, capabilities, networkId, deviceId,
-                                   serviceDirectory.get(OFSwitchService.class));
+        return new DefaultOFSwitch(dpid, capabilities, networkId, deviceId, serviceDirectory);
     }
 
     @Override
@@ -224,10 +235,53 @@
         log.debug("processPacketIn: Functionality not yet supported for {}", packet);
     }
 
+    private void processPortMod(OFPortMod portMod) {
+//        PortNumber portNumber = PortNumber.portNumber(portMod.getPortNo().getPortNumber());
+        log.debug("processPortMod: {} not yet supported for {}",
+                  portMod.getType(), portMod);
+    }
+
+    private void processFlowMod(OFFlowMod flowMod) {
+        // convert OFFlowMod to FLowRule object
+        OFAgentVirtualFlowEntryBuilder flowEntryBuilder =
+                new OFAgentVirtualFlowEntryBuilder(deviceId, flowMod, driverService);
+        FlowEntry flowEntry = flowEntryBuilder.build();
+        flowRuleService.applyFlowRules(flowEntry);
+    }
+
     @Override
     public void processControllerCommand(Channel channel, OFMessage msg) {
-        // TODO process controller command
-        log.debug("processControllerCommand: Functionality not yet supported for {}", msg);
+
+        OFControllerRole myRole = role(channel);
+        if (OFControllerRole.ROLE_SLAVE.equals(myRole)) {
+            OFBadRequestErrorMsg errorMsg = FACTORY.errorMsgs()
+                    .buildBadRequestErrorMsg()
+                    .setXid(msg.getXid())
+                    .setCode(OFBadRequestCode.IS_SLAVE)
+                    .build();
+            channel.writeAndFlush(Collections.singletonList(errorMsg));
+            return;
+        }
+
+        switch (msg.getType()) {
+            case PORT_MOD:
+                OFPortMod portMod = (OFPortMod) msg;
+                processPortMod(portMod);
+                break;
+            case FLOW_MOD:
+                OFFlowMod flowMod = (OFFlowMod) msg;
+                processFlowMod(flowMod);
+                break;
+            case GROUP_MOD:
+            case METER_MOD:
+            case TABLE_MOD:
+                log.debug("processControllerCommand: {} not yet supported for {}",
+                          msg.getType(), msg);
+                break;
+            default:
+                log.warn("Unexpected message {} received for switch {}",
+                         msg.getType(), this);
+        }
     }
 
     private void sendPortStatus(Port port, OFPortReason ofPortReason) {
diff --git a/apps/ofagent/src/main/java/org/onosproject/ofagent/impl/OFAgentVirtualFlowEntryBuilder.java b/apps/ofagent/src/main/java/org/onosproject/ofagent/impl/OFAgentVirtualFlowEntryBuilder.java
new file mode 100644
index 0000000..e3cb9e3
--- /dev/null
+++ b/apps/ofagent/src/main/java/org/onosproject/ofagent/impl/OFAgentVirtualFlowEntryBuilder.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright 2017-present Open Networking Foundation
+ *
+ * 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.ofagent.impl;
+
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.driver.DefaultDriverData;
+import org.onosproject.net.driver.DefaultDriverHandler;
+import org.onosproject.net.driver.Driver;
+import org.onosproject.net.driver.DriverHandler;
+import org.onosproject.net.driver.DriverService;
+import org.onosproject.provider.of.flow.util.FlowEntryBuilder;
+import org.projectfloodlight.openflow.protocol.OFFlowMod;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+// FlowEntryBuilder customized for OFAgent.  This builder will be used to build FlowEntry objects for
+// virtual devices encountered by OFAgent.  The driver has been hardcoded to "ovs".
+public class OFAgentVirtualFlowEntryBuilder extends FlowEntryBuilder {
+    private static final Logger log = LoggerFactory.getLogger(OFAgentVirtualFlowEntryBuilder.class);
+    private static final String DRIVER_NAME = "ovs";
+
+    private final DriverService driverService;
+
+    public OFAgentVirtualFlowEntryBuilder(DeviceId deviceId, OFFlowMod fm, DriverService driverService) {
+        super(deviceId, fm, driverService);
+        this.driverService = driverService;
+    }
+
+    protected DriverHandler getDriver(DeviceId devId) {
+        log.debug("calling getDriver for {}", devId);
+        Driver driver = driverService.getDriver(DRIVER_NAME);
+        DriverHandler handler = new DefaultDriverHandler(new DefaultDriverData(driver, devId));
+        return handler;
+    }
+}
diff --git a/apps/ofagent/src/main/java/org/onosproject/ofagent/impl/OFChannelHandler.java b/apps/ofagent/src/main/java/org/onosproject/ofagent/impl/OFChannelHandler.java
index aea97d1..ddfadc2 100644
--- a/apps/ofagent/src/main/java/org/onosproject/ofagent/impl/OFChannelHandler.java
+++ b/apps/ofagent/src/main/java/org/onosproject/ofagent/impl/OFChannelHandler.java
@@ -128,6 +128,13 @@
                         // TODO: check if this is lldp - ignore if it is not lldp
                         handler.ofSwitch.processLldp(handler.channel, msg);
                         break;
+                    case FLOW_MOD:
+                    case PORT_MOD:
+                    case GROUP_MOD:
+                    case METER_MOD:
+                    case TABLE_MOD:
+                        handler.ofSwitch.processControllerCommand(handler.channel, msg);
+                        break;
                     case ERROR:
                         handler.logErrorClose((OFErrorMsg) msg);
                         break;