ConfigFlowRuleProgrammable

- FlowRuleProgrammable implementation which acts as it has accepted any FlowRule request.

-- To be used for a device which exist in-line transparently (e.g., Amplifier ONOS-6067)

Change-Id: Ief09297eb900b804b1c8eb4d6705bbad85a552ad
diff --git a/drivers/optical/src/main/java/org/onosproject/driver/optical/config/ConfigFlowRuleProgrammable.java b/drivers/optical/src/main/java/org/onosproject/driver/optical/config/ConfigFlowRuleProgrammable.java
new file mode 100644
index 0000000..8675d32
--- /dev/null
+++ b/drivers/optical/src/main/java/org/onosproject/driver/optical/config/ConfigFlowRuleProgrammable.java
@@ -0,0 +1,107 @@
+/*
+ * Copyright 2017-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.driver.optical.config;
+
+import static org.slf4j.LoggerFactory.getLogger;
+
+import java.util.Collection;
+import java.util.LinkedHashSet;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.config.NetworkConfigService;
+import org.onosproject.net.driver.AbstractHandlerBehaviour;
+import org.onosproject.net.flow.DefaultFlowEntry;
+import org.onosproject.net.flow.FlowEntry;
+import org.onosproject.net.flow.FlowRule;
+import org.onosproject.net.flow.FlowRuleProgrammable;
+
+import com.google.common.annotations.Beta;
+import com.google.common.collect.ImmutableSet;
+
+import org.onosproject.net.flow.FlowEntry.FlowEntryState;
+import org.slf4j.Logger;
+
+// TODO consider relocating
+/**
+ * {@link FlowRuleProgrammable} which pretends it accepted the requests.
+ *
+ * Can be useful, when you need to send totally different flow rules
+ * down to the Device.
+ */
+@Beta
+public class ConfigFlowRuleProgrammable
+    extends AbstractHandlerBehaviour
+    implements FlowRuleProgrammable {
+
+    private static final Logger log = getLogger(ConfigFlowRuleProgrammable.class);
+
+
+    @Override
+    public Collection<FlowEntry> getFlowEntries() {
+        Set<FlowRule> flowtable = getFlowTable(getFlowTableConfig());
+        return flowtable.stream()
+                .map(fr -> new DefaultFlowEntry(fr, FlowEntryState.ADDED))
+                .collect(Collectors.toList());
+    }
+
+    @Override
+    public Collection<FlowRule> applyFlowRules(Collection<FlowRule> rules) {
+        log.trace("applyFlowRules: {}", rules);
+
+        Optional<FlowTableConfig> config = createFlowTableConfig();
+        Set<FlowRule> table = new LinkedHashSet<>(getFlowTable(config));
+        table.addAll(rules);
+        config.map(cfg -> cfg.flowtable(table))
+              .ifPresent(cfg -> cfg.apply());
+        log.trace("Updated flowtable: {}", table);
+        return table;
+    }
+
+    @Override
+    public Collection<FlowRule> removeFlowRules(Collection<FlowRule> rules) {
+        log.trace("removeFlowRules: {}", rules);
+        Optional<FlowTableConfig> config = getFlowTableConfig();
+        Set<FlowRule> table = new LinkedHashSet<>(getFlowTable(config));
+        table.removeAll(rules);
+        config.map(cfg -> cfg.flowtable(table))
+              .ifPresent(cfg -> cfg.apply());
+        log.trace("Updated flowtable: {}", table);
+        return table;
+    }
+
+    private Set<FlowRule> getFlowTable(Optional<FlowTableConfig> cfg) {
+        Set<FlowRule> flowtable = cfg
+                                    .map(FlowTableConfig::flowtable)
+                                    .orElse(ImmutableSet.of());
+        return flowtable;
+    }
+
+    private Optional<FlowTableConfig> createFlowTableConfig() {
+        NetworkConfigService netcfg = handler().get(NetworkConfigService.class);
+        DeviceId did = data().deviceId();
+        return Optional.ofNullable(netcfg.addConfig(did, FlowTableConfig.class));
+    }
+
+    private Optional<FlowTableConfig> getFlowTableConfig() {
+        NetworkConfigService netcfg = handler().get(NetworkConfigService.class);
+        DeviceId did = data().deviceId();
+        return Optional.ofNullable(netcfg.getConfig(did, FlowTableConfig.class));
+    }
+
+}
diff --git a/drivers/optical/src/main/java/org/onosproject/driver/optical/config/FlowTableConfig.java b/drivers/optical/src/main/java/org/onosproject/driver/optical/config/FlowTableConfig.java
new file mode 100644
index 0000000..7bd1688
--- /dev/null
+++ b/drivers/optical/src/main/java/org/onosproject/driver/optical/config/FlowTableConfig.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright 2017-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.driver.optical.config;
+
+import java.util.Set;
+
+import org.onosproject.codec.JsonCodec;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.config.BaseConfig;
+import org.onosproject.net.flow.FlowRule;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.ImmutableSet.Builder;
+
+/**
+ * Config to store FlowTable.
+ *
+ * Used by ConfigFlowRuleProgrammable
+ */
+public class FlowTableConfig extends BaseConfig<DeviceId> {
+
+    /**
+     * Configuration key for {@link FlowTableConfig}.
+     */
+    public static final String CONFIG_KEY = "flowtable";
+
+    public static final String ENTRIES = "entries";
+
+
+    @Override
+    public boolean isValid() {
+        return hasField(ENTRIES);
+    }
+
+
+    public Set<FlowRule> flowtable() {
+        JsonNode ents = object.path(ENTRIES);
+        if (!ents.isArray()) {
+
+            return ImmutableSet.of();
+        }
+        ArrayNode entries = (ArrayNode) ents;
+
+        Builder<FlowRule> builder = ImmutableSet.builder();
+        entries.forEach(entry -> builder.add(decode(entry, FlowRule.class)));
+        return builder.build();
+    }
+
+    public FlowTableConfig flowtable(Set<FlowRule> table) {
+        JsonCodec<FlowRule> codec = codec(FlowRule.class);
+        ArrayNode entries = codec.encode(table, this);
+        object.set(ENTRIES, entries);
+        return this;
+    }
+
+    /**
+     * Create a {@link FlowTableConfig}.
+     * <p>
+     * Note: created instance needs to be initialized by #init(..) before using.
+     */
+    public FlowTableConfig() {
+        super();
+    }
+
+    /**
+     * Create a {@link FlowTableConfig} for specified Device.
+     * <p>
+     * Note: created instance is not bound to NetworkConfigService,
+     * cannot use {@link #apply()}. Must be passed to the service
+     * using NetworkConfigService#applyConfig
+     *
+     * @param did DeviceId
+     */
+    public FlowTableConfig(DeviceId did) {
+        ObjectMapper mapper = new ObjectMapper();
+        init(did, CONFIG_KEY, mapper.createObjectNode(), mapper, null);
+    }
+}
diff --git a/drivers/optical/src/main/java/org/onosproject/driver/optical/config/package-info.java b/drivers/optical/src/main/java/org/onosproject/driver/optical/config/package-info.java
new file mode 100644
index 0000000..ca8add2
--- /dev/null
+++ b/drivers/optical/src/main/java/org/onosproject/driver/optical/config/package-info.java
@@ -0,0 +1,19 @@
+/*
+ * Copyright 2017-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.
+ */
+/**
+ * Config used in optical driver.
+ */
+package org.onosproject.driver.optical.config;
diff --git a/drivers/optical/src/main/java/org/onosproject/drivers/optical/OpticalDriversLoader.java b/drivers/optical/src/main/java/org/onosproject/drivers/optical/OpticalDriversLoader.java
index 89872e4..4c1dc4f 100644
--- a/drivers/optical/src/main/java/org/onosproject/drivers/optical/OpticalDriversLoader.java
+++ b/drivers/optical/src/main/java/org/onosproject/drivers/optical/OpticalDriversLoader.java
@@ -16,10 +16,24 @@
 
 package org.onosproject.drivers.optical;
 
