added FlowObjectiveService to act as an objective manager between applications and drivers

Change-Id: I4dc44db8bafae8a55b7663895c87b1b08645637f
diff --git a/core/api/src/main/java/org/onosproject/net/behaviour/Pipeliner.java b/core/api/src/main/java/org/onosproject/net/behaviour/Pipeliner.java
index 6d35adf..c4700fc 100644
--- a/core/api/src/main/java/org/onosproject/net/behaviour/Pipeliner.java
+++ b/core/api/src/main/java/org/onosproject/net/behaviour/Pipeliner.java
@@ -17,8 +17,10 @@
 
 import org.onlab.osgi.ServiceDirectory;
 import org.onosproject.net.DeviceId;
+import org.onosproject.net.driver.HandlerBehaviour;
 import org.onosproject.net.flowobjective.FilteringObjective;
 import org.onosproject.net.flowobjective.ForwardingObjective;
+import org.onosproject.net.flowobjective.NextObjective;
 
 import java.util.Collection;
 import java.util.concurrent.Future;
@@ -26,7 +28,7 @@
 /**
  * Behaviour for handling various pipelines.
  */
-public interface Pipeliner {
+public interface Pipeliner extends HandlerBehaviour {
 
     /**
      * Injecting the service directory into the driver.
@@ -39,17 +41,24 @@
     /**
      * Installs the filtering rules onto the device.
      *
-     * @param filters the collection of filters
+     * @param filteringObjectives the collection of filters
      * @return a future indicating the success of the operation
      */
-     Future<Boolean> filter(Collection<FilteringObjective> filters);
+     Future<Boolean> filter(Collection<FilteringObjective> filteringObjectives);
 
     /**
      * Installs the forwarding rules onto the device.
      *
-     * @param forwardings the collection of forwarding objectives
+     * @param forwardObjectives the collection of forwarding objectives
      * @return a future indicating the success of the operation
      */
-    Future<Boolean> forward(Collection<ForwardingObjective> forwardings);
+    Future<Boolean> forward(Collection<ForwardingObjective> forwardObjectives);
 
+    /**
+     * Installs the next hop elements into the device.
+     *
+     * @param nextObjectives the collection of next objectives
+     * @return a future indicating the success of the operation
+     */
+    Future<Boolean> next(Collection<NextObjective> nextObjectives);
 }
diff --git a/core/api/src/main/java/org/onosproject/net/flowobjective/FlowObjectiveService.java b/core/api/src/main/java/org/onosproject/net/flowobjective/FlowObjectiveService.java
new file mode 100644
index 0000000..dc5e5e1
--- /dev/null
+++ b/core/api/src/main/java/org/onosproject/net/flowobjective/FlowObjectiveService.java
@@ -0,0 +1,34 @@
+/*
+ * 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.net.flowobjective;
+
+import org.onosproject.net.DeviceId;
+
+import java.util.Collection;
+import java.util.concurrent.Future;
+
+/**
+ * Created by ash on 07/04/15.
+ */
+public interface FlowObjectiveService {
+
+    Future<Boolean> filter(DeviceId deviceId, Collection<FilteringObjective> filterObjectives);
+
+    Future<Boolean> forward(DeviceId deviceId, Collection<ForwardingObjective> forwardingObjectives);
+
+    Future<Boolean> next(DeviceId deviceId, Collection<NextObjective> nextObjectives);
+
+}
diff --git a/core/net/src/main/java/org/onosproject/net/driver/impl/DriverManager.java b/core/net/src/main/java/org/onosproject/net/driver/impl/DriverManager.java
new file mode 100644
index 0000000..dc9c6aa
--- /dev/null
+++ b/core/net/src/main/java/org/onosproject/net/driver/impl/DriverManager.java
@@ -0,0 +1,121 @@
+/*
+ * 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.net.driver.impl;
+
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Maps;
+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.Service;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.driver.Behaviour;
+import org.onosproject.net.driver.DefaultDriverData;
+import org.onosproject.net.driver.DefaultDriverHandler;
+import org.onosproject.net.driver.Driver;
+import org.onosproject.net.driver.DriverAdminService;
+import org.onosproject.net.driver.DriverData;
+import org.onosproject.net.driver.DriverHandler;
+import org.onosproject.net.driver.DriverProvider;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Map;
+import java.util.Set;
+
+
+@Component(immediate = true)
+@Service
+public class DriverManager implements DriverAdminService {
+
+    private final Logger log = LoggerFactory.getLogger(getClass());
+
+    private Set<DriverProvider> providers = Sets.newConcurrentHashSet();
+    private Map<String, Driver> driverByName = Maps.newConcurrentMap();
+    private Map<String, Driver> driverByKey = Maps.newConcurrentMap();
+
+    @Activate
+    protected void activate() {
+        log.info("Started");
+    }
+
+    @Deactivate
+    protected void deactivate() {
+        log.info("Stopped");
+    }
+
+
+    @Override
+    public Set<DriverProvider> getProviders() {
+        return ImmutableSet.copyOf(providers);
+    }
+
+    @Override
+    public void registerProvider(DriverProvider provider) {
+        provider.getDrivers().forEach(driver -> {
+            driverByName.put(driver.name(), driver);
+            driverByKey.put(key(driver.manufacturer(),
+                                driver.hwVersion(),
+                                driver.swVersion()), driver);
+        });
+        providers.add(provider);
+    }
+
+    @Override
+    public void unregisterProvider(DriverProvider provider) {
+        provider.getDrivers().forEach(driver -> {
+            driverByName.remove(driver.name());
+            driverByKey.remove(key(driver.manufacturer(),
+                                   driver.hwVersion(),
+                                   driver.swVersion()));
+        });
+        providers.remove(provider);
+    }
+
+    @Override
+    public Set<Driver> getDrivers(Class<? extends Behaviour>... withBehaviours) {
+        //TODO
+        return null;
+    }
+
+    @Override
+    public Driver getDriver(String driverName) {
+        //TODO: replace with fallback driver.
+        return driverByName.getOrDefault(driverName, driverByName.get("default"));
+    }
+
+    @Override
+    public Driver getDriver(String mfr, String hw, String sw) {
+        return driverByKey.getOrDefault(key(mfr, hw, sw), driverByName.get("default"));
+    }
+
+    @Override
+    public DriverHandler createHandler(String driverName, DeviceId deviceId, String... credentials) {
+        Driver driver = driverByName.get(driverName);
+        return new DefaultDriverHandler(new DefaultDriverData(driver));
+    }
+
+    @Override
+    public DriverHandler createHandler(DriverData data, DeviceId deviceId, String... credentials) {
+        return null;
+    }
+
+    private String key(String mfr, String hw, String sw) {
+        return String.format("%s-%s-%s", mfr, hw, sw);
+    }
+
+}
diff --git a/core/net/src/main/java/org/onosproject/net/flowobjective/impl/FlowObjectiveManager.java b/core/net/src/main/java/org/onosproject/net/flowobjective/impl/FlowObjectiveManager.java
new file mode 100644
index 0000000..49d9696
--- /dev/null
+++ b/core/net/src/main/java/org/onosproject/net/flowobjective/impl/FlowObjectiveManager.java
@@ -0,0 +1,163 @@
+/*
+ * 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.net.flowobjective.impl;
+
+import com.google.common.collect.Maps;
+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.onlab.osgi.DefaultServiceDirectory;
+import org.onlab.osgi.ServiceDirectory;
+import org.onosproject.cluster.ClusterService;
+import org.onosproject.mastership.MastershipEvent;
+import org.onosproject.mastership.MastershipListener;
+import org.onosproject.mastership.MastershipService;
+import org.onosproject.net.Device;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.behaviour.Pipeliner;
+import org.onosproject.net.device.DeviceService;
+import org.onosproject.net.driver.Driver;
+import org.onosproject.net.driver.DriverHandler;
+import org.onosproject.net.driver.DriverService;
+import org.onosproject.net.flowobjective.FilteringObjective;
+import org.onosproject.net.flowobjective.FlowObjectiveService;
+import org.onosproject.net.flowobjective.ForwardingObjective;
+import org.onosproject.net.flowobjective.NextObjective;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Collection;
+import java.util.Map;
+import java.util.concurrent.Future;
+
+import static com.google.common.base.Preconditions.checkState;
+
+/**
+ * Created by ash on 07/04/15.
+ */
+@Component(immediate = true)
+@Service
+public class FlowObjectiveManager implements FlowObjectiveService {
+
+    private final Logger log = LoggerFactory.getLogger(getClass());
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected DriverService driverService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected DeviceService deviceService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected MastershipService mastershipService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected ClusterService clusterService;
+
+    protected ServiceDirectory serviceDirectory = new DefaultServiceDirectory();
+
+    private MastershipListener mastershipListener = new InnerMastershipListener();
+
+    private Map<DeviceId, DriverHandler> driverHandlers =
+            Maps.newConcurrentMap();
+
+    @Activate
+    protected void activate() {
+        mastershipService.addListener(mastershipListener);
+        log.info("Started");
+    }
+
+    @Deactivate
+    protected void deactivate() {
+        mastershipService.removeListener(mastershipListener);
+        log.info("Stopped");
+    }
+
+    @Override
+    public Future<Boolean> filter(DeviceId deviceId,
+                                  Collection<FilteringObjective> filterObjectives) {
+        DriverHandler handler = driverHandlers.get(deviceId);
+        checkState(handler != null, "Driver not initialized");
+
+        Pipeliner pipe = handler.behaviour(Pipeliner.class);
+
+        return pipe.filter(filterObjectives);
+    }
+
+    @Override
+    public Future<Boolean> forward(DeviceId deviceId,
+                                   Collection<ForwardingObjective> forwardingObjectives) {
+        DriverHandler handler = driverHandlers.get(deviceId);
+        checkState(handler != null, "Driver not initialized");
+
+        Pipeliner pipe = handler.behaviour(Pipeliner.class);
+
+        return pipe.forward(forwardingObjectives);
+    }
+
+    @Override
+    public Future<Boolean> next(DeviceId deviceId,
+                                Collection<NextObjective> nextObjectives) {
+        DriverHandler handler = driverHandlers.get(deviceId);
+        checkState(handler != null, "Driver not initialized");
+
+        Pipeliner pipe = handler.behaviour(Pipeliner.class);
+
+        return pipe.next(nextObjectives);
+    }
+
+    private class InnerMastershipListener implements MastershipListener {
+        @Override
+        public void event(MastershipEvent event) {
+            switch (event.type()) {
+
+                case MASTER_CHANGED:
+                    //TODO: refactor this into a method
+                    if (event.roleInfo().master().equals(
+                            clusterService.getLocalNode().id())) {
+                        DriverHandler handler = lookupDriver(event.subject());
+                        if (handler != null) {
+                            Pipeliner pipe = handler.behaviour(Pipeliner.class);
+                            pipe.init(event.subject(), serviceDirectory);
+                            driverHandlers.put(event.subject(), handler);
+                            log.info("Driver {} bound to device {}",
+                                     handler.data().type().name(), event.subject());
+                        } else {
+                            log.error("No driver for device {}", event.subject());
+                        }
+
+                    }
+
+                    break;
+                case BACKUPS_CHANGED:
+                    break;
+                default:
+                    log.warn("Unknown mastership type {}", event.type());
+            }
+        }
+
+        private DriverHandler lookupDriver(DeviceId deviceId) {
+            Device device = deviceService.getDevice(deviceId);
+
+            Driver driver = driverService.getDriver(device.manufacturer(),
+                                           device.hwVersion(), device.swVersion());
+
+            return driverService.createHandler(driver.name(), deviceId);
+        }
+    }
+}
diff --git a/drivers/pom.xml b/drivers/pom.xml
index a4db521..8538f4a 100644
--- a/drivers/pom.xml
+++ b/drivers/pom.xml
@@ -49,12 +49,21 @@
             <scope>test</scope>
         </dependency>
 
+        <dependency>
+            <groupId>org.apache.felix</groupId>
+            <artifactId>org.apache.felix.scr.annotations</artifactId>
+        </dependency>
+
     </dependencies>
 
     <build>
         <plugins>
             <plugin>
                 <groupId>org.apache.felix</groupId>
+                <artifactId>maven-scr-plugin</artifactId>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
                 <artifactId>maven-bundle-plugin</artifactId>
             </plugin>
 
diff --git a/drivers/src/main/java/org/onosproject/driver/pipeline/DefaultDrivers.java b/drivers/src/main/java/org/onosproject/driver/pipeline/DefaultDrivers.java
new file mode 100644
index 0000000..e42e346
--- /dev/null
+++ b/drivers/src/main/java/org/onosproject/driver/pipeline/DefaultDrivers.java
@@ -0,0 +1,67 @@
+/*
+ * 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.driver.pipeline;
+
+import org.apache.felix.scr.annotations.Activate;
+import org.apache.felix.scr.annotations.Deactivate;
+import org.apache.felix.scr.annotations.Reference;
+import org.apache.felix.scr.annotations.ReferenceCardinality;
+import org.onosproject.net.driver.DriverAdminService;
+import org.onosproject.net.driver.DriverProvider;
+import org.onosproject.net.driver.XmlDriverLoader;
+import org.apache.felix.scr.annotations.Component;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+
+/**
+ * Bootstrap for built in drivers.
+ */
+@Component(immediate = true)
+public class DefaultDrivers {
+
+    private final Logger log = LoggerFactory.getLogger(getClass());
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected DriverAdminService driverService;
+
+    private DriverProvider provider;
+
+    @Activate
+    protected void activate() {
+        XmlDriverLoader xmlDriverLoader =
+                new XmlDriverLoader(getClass().getClassLoader());
+        try {
+            provider = xmlDriverLoader.loadDrivers(
+                    getClass().getResourceAsStream("/default.xml"));
+            driverService.registerProvider(
+                    provider);
+        } catch (IOException e) {
+            log.warn("Unable to load drivers");
+        }
+
+        log.info("Started");
+    }
+
+    @Deactivate
+    protected void deactivate() {
+        driverService.unregisterProvider(provider);
+        log.info("Stopped");
+    }
+
+
+}
diff --git a/drivers/src/main/java/org/onosproject/driver/pipeline/DefaultSingleTablePipeline.java b/drivers/src/main/java/org/onosproject/driver/pipeline/DefaultSingleTablePipeline.java
index 8516697..48114ab 100644
--- a/drivers/src/main/java/org/onosproject/driver/pipeline/DefaultSingleTablePipeline.java
+++ b/drivers/src/main/java/org/onosproject/driver/pipeline/DefaultSingleTablePipeline.java
@@ -20,6 +20,7 @@
 import org.onosproject.core.DefaultGroupId;
 import org.onosproject.net.DeviceId;
 import org.onosproject.net.behaviour.Pipeliner;
+import org.onosproject.net.driver.DriverData;
 import org.onosproject.net.flow.DefaultFlowRule;
 import org.onosproject.net.flow.FlowRule;
 import org.onosproject.net.flow.FlowRuleOperations;
@@ -28,6 +29,7 @@
 import org.onosproject.net.flow.TrafficSelector;
 import org.onosproject.net.flowobjective.FilteringObjective;
 import org.onosproject.net.flowobjective.ForwardingObjective;
+import org.onosproject.net.flowobjective.NextObjective;
 import org.slf4j.Logger;
 
 import java.util.Collection;
@@ -106,4 +108,14 @@
         }));
         return future;
     }