+import static org.onosproject.net.config.basics.SubjectFactories.DEVICE_SUBJECT_FACTORY;
+
+import java.util.List;
+import org.apache.felix.scr.annotations.Activate;
 import org.apache.felix.scr.annotations.Component;
+import org.apache.felix.scr.annotations.Deactivate;
+import org.apache.felix.scr.annotations.Reference;
+import org.apache.felix.scr.annotations.ReferenceCardinality;
+import org.onosproject.driver.optical.config.FlowTableConfig;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.config.ConfigFactory;
+import org.onosproject.net.config.NetworkConfigRegistry;
+import org.onosproject.net.config.NetworkConfigRegistryAdapter;
 import org.onosproject.net.driver.AbstractDriverLoader;
 import org.onosproject.net.optical.OpticalDevice;
 
+import com.google.common.collect.ImmutableList;
+
 /**
  * Loader for other optical device drivers.
  */
@@ -30,7 +44,40 @@
     @SuppressWarnings("unused")
     private OpticalDevice optical;
 
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected NetworkConfigRegistry registry = new NetworkConfigRegistryAdapter();
+
+
+
+    private final List<ConfigFactory> factories = ImmutableList.of(
+         new ConfigFactory<DeviceId, FlowTableConfig>(DEVICE_SUBJECT_FACTORY,
+                 FlowTableConfig.class,
+                 FlowTableConfig.CONFIG_KEY) {
+             @Override
+             public FlowTableConfig createConfig() {
+                 return new FlowTableConfig();
+             }
+
+         });
+
+
     public OpticalDriversLoader() {
         super("/optical-drivers.xml");
     }
+
+    @Activate
+    @Override
+    protected void activate() {
+        factories.forEach(registry::registerConfigFactory);
+
+        super.activate();
+    }
+
+    @Deactivate
+    @Override
+    protected void deactivate() {
+        factories.forEach(registry::unregisterConfigFactory);
+        super.deactivate();
+    }
+
 }
diff --git a/drivers/optical/src/main/resources/optical-drivers.xml b/drivers/optical/src/main/resources/optical-drivers.xml
index ca4016f..203278f 100644
--- a/drivers/optical/src/main/resources/optical-drivers.xml
+++ b/drivers/optical/src/main/resources/optical-drivers.xml
@@ -68,6 +68,11 @@
             manufacturer="Oplink a Molex company" hwVersion="protection-switch" swVersion="of-agent-1.0">
         <behaviour api="org.onosproject.openflow.controller.driver.OpenFlowSwitchDriver"
             impl="org.onosproject.driver.optical.handshaker.OplinkSwitchHandshaker"/>
+
+        <!-- Transparent in-line device ignore all FlowRules  -->
+        <behaviour api="org.onosproject.net.flow.FlowRuleProgrammable"
+            impl="org.onosproject.driver.optical.config.ConfigFlowRuleProgrammable"/>
+
     </driver>
 
     <driver name="oplk-edfa" extends="default"
@@ -78,6 +83,11 @@
                    impl="org.onosproject.driver.optical.query.OplinkEdfaLambdaQuery"/>
         <behaviour api="org.onosproject.net.behaviour.PowerConfig"
                    impl="org.onosproject.driver.optical.power.OplinkEdfaPowerConfig"/>
+
+        <!-- Transparent in-line device ignore all FlowRules  -->
+        <behaviour api="org.onosproject.net.flow.FlowRuleProgrammable"
+            impl="org.onosproject.driver.optical.config.ConfigFlowRuleProgrammable"/>
+
     </driver>
 </drivers>
 