+
+    @Override
+    public Future<Boolean> next(Collection<NextObjective> nextObjectives) {
+        throw new UnsupportedOperationException("Single table does not next hop.");
+    }
+
+    @Override
+    public void setData(DriverData data) {
+
+    }
 }
diff --git a/drivers/src/main/resources/default.xml b/drivers/src/main/resources/default.xml
new file mode 100644
index 0000000..6626412
--- /dev/null
+++ b/drivers/src/main/resources/default.xml
@@ -0,0 +1,22 @@
+<?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.
+  -->
+<drivers>
+    <driver name="default" manufacturer="ON.Lab" hwVersion="0.0.1" swVersion="0.0.1">
+        <behaviour api="org.onosproject.net.behaviour.Pipeliner"
+                   impl="org.onosproject.driver.pipeline.DefaultSingleTablePipeline"/>
+    </driver>
+</drivers>
\ No newline at end of file
diff --git a/features/features.xml b/features/features.xml
index 7e4ebbd..a345962 100644
--- a/features/features.xml
+++ b/features/features.xml
@@ -147,6 +147,7 @@
         <bundle>mvn:org.onosproject/onos-of-api/@ONOS-VERSION</bundle>
         <bundle>mvn:org.onosproject/onos-of-drivers/@ONOS-VERSION</bundle>
         <bundle>mvn:org.onosproject/onos-of-ctl/@ONOS-VERSION</bundle>
+        <bundle>mvn:org.onosproject/onos-drivers/@ONOS-VERSION</bundle>
 
         <bundle>mvn:org.onosproject/onos-lldp-provider/@ONOS-VERSION</bundle>
         <bundle>mvn:org.onosproject/onos-host-provider/@ONOS-VERSION</bundle>