diff --git a/drivers/optical/src/test/java/org/onosproject/driver/optical/config/BaseConfigTestHelper.java b/drivers/optical/src/test/java/org/onosproject/driver/optical/config/BaseConfigTestHelper.java
new file mode 100644
index 0000000..d607689
--- /dev/null
+++ b/drivers/optical/src/test/java/org/onosproject/driver/optical/config/BaseConfigTestHelper.java
@@ -0,0 +1,117 @@
+/*
+ * Copyright 2017-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.driver.optical.config;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.onlab.junit.TestUtils;
+import org.onlab.junit.TestUtils.TestUtilsException;
+import org.onlab.osgi.ServiceDirectory;
+import org.onlab.osgi.TestServiceDirectory;
+import org.onosproject.codec.CodecService;
+import org.onosproject.codec.impl.CodecManager;
+import org.onosproject.net.config.BaseConfig;
+import org.onosproject.net.config.ConfigApplyDelegate;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.JsonNodeFactory;
+import com.fasterxml.jackson.databind.node.NumericNode;
+
+/**
+ * Common utility required for testing BaseConfig instance.
+ */
+public class BaseConfigTestHelper {
+
+    /**
+     * {@link ServiceDirectory} to be used by BaseConfig.
+     */
+    protected static TestServiceDirectory directory;
+
+    /**
+     * No-op ConfigApplyDelegate.
+     */
+    protected final ConfigApplyDelegate noopDelegate = cfg -> { };
+
+    private static ServiceDirectory original;
+
+
+    @BeforeClass
+    public static void setUpBaseConfigClass() throws TestUtilsException {
+        directory = new TestServiceDirectory();
+
+        CodecManager codecService = new CodecManager();
+        codecService.activate();
+        directory.add(CodecService.class, codecService);
+
+        // replace service directory used by BaseConfig
+        original = TestUtils.getField(BaseConfig.class, "services");
+        TestUtils.setField(BaseConfig.class, "services", directory);
+    }
+
+    @AfterClass
+    public static void tearDownBaseConfigClass() throws TestUtilsException {
+        TestUtils.setField(BaseConfig.class, "services", original);
+    }
+
+    /**
+     * Returns ObjectMapper configured for ease of testing.
+     * <p>
+     * It will treat all integral number node as long node.
+     *
+     * @return mapper
+     */
+    public static ObjectMapper testFriendlyMapper() {
+        ObjectMapper mapper = new ObjectMapper();
+        // Jackson configuration for ease of Numeric node comparison
+        // - treat integral number node as long node
+        mapper.enable(DeserializationFeature.USE_LONG_FOR_INTS);
+        mapper.setNodeFactory(new JsonNodeFactory(false) {
+            @Override
+            public NumericNode numberNode(int v) {
+                return super.numberNode((long) v);
+            }
+            @Override
+            public NumericNode numberNode(short v) {
+                return super.numberNode((long) v);
+            }
+        });
+
+        return mapper;
+    }
+
+    /**
+     * Load JSON file from resource.
+     *
+     * @param filename JSON file name
+     * @param mapper to use to read file.
+     * @return JSON node
+     * @throws JsonProcessingException
+     * @throws IOException
+     */
+    public JsonNode loadJsonFromResource(String filename, ObjectMapper mapper)
+                throws JsonProcessingException, IOException {
+
+        InputStream stream = getClass().getResourceAsStream(filename);
+        JsonNode tree = mapper.readTree(stream);
+        return tree;
+    }
+}
diff --git a/drivers/optical/src/test/java/org/onosproject/driver/optical/config/FlowTableConfigTest.java b/drivers/optical/src/test/java/org/onosproject/driver/optical/config/FlowTableConfigTest.java
new file mode 100644
index 0000000..c8622bb
--- /dev/null
+++ b/drivers/optical/src/test/java/org/onosproject/driver/optical/config/FlowTableConfigTest.java
@@ -0,0 +1,131 @@
+/*
+ * Copyright 2017-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.driver.optical.config;
+
+import static org.hamcrest.Matchers.*;
+import static org.junit.Assert.*;
+import static org.onosproject.net.PortNumber.portNumber;
+import static org.onosproject.net.flow.instructions.Instructions.modL0Lambda;
+
+import java.io.IOException;
+import java.util.Set;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreService;
+import org.onosproject.core.CoreServiceAdapter;
+import org.onosproject.core.DefaultApplicationId;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.OchSignal;
+import org.onosproject.net.PortNumber;
+import org.onosproject.net.flow.DefaultFlowRule;
+import org.onosproject.net.flow.DefaultTrafficSelector;
+import org.onosproject.net.flow.DefaultTrafficTreatment;
+import org.onosproject.net.flow.FlowRule;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.collect.ImmutableSet;
+
+public class FlowTableConfigTest extends BaseConfigTestHelper {
+
+    private static final String SAMPLE = "flow_table_config.json";
+
+
+    private static final DeviceId DID = DeviceId.deviceId("of:0000000000000001");
+    private static final PortNumber PN_1 = portNumber(1);
+    private static final PortNumber PN_2 = portNumber(2);
+    private static final int FLOW_ID_3 = 3;
+    private static final int PRIO_4 = 4;
+
+    private static final DefaultApplicationId APP_ID =
+                new DefaultApplicationId(FLOW_ID_3 >>> 48, "test");
+
+    private static final OchSignal LAMBDA_42 = OchSignal.newFlexGridSlot(42);
+
+    private static final FlowRule FLOW_RULE = DefaultFlowRule.builder()
+                        .forDevice(DID)
+                        .withCookie(FLOW_ID_3)
+                        .makePermanent()
+                        .withPriority(PRIO_4)
+                        .withSelector(DefaultTrafficSelector.builder()
+                                          .matchInPort(PN_1)
+                                          .build())
+                        .withTreatment(DefaultTrafficTreatment.builder()
+                                           .setOutput(PN_2)
+                                           .add(modL0Lambda(LAMBDA_42))
+                                           .build())
+                        .build();
+
+
+    private ObjectMapper mapper;
+
+
+    private JsonNode cfgnode;
+
+    @Before
+    public void setUp() throws Exception {
+
+        directory.add(CoreService.class, new CoreServiceAdapter() {
+            @Override
+            public ApplicationId getAppId(Short id) {
+                return APP_ID;
+            }
+
+            @Override
+            public ApplicationId registerApplication(String name) {
+                return APP_ID;
+            }
+        });
+
+        mapper = testFriendlyMapper();
+        JsonNode sample = loadJsonFromResource(SAMPLE, mapper);
+
+        cfgnode = sample.path("devices")
+                                    .path(DID.toString())
+                                       .path(FlowTableConfig.CONFIG_KEY);
+
+    }
+
+    @After
+    public void tearDown() throws Exception {
+    }
+
+    @Test
+    public void readTest() throws JsonProcessingException, IOException {
+
+        FlowTableConfig sut = new FlowTableConfig();
+        sut.init(DID, FlowTableConfig.CONFIG_KEY, cfgnode, mapper, noopDelegate);
+
+        assertThat(sut.flowtable(), is(equalTo(ImmutableSet.of(FLOW_RULE))));
+    }
+
+    @Test
+    public void writeTest() throws JsonProcessingException, IOException {
+
+        FlowTableConfig w = new FlowTableConfig();
+        w.init(DID, FlowTableConfig.CONFIG_KEY, mapper.createObjectNode(), mapper, noopDelegate);
+
+        Set<FlowRule> table = ImmutableSet.of(FLOW_RULE);
+        w.flowtable(table);
+
+        assertEquals(cfgnode, w.node());
+    }
+
+}
diff --git a/drivers/optical/src/test/resources/org/onosproject/driver/optical/config/flow_table_config.json b/drivers/optical/src/test/resources/org/onosproject/driver/optical/config/flow_table_config.json
new file mode 100644
index 0000000..3d8a8c3
--- /dev/null
+++ b/drivers/optical/src/test/resources/org/onosproject/driver/optical/config/flow_table_config.json
@@ -0,0 +1,48 @@
+{
+  "devices" : {
+    "of:0000000000000001" : {
+      "flowtable" : {
+        "entries" : [
+
+          {
+            "id": "3",
+            "tableId": 0,
+            "appId": "test",
+            "priority": 4,
+            "timeout": 0,
+            "isPermanent": true,
+            "deviceId": "of:0000000000000001",
+            "treatment": {
+              "instructions": [
+                {
+                  "type": "OUTPUT",
+                  "port": "2"
+                },
+                {
+                  "type": "L0MODIFICATION",
+                  "subtype": "OCH",
+                  "gridType": "FLEX",
+                  "channelSpacing": "CHL_6P25GHZ",
+                  "spacingMultiplier": 42,
+                  "slotGranularity": 1
+                }
+              ],
+              "deferred": [
+
+              ]
+            },
+            "selector": {
+              "criteria": [
+                {
+                  "type": "IN_PORT",
+                  "port": 1
+                }
+              ]
+            }
+          }
+
+        ]
+      }
+    }
+  }
+}