ONOS-3758 restructuring driver module with sub-modules for different drivers
Change-Id: I3c65d19be87066448655610abf9d8b89385a4141
diff --git a/drivers/default/features.xml b/drivers/default/features.xml
new file mode 100644
index 0000000..1dc6b2a
--- /dev/null
+++ b/drivers/default/features.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<!--
+ ~ 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.
+ -->
+<features xmlns="http://karaf.apache.org/xmlns/features/v1.2.0" name="${project.artifactId}-${project.version}">
+ <feature name="${project.artifactId}" version="${project.version}"
+ description="${project.description}">
+ <feature>onos-api</feature>
+ <bundle>mvn:${project.groupId}/${project.artifactId}/${project.version}</bundle>
+
+ <bundle>mvn:${project.groupId}/onos-of-api/${project.version}</bundle>
+
+ </feature>
+</features>
diff --git a/drivers/default/pom.xml b/drivers/default/pom.xml
new file mode 100644
index 0000000..c77688a
--- /dev/null
+++ b/drivers/default/pom.xml
@@ -0,0 +1,42 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ ~ 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.
+ -->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <parent>
+ <artifactId>onos-drivers-general</artifactId>
+ <groupId>org.onosproject</groupId>
+ <version>1.5.0-SNAPSHOT</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+
+ <description>Default device drivers</description>
+ <!--should be onos-drivers-default for clarity but left as onos-drivers for compatibility-->
+ <artifactId>onos-drivers</artifactId>
+ <packaging>bundle</packaging>
+
+ <properties>
+ <onos.app.name>org.onosproject.drivers</onos.app.name>
+ </properties>
+ <dependencies>
+ <dependency>
+ <groupId>org.onosproject</groupId>
+ <artifactId>onos-of-api</artifactId>
+ </dependency>
+ </dependencies>
+</project>
\ No newline at end of file
diff --git a/drivers/default/src/main/java/org/onosproject/driver/DefaultDriversLoader.java b/drivers/default/src/main/java/org/onosproject/driver/DefaultDriversLoader.java
new file mode 100644
index 0000000..ad7d4a8
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/DefaultDriversLoader.java
@@ -0,0 +1,44 @@
+/*
+ * 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.driver;
+
+import org.apache.felix.scr.annotations.Component;
+import org.apache.felix.scr.annotations.Service;
+import org.onosproject.net.driver.AbstractDriverLoader;
+import org.onosproject.net.driver.DefaultDriverProviderService;
+
+import java.io.InputStream;
+
+/**
+ * Loader for default device drivers from specific xml.
+ */
+@Service
+@Component(immediate = true)
+public class DefaultDriversLoader extends AbstractDriverLoader implements DefaultDriverProviderService {
+
+ private static final String DRIVERS_XML = "/onos-drivers.xml";
+
+ @Override
+ protected InputStream loadXMLDriversStream() {
+ return getClassLoaderInstance().getResourceAsStream(DRIVERS_XML);
+ }
+
+ @Override
+ protected ClassLoader getClassLoaderInstance() {
+ return getClass().getClassLoader();
+ }
+}
diff --git a/drivers/default/src/main/java/org/onosproject/driver/extensions/DefaultMoveExtensionTreatment.java b/drivers/default/src/main/java/org/onosproject/driver/extensions/DefaultMoveExtensionTreatment.java
new file mode 100644
index 0000000..b86b771
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/extensions/DefaultMoveExtensionTreatment.java
@@ -0,0 +1,145 @@
+/*
+ * 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.extensions;
+
+import com.google.common.base.MoreObjects;
+import com.google.common.collect.Maps;
+import org.onlab.util.KryoNamespace;
+import org.onosproject.net.flow.AbstractExtension;
+import org.onosproject.net.flow.instructions.ExtensionTreatmentType;
+
+import java.util.Map;
+import java.util.Objects;
+
+/**
+ * Default implementation of Move treatment.
+ */
+public class DefaultMoveExtensionTreatment extends AbstractExtension
+ implements MoveExtensionTreatment {
+
+ private int srcOfs;
+ private int dstOfs;
+ private int nBits;
+ private int src;
+ private int dst;
+ private ExtensionTreatmentType type;
+
+ private final KryoNamespace appKryo = new KryoNamespace.Builder()
+ .register(byte[].class).register(Integer.class).register(Map.class)
+ .build();
+
+ /**
+ * Creates a new move Treatment.
+ *
+ * @param srcOfs source offset
+ * @param dstOfs destination offset
+ * @param nBits nbits
+ * @param src source
+ * @param dst destination
+ * @param type extension treatment type
+ */
+ public DefaultMoveExtensionTreatment(int srcOfs, int dstOfs, int nBits,
+ int src, int dst, ExtensionTreatmentType type) {
+ this.srcOfs = srcOfs;
+ this.dstOfs = dstOfs;
+ this.nBits = nBits;
+ this.src = src;
+ this.dst = dst;
+ this.type = type;
+ }
+
+ @Override
+ public ExtensionTreatmentType type() {
+ return type;
+ }
+
+ @Override
+ public byte[] serialize() {
+ Map<String, Integer> values = Maps.newHashMap();
+ values.put("srcOfs", srcOfs);
+ values.put("dstOfs", dstOfs);
+ values.put("nBits", nBits);
+ values.put("src", src);
+ values.put("dst", dst);
+ values.put("type", ExtensionTreatmentType.ExtensionTreatmentTypes.valueOf(type.toString()).ordinal());
+ return appKryo.serialize(values);
+ }
+
+ @Override
+ public void deserialize(byte[] data) {
+ Map<String, Integer> values = appKryo.deserialize(data);
+ srcOfs = values.get("srcOfs");
+ dstOfs = values.get("dstOfs");
+ nBits = values.get("nBits");
+ src = values.get("src");
+ dst = values.get("dst");
+ type = new ExtensionTreatmentType(values.get("type").intValue());
+ }
+
+ @Override
+ public int srcOffset() {
+ return srcOfs;
+ }
+
+ @Override
+ public int dstOffset() {
+ return dstOfs;
+ }
+
+ @Override
+ public int src() {
+ return src;
+ }
+
+ @Override
+ public int dst() {
+ return dst;
+ }
+
+ @Override
+ public int nBits() {
+ return nBits;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(srcOfs, dstOfs, src, dst, nBits);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj instanceof DefaultMoveExtensionTreatment) {
+ DefaultMoveExtensionTreatment that = (DefaultMoveExtensionTreatment) obj;
+ return Objects.equals(srcOfs, that.srcOfs)
+ && Objects.equals(dstOfs, that.dstOfs)
+ && Objects.equals(src, that.src)
+ && Objects.equals(dst, that.dst)
+ && Objects.equals(nBits, that.nBits);
+
+ }
+ return false;
+ }
+
+ @Override
+ public String toString() {
+ return MoreObjects.toStringHelper(getClass()).add("srcOfs", srcOfs)
+ .add("dstOfs", dstOfs).add("nBits", nBits).add("src", src)
+ .add("dst", dst).toString();
+ }
+}
diff --git a/drivers/default/src/main/java/org/onosproject/driver/extensions/MoveExtensionTreatment.java b/drivers/default/src/main/java/org/onosproject/driver/extensions/MoveExtensionTreatment.java
new file mode 100644
index 0000000..b67e1be
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/extensions/MoveExtensionTreatment.java
@@ -0,0 +1,59 @@
+/*
+ * 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.extensions;
+
+import org.onosproject.net.flow.instructions.ExtensionTreatment;
+
+/**
+ * The abstraction of Move Treatment.
+ */
+public interface MoveExtensionTreatment extends ExtensionTreatment {
+
+ /**
+ * Returns SRC_OFS field of move extension action.
+ *
+ * @return SRC_OFS
+ */
+ int srcOffset();
+
+ /**
+ * Returns DST_OFS field of move extension action.
+ *
+ * @return DST_OFS
+ */
+ int dstOffset();
+
+ /**
+ * Returns SRC field of move extension action.
+ *
+ * @return SRC
+ */
+ int src();
+
+ /**
+ * Returns DST field of move extension action.
+ *
+ * @return DST
+ */
+ int dst();
+
+ /**
+ * Returns N_BITS field of move extension action.
+ *
+ * @return N_BITS
+ */
+ int nBits();
+}
diff --git a/drivers/default/src/main/java/org/onosproject/driver/extensions/NiciraExtensionSelectorInterpreter.java b/drivers/default/src/main/java/org/onosproject/driver/extensions/NiciraExtensionSelectorInterpreter.java
new file mode 100644
index 0000000..9f30299
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/extensions/NiciraExtensionSelectorInterpreter.java
@@ -0,0 +1,102 @@
+/*
+ * 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.extensions;
+
+import org.onosproject.net.behaviour.ExtensionSelectorResolver;
+import org.onosproject.net.driver.AbstractHandlerBehaviour;
+import org.onosproject.net.flow.criteria.ExtensionSelector;
+import org.onosproject.net.flow.criteria.ExtensionSelectorType;
+import org.onosproject.openflow.controller.ExtensionSelectorInterpreter;
+import org.projectfloodlight.openflow.protocol.OFFactory;
+import org.projectfloodlight.openflow.protocol.oxm.OFOxm;
+
+/**
+ * Interpreter for Nicira OpenFlow selector extensions.
+ */
+public class NiciraExtensionSelectorInterpreter
+ extends AbstractHandlerBehaviour
+ implements ExtensionSelectorInterpreter, ExtensionSelectorResolver {
+
+ @Override
+ public boolean supported(ExtensionSelectorType extensionSelectorType) {
+ if (extensionSelectorType.equals(ExtensionSelectorType.ExtensionSelectorTypes.NICIRA_MATCH_NSH_SPI.type())) {
+ return true;
+ }
+ if (extensionSelectorType.equals(ExtensionSelectorType.ExtensionSelectorTypes.NICIRA_MATCH_NSH_SI.type())) {
+ return true;
+ }
+ if (extensionSelectorType.equals(ExtensionSelectorType.ExtensionSelectorTypes.NICIRA_MATCH_NSH_CH1.type())) {
+ return true;
+ }
+ if (extensionSelectorType.equals(ExtensionSelectorType.ExtensionSelectorTypes.NICIRA_MATCH_NSH_CH2.type())) {
+ return true;
+ }
+ if (extensionSelectorType.equals(ExtensionSelectorType.ExtensionSelectorTypes.NICIRA_MATCH_NSH_CH3.type())) {
+ return true;
+ }
+ if (extensionSelectorType.equals(ExtensionSelectorType.ExtensionSelectorTypes.NICIRA_MATCH_NSH_CH4.type())) {
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public OFOxm<?> mapSelector(OFFactory factory, ExtensionSelector extensionSelector) {
+ ExtensionSelectorType type = extensionSelector.type();
+ if (type.equals(ExtensionSelectorType.ExtensionSelectorTypes.NICIRA_MATCH_NSH_SPI.type())) {
+ // TODO
+ }
+ if (type.equals(ExtensionSelectorType.ExtensionSelectorTypes.NICIRA_MATCH_NSH_SI.type())) {
+ // TODO
+ }
+ if (type.equals(ExtensionSelectorType.ExtensionSelectorTypes.NICIRA_MATCH_NSH_CH1.type())) {
+ // TODO
+ }
+ if (type.equals(ExtensionSelectorType.ExtensionSelectorTypes.NICIRA_MATCH_NSH_CH2.type())) {
+ // TODO
+ }
+ if (type.equals(ExtensionSelectorType.ExtensionSelectorTypes.NICIRA_MATCH_NSH_CH3.type())) {
+ // TODO
+ }
+ if (type.equals(ExtensionSelectorType.ExtensionSelectorTypes.NICIRA_MATCH_NSH_CH4.type())) {
+ // TODO
+ }
+ return null;
+ }
+
+ @Override
+ public ExtensionSelector mapOxm(OFOxm<?> oxm) {
+ return null;
+ }
+
+ @Override
+ public ExtensionSelector getExtensionSelector(ExtensionSelectorType type) {
+ if (type.equals(ExtensionSelectorType.ExtensionSelectorTypes.NICIRA_MATCH_NSH_SPI.type())) {
+ return new NiciraMatchNshSpi();
+ }
+ if (type.equals(ExtensionSelectorType.ExtensionSelectorTypes.NICIRA_MATCH_NSH_SI.type())) {
+ return new NiciraMatchNshSi();
+ }
+ if (type.equals(ExtensionSelectorType.ExtensionSelectorTypes.NICIRA_MATCH_NSH_CH1.type())
+ || type.equals(ExtensionSelectorType.ExtensionSelectorTypes.NICIRA_MATCH_NSH_CH2.type())
+ || type.equals(ExtensionSelectorType.ExtensionSelectorTypes.NICIRA_MATCH_NSH_CH3.type())
+ || type.equals(ExtensionSelectorType.ExtensionSelectorTypes.NICIRA_MATCH_NSH_CH4.type())) {
+ return new NiciraMatchNshContextHeader(type);
+ }
+ return null;
+ }
+}
diff --git a/drivers/default/src/main/java/org/onosproject/driver/extensions/NiciraExtensionTreatmentInterpreter.java b/drivers/default/src/main/java/org/onosproject/driver/extensions/NiciraExtensionTreatmentInterpreter.java
new file mode 100644
index 0000000..923dcde
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/extensions/NiciraExtensionTreatmentInterpreter.java
@@ -0,0 +1,242 @@
+/*
+ * 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.extensions;
+
+import org.onlab.packet.Ip4Address;
+import org.onosproject.net.behaviour.ExtensionTreatmentResolver;
+import org.onosproject.net.driver.AbstractHandlerBehaviour;
+import org.onosproject.net.flow.instructions.ExtensionTreatment;
+import org.onosproject.net.flow.instructions.ExtensionTreatmentType;
+import org.onosproject.openflow.controller.ExtensionTreatmentInterpreter;
+import org.projectfloodlight.openflow.protocol.OFActionType;
+import org.projectfloodlight.openflow.protocol.OFFactory;
+import org.projectfloodlight.openflow.protocol.action.OFAction;
+import org.projectfloodlight.openflow.protocol.action.OFActionExperimenter;
+import org.projectfloodlight.openflow.protocol.action.OFActionNicira;
+import org.projectfloodlight.openflow.protocol.action.OFActionNiciraMove;
+import org.projectfloodlight.openflow.protocol.action.OFActionSetField;
+import org.projectfloodlight.openflow.protocol.oxm.OFOxm;
+import org.projectfloodlight.openflow.protocol.oxm.OFOxmTunnelIpv4Dst;
+import org.projectfloodlight.openflow.types.IPv4Address;
+
+/**
+ * Interpreter for Nicira OpenFlow treatment extensions.
+ */
+public class NiciraExtensionTreatmentInterpreter extends AbstractHandlerBehaviour
+ implements ExtensionTreatmentInterpreter, ExtensionTreatmentResolver {
+
+ private static final int TYPE_NICIRA = 0x2320;
+ private static final int SUB_TYPE_MOVE = 6;
+ private static final int SRC_ARP_SHA = 0x00012206;
+ private static final int SRC_ARP_SPA = 0x00002004;
+ private static final int SRC_ETH = 0x00000406;
+ private static final int SRC_IP = 0x00000e04;
+
+ @Override
+ public boolean supported(ExtensionTreatmentType extensionTreatmentType) {
+ if (extensionTreatmentType.equals(
+ ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_SET_TUNNEL_DST.type())) {
+ return true;
+ }
+ if (extensionTreatmentType.equals(
+ ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_RESUBMIT.type())) {
+ return true;
+ }
+ if (extensionTreatmentType.equals(ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_SET_NSH_SPI.type())) {
+ return true;
+ }
+ if (extensionTreatmentType.equals(ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_SET_NSH_SI.type())) {
+ return true;
+ }
+ if (extensionTreatmentType.equals(ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_SET_NSH_CH1.type())) {
+ return true;
+ }
+ if (extensionTreatmentType.equals(ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_SET_NSH_CH2.type())) {
+ return true;
+ }
+ if (extensionTreatmentType.equals(ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_SET_NSH_CH3.type())) {
+ return true;
+ }
+ if (extensionTreatmentType.equals(ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_SET_NSH_CH4.type())) {
+ return true;
+ }
+ if (extensionTreatmentType.equals(
+ ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_RESUBMIT_TABLE.type())) {
+ return true;
+ }
+ if (extensionTreatmentType.equals(
+ ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_MOV_ARP_SHA_TO_THA.type())) {
+ return true;
+ }
+ if (extensionTreatmentType.equals(
+ ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_MOV_ARP_SPA_TO_TPA.type())) {
+ return true;
+ }
+ if (extensionTreatmentType.equals(
+ ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_MOV_ETH_SRC_TO_DST.type())) {
+ return true;
+ }
+ if (extensionTreatmentType.equals(
+ ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_MOV_IP_SRC_TO_DST.type())) {
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public OFAction mapInstruction(OFFactory factory, ExtensionTreatment extensionTreatment) {
+ ExtensionTreatmentType type = extensionTreatment.type();
+ if (type.equals(ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_SET_TUNNEL_DST.type())) {
+ NiciraSetTunnelDst tunnelDst = (NiciraSetTunnelDst) extensionTreatment;
+ return factory.actions().setField(factory.oxms().tunnelIpv4Dst(
+ IPv4Address.of(tunnelDst.tunnelDst().toInt())));
+ }
+ if (type.equals(ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_RESUBMIT.type())) {
+ NiciraResubmit resubmit = (NiciraResubmit) extensionTreatment;
+ return factory.actions().niciraResubmit((int) resubmit.inPort().toLong(),
+ resubmit.table());
+ }
+ if (type.equals(ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_RESUBMIT_TABLE.type())) {
+ NiciraResubmitTable resubmitTable = (NiciraResubmitTable) extensionTreatment;
+ return factory.actions().niciraResubmitTable((int) resubmitTable.inPort().toLong(),
+ resubmitTable.table());
+ }
+ if (type.equals(ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_SET_NSH_SPI.type())) {
+ NiciraSetNshSpi niciraNshSpi = (NiciraSetNshSpi) extensionTreatment;
+ return factory.actions().niciraSetNsp(niciraNshSpi.nshSpi().servicePathId());
+ }
+ if (type.equals(ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_SET_NSH_SI.type())) {
+ NiciraSetNshSi niciraNshSi = (NiciraSetNshSi) extensionTreatment;
+ return factory.actions().niciraSetNsp(niciraNshSi.nshSi().serviceIndex());
+ }
+ if (type.equals(ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_SET_NSH_CH1.type())) {
+ NiciraSetNshContextHeader niciraNshch = (NiciraSetNshContextHeader) extensionTreatment;
+ return factory.actions().niciraSetNshc1(niciraNshch.nshCh().nshContextHeader());
+ }
+ if (type.equals(ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_SET_NSH_CH2.type())) {
+ NiciraSetNshContextHeader niciraNshch = (NiciraSetNshContextHeader) extensionTreatment;
+ return factory.actions().niciraSetNshc2(niciraNshch.nshCh().nshContextHeader());
+ }
+ if (type.equals(ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_SET_NSH_CH3.type())) {
+ NiciraSetNshContextHeader niciraNshch = (NiciraSetNshContextHeader) extensionTreatment;
+ return factory.actions().niciraSetNshc3(niciraNshch.nshCh().nshContextHeader());
+ }
+ if (type.equals(ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_SET_NSH_CH4.type())) {
+ NiciraSetNshContextHeader niciraNshch = (NiciraSetNshContextHeader) extensionTreatment;
+ return factory.actions().niciraSetNshc4(niciraNshch.nshCh().nshContextHeader());
+ }
+ if (type.equals(ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_MOV_ARP_SHA_TO_THA.type())
+ || type.equals(ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_MOV_ARP_SPA_TO_TPA.type())
+ || type.equals(ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_MOV_ETH_SRC_TO_DST.type())
+ || type.equals(ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_MOV_IP_SRC_TO_DST.type())) {
+ MoveExtensionTreatment mov = (MoveExtensionTreatment) extensionTreatment;
+ OFActionNiciraMove.Builder action = factory.actions()
+ .buildNiciraMove();
+ action.setDstOfs(mov.dstOffset());
+ action.setSrcOfs(mov.srcOffset());
+ action.setNBits(mov.nBits());
+ action.setSrc(mov.src());
+ action.setDst(mov.dst());
+ return action.build();
+ }
+ return null;
+ }
+
+ @Override
+ public ExtensionTreatment mapAction(OFAction action) {
+ if (action.getType().equals(OFActionType.SET_FIELD)) {
+ OFActionSetField setFieldAction = (OFActionSetField) action;
+ OFOxm<?> oxm = setFieldAction.getField();
+ switch (oxm.getMatchField().id) {
+ case TUNNEL_IPV4_DST:
+ OFOxmTunnelIpv4Dst tunnelIpv4Dst = (OFOxmTunnelIpv4Dst) oxm;
+ return new NiciraSetTunnelDst(Ip4Address.valueOf(tunnelIpv4Dst.getValue().getInt()));
+ default:
+ throw new UnsupportedOperationException(
+ "Driver does not support extension type " + oxm.getMatchField().id);
+ }
+ }
+ if (action.getType().equals(OFActionType.EXPERIMENTER)) {
+ OFActionExperimenter experimenter = (OFActionExperimenter) action;
+ if (Long.valueOf(experimenter.getExperimenter())
+ .intValue() == TYPE_NICIRA) {
+ OFActionNicira nicira = (OFActionNicira) experimenter;
+ if (nicira.getSubtype() == SUB_TYPE_MOVE) {
+ OFActionNiciraMove moveAction = (OFActionNiciraMove) nicira;
+ switch (Long.valueOf(moveAction.getSrc()).intValue()) {
+ case SRC_ARP_SHA:
+ return NiciraMoveTreatmentFactory
+ .createNiciraMovArpShaToTha();
+ case SRC_ETH:
+ return NiciraMoveTreatmentFactory
+ .createNiciraMovEthSrcToDst();
+ case SRC_IP:
+ return NiciraMoveTreatmentFactory
+ .createNiciraMovIpSrcToDst();
+ case SRC_ARP_SPA:
+ return NiciraMoveTreatmentFactory
+ .createNiciraMovArpSpaToTpa();
+ default:
+ throw new UnsupportedOperationException("Driver does not support move from "
+ + moveAction.getSrc() + " to "
+ + moveAction.getDst());
+ }
+ }
+ }
+ }
+ return null;
+ }
+
+ @Override
+ public ExtensionTreatment getExtensionInstruction(ExtensionTreatmentType type) {
+ if (type.equals(ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_SET_TUNNEL_DST.type())) {
+ return new NiciraSetTunnelDst();
+ }
+ if (type.equals(ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_RESUBMIT.type())) {
+ return new NiciraResubmit();
+ }
+ if (type.equals(ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_RESUBMIT_TABLE.type())) {
+ return new NiciraResubmitTable();
+ }
+ if (type.equals(ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_SET_NSH_SPI.type())) {
+ return new NiciraSetNshSpi();
+ }
+ if (type.equals(ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_SET_NSH_SI.type())) {
+ return new NiciraSetNshSi();
+ }
+ if (type.equals(ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_SET_NSH_CH1.type())
+ || type.equals(ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_SET_NSH_CH2.type())
+ || type.equals(ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_SET_NSH_CH3.type())
+ || type.equals(ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_SET_NSH_CH4.type())) {
+ return new NiciraSetNshContextHeader(type);
+ }
+ if (type.equals(ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_MOV_ARP_SHA_TO_THA.type())) {
+ return NiciraMoveTreatmentFactory.createNiciraMovArpShaToTha();
+ }
+ if (type.equals(ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_MOV_ARP_SPA_TO_TPA.type())) {
+ return NiciraMoveTreatmentFactory.createNiciraMovArpSpaToTpa();
+ }
+ if (type.equals(ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_MOV_ETH_SRC_TO_DST.type())) {
+ return NiciraMoveTreatmentFactory.createNiciraMovEthSrcToDst();
+ }
+ if (type.equals(ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_MOV_IP_SRC_TO_DST.type())) {
+ return NiciraMoveTreatmentFactory.createNiciraMovIpSrcToDst();
+ }
+ throw new UnsupportedOperationException(
+ "Driver does not support extension type " + type.toString());
+ }
+}
diff --git a/drivers/default/src/main/java/org/onosproject/driver/extensions/NiciraMatchNshContextHeader.java b/drivers/default/src/main/java/org/onosproject/driver/extensions/NiciraMatchNshContextHeader.java
new file mode 100644
index 0000000..5f37247
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/extensions/NiciraMatchNshContextHeader.java
@@ -0,0 +1,95 @@
+/*
+ * 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.extensions;
+
+import static com.google.common.base.MoreObjects.toStringHelper;
+
+import java.util.Objects;
+
+import org.onlab.util.KryoNamespace;
+import org.onosproject.net.NshContextHeader;
+import org.onosproject.net.flow.AbstractExtension;
+import org.onosproject.net.flow.criteria.ExtensionSelector;
+import org.onosproject.net.flow.criteria.ExtensionSelectorType;
+/**
+ * Implementation of Nsh context header criterion.
+ */
+public final class NiciraMatchNshContextHeader extends AbstractExtension implements ExtensionSelector {
+ private NshContextHeader nshContextHeader;
+ private ExtensionSelectorType type;
+
+ private final KryoNamespace appKryo = new KryoNamespace.Builder().build();
+
+ /**
+ * Constructor to create Nsh context header.
+ *
+ * @param type extension selector type
+ */
+ public NiciraMatchNshContextHeader(ExtensionSelectorType type) {
+ this.nshContextHeader = null;
+ this.type = type;
+ }
+
+ /**
+ * Gets the nsh context header to match.
+ *
+ * @return the nsh context header to match
+ */
+ public NshContextHeader nshContextHeader() {
+ return nshContextHeader;
+ }
+
+ @Override
+ public byte[] serialize() {
+ return appKryo.serialize(nshContextHeader.nshContextHeader());
+ }
+
+ @Override
+ public void deserialize(byte[] data) {
+ nshContextHeader = nshContextHeader.of(appKryo.deserialize(data));
+
+ }
+
+ @Override
+ public ExtensionSelectorType type() {
+ return type;
+ }
+
+ @Override
+ public String toString() {
+ return toStringHelper(type().toString())
+ .add("nshContextHeader", nshContextHeader.toString())
+ .toString();
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(type(), nshContextHeader);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj instanceof NiciraMatchNshContextHeader) {
+ NiciraMatchNshContextHeader that = (NiciraMatchNshContextHeader) obj;
+ return Objects.equals(nshContextHeader, that.nshContextHeader) &&
+ Objects.equals(this.type(), that.type());
+ }
+ return false;
+ }
+}
diff --git a/drivers/default/src/main/java/org/onosproject/driver/extensions/NiciraMatchNshSi.java b/drivers/default/src/main/java/org/onosproject/driver/extensions/NiciraMatchNshSi.java
new file mode 100644
index 0000000..c98a584
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/extensions/NiciraMatchNshSi.java
@@ -0,0 +1,91 @@
+/*
+ * 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.extensions;
+
+import static com.google.common.base.MoreObjects.toStringHelper;
+
+import java.util.Objects;
+
+import org.onlab.util.KryoNamespace;
+import org.onosproject.net.NshServiceIndex;
+import org.onosproject.net.flow.AbstractExtension;
+import org.onosproject.net.flow.criteria.ExtensionSelector;
+import org.onosproject.net.flow.criteria.ExtensionSelectorType;
+/**
+ * Implementation of NSH Service Index(SI).
+ */
+public final class NiciraMatchNshSi extends AbstractExtension implements ExtensionSelector {
+
+ private NshServiceIndex nshSi;
+
+ private final KryoNamespace appKryo = new KryoNamespace.Builder().build();
+
+ /**
+ * Default constructor.
+ *
+ */
+ public NiciraMatchNshSi() {
+ this.nshSi = null;
+ }
+
+ /**
+ * Gets the nsh service index to match.
+ *
+ * @return the si to match
+ */
+ public NshServiceIndex nshSi() {
+ return nshSi;
+ }
+
+ @Override
+ public byte[] serialize() {
+ return appKryo.serialize(nshSi.serviceIndex());
+ }
+
+ @Override
+ public void deserialize(byte[] data) {
+ nshSi = NshServiceIndex.of(appKryo.deserialize(data));
+ }
+
+ @Override
+ public ExtensionSelectorType type() {
+ return ExtensionSelectorType.ExtensionSelectorTypes.NICIRA_MATCH_NSH_SI.type();
+ }
+
+ @Override
+ public String toString() {
+ return toStringHelper(type().toString())
+ .add("nshSi", nshSi.toString())
+ .toString();
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(type(), nshSi);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj instanceof NiciraMatchNshSi) {
+ NiciraMatchNshSi that = (NiciraMatchNshSi) obj;
+ return Objects.equals(nshSi, that.nshSi);
+ }
+ return false;
+ }
+}
diff --git a/drivers/default/src/main/java/org/onosproject/driver/extensions/NiciraMatchNshSpi.java b/drivers/default/src/main/java/org/onosproject/driver/extensions/NiciraMatchNshSpi.java
new file mode 100644
index 0000000..42bb78d
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/extensions/NiciraMatchNshSpi.java
@@ -0,0 +1,91 @@
+/*
+ * 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.extensions;
+
+import static com.google.common.base.MoreObjects.toStringHelper;
+
+import java.util.Objects;
+
+import org.onlab.util.KryoNamespace;
+import org.onosproject.net.NshServicePathId;
+import org.onosproject.net.flow.AbstractExtension;
+import org.onosproject.net.flow.criteria.ExtensionSelector;
+import org.onosproject.net.flow.criteria.ExtensionSelectorType;
+
+/**
+ * Implementation of NSH Service Path Id selector.
+ */
+public final class NiciraMatchNshSpi extends AbstractExtension implements ExtensionSelector {
+ private NshServicePathId nshSpi;
+
+ private final KryoNamespace appKryo = new KryoNamespace.Builder().build();
+
+ /**
+ * Default constructor.
+ */
+ public NiciraMatchNshSpi() {
+ this.nshSpi = null;
+ }
+
+ /**
+ * Gets the network service path id to match.
+ *
+ * @return the nshSpi to match
+ */
+ public NshServicePathId nshSpi() {
+ return nshSpi;
+ }
+
+ @Override
+ public ExtensionSelectorType type() {
+ return ExtensionSelectorType.ExtensionSelectorTypes.NICIRA_MATCH_NSH_SPI.type();
+ }
+
+ @Override
+ public byte[] serialize() {
+ return appKryo.serialize(nshSpi);
+ }
+
+ @Override
+ public void deserialize(byte[] data) {
+ nshSpi = NshServicePathId.of(appKryo.deserialize(data));
+ }
+
+ @Override
+ public String toString() {
+ return toStringHelper(type().toString())
+ .add("nshSpi", nshSpi.toString())
+ .toString();
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(type(), nshSpi);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj instanceof NiciraMatchNshSpi) {
+ NiciraMatchNshSpi that = (NiciraMatchNshSpi) obj;
+ return Objects.equals(nshSpi, that.nshSpi) &&
+ Objects.equals(this.type(), that.type());
+ }
+ return false;
+ }
+}
diff --git a/drivers/default/src/main/java/org/onosproject/driver/extensions/NiciraMoveTreatmentFactory.java b/drivers/default/src/main/java/org/onosproject/driver/extensions/NiciraMoveTreatmentFactory.java
new file mode 100644
index 0000000..c7b00be
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/extensions/NiciraMoveTreatmentFactory.java
@@ -0,0 +1,100 @@
+/*
+ * 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.extensions;
+
+import org.onosproject.net.flow.instructions.ExtensionTreatment;
+import org.onosproject.net.flow.instructions.ExtensionTreatmentType;
+
+/**
+ * The factory of move treatment.
+ */
+public final class NiciraMoveTreatmentFactory {
+
+ /**
+ * Public constructor is prohibited.
+ */
+ private NiciraMoveTreatmentFactory() {
+
+ }
+
+ /**
+ * Creates a move treatment that move arp sha to tha.
+ *
+ * @return ExtensionTreatment
+ */
+ public static ExtensionTreatment createNiciraMovArpShaToTha() {
+ int srcOfs = 0;
+ int dstOfs = 0;
+ int nBits = 48;
+ int srcSha = 0x00012206;
+ int dstTha = 0x00012406;
+ return new DefaultMoveExtensionTreatment(srcOfs, dstOfs, nBits, srcSha,
+ dstTha,
+ ExtensionTreatmentType.ExtensionTreatmentTypes
+ .NICIRA_MOV_ARP_SHA_TO_THA.type());
+ }
+
+ /**
+ * Creates a move treatment that move arp spa to tpa.
+ *
+ * @return ExtensionTreatment
+ */
+ public static ExtensionTreatment createNiciraMovArpSpaToTpa() {
+ int srcOfs = 0;
+ int dstOfs = 0;
+ int nBits = 32;
+ int srcSpa = 0x00002004;
+ int dstTpa = 0x00002204;
+ return new DefaultMoveExtensionTreatment(srcOfs, dstOfs, nBits, srcSpa,
+ dstTpa,
+ ExtensionTreatmentType.ExtensionTreatmentTypes
+ .NICIRA_MOV_ARP_SPA_TO_TPA.type());
+ }
+
+ /**
+ * Creates a move treatment that move eth src to dst.
+ *
+ * @return ExtensionTreatment
+ */
+ public static ExtensionTreatment createNiciraMovEthSrcToDst() {
+ int srcOfs = 0;
+ int dstOfs = 0;
+ int nBits = 48;
+ int srcEth = 0x00000406;
+ int dstEth = 0x00000206;
+ return new DefaultMoveExtensionTreatment(srcOfs, dstOfs, nBits, srcEth,
+ dstEth,
+ ExtensionTreatmentType.ExtensionTreatmentTypes
+ .NICIRA_MOV_ETH_SRC_TO_DST.type());
+ }
+
+ /**
+ * Creates a move treatment that move ip src to dst.
+ *
+ * @return ExtensionTreatment
+ */
+ public static ExtensionTreatment createNiciraMovIpSrcToDst() {
+ int srcOfs = 0;
+ int dstOfs = 0;
+ int nBits = 32;
+ int srcIp = 0x00000e04;
+ int dstIp = 0x00001004;
+ return new DefaultMoveExtensionTreatment(srcOfs, dstOfs, nBits, srcIp,
+ dstIp,
+ ExtensionTreatmentType.ExtensionTreatmentTypes
+ .NICIRA_MOV_IP_SRC_TO_DST.type());
+ }
+}
diff --git a/drivers/default/src/main/java/org/onosproject/driver/extensions/NiciraResubmit.java b/drivers/default/src/main/java/org/onosproject/driver/extensions/NiciraResubmit.java
new file mode 100644
index 0000000..ea0d1b8
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/extensions/NiciraResubmit.java
@@ -0,0 +1,133 @@
+/*
+ * 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.extensions;
+
+import com.google.common.base.MoreObjects;
+import com.google.common.collect.Maps;
+
+import org.onlab.util.KryoNamespace;
+import org.onosproject.net.PortNumber;
+import org.onosproject.net.flow.AbstractExtension;
+import org.onosproject.net.flow.instructions.ExtensionTreatment;
+import org.onosproject.net.flow.instructions.ExtensionTreatmentType;
+import org.onosproject.store.serializers.PortNumberSerializer;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+/**
+ * Nicira resubmit extension instruction.
+ */
+public class NiciraResubmit extends AbstractExtension implements ExtensionTreatment {
+
+ private static final short DEFAULT_TABLE_ID = 0;
+
+ private PortNumber inPort;
+ private short table;
+
+ private final KryoNamespace appKryo = new KryoNamespace.Builder()
+ .register(new PortNumberSerializer(), PortNumber.class)
+ .register(Map.class).register(HashMap.class)
+ .register(byte[].class)
+ .build();
+
+ /**
+ * Creates a new resubmit instruction.
+ */
+ NiciraResubmit() {
+ inPort = null;
+ table = DEFAULT_TABLE_ID;
+ }
+
+ /**
+ * Creates a new resubmit instruction with a particular inPort.
+ *
+ * @param inPort in port number
+ */
+ public NiciraResubmit(PortNumber inPort) {
+ checkNotNull(inPort);
+ this.inPort = inPort;
+ this.table = DEFAULT_TABLE_ID;
+ }
+
+ /**
+ * Gets the inPort.
+ *
+ * @return inPort
+ */
+ public PortNumber inPort() {
+ return inPort;
+ }
+
+ /**
+ * Gets the table.
+ *
+ * @return table
+ */
+ public short table() {
+ return table;
+ }
+
+ @Override
+ public ExtensionTreatmentType type() {
+ return ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_RESUBMIT.type();
+ }
+
+ @Override
+ public void deserialize(byte[] data) {
+ Map<String, Object> values = appKryo.deserialize(data);
+ inPort = (PortNumber) values.get("inPort");
+ table = (short) values.get("table");
+ }
+
+ @Override
+ public byte[] serialize() {
+ Map<String, Object> values = Maps.newHashMap();
+ values.put("inPort", inPort);
+ values.put("table", table);
+ return appKryo.serialize(values);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(inPort, table);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj instanceof NiciraResubmit) {
+ NiciraResubmit that = (NiciraResubmit) obj;
+ return Objects.equals(inPort, that.inPort)
+ && (table == that.table());
+ }
+ return false;
+ }
+
+ @Override
+ public String toString() {
+ return MoreObjects.toStringHelper(getClass())
+ .add("inPort", inPort)
+ .add("table", table)
+ .toString();
+ }
+}
diff --git a/drivers/default/src/main/java/org/onosproject/driver/extensions/NiciraResubmitTable.java b/drivers/default/src/main/java/org/onosproject/driver/extensions/NiciraResubmitTable.java
new file mode 100644
index 0000000..b7792ed
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/extensions/NiciraResubmitTable.java
@@ -0,0 +1,147 @@
+/*
+ * 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.extensions;
+
+import com.google.common.base.MoreObjects;
+import com.google.common.collect.Maps;
+
+import org.onlab.util.KryoNamespace;
+import org.onosproject.net.PortNumber;
+import org.onosproject.net.flow.AbstractExtension;
+import org.onosproject.net.flow.instructions.ExtensionTreatment;
+import org.onosproject.net.flow.instructions.ExtensionTreatmentType;
+import org.onosproject.store.serializers.PortNumberSerializer;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+/**
+ * Nicira resubmit-table extension instruction.
+ */
+public class NiciraResubmitTable extends AbstractExtension implements
+ ExtensionTreatment {
+
+ private static final PortNumber DEFAULT_IN_PORT = PortNumber.portNumber(65528);
+
+ private PortNumber inPort;
+ private short table;
+
+ private final KryoNamespace appKryo = new KryoNamespace.Builder()
+ .register(new PortNumberSerializer(), PortNumber.class)
+ .register(Map.class).register(HashMap.class)
+ .register(byte[].class)
+ .build();
+
+ /**
+ * Creates a new resubmit-table instruction.
+ */
+ NiciraResubmitTable() {
+ inPort = DEFAULT_IN_PORT;
+ table = -1;
+ }
+
+ /**
+ * Creates a new resubmit-table instruction with a particular inPort and table.
+ *
+ * @param inPort the in port number
+ * @param table table
+ */
+ public NiciraResubmitTable(PortNumber inPort, short table) {
+ checkNotNull(inPort);
+ checkNotNull(table);
+ this.inPort = inPort;
+ this.table = table;
+ }
+
+ /**
+ * Creates a new resubmit-table instruction with a particular table.
+ *
+ * @param table table
+ */
+ public NiciraResubmitTable(short table) {
+ checkNotNull(table);
+ this.inPort = DEFAULT_IN_PORT;
+ this.table = table;
+ }
+
+ /**
+ * Gets the inPort.
+ *
+ * @return inPort
+ */
+ public PortNumber inPort() {
+ return inPort;
+ }
+
+ /**
+ * Gets the table.
+ *
+ * @return table
+ */
+ public short table() {
+ return table;
+ }
+
+ @Override
+ public ExtensionTreatmentType type() {
+ return ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_RESUBMIT_TABLE.type();
+ }
+
+ @Override
+ public void deserialize(byte[] data) {
+ Map<String, Object> values = appKryo.deserialize(data);
+ inPort = (PortNumber) values.get("inPort");
+ table = (short) values.get("table");
+ }
+
+ @Override
+ public byte[] serialize() {
+ Map<String, Object> values = Maps.newHashMap();
+ values.put("inPort", inPort);
+ values.put("table", table);
+ return appKryo.serialize(values);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(inPort, table);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj instanceof NiciraResubmitTable) {
+ NiciraResubmitTable that = (NiciraResubmitTable) obj;
+ return Objects.equals(inPort, that.inPort)
+ && (table == that.table);
+ }
+ return false;
+ }
+
+ @Override
+ public String toString() {
+ return MoreObjects.toStringHelper(getClass())
+ .add("inPort", inPort)
+ .add("table", table)
+ .toString();
+ }
+}
\ No newline at end of file
diff --git a/drivers/default/src/main/java/org/onosproject/driver/extensions/NiciraSetNshContextHeader.java b/drivers/default/src/main/java/org/onosproject/driver/extensions/NiciraSetNshContextHeader.java
new file mode 100644
index 0000000..a6d50a0
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/extensions/NiciraSetNshContextHeader.java
@@ -0,0 +1,110 @@
+/*
+ * 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.extensions;
+
+import java.util.Objects;
+
+import org.onlab.util.KryoNamespace;
+import org.onosproject.net.NshContextHeader;
+import org.onosproject.net.flow.AbstractExtension;
+import org.onosproject.net.flow.instructions.ExtensionTreatment;
+import org.onosproject.net.flow.instructions.ExtensionTreatmentType;
+
+import com.google.common.base.MoreObjects;
+
+/**
+ * Nicira set NSH Context header extension instruction.
+ */
+public class NiciraSetNshContextHeader extends AbstractExtension implements
+ ExtensionTreatment {
+
+ private NshContextHeader nshCh;
+ private ExtensionTreatmentType type;
+
+ private final KryoNamespace appKryo = new KryoNamespace.Builder().build();
+
+ /**
+ * Creates a new set nsh context header instruction.
+ *
+ * @param type extension treatment type
+ */
+ NiciraSetNshContextHeader(ExtensionTreatmentType type) {
+ this.nshCh = NshContextHeader.of(0);
+ this.type = type;
+ }
+
+ /**
+ * Creates a new set nsh context header instruction.
+ *
+ * @param nshCh nsh context header
+ * @param type extension treatment type
+ */
+ NiciraSetNshContextHeader(NshContextHeader nshCh, ExtensionTreatmentType type) {
+ this.nshCh = nshCh;
+ this.type = type;
+ }
+
+ /**
+ * Gets the nsh context header.
+ *
+ * @return nsh context header
+ */
+ public NshContextHeader nshCh() {
+ return nshCh;
+ }
+
+ @Override
+ public ExtensionTreatmentType type() {
+ return type;
+ }
+
+ @Override
+ public void deserialize(byte[] data) {
+ nshCh = NshContextHeader.of(appKryo.deserialize(data));
+ }
+
+ @Override
+ public byte[] serialize() {
+ return appKryo.serialize(nshCh.nshContextHeader());
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(nshCh, type);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj instanceof NiciraSetNshContextHeader) {
+ NiciraSetNshContextHeader that = (NiciraSetNshContextHeader) obj;
+ return Objects.equals(nshCh, that.nshCh) && Objects.equals(type, that.type);
+
+ }
+ return false;
+ }
+
+ @Override
+ public String toString() {
+ return MoreObjects.toStringHelper(getClass())
+ .add("nshCh", nshCh)
+ .add("type", type)
+ .toString();
+ }
+}
diff --git a/drivers/default/src/main/java/org/onosproject/driver/extensions/NiciraSetNshSi.java b/drivers/default/src/main/java/org/onosproject/driver/extensions/NiciraSetNshSi.java
new file mode 100644
index 0000000..dec66c9
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/extensions/NiciraSetNshSi.java
@@ -0,0 +1,103 @@
+/*
+ * 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.extensions;
+
+import java.util.Objects;
+
+import org.onlab.util.KryoNamespace;
+import org.onosproject.net.NshServiceIndex;
+import org.onosproject.net.flow.AbstractExtension;
+import org.onosproject.net.flow.instructions.ExtensionTreatment;
+import org.onosproject.net.flow.instructions.ExtensionTreatmentType;
+
+import com.google.common.base.MoreObjects;
+
+/**
+ * Nicira set NSH SI extension instruction.
+ */
+public class NiciraSetNshSi extends AbstractExtension implements
+ ExtensionTreatment {
+
+ private NshServiceIndex nshSi;
+
+ private final KryoNamespace appKryo = new KryoNamespace.Builder().build();
+
+ /**
+ * Creates a new set nsh si instruction.
+ */
+ NiciraSetNshSi() {
+ nshSi = NshServiceIndex.of((short) 0);
+ }
+
+ /**
+ * Creates a new set nsh si instruction with given si.
+ *
+ * @param nshSi nsh service index
+ */
+ NiciraSetNshSi(NshServiceIndex nshSi) {
+ this.nshSi = nshSi;
+ }
+
+ /**
+ * Gets the nsh service index.
+ *
+ * @return nsh service index
+ */
+ public NshServiceIndex nshSi() {
+ return nshSi;
+ }
+
+ @Override
+ public ExtensionTreatmentType type() {
+ return ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_SET_NSH_SI.type();
+ }
+
+ @Override
+ public void deserialize(byte[] data) {
+ nshSi = NshServiceIndex.of(appKryo.deserialize(data));
+ }
+
+ @Override
+ public byte[] serialize() {
+ return appKryo.serialize(nshSi.serviceIndex());
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(nshSi);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj instanceof NiciraSetNshSi) {
+ NiciraSetNshSi that = (NiciraSetNshSi) obj;
+ return Objects.equals(nshSi, that.nshSi);
+
+ }
+ return false;
+ }
+
+ @Override
+ public String toString() {
+ return MoreObjects.toStringHelper(getClass())
+ .add("nshSi", nshSi)
+ .toString();
+ }
+}
diff --git a/drivers/default/src/main/java/org/onosproject/driver/extensions/NiciraSetNshSpi.java b/drivers/default/src/main/java/org/onosproject/driver/extensions/NiciraSetNshSpi.java
new file mode 100644
index 0000000..72eef0d
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/extensions/NiciraSetNshSpi.java
@@ -0,0 +1,103 @@
+/*
+ * 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.extensions;
+
+import java.util.Objects;
+
+import org.onlab.util.KryoNamespace;
+import org.onosproject.net.NshServicePathId;
+import org.onosproject.net.flow.AbstractExtension;
+import org.onosproject.net.flow.instructions.ExtensionTreatment;
+import org.onosproject.net.flow.instructions.ExtensionTreatmentType;
+
+import com.google.common.base.MoreObjects;
+
+/**
+ * Nicira set NSH SPI extension instruction.
+ */
+public class NiciraSetNshSpi extends AbstractExtension implements
+ ExtensionTreatment {
+
+ private NshServicePathId nshSpi;
+
+ private final KryoNamespace appKryo = new KryoNamespace.Builder().build();
+
+ /**
+ * Creates a new set nsh spi instruction.
+ */
+ NiciraSetNshSpi() {
+ nshSpi = NshServicePathId.of(0);
+ }
+
+ /**
+ * Creates a new set nsh spi instruction with given spi.
+ *
+ * @param nshSpi nsh service path id
+ */
+ NiciraSetNshSpi(NshServicePathId nshSpi) {
+ this.nshSpi = nshSpi;
+ }
+
+ /**
+ * Gets the nsh service path id.
+ *
+ * @return nsh service path id
+ */
+ public NshServicePathId nshSpi() {
+ return nshSpi;
+ }
+
+ @Override
+ public ExtensionTreatmentType type() {
+ return ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_SET_NSH_SPI.type();
+ }
+
+ @Override
+ public void deserialize(byte[] data) {
+ nshSpi = NshServicePathId.of(appKryo.deserialize(data));
+ }
+
+ @Override
+ public byte[] serialize() {
+ return appKryo.serialize(nshSpi.servicePathId());
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(nshSpi);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj instanceof NiciraSetNshSpi) {
+ NiciraSetNshSpi that = (NiciraSetNshSpi) obj;
+ return Objects.equals(nshSpi, that.nshSpi);
+
+ }
+ return false;
+ }
+
+ @Override
+ public String toString() {
+ return MoreObjects.toStringHelper(getClass())
+ .add("nshSpi", nshSpi.toString())
+ .toString();
+ }
+}
diff --git a/drivers/default/src/main/java/org/onosproject/driver/extensions/NiciraSetTunnelDst.java b/drivers/default/src/main/java/org/onosproject/driver/extensions/NiciraSetTunnelDst.java
new file mode 100644
index 0000000..e28a1e2
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/extensions/NiciraSetTunnelDst.java
@@ -0,0 +1,110 @@
+/*
+ * 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.extensions;
+
+import com.google.common.base.MoreObjects;
+import org.onlab.packet.Ip4Address;
+import org.onlab.util.KryoNamespace;
+import org.onosproject.net.flow.AbstractExtension;
+import org.onosproject.net.flow.instructions.ExtensionTreatment;
+import org.onosproject.net.flow.instructions.ExtensionTreatmentType;
+import org.onosproject.store.serializers.Ip4AddressSerializer;
+
+import java.util.Objects;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+/**
+ * Nicira set tunnel destination extension instruction.
+ */
+public class NiciraSetTunnelDst extends AbstractExtension implements
+ ExtensionTreatment {
+
+ private Ip4Address tunnelDst;
+
+ private final KryoNamespace appKryo = new KryoNamespace.Builder()
+ .register(new Ip4AddressSerializer(), Ip4Address.class)
+ .register(byte[].class)
+ .build();
+
+ /**
+ * Creates a new set tunnel destination instruction.
+ */
+ NiciraSetTunnelDst() {
+ tunnelDst = null;
+ }
+
+ /**
+ * Creates a new set tunnel destination instruction with a particular IPv4
+ * address.
+ *
+ * @param tunnelDst tunnel destination IPv4 address
+ */
+ NiciraSetTunnelDst(Ip4Address tunnelDst) {
+ checkNotNull(tunnelDst);
+ this.tunnelDst = tunnelDst;
+ }
+
+ /**
+ * Gets the tunnel destination IPv4 address.
+ *
+ * @return tunnel destination IPv4 address
+ */
+ public Ip4Address tunnelDst() {
+ return tunnelDst;
+ }
+
+ @Override
+ public ExtensionTreatmentType type() {
+ return ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_SET_TUNNEL_DST.type();
+ }
+
+ @Override
+ public void deserialize(byte[] data) {
+ tunnelDst = appKryo.deserialize(data);
+ }
+
+ @Override
+ public byte[] serialize() {
+ return appKryo.serialize(tunnelDst);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(tunnelDst);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj instanceof NiciraSetTunnelDst) {
+ NiciraSetTunnelDst that = (NiciraSetTunnelDst) obj;
+ return Objects.equals(tunnelDst, that.tunnelDst);
+
+ }
+ return false;
+ }
+
+ @Override
+ public String toString() {
+ return MoreObjects.toStringHelper(getClass())
+ .add("tunnelDst", tunnelDst)
+ .toString();
+ }
+}
diff --git a/drivers/default/src/main/java/org/onosproject/driver/extensions/package-info.java b/drivers/default/src/main/java/org/onosproject/driver/extensions/package-info.java
new file mode 100644
index 0000000..d9d2460
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/extensions/package-info.java
@@ -0,0 +1,19 @@
+/*
+ * 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.
+ */
+/**
+ * Processing of Nicira extensions.
+ */
+package org.onosproject.driver.extensions;
diff --git a/drivers/default/src/main/java/org/onosproject/driver/handshaker/CalientFiberSwitchHandshaker.java b/drivers/default/src/main/java/org/onosproject/driver/handshaker/CalientFiberSwitchHandshaker.java
new file mode 100644
index 0000000..66aa8b7
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/handshaker/CalientFiberSwitchHandshaker.java
@@ -0,0 +1,188 @@
+/*
+ * 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.handshaker;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import org.onosproject.net.Device;
+import org.onosproject.openflow.controller.OpenFlowOpticalSwitch;
+import org.onosproject.openflow.controller.PortDescPropertyType;
+import org.onosproject.openflow.controller.driver.AbstractOpenFlowSwitch;
+import org.onosproject.openflow.controller.driver.SwitchDriverSubHandshakeAlreadyStarted;
+import org.onosproject.openflow.controller.driver.SwitchDriverSubHandshakeCompleted;
+import org.onosproject.openflow.controller.driver.SwitchDriverSubHandshakeNotStarted;
+import org.projectfloodlight.openflow.protocol.OFCalientFlowStatsRequest;
+import org.projectfloodlight.openflow.protocol.OFCalientPortDescStatsEntry;
+import org.projectfloodlight.openflow.protocol.OFCalientPortDescStatsReply;
+import org.projectfloodlight.openflow.protocol.OFCalientPortDescStatsRequest;
+import org.projectfloodlight.openflow.protocol.OFFlowStatsRequest;
+import org.projectfloodlight.openflow.protocol.OFMessage;
+import org.projectfloodlight.openflow.protocol.OFObject;
+import org.projectfloodlight.openflow.protocol.OFStatsReplyFlags;
+import org.projectfloodlight.openflow.protocol.OFStatsRequest;
+import org.projectfloodlight.openflow.protocol.OFType;
+import org.projectfloodlight.openflow.types.OFPort;
+import org.projectfloodlight.openflow.types.TableId;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/**
+ * Driver for Calient S160 Optical Circuit Switch. Untested on Calient S320 but probably works ok.
+ *
+ * Driver implements custom handshaker, and rewrites flow stats as expected by the device. Port stats are currently
+ * not supported.
+ *
+ * The device consists of OMS ports only.
+ */
+public class CalientFiberSwitchHandshaker extends AbstractOpenFlowSwitch implements OpenFlowOpticalSwitch {
+
+ private final AtomicBoolean driverHandshakeComplete = new AtomicBoolean(false);
+ private List<OFCalientPortDescStatsEntry> fiberPorts = new ArrayList<>();
+
+
+ @Override
+ public Boolean supportNxRole() {
+ return false;
+ }
+
+ @Override
+ public void startDriverHandshake() {
+ log.warn("Starting driver handshake for sw {}", getStringId());
+ if (startDriverHandshakeCalled) {
+ throw new SwitchDriverSubHandshakeAlreadyStarted();
+ }
+ startDriverHandshakeCalled = true;
+ try {
+ sendHandshakeOFExperimenterPortDescRequest();
+ } catch (IOException e) {
+ log.error("Exception while sending experimenter port desc:", e);
+ }
+
+ }
+
+ private void sendHandshakeOFExperimenterPortDescRequest() throws IOException {
+ // send multi part message for port description for optical switches
+ OFCalientPortDescStatsRequest portsRequest = factory()
+ .buildCalientPortDescStatsRequest()
+ .build();
+ log.warn("Sending experimenter port description message {}",
+ portsRequest.toString());
+ this.sendHandshakeMessage(portsRequest);
+ }
+
+ @Override
+ public boolean isDriverHandshakeComplete() {
+ return driverHandshakeComplete.get();
+ }
+
+ @Override
+ public void processDriverHandshakeMessage(OFMessage m) {
+ if (!startDriverHandshakeCalled) {
+ throw new SwitchDriverSubHandshakeNotStarted();
+ }
+ if (driverHandshakeComplete.get()) {
+ throw new SwitchDriverSubHandshakeCompleted(m);
+ }
+
+ switch (m.getType()) {
+ case BARRIER_REPLY:
+ break;
+ case ERROR:
+ log.error("Switch Error {} {}", getStringId(), m);
+ break;
+ case FEATURES_REPLY:
+ break;
+ case FLOW_REMOVED:
+ break;
+ case GET_ASYNC_REPLY:
+ break;
+ case PACKET_IN:
+ break;
+ case PORT_STATUS:
+ break;
+ case QUEUE_GET_CONFIG_REPLY:
+ break;
+ case ROLE_REPLY:
+ break;
+ case STATS_REPLY:
+ log.warn("Received port desc reply");
+ OFCalientPortDescStatsReply descStatsReply = (OFCalientPortDescStatsReply) m;
+ fiberPorts.addAll(descStatsReply.getPortDesc());
+ // Multi-part message
+ if (!descStatsReply.getFlags().contains(OFStatsReplyFlags.REPLY_MORE)) {
+ driverHandshakeComplete.set(true);
+ }
+ break;
+ default:
+ log.warn("Received message {} during switch-driver " +
+ "subhandshake " + "from switch {} ... " +
+ "Ignoring message", m,
+ getStringId());
+
+ }
+ }
+
+ @Override
+ public Device.Type deviceType() {
+ return Device.Type.FIBER_SWITCH;
+ }
+
+ @Override
+ public List<? extends OFObject> getPortsOf(PortDescPropertyType type) {
+ return ImmutableList.copyOf(fiberPorts);
+ }
+
+ @Override
+ public Set<PortDescPropertyType> getPortTypes() {
+ return ImmutableSet.of(PortDescPropertyType.OPTICAL_TRANSPORT);
+ }
+
+ @Override
+ public final void sendMsg(OFMessage m) {
+ OFMessage newMsg = m;
+
+ if (m.getType() == OFType.STATS_REQUEST) {
+ OFStatsRequest sr = (OFStatsRequest) m;
+ log.debug("Rebuilding stats request type {}", sr.getStatsType());
+ switch (sr.getStatsType()) {
+ case FLOW:
+ OFCalientFlowStatsRequest request = this.factory().buildCalientFlowStatsRequest()
+ .setCookie(((OFFlowStatsRequest) sr).getCookie())
+ .setCookieMask(((OFFlowStatsRequest) sr).getCookieMask())
+ .setMatch(this.factory().matchWildcardAll())
+ .setOutGroup(((OFFlowStatsRequest) sr).getOutGroup().getGroupNumber())
+ .setOutPort(OFPort.ANY)
+ .setTableId(TableId.ALL)
+ .setXid(sr.getXid())
+ .setFlags(sr.getFlags())
+ .build();
+ newMsg = request;
+ break;
+ case PORT:
+ // TODO
+ break;
+ default:
+ break;
+ }
+ }
+
+ super.sendMsg(newMsg);
+ }
+}
diff --git a/drivers/default/src/main/java/org/onosproject/driver/handshaker/CorsaSwitchHandshaker.java b/drivers/default/src/main/java/org/onosproject/driver/handshaker/CorsaSwitchHandshaker.java
new file mode 100644
index 0000000..a9ba6a1
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/handshaker/CorsaSwitchHandshaker.java
@@ -0,0 +1,109 @@
+/*
+ * 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.handshaker;
+
+import org.onosproject.net.meter.MeterId;
+import org.onosproject.openflow.controller.driver.AbstractOpenFlowSwitch;
+import org.onosproject.openflow.controller.driver.SwitchDriverSubHandshakeAlreadyStarted;
+import org.onosproject.openflow.controller.driver.SwitchDriverSubHandshakeCompleted;
+import org.onosproject.openflow.controller.driver.SwitchDriverSubHandshakeNotStarted;
+import org.projectfloodlight.openflow.protocol.OFBarrierRequest;
+import org.projectfloodlight.openflow.protocol.OFFlowMod;
+import org.projectfloodlight.openflow.protocol.OFGroupMod;
+import org.projectfloodlight.openflow.protocol.OFGroupType;
+import org.projectfloodlight.openflow.protocol.OFMessage;
+import org.projectfloodlight.openflow.protocol.OFMeterMod;
+import org.projectfloodlight.openflow.protocol.OFType;
+import org.projectfloodlight.openflow.types.OFGroup;
+import org.projectfloodlight.openflow.types.TableId;
+
+import java.util.Collections;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+
+/**
+ * Corsa switch handshaker.
+ */
+public class CorsaSwitchHandshaker extends AbstractOpenFlowSwitch {
+
+ private AtomicBoolean handshakeComplete = new AtomicBoolean(false);
+
+ private int barrierXid;
+
+
+ @Override
+ public Boolean supportNxRole() {
+ return false;
+ }
+
+ @Override
+ public void startDriverHandshake() {
+ if (startDriverHandshakeCalled) {
+ throw new SwitchDriverSubHandshakeAlreadyStarted();
+ }
+ startDriverHandshakeCalled = true;
+ OFFlowMod fm = factory().buildFlowDelete()
+ .setTableId(TableId.ALL)
+ .setOutGroup(OFGroup.ANY)
+ .build();
+
+ sendMsg(Collections.singletonList(fm));
+
+ OFGroupMod gm = factory().buildGroupDelete()
+ .setGroup(OFGroup.ALL)
+ .setGroupType(OFGroupType.ALL)
+ .build();
+
+ sendMsg(Collections.singletonList(gm));
+
+ OFMeterMod mm = factory().buildMeterMod()
+ .setMeterId(MeterId.ALL.id())
+ .build();
+
+ sendMsg(Collections.singletonList(mm));
+
+ barrierXid = getNextTransactionId();
+ OFBarrierRequest barrier = factory().buildBarrierRequest()
+ .setXid(barrierXid).build();
+
+
+ sendHandshakeMessage(barrier);
+
+ }
+
+ @Override
+ public boolean isDriverHandshakeComplete() {
+ if (!startDriverHandshakeCalled) {
+ throw new SwitchDriverSubHandshakeAlreadyStarted();
+ }
+ return handshakeComplete.get();
+ }
+
+ @Override
+ public void processDriverHandshakeMessage(OFMessage m) {
+ if (!startDriverHandshakeCalled) {
+ throw new SwitchDriverSubHandshakeNotStarted();
+ }
+ if (handshakeComplete.get()) {
+ throw new SwitchDriverSubHandshakeCompleted(m);
+ }
+ if (m.getType() == OFType.BARRIER_REPLY &&
+ m.getXid() == barrierXid) {
+ handshakeComplete.set(true);
+ }
+ }
+
+}
diff --git a/drivers/default/src/main/java/org/onosproject/driver/handshaker/DefaultSwitchHandshaker.java b/drivers/default/src/main/java/org/onosproject/driver/handshaker/DefaultSwitchHandshaker.java
new file mode 100644
index 0000000..fb78944
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/handshaker/DefaultSwitchHandshaker.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.handshaker;
+
+import org.onosproject.openflow.controller.driver.AbstractOpenFlowSwitch;
+import org.projectfloodlight.openflow.protocol.OFFlowAdd;
+import org.projectfloodlight.openflow.protocol.OFMessage;
+import org.projectfloodlight.openflow.protocol.OFPortDesc;
+import org.projectfloodlight.openflow.protocol.OFVersion;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.stream.Collectors;
+
+/**
+ * Default driver to fallback on if no other driver is available.
+ */
+public class DefaultSwitchHandshaker extends AbstractOpenFlowSwitch {
+
+ private static final int LOWEST_PRIORITY = 0;
+
+ @Override
+ public Boolean supportNxRole() {
+ return false;
+ }
+
+ @Override
+ public void startDriverHandshake() {
+ if (factory().getVersion() == OFVersion.OF_10) {
+ OFFlowAdd.Builder fmBuilder = factory().buildFlowAdd();
+ fmBuilder.setPriority(LOWEST_PRIORITY);
+ sendHandshakeMessage(fmBuilder.build());
+ }
+ }
+
+ @Override
+ public void processDriverHandshakeMessage(OFMessage m) {}
+
+ @Override
+ public boolean isDriverHandshakeComplete() {
+ return true;
+ }
+
+ @Override
+ public List<OFPortDesc> getPorts() {
+ if (this.factory().getVersion() == OFVersion.OF_10) {
+ return Collections.unmodifiableList(features.getPorts());
+ } else {
+ return Collections.unmodifiableList(
+ ports.stream().flatMap(p -> p.getEntries().stream())
+ .collect(Collectors.toList()));
+ }
+ }
+}
diff --git a/drivers/default/src/main/java/org/onosproject/driver/handshaker/NiciraSwitchHandshaker.java b/drivers/default/src/main/java/org/onosproject/driver/handshaker/NiciraSwitchHandshaker.java
new file mode 100644
index 0000000..4f61361
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/handshaker/NiciraSwitchHandshaker.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.driver.handshaker;
+
+import org.projectfloodlight.openflow.protocol.OFVersion;
+
+/**
+ * Default driver to fallback on if no other driver is available.
+ */
+public class NiciraSwitchHandshaker extends DefaultSwitchHandshaker {
+
+ @Override
+ public Boolean supportNxRole() {
+ if (this.factory().getVersion() == OFVersion.OF_10) {
+ return true;
+ }
+ return false;
+ }
+
+}
diff --git a/drivers/default/src/main/java/org/onosproject/driver/handshaker/OFOpticalSwitch13.java b/drivers/default/src/main/java/org/onosproject/driver/handshaker/OFOpticalSwitch13.java
new file mode 100644
index 0000000..64c6bc4
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/handshaker/OFOpticalSwitch13.java
@@ -0,0 +1,177 @@
+/*
+ * 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.handshaker;
+
+import org.projectfloodlight.openflow.protocol.OFExpPort;
+import org.projectfloodlight.openflow.protocol.OFExpPortDescReply;
+import org.projectfloodlight.openflow.protocol.OFExpPortDescRequest;
+import org.projectfloodlight.openflow.protocol.OFMessage;
+import org.projectfloodlight.openflow.protocol.OFPortDesc;
+import org.projectfloodlight.openflow.protocol.OFStatsReply;
+import org.projectfloodlight.openflow.protocol.OFStatsReplyFlags;
+import org.projectfloodlight.openflow.protocol.OFStatsType;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.stream.Collectors;
+
+import org.onosproject.net.Device;
+import org.onosproject.openflow.controller.OpenFlowOpticalSwitch;
+import org.onosproject.openflow.controller.PortDescPropertyType;
+import org.onosproject.openflow.controller.driver.AbstractOpenFlowSwitch;
+import org.onosproject.openflow.controller.driver.SwitchDriverSubHandshakeAlreadyStarted;
+import org.onosproject.openflow.controller.driver.SwitchDriverSubHandshakeCompleted;
+import org.onosproject.openflow.controller.driver.SwitchDriverSubHandshakeNotStarted;
+import org.projectfloodlight.openflow.protocol.OFObject;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+
+
+/**
+ * Open Flow Optical Switch handshaker - for Open Flow 13.
+ */
+public class OFOpticalSwitch13 extends AbstractOpenFlowSwitch implements OpenFlowOpticalSwitch {
+
+ private final AtomicBoolean driverHandshakeComplete = new AtomicBoolean(false);
+ private List<OFExpPort> expPortDes = new ArrayList<>();
+
+ @Override
+ public Boolean supportNxRole() {
+ return false;
+ }
+
+ @Override
+ public void startDriverHandshake() {
+ log.info("Starting driver handshake for sw {}", getStringId());
+ if (startDriverHandshakeCalled) {
+ throw new SwitchDriverSubHandshakeAlreadyStarted();
+ }
+ startDriverHandshakeCalled = true;
+
+ log.debug("sendHandshakeOFExperimenterPortDescRequest for sw {}", getStringId());
+
+ try {
+ sendHandshakeOFExperimenterPortDescRequest();
+ } catch (IOException e) {
+ log.error("Failed to send handshaker message OFExperimenterPortDescRequestfor sw {}", e);
+ }
+ }
+
+ @Override
+ public void processDriverHandshakeMessage(OFMessage m) {
+ if (!startDriverHandshakeCalled) {
+ throw new SwitchDriverSubHandshakeNotStarted();
+ }
+ if (driverHandshakeComplete.get()) {
+ throw new SwitchDriverSubHandshakeCompleted(m);
+ }
+
+ log.debug("processDriverHandshakeMessage for sw {}", getStringId());
+
+ switch (m.getType()) {
+ case STATS_REPLY: // multipart message is reported as STAT
+ processOFMultipartReply((OFStatsReply) m);
+ break;
+ default:
+ log.warn("Received message {} during switch-driver " +
+ "subhandshake " + "from switch {} ... " +
+ "Ignoring message", m,
+ getStringId());
+ }
+ }
+
+ private void processOFMultipartReply(OFStatsReply stats) {
+ log.debug("Received message {} during switch-driver " +
+ "subhandshake " + "from switch {} ... " +
+ stats,
+ getStringId());
+
+ if (stats.getStatsType() == OFStatsType.EXPERIMENTER) {
+ try {
+ OFExpPortDescReply expPortDescReply = (OFExpPortDescReply) stats;
+ expPortDes.addAll(expPortDescReply.getEntries());
+ if (!expPortDescReply.getFlags().contains(OFStatsReplyFlags.REPLY_MORE)) {
+ driverHandshakeComplete.set(true);
+ return;
+ }
+ } catch (ClassCastException e) {
+ log.error("Unexspected Experimenter Multipart message type {} ",
+ stats.getClass().getName());
+ }
+ }
+ }
+
+
+ @Override
+ public boolean isDriverHandshakeComplete() {
+ return driverHandshakeComplete.get();
+ }
+
+ private void sendHandshakeOFExperimenterPortDescRequest() throws
+ IOException {
+
+ OFExpPortDescRequest preq = factory()
+ .buildExpPortDescRequest()
+ .setXid(getNextTransactionId())
+ .build();
+
+ log.debug("Sending experimented port description " +
+ "message " +
+ "{}",
+ preq.toString());
+
+ this.sendHandshakeMessage(preq);
+ }
+
+ @Override
+ public Device.Type deviceType() {
+ String hwDesc = hardwareDescription();
+ switch (hwDesc) {
+ case "Optical-ROADM":
+ return Device.Type.ROADM;
+ case "Optical-OTN":
+ return Device.Type.OTN;
+ default:
+ log.error("Unsupported hardwareDescription {}", hwDesc);
+ return Device.Type.OTHER;
+ }
+ }
+
+ /*
+ * OduClt ports are reported as regular ETH ports.
+ */
+ @Override
+ public List<OFPortDesc> getPorts() {
+ return ImmutableList.copyOf(
+ ports.stream().flatMap(p -> p.getEntries().stream())
+ .collect(Collectors.toList()));
+ }
+
+ @Override
+ public List<? extends OFObject> getPortsOf(PortDescPropertyType type) {
+ return ImmutableList.copyOf(expPortDes);
+ }
+
+ @Override
+ public Set<PortDescPropertyType> getPortTypes() {
+ return ImmutableSet.of(PortDescPropertyType.OPTICAL_TRANSPORT);
+ }
+
+}
diff --git a/drivers/default/src/main/java/org/onosproject/driver/handshaker/OfOpticalSwitchImplLinc13.java b/drivers/default/src/main/java/org/onosproject/driver/handshaker/OfOpticalSwitchImplLinc13.java
new file mode 100644
index 0000000..8d5822c
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/handshaker/OfOpticalSwitchImplLinc13.java
@@ -0,0 +1,350 @@
+/*
+ * 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.handshaker;
+
+import com.google.common.collect.ImmutableSet;
+import org.onosproject.net.Device;
+import org.onosproject.openflow.controller.OpenFlowOpticalSwitch;
+import org.onosproject.openflow.controller.PortDescPropertyType;
+import org.onosproject.openflow.controller.driver.AbstractOpenFlowSwitch;
+import org.onosproject.openflow.controller.driver.SwitchDriverSubHandshakeAlreadyStarted;
+import org.onosproject.openflow.controller.driver.SwitchDriverSubHandshakeCompleted;
+import org.onosproject.openflow.controller.driver.SwitchDriverSubHandshakeNotStarted;
+import org.projectfloodlight.openflow.protocol.OFCircuitPortStatus;
+import org.projectfloodlight.openflow.protocol.OFCircuitPortsReply;
+import org.projectfloodlight.openflow.protocol.OFCircuitPortsRequest;
+import org.projectfloodlight.openflow.protocol.OFFlowMod;
+import org.projectfloodlight.openflow.protocol.OFFlowStatsRequest;
+import org.projectfloodlight.openflow.protocol.OFMessage;
+import org.projectfloodlight.openflow.protocol.OFObject;
+import org.projectfloodlight.openflow.protocol.OFPortDesc;
+import org.projectfloodlight.openflow.protocol.OFPortDescPropOpticalTransport;
+import org.projectfloodlight.openflow.protocol.OFPortDescStatsReply;
+import org.projectfloodlight.openflow.protocol.OFPortOptical;
+import org.projectfloodlight.openflow.protocol.OFStatsReply;
+import org.projectfloodlight.openflow.protocol.OFStatsType;
+import org.projectfloodlight.openflow.protocol.action.OFAction;
+import org.projectfloodlight.openflow.protocol.action.OFActionSetField;
+import org.projectfloodlight.openflow.protocol.match.Match;
+import org.projectfloodlight.openflow.protocol.match.MatchField;
+import org.projectfloodlight.openflow.protocol.oxm.OFOxmExpOchSigId;
+import org.projectfloodlight.openflow.types.CircuitSignalID;
+import org.projectfloodlight.openflow.types.U8;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/**
+ * LINC-OE Optical Emulator switch class.
+ *
+ * The LINC ROADM emulator exposes two types of ports: OCh ports connect to ports in the packet layer,
+ * while OMS ports connect to an OMS port on a neighbouring ROADM.
+ *
+ * LINC sends the tap ports (OCh for our purposes) in the regular port desc stats reply,
+ * while it sends *all* ports (both tap and WDM ports, i.e., OCh and OMS) in the experimenter port desc stats reply.
+ *
+ * As LINC implements custom OF optical extensions (in contrast to the final standard as specified in
+ * ONF TS-022 (March 15, 2015), we need to rewrite flow stat requests and flow mods in {@link #sendMsg(OFMessage)}.
+ */
+public class OfOpticalSwitchImplLinc13 extends AbstractOpenFlowSwitch implements OpenFlowOpticalSwitch {
+
+ private final AtomicBoolean driverHandshakeComplete = new AtomicBoolean(false);
+ private long barrierXidToWaitFor = -1;
+
+ private List<OFPortOptical> opticalPorts;
+
+ @Override
+ public void startDriverHandshake() {
+ log.warn("Starting driver handshake for sw {}", getStringId());
+ if (startDriverHandshakeCalled) {
+ throw new SwitchDriverSubHandshakeAlreadyStarted();
+ }
+ startDriverHandshakeCalled = true;
+ try {
+ sendHandshakeOFExperimenterPortDescRequest();
+ } catch (IOException e) {
+ log.error("LINC-OE exception while sending experimenter port desc:",
+ e);
+ }
+ }
+
+ @Override
+ public boolean isDriverHandshakeComplete() {
+ return driverHandshakeComplete.get();
+ }
+
+ @Override
+ public void processDriverHandshakeMessage(OFMessage m) {
+ if (!startDriverHandshakeCalled) {
+ throw new SwitchDriverSubHandshakeNotStarted();
+ }
+ if (driverHandshakeComplete.get()) {
+ throw new SwitchDriverSubHandshakeCompleted(m);
+ }
+
+ switch (m.getType()) {
+ case BARRIER_REPLY:
+ if (m.getXid() == barrierXidToWaitFor) {
+ log.debug("LINC-OE Received barrier response");
+ }
+ break;
+ case ERROR:
+ log.error("Switch {} Error {}", getStringId(), m);
+ break;
+ case FEATURES_REPLY:
+ break;
+ case FLOW_REMOVED:
+ break;
+ case GET_ASYNC_REPLY:
+ break;
+ case PACKET_IN:
+ break;
+ case PORT_STATUS:
+ log.warn("****LINC-OE Port Status {} {}", getStringId(), m);
+ processOFPortStatus((OFCircuitPortStatus) m);
+ break;
+ case QUEUE_GET_CONFIG_REPLY:
+ break;
+ case ROLE_REPLY:
+ break;
+ case STATS_REPLY:
+ OFStatsReply stats = (OFStatsReply) m;
+ if (stats.getStatsType() == OFStatsType.EXPERIMENTER) {
+ log.warn("LINC-OE : Received stats reply message {}", m);
+ createOpticalPortList((OFCircuitPortsReply) m);
+ driverHandshakeComplete.set(true);
+ }
+ break;
+ default:
+ log.warn("Received message {} during switch-driver " +
+ "subhandshake " + "from switch {} ... " +
+ "Ignoring message", m,
+ getStringId());
+
+ }
+ }
+
+ public void processOFPortStatus(OFCircuitPortStatus ps) {
+ log.debug("LINC-OE ..OF Port Status :", ps);
+ }
+
+ private void sendHandshakeOFExperimenterPortDescRequest() throws
+ IOException {
+ // send multi part message for port description for optical switches
+ OFCircuitPortsRequest circuitPortsRequest = factory()
+ .buildCircuitPortsRequest().setXid(getNextTransactionId())
+ .build();
+ log.warn("LINC-OE : Sending experimented circuit port stats " +
+ "message " +
+ "{}",
+ circuitPortsRequest.toString());
+ this.sendHandshakeMessage(circuitPortsRequest);
+ }
+
+ @Override
+ /**
+ * Returns a list of standard (Ethernet) ports.
+ *
+ * @return List of ports
+ */
+ public List<OFPortDesc> getPorts() {
+ return Collections.EMPTY_LIST;
+ }
+
+ /**
+ * Rewrite match object to use LINC OF optical extensions.
+ *
+ * @param match original match
+ * @return rewritten match
+ */
+ private Match rewriteMatch(Match match) {
+ Match.Builder mBuilder = factory().buildMatch();
+ for (MatchField mf : match.getMatchFields()) {
+ if (mf == MatchField.EXP_OCH_SIG_ID) {
+ mBuilder.setExact(MatchField.OCH_SIGID, (CircuitSignalID) match.get(mf));
+ continue;
+ }
+ if (mf == MatchField.EXP_OCH_SIGTYPE) {
+ mBuilder.setExact(MatchField.OCH_SIGTYPE, (U8) match.get(mf));
+ continue;
+ }
+ mBuilder.setExact(mf, match.get(mf));
+ }
+
+ return mBuilder.build();
+ }
+
+ /**
+ * Rewrite actions to use LINC OF optical extensions.
+ *
+ * @param actions original actions
+ * @return rewritten actions
+ */
+ private List<OFAction> rewriteActions(List<OFAction> actions) {
+ List<OFAction> newActions = new LinkedList<>();
+
+ for (OFAction action : actions) {
+ if (!(action instanceof OFActionSetField)) {
+ newActions.add(action);
+ continue;
+ }
+
+ OFActionSetField sf = (OFActionSetField) action;
+ if (!(sf.getField() instanceof OFOxmExpOchSigId)) {
+ newActions.add(action);
+ continue;
+ }
+
+ OFOxmExpOchSigId oxm = (OFOxmExpOchSigId) sf.getField();
+ CircuitSignalID signalId = oxm.getValue();
+
+ newActions.add(
+ factory().actions().circuit(factory().oxms().ochSigid(signalId)));
+ }
+
+ return newActions;
+ }
+
+ @Override
+ public void sendMsg(OFMessage msg) {
+ // Ignore everything but flow mods and stat requests
+ if (!(msg instanceof OFFlowMod || msg instanceof OFFlowStatsRequest)) {
+ super.sendMsg(msg);
+ return;
+ }
+
+ Match newMatch;
+ OFMessage newMsg = null;
+
+ if (msg instanceof OFFlowStatsRequest) {
+ // Rewrite match only
+ OFFlowStatsRequest fsr = (OFFlowStatsRequest) msg;
+ newMatch = rewriteMatch(fsr.getMatch());
+ newMsg = fsr.createBuilder().setMatch(newMatch).build();
+ } else if (msg instanceof OFFlowMod) {
+ // Rewrite match and actions
+ OFFlowMod fm = (OFFlowMod) msg;
+ newMatch = rewriteMatch(fm.getMatch());
+ List<OFAction> actions = rewriteActions(fm.getActions());
+ newMsg = fm.createBuilder().setMatch(newMatch).setActions(actions).build();
+ }
+
+ super.sendMsg(newMsg);
+ }
+
+ @Override
+ public Boolean supportNxRole() {
+ return false;
+ }
+
+ @Override
+ public Device.Type deviceType() {
+ return Device.Type.ROADM;
+ }
+
+ /**
+ * Checks if given port is also part of the regular port desc stats, i.e., is the port a tap port.
+ *
+ * @param port given port number
+ * @return true if the port is a tap (OCh), false otherwise (OMS port)
+ */
+ private boolean isOChPort(long port) {
+ for (OFPortDescStatsReply reply : this.ports) {
+ for (OFPortDesc p : reply.getEntries()) {
+ if (p.getPortNo().getPortNumber() == port) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Creates an OpenFlow optical port based on the given port and transport type.
+ *
+ * @param port OpenFlow optical port
+ * @param type transport type
+ * @return OpenFlow optical port
+ */
+ private OFPortOptical createOpticalPort(OFPortOptical port, short type) {
+ List<OFPortDescPropOpticalTransport> descList = new ArrayList<>(port.getDesc().size());
+
+ for (OFPortDescPropOpticalTransport desc : port.getDesc()) {
+ OFPortDescPropOpticalTransport newDesc = desc.createBuilder()
+ .setType(desc.getType())
+ .setPortSignalType(type)
+ .setPortType(desc.getPortType())
+ .setReserved(desc.getReserved())
+ .build();
+ descList.add(newDesc);
+ }
+
+ OFPortOptical newPort = port.createBuilder()
+ .setConfig(port.getConfig())
+ .setDesc(descList)
+ .setHwAddr(port.getHwAddr())
+ .setName(port.getName())
+ .setPortNo(port.getPortNo())
+ .setState(port.getState())
+ .build();
+
+ return newPort;
+ }
+
+ /**
+ * Builds list of OFPortOptical ports based on the multi-part circuit ports reply.
+ *
+ * Ensure the optical transport port's signal type is configured correctly.
+ *
+ * @param wPorts OF reply with circuit ports
+ */
+ private void createOpticalPortList(OFCircuitPortsReply wPorts) {
+ opticalPorts = new ArrayList<>(wPorts.getEntries().size());
+
+ for (OFPortOptical p : wPorts.getEntries()) {
+ short signalType;
+
+ // FIXME: use constants once loxi has full optical extensions
+ if (isOChPort(p.getPortNo().getPortNumber())) {
+ signalType = 5; // OCH port
+ } else {
+ signalType = 2; // OMS port
+ }
+
+ opticalPorts.add(createOpticalPort(p, signalType));
+ }
+ }
+
+ @Override
+ public List<? extends OFObject> getPortsOf(PortDescPropertyType type) {
+ if (!type.equals(PortDescPropertyType.OPTICAL_TRANSPORT)) {
+ return Collections.EMPTY_LIST;
+ }
+
+ return opticalPorts;
+ }
+
+ @Override
+ public Set<PortDescPropertyType> getPortTypes() {
+ return ImmutableSet.of(PortDescPropertyType.OPTICAL_TRANSPORT);
+ }
+}
diff --git a/drivers/default/src/main/java/org/onosproject/driver/handshaker/OplinkRoadmHandshaker.java b/drivers/default/src/main/java/org/onosproject/driver/handshaker/OplinkRoadmHandshaker.java
new file mode 100644
index 0000000..bbfb9c2
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/handshaker/OplinkRoadmHandshaker.java
@@ -0,0 +1,188 @@
+/*
+ * 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.driver.handshaker;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.onosproject.net.Device;
+import org.onosproject.openflow.controller.OpenFlowOpticalSwitch;
+import org.onosproject.openflow.controller.PortDescPropertyType;
+import org.onosproject.openflow.controller.driver.AbstractOpenFlowSwitch;
+import org.onosproject.openflow.controller.driver.SwitchDriverSubHandshakeAlreadyStarted;
+import org.onosproject.openflow.controller.driver.SwitchDriverSubHandshakeCompleted;
+import org.onosproject.openflow.controller.driver.SwitchDriverSubHandshakeNotStarted;
+import org.projectfloodlight.openflow.protocol.OFCircuitPortStatus;
+import org.projectfloodlight.openflow.protocol.OFCircuitPortsReply;
+import org.projectfloodlight.openflow.protocol.OFCircuitPortsRequest;
+import org.projectfloodlight.openflow.protocol.OFMessage;
+import org.projectfloodlight.openflow.protocol.OFObject;
+import org.projectfloodlight.openflow.protocol.OFPortDesc;
+import org.projectfloodlight.openflow.protocol.OFPortOptical;
+import org.projectfloodlight.openflow.protocol.OFStatsReply;
+import org.projectfloodlight.openflow.protocol.OFStatsType;
+
+/**
+ * Driver for Oplink single WSS 8D ROADM.
+ *
+ * Driver implements custom handshaker and supports for Optical channel Port based on OpenFlow OTN extension.
+ * The device consists of Och ports, and performances wavelength cross-connect among the ports.
+ */
+public class OplinkRoadmHandshaker extends AbstractOpenFlowSwitch implements OpenFlowOpticalSwitch {
+ private final AtomicBoolean driverHandshakeComplete = new AtomicBoolean(false);
+ private List<OFPortOptical> opticalPorts;
+
+ @Override
+ public List<? extends OFObject> getPortsOf(PortDescPropertyType type) {
+ return ImmutableList.copyOf(opticalPorts);
+ }
+
+ @Override
+ /**
+ * Returns a list of standard (Ethernet) ports.
+ *
+ * @return List of ports
+ */
+ public List<OFPortDesc> getPorts() {
+ return Collections.EMPTY_LIST;
+ }
+
+ @Override
+ public Set<PortDescPropertyType> getPortTypes() {
+ return ImmutableSet.of(PortDescPropertyType.OPTICAL_TRANSPORT);
+ }
+
+ @Override
+ public Boolean supportNxRole() {
+ return false;
+ }
+
+ @Override
+ public void startDriverHandshake() {
+ log.warn("Starting driver handshake for sw {}", getStringId());
+ if (startDriverHandshakeCalled) {
+ throw new SwitchDriverSubHandshakeAlreadyStarted();
+ }
+ startDriverHandshakeCalled = true;
+ try {
+ sendHandshakeOFExperimenterPortDescRequest();
+ } catch (IOException e) {
+ log.error("OPLK ROADM exception while sending experimenter port desc:", e);
+ }
+ }
+
+ @Override
+ public boolean isDriverHandshakeComplete() {
+ return driverHandshakeComplete.get();
+ }
+
+ @Override
+ public void processDriverHandshakeMessage(OFMessage m) {
+
+ if (!startDriverHandshakeCalled) {
+ throw new SwitchDriverSubHandshakeNotStarted();
+ }
+
+ if (driverHandshakeComplete.get()) {
+ throw new SwitchDriverSubHandshakeCompleted(m);
+ }
+
+ switch (m.getType()) {
+ case BARRIER_REPLY:
+ log.debug("OPLK ROADM Received barrier response");
+ break;
+ case ERROR:
+ log.error("Switch {} Error {}", getStringId(), m);
+ break;
+ case FEATURES_REPLY:
+ break;
+ case FLOW_REMOVED:
+ break;
+ case GET_ASYNC_REPLY:
+ break;
+ case PACKET_IN:
+ break;
+ case PORT_STATUS:
+ processOFPortStatus((OFCircuitPortStatus) m);
+ break;
+ case QUEUE_GET_CONFIG_REPLY:
+ break;
+ case ROLE_REPLY:
+ break;
+ case STATS_REPLY:
+ OFStatsReply stats = (OFStatsReply) m;
+ if (stats.getStatsType() == OFStatsType.EXPERIMENTER) {
+ log.warn("OPLK ROADM : Received multipart (port desc) reply message {}", m);
+ //OTN Optical extension 1.0 port-desc
+ createOpticalPortList((OFCircuitPortsReply) m);
+ driverHandshakeComplete.set(true);
+ }
+ break;
+ default:
+ log.warn("Received message {} during switch-driver " +
+ "subhandshake " + "from switch {} ... " +
+ "Ignoring message", m,
+ getStringId());
+
+ }
+ }
+
+ private void processOFPortStatus(OFCircuitPortStatus ps) {
+ log.debug("OPLK ROADM ..OF Port Status :", ps);
+ }
+
+ @Override
+ public Device.Type deviceType() {
+ return Device.Type.ROADM;
+ }
+
+ @Override
+ public final void sendMsg(OFMessage m) {
+ OFMessage newMsg = m;
+ //Stub for later enhancement.
+ super.sendMsg(newMsg);
+ }
+
+ private void sendHandshakeOFExperimenterPortDescRequest() throws IOException {
+ // send multi part message for port description for optical switches
+ OFCircuitPortsRequest circuitPortsRequest = factory()
+ .buildCircuitPortsRequest().setXid(getNextTransactionId())
+ .build();
+ log.info("OPLK ROADM : Sending experimented circuit port stats " +
+ "message " +
+ "{}",
+ circuitPortsRequest);
+ this.sendHandshakeMessage(circuitPortsRequest);
+ }
+
+ /**
+ * Builds list of OFPortOptical ports based on the multi-part circuit ports reply.
+ * Ensure the optical transport port's signal type is configured correctly.
+ *
+ * @param wPorts OF reply with circuit ports
+ */
+ private void createOpticalPortList(OFCircuitPortsReply wPorts) {
+ opticalPorts = new ArrayList<>();
+ opticalPorts.addAll(wPorts.getEntries());
+ }
+}
diff --git a/drivers/default/src/main/java/org/onosproject/driver/handshaker/package-info.java b/drivers/default/src/main/java/org/onosproject/driver/handshaker/package-info.java
new file mode 100644
index 0000000..754309e
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/handshaker/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * 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.
+ */
+
+/**
+ * Implementations of the OpenFlow handshake driver behaviours.
+ */
+package org.onosproject.driver.handshaker;
\ No newline at end of file
diff --git a/drivers/default/src/main/java/org/onosproject/driver/package-info.java b/drivers/default/src/main/java/org/onosproject/driver/package-info.java
new file mode 100644
index 0000000..41a6a02
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * 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.
+ */
+
+/**
+ * Bootstrap of built-in device drivers.
+ */
+package org.onosproject.driver;
\ No newline at end of file
diff --git a/drivers/default/src/main/java/org/onosproject/driver/pipeline/CentecV350Pipeline.java b/drivers/default/src/main/java/org/onosproject/driver/pipeline/CentecV350Pipeline.java
new file mode 100644
index 0000000..2c6e24c
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/pipeline/CentecV350Pipeline.java
@@ -0,0 +1,641 @@
+/*
+ * 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 com.google.common.cache.Cache;
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.RemovalCause;
+import com.google.common.cache.RemovalNotification;
+
+import org.onlab.osgi.ServiceDirectory;
+import org.onlab.packet.Ethernet;
+import org.onlab.packet.IPv4;
+import org.onlab.packet.TpPort;
+import org.onlab.packet.VlanId;
+import org.onlab.util.KryoNamespace;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreService;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.PortNumber;
+import org.onosproject.net.behaviour.NextGroup;
+import org.onosproject.net.behaviour.Pipeliner;
+import org.onosproject.net.behaviour.PipelinerContext;
+import org.onosproject.net.driver.AbstractHandlerBehaviour;
+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 org.onosproject.net.flow.FlowRuleOperations;
+import org.onosproject.net.flow.FlowRuleOperationsContext;
+import org.onosproject.net.flow.FlowRuleService;
+import org.onosproject.net.flow.TrafficSelector;
+import org.onosproject.net.flow.TrafficTreatment;
+import org.onosproject.net.flow.criteria.Criterion;
+import org.onosproject.net.flow.criteria.Criteria;
+import org.onosproject.net.flow.criteria.EthCriterion;
+import org.onosproject.net.flow.criteria.PortCriterion;
+import org.onosproject.net.flow.criteria.EthTypeCriterion;
+import org.onosproject.net.flow.criteria.IPCriterion;
+import org.onosproject.net.flow.criteria.VlanIdCriterion;
+import org.onosproject.net.flow.instructions.Instruction;
+import org.onosproject.net.flow.instructions.L2ModificationInstruction;
+import org.onosproject.net.flowobjective.FilteringObjective;
+import org.onosproject.net.flowobjective.FlowObjectiveStore;
+import org.onosproject.net.flowobjective.ForwardingObjective;
+import org.onosproject.net.flowobjective.NextObjective;
+import org.onosproject.net.flowobjective.Objective;
+import org.onosproject.net.flowobjective.ObjectiveError;
+import org.onosproject.net.group.DefaultGroupBucket;
+import org.onosproject.net.group.DefaultGroupDescription;
+import org.onosproject.net.group.DefaultGroupKey;
+import org.onosproject.net.group.Group;
+import org.onosproject.net.group.GroupBucket;
+import org.onosproject.net.group.GroupBuckets;
+import org.onosproject.net.group.GroupDescription;
+import org.onosproject.net.group.GroupEvent;
+import org.onosproject.net.group.GroupKey;
+import org.onosproject.net.group.GroupListener;
+import org.onosproject.net.group.GroupService;
+import org.slf4j.Logger;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+
+import static org.onlab.util.Tools.groupedThreads;
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * Driver for Centec's V350 switches.
+ */
+public class CentecV350Pipeline extends AbstractHandlerBehaviour implements Pipeliner {
+
+ protected static final int PORT_VLAN_TABLE = 0;
+ protected static final int FILTER_TABLE = 1;
+ // TMAC is configured in MAC Table to redirect packets to ROUTE_TABLE.
+ protected static final int MAC_TABLE = 2;
+ protected static final int ROUTE_TABLE = 3;
+
+ private static final long DEFAULT_METADATA = 100;
+ private static final long DEFAULT_METADATA_MASK = 0xffffffffffffffffL;
+
+ // Priority used in PORT_VLAN Table, the only priority accepted is PORT_VLAN_TABLE_PRIORITY.
+ // The packet passed PORT+VLAN check will goto FILTER Table.
+ private static final int PORT_VLAN_TABLE_PRIORITY = 0xffff;
+
+ // Priority used in Filter Table.
+ private static final int FILTER_TABLE_CONTROLLER_PRIORITY = 500;
+ // TMAC priority should be lower than controller.
+ private static final int FILTER_TABLE_TMAC_PRIORITY = 200;
+ private static final int FILTER_TABLE_HIGHEST_PRIORITY = 0xffff;
+
+ // Priority used in MAC Table.
+ // We do exact matching for DMAC+metadata, so priority is ignored and required to be set to 0xffff.
+ private static final int MAC_TABLE_PRIORITY = 0xffff;
+
+ // Priority used in Route Table.
+ // We do LPM matching in Route Table, so priority is ignored and required to be set to 0xffff.
+ private static final int ROUTE_TABLE_PRIORITY = 0xffff;
+
+ private static final short BGP_PORT = 179;
+
+ private final Logger log = getLogger(getClass());
+
+ private ServiceDirectory serviceDirectory;
+ private FlowRuleService flowRuleService;
+ private CoreService coreService;
+ private GroupService groupService;
+ private FlowObjectiveStore flowObjectiveStore;
+ private DeviceId deviceId;
+ private ApplicationId appId;
+
+ private KryoNamespace appKryo = new KryoNamespace.Builder()
+ .register(GroupKey.class)
+ .register(DefaultGroupKey.class)
+ .register(CentecV350Group.class)
+ .register(byte[].class)
+ .build();
+
+ private Cache<GroupKey, NextObjective> pendingGroups;
+
+ private ScheduledExecutorService groupChecker =
+ Executors.newScheduledThreadPool(2, groupedThreads("onos/pipeliner",
+ "centec-V350-%d"));
+
+ @Override
+ public void init(DeviceId deviceId, PipelinerContext context) {
+ this.serviceDirectory = context.directory();
+ this.deviceId = deviceId;
+
+ pendingGroups = CacheBuilder.newBuilder()
+ .expireAfterWrite(20, TimeUnit.SECONDS)
+ .removalListener((RemovalNotification<GroupKey, NextObjective> notification) -> {
+ if (notification.getCause() == RemovalCause.EXPIRED) {
+ fail(notification.getValue(), ObjectiveError.GROUPINSTALLATIONFAILED);
+ }
+ }).build();
+
+ groupChecker.scheduleAtFixedRate(new GroupChecker(), 0, 500, TimeUnit.MILLISECONDS);
+
+ coreService = serviceDirectory.get(CoreService.class);
+ flowRuleService = serviceDirectory.get(FlowRuleService.class);
+ groupService = serviceDirectory.get(GroupService.class);
+ flowObjectiveStore = context.store();
+
+ groupService.addListener(new InnerGroupListener());
+
+ appId = coreService.registerApplication(
+ "org.onosproject.driver.CentecV350Pipeline");
+
+ initializePipeline();
+ }
+
+ @Override
+ public void filter(FilteringObjective filteringObjective) {
+ if (filteringObjective.type() == FilteringObjective.Type.PERMIT) {
+ processFilter(filteringObjective,
+ filteringObjective.op() == Objective.Operation.ADD,
+ filteringObjective.appId());
+ } else {
+ fail(filteringObjective, ObjectiveError.UNSUPPORTED);
+ }
+ }
+
+ @Override
+ public void forward(ForwardingObjective fwd) {
+ Collection<FlowRule> rules;
+ FlowRuleOperations.Builder flowBuilder = FlowRuleOperations.builder();
+
+ rules = processForward(fwd);
+ switch (fwd.op()) {
+ case ADD:
+ rules.stream()
+ .filter(Objects::nonNull)
+ .forEach(flowBuilder::add);
+ break;
+ case REMOVE:
+ rules.stream()
+ .filter(Objects::nonNull)
+ .forEach(flowBuilder::remove);
+ break;
+ default:
+ fail(fwd, ObjectiveError.UNKNOWN);
+ log.warn("Unknown forwarding type {}", fwd.op());
+ }
+
+
+ flowRuleService.apply(flowBuilder.build(new FlowRuleOperationsContext() {
+ @Override
+ public void onSuccess(FlowRuleOperations ops) {
+ pass(fwd);
+ }
+
+ @Override
+ public void onError(FlowRuleOperations ops) {
+ fail(fwd, ObjectiveError.FLOWINSTALLATIONFAILED);
+ }
+ }));
+
+ }
+
+ @Override
+ public void next(NextObjective nextObjective) {
+ switch (nextObjective.type()) {
+ case SIMPLE:
+ Collection<TrafficTreatment> treatments = nextObjective.next();
+ if (treatments.size() == 1) {
+ TrafficTreatment treatment = treatments.iterator().next();
+
+ // Since we do not support strip_vlan in PORT_VLAN table, we use mod_vlan
+ // to modify the packet to desired vlan.
+ // Note: if we use push_vlan here, the switch will add a second VLAN tag to the outgoing
+ // packet, which is not what we want.
+ TrafficTreatment.Builder treatmentWithoutPushVlan = DefaultTrafficTreatment.builder();
+ VlanId modVlanId;
+ for (Instruction ins : treatment.allInstructions()) {
+ if (ins.type() == Instruction.Type.L2MODIFICATION) {
+ L2ModificationInstruction l2ins = (L2ModificationInstruction) ins;
+ switch (l2ins.subtype()) {
+ case ETH_DST:
+ treatmentWithoutPushVlan.setEthDst(
+ ((L2ModificationInstruction.ModEtherInstruction) l2ins).mac());
+ break;
+ case ETH_SRC:
+ treatmentWithoutPushVlan.setEthSrc(
+ ((L2ModificationInstruction.ModEtherInstruction) l2ins).mac());
+ break;
+ case VLAN_ID:
+ modVlanId = ((L2ModificationInstruction.ModVlanIdInstruction) l2ins).vlanId();
+ treatmentWithoutPushVlan.setVlanId(modVlanId);
+ break;
+ default:
+ break;
+ }
+ } else if (ins.type() == Instruction.Type.OUTPUT) {
+ //long portNum = ((Instructions.OutputInstruction) ins).port().toLong();
+ treatmentWithoutPushVlan.add(ins);
+ } else {
+ // Ignore the vlan_pcp action since it's does matter much.
+ log.warn("Driver does not handle this type of TrafficTreatment"
+ + " instruction in nextObjectives: {}", ins.type());
+ }
+ }
+
+ GroupBucket bucket =
+ DefaultGroupBucket.createIndirectGroupBucket(treatmentWithoutPushVlan.build());
+ final GroupKey key = new DefaultGroupKey(appKryo.serialize(nextObjective.id()));
+ GroupDescription groupDescription
+ = new DefaultGroupDescription(deviceId,
+ GroupDescription.Type.INDIRECT,
+ new GroupBuckets(Collections
+ .singletonList(bucket)),
+ key,
+ null, // let group service determine group id
+ nextObjective.appId());
+ groupService.addGroup(groupDescription);
+ pendingGroups.put(key, nextObjective);
+ }
+ break;
+ case HASHED:
+ case BROADCAST:
+ case FAILOVER:
+ fail(nextObjective, ObjectiveError.UNSUPPORTED);
+ log.warn("Unsupported next objective type {}", nextObjective.type());
+ break;
+ default:
+ fail(nextObjective, ObjectiveError.UNKNOWN);
+ log.warn("Unknown next objective type {}", nextObjective.type());
+ }
+
+ }
+
+ private Collection<FlowRule> processForward(ForwardingObjective fwd) {
+ switch (fwd.flag()) {
+ case SPECIFIC:
+ return processSpecific(fwd);
+ case VERSATILE:
+ return processVersatile(fwd);
+ default:
+ fail(fwd, ObjectiveError.UNKNOWN);
+ log.warn("Unknown forwarding flag {}", fwd.flag());
+ }
+ return Collections.emptySet();
+ }
+
+ private Collection<FlowRule> processVersatile(ForwardingObjective fwd) {
+ log.warn("Driver does not support versatile forwarding objective");
+ fail(fwd, ObjectiveError.UNSUPPORTED);
+ return Collections.emptySet();
+ }
+
+ private Collection<FlowRule> processSpecific(ForwardingObjective fwd) {
+ log.debug("Processing specific forwarding objective");
+ TrafficSelector selector = fwd.selector();
+ EthTypeCriterion ethType =
+ (EthTypeCriterion) selector.getCriterion(Criterion.Type.ETH_TYPE);
+ if (ethType == null || ethType.ethType().toShort() != Ethernet.TYPE_IPV4) {
+ fail(fwd, ObjectiveError.UNSUPPORTED);
+ return Collections.emptySet();
+ }
+
+ // Must have metadata as key.
+ TrafficSelector filteredSelector =
+ DefaultTrafficSelector.builder()
+ .matchEthType(Ethernet.TYPE_IPV4)
+ .matchMetadata(DEFAULT_METADATA)
+ .matchIPDst(
+ ((IPCriterion)
+ selector.getCriterion(Criterion.Type.IPV4_DST)).ip())
+ .build();
+
+ TrafficTreatment.Builder tb = DefaultTrafficTreatment.builder();
+
+ if (fwd.nextId() != null) {
+ NextGroup next = flowObjectiveStore.getNextGroup(fwd.nextId());
+ GroupKey key = appKryo.deserialize(next.data());
+ Group group = groupService.getGroup(deviceId, key);
+ if (group == null) {
+ log.warn("The group left!");
+ fail(fwd, ObjectiveError.GROUPMISSING);
+ return Collections.emptySet();
+ }
+ tb.group(group.id());
+ }
+
+ FlowRule.Builder ruleBuilder = DefaultFlowRule.builder()
+ .fromApp(fwd.appId())
+ .withPriority(ROUTE_TABLE_PRIORITY)
+ .forDevice(deviceId)
+ .withSelector(filteredSelector)
+ .withTreatment(tb.build());
+
+ if (fwd.permanent()) {
+ ruleBuilder.makePermanent();
+ } else {
+ ruleBuilder.makeTemporary(fwd.timeout());
+ }
+
+ ruleBuilder.forTable(ROUTE_TABLE);
+
+ return Collections.singletonList(ruleBuilder.build());
+
+ }
+
+ private void processFilter(FilteringObjective filt, boolean install,
+ ApplicationId applicationId) {
+ PortCriterion p;
+ if (!filt.key().equals(Criteria.dummy()) &&
+ filt.key().type() == Criterion.Type.IN_PORT) {
+ p = (PortCriterion) filt.key();
+ } else {
+ log.warn("No key defined in filtering objective from app: {}. Not"
+ + "processing filtering objective", applicationId);
+ fail(filt, ObjectiveError.UNKNOWN);
+ return;
+ }
+
+ // Convert filtering conditions for switch-intfs into flow rules.
+ FlowRuleOperations.Builder ops = FlowRuleOperations.builder();
+
+ for (Criterion c : filt.conditions()) {
+ // Here we do a trick to install 2 flow rules to MAC_TABLE and ROUTE_TABLE.
+ if (c.type() == Criterion.Type.ETH_DST) {
+ EthCriterion e = (EthCriterion) c;
+
+ // Install TMAC flow rule.
+ log.debug("adding rule for Termination MAC in Filter Table: {}", e.mac());
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
+ selector.matchEthDst(e.mac());
+ // Add IPv4 matching explicitly since we will redirect it to ROUTE Table
+ // through MAC table.
+ selector.matchEthType(Ethernet.TYPE_IPV4);
+ treatment.transition(MAC_TABLE);
+ FlowRule rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(FILTER_TABLE_TMAC_PRIORITY)
+ .fromApp(applicationId)
+ .makePermanent()
+ .forTable(FILTER_TABLE).build();
+ ops = install ? ops.add(rule) : ops.remove(rule);
+
+ // Must install another rule to direct the IPv4 packets that hit TMAC to
+ // Route table.
+ log.debug("adding rule for Termination MAC in MAC Table: {}", e.mac());
+ selector = DefaultTrafficSelector.builder();
+ treatment = DefaultTrafficTreatment.builder();
+ selector.matchEthDst(e.mac());
+ // MAC_Table must have metadata matching configured, use the default metadata.
+ selector.matchMetadata(DEFAULT_METADATA);
+ treatment.transition(ROUTE_TABLE);
+ rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(MAC_TABLE_PRIORITY)
+ .fromApp(applicationId)
+ .makePermanent()
+ .forTable(MAC_TABLE).build();
+ ops = install ? ops.add(rule) : ops.remove(rule);
+ } else if (c.type() == Criterion.Type.VLAN_VID) {
+ VlanIdCriterion v = (VlanIdCriterion) c;
+ log.debug("adding rule for VLAN: {}", v.vlanId());
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
+ selector.matchVlanId(v.vlanId());
+ selector.matchInPort(p.port());
+ // Although the accepted packets will be sent to filter table, we must
+ // explicitly set goto_table instruction here.
+ treatment.writeMetadata(DEFAULT_METADATA, DEFAULT_METADATA_MASK);
+ // set default metadata written by PORT_VLAN Table.
+ treatment.transition(FILTER_TABLE);
+ // We do not support strip vlan here, treatment.deferred().popVlan();
+ // PORT_VLAN table only accept 0xffff priority since it does exact match only.
+ FlowRule rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(PORT_VLAN_TABLE_PRIORITY)
+ .fromApp(applicationId)
+ .makePermanent()
+ .forTable(PORT_VLAN_TABLE).build();
+ ops = install ? ops.add(rule) : ops.remove(rule);
+ } else if (c.type() == Criterion.Type.IPV4_DST) {
+ IPCriterion ipaddr = (IPCriterion) c;
+ log.debug("adding IP filtering rules in FILTER table: {}", ipaddr.ip());
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
+ selector.matchEthType(Ethernet.TYPE_IPV4);
+ selector.matchIPDst(ipaddr.ip()); // router IPs to the controller
+ treatment.setOutput(PortNumber.CONTROLLER);
+ FlowRule rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(FILTER_TABLE_CONTROLLER_PRIORITY)
+ .fromApp(applicationId)
+ .makePermanent()
+ .forTable(FILTER_TABLE).build();
+ ops = install ? ops.add(rule) : ops.remove(rule);
+ } else {
+ log.warn("Driver does not currently process filtering condition"
+ + " of type: {}", c.type());
+ fail(filt, ObjectiveError.UNSUPPORTED);
+ }
+ }
+
+ // apply filtering flow rules
+ flowRuleService.apply(ops.build(new FlowRuleOperationsContext() {
+ @Override
+ public void onSuccess(FlowRuleOperations ops) {
+ pass(filt);
+ log.info("Applied filtering rules");
+ }
+
+ @Override
+ public void onError(FlowRuleOperations ops) {
+ fail(filt, ObjectiveError.FLOWINSTALLATIONFAILED);
+ log.info("Failed to apply filtering rules");
+ }
+ }));
+ }
+
+ private void pass(Objective obj) {
+ if (obj.context().isPresent()) {
+ obj.context().get().onSuccess(obj);
+ }
+ }
+
+ private void fail(Objective obj, ObjectiveError error) {
+ if (obj.context().isPresent()) {
+ obj.context().get().onError(obj, error);
+ }
+ }
+
+ private void initializePipeline() {
+ // CENTEC_V350: PORT_VLAN_TABLE->FILTER_TABLE->MAC_TABLE(TMAC)->ROUTE_TABLE.
+ processPortVlanTable(true);
+ processFilterTable(true);
+ }
+
+ private void processPortVlanTable(boolean install) {
+ // By default the packet are dropped, need install port+vlan by some ways.
+
+ // XXX can we add table-miss-entry to drop? Code says drops by default
+ // XXX TTP description says default goes to table1.
+ // It also says that match is only on vlan -- not port-vlan -- which one is true?
+ }
+
+ private void processFilterTable(boolean install) {
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment
+ .builder();
+ FlowRuleOperations.Builder ops = FlowRuleOperations.builder();
+ FlowRule rule;
+
+ // Punt ARP packets to controller by default.
+ selector.matchEthType(Ethernet.TYPE_ARP);
+ treatment.punt();
+ rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(FILTER_TABLE_CONTROLLER_PRIORITY)
+ .fromApp(appId)
+ .makePermanent()
+ .forTable(FILTER_TABLE).build();
+ ops = install ? ops.add(rule) : ops.remove(rule);
+
+ // Punt BGP packets to controller directly.
+ selector = DefaultTrafficSelector.builder();
+ treatment = DefaultTrafficTreatment.builder();
+ selector.matchEthType(Ethernet.TYPE_IPV4)
+ .matchIPProtocol(IPv4.PROTOCOL_TCP)
+ .matchTcpSrc(TpPort.tpPort(BGP_PORT));
+ treatment.punt();
+ rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withPriority(FILTER_TABLE_HIGHEST_PRIORITY)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .fromApp(appId)
+ .makePermanent()
+ .forTable(FILTER_TABLE).build();
+ ops = install ? ops.add(rule) : ops.remove(rule);
+
+ selector = DefaultTrafficSelector.builder();
+ treatment = DefaultTrafficTreatment.builder();
+ selector.matchEthType(Ethernet.TYPE_IPV4)
+ .matchIPProtocol(IPv4.PROTOCOL_TCP)
+ .matchTcpDst(TpPort.tpPort(BGP_PORT));
+ treatment.punt();
+ rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withPriority(FILTER_TABLE_HIGHEST_PRIORITY)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .fromApp(appId)
+ .makePermanent()
+ .forTable(FILTER_TABLE).build();
+
+ ops = install ? ops.add(rule) : ops.remove(rule);
+
+ // Packet will be discard in PORT_VLAN table, no need to install rule in
+ // filter table.
+
+ // XXX does not tell me if packets are going to be dropped by default in
+ // filter table or not? TTP says it will be dropped by default
+
+ flowRuleService.apply(ops.build(new FlowRuleOperationsContext() {
+ @Override
+ public void onSuccess(FlowRuleOperations ops) {
+ log.info("Provisioned filter table");
+ }
+
+ @Override
+ public void onError(FlowRuleOperations ops) {
+ log.info("Failed to provision filter table");
+ }
+ }));
+ }
+
+ private class InnerGroupListener implements GroupListener {
+ @Override
+ public void event(GroupEvent event) {
+ if (event.type() == GroupEvent.Type.GROUP_ADDED) {
+ GroupKey key = event.subject().appCookie();
+
+ NextObjective obj = pendingGroups.getIfPresent(key);
+ if (obj != null) {
+ flowObjectiveStore.putNextGroup(obj.id(), new CentecV350Group(key));
+ pass(obj);
+ pendingGroups.invalidate(key);
+ }
+ }
+ }
+ }
+
+
+ private class GroupChecker implements Runnable {
+
+ @Override
+ public void run() {
+ Set<GroupKey> keys = pendingGroups.asMap().keySet().stream()
+ .filter(key -> groupService.getGroup(deviceId, key) != null)
+ .collect(Collectors.toSet());
+
+ keys.stream().forEach(key -> {
+ NextObjective obj = pendingGroups.getIfPresent(key);
+ if (obj == null) {
+ return;
+ }
+ pass(obj);
+ pendingGroups.invalidate(key);
+ log.info("Heard back from group service for group {}. "
+ + "Applying pending forwarding objectives", obj.id());
+ flowObjectiveStore.putNextGroup(obj.id(), new CentecV350Group(key));
+ });
+ }
+ }
+
+ private class CentecV350Group implements NextGroup {
+
+ private final GroupKey key;
+
+ public CentecV350Group(GroupKey key) {
+ this.key = key;
+ }
+
+ @SuppressWarnings("unused")
+ public GroupKey key() {
+ return key;
+ }
+
+ @Override
+ public byte[] data() {
+ return appKryo.serialize(key);
+ }
+
+ }
+}
diff --git a/drivers/default/src/main/java/org/onosproject/driver/pipeline/CorsaPipeline.java b/drivers/default/src/main/java/org/onosproject/driver/pipeline/CorsaPipeline.java
new file mode 100644
index 0000000..c640bff
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/pipeline/CorsaPipeline.java
@@ -0,0 +1,88 @@
+/*
+ * 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 static org.slf4j.LoggerFactory.getLogger;
+
+import org.onlab.packet.Ethernet;
+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 org.onosproject.net.flow.FlowRuleOperations;
+import org.onosproject.net.flow.FlowRuleOperationsContext;
+import org.onosproject.net.flow.TrafficSelector;
+import org.onosproject.net.flow.TrafficTreatment;
+import org.onosproject.net.flowobjective.ForwardingObjective;
+import org.onosproject.net.flowobjective.ObjectiveError;
+import org.slf4j.Logger;
+
+import java.util.Collection;
+import java.util.Collections;
+
+/**
+ * Driver for Corsa TTP.
+ *
+ */
+public class CorsaPipeline extends OVSCorsaPipeline {
+
+ private final Logger log = getLogger(getClass());
+
+ @Override
+ protected void processVlanMplsTable(boolean install) {
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment
+ .builder();
+ FlowRuleOperations.Builder ops = FlowRuleOperations.builder();
+ FlowRule rule;
+ // corsa uses non-OF-standard way to match on presence of VLAN tags
+ selector.matchEthType(Ethernet.TYPE_VLAN);
+ treatment.transition(VLAN_TABLE);
+
+ rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(CONTROLLER_PRIORITY)
+ .fromApp(appId)
+ .makePermanent()
+ .forTable(VLAN_MPLS_TABLE).build();
+
+ ops = install ? ops.add(rule) : ops.remove(rule);
+
+ flowRuleService.apply(ops.build(new FlowRuleOperationsContext() {
+ @Override
+ public void onSuccess(FlowRuleOperations ops) {
+ log.info("Provisioned vlan/mpls table");
+ }
+
+ @Override
+ public void onError(FlowRuleOperations ops) {
+ log.info(
+ "Failed to provision vlan/mpls table");
+ }
+ }));
+ }
+
+ @Override
+ protected Collection<FlowRule> processSpecificSwitch(ForwardingObjective fwd) {
+ /* Not supported by until CorsaPipelineV3 */
+ log.warn("Vlan switching not supported in corsa-v1 driver");
+ fail(fwd, ObjectiveError.UNSUPPORTED);
+ return Collections.emptySet();
+ }
+
+}
diff --git a/drivers/default/src/main/java/org/onosproject/driver/pipeline/CorsaPipelineV3.java b/drivers/default/src/main/java/org/onosproject/driver/pipeline/CorsaPipelineV3.java
new file mode 100644
index 0000000..a734899
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/pipeline/CorsaPipelineV3.java
@@ -0,0 +1,421 @@
+package org.onosproject.driver.pipeline;
+
+import org.onlab.packet.Ethernet;
+import org.onlab.packet.MacAddress;
+import org.onlab.packet.VlanId;
+import org.onosproject.core.ApplicationId;
+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 org.onosproject.net.flow.FlowRuleOperations;
+import org.onosproject.net.flow.FlowRuleOperationsContext;
+import org.onosproject.net.flow.TrafficSelector;
+import org.onosproject.net.flow.TrafficTreatment;
+import org.onosproject.net.flow.criteria.Criteria;
+import org.onosproject.net.flow.criteria.Criterion;
+import org.onosproject.net.flow.criteria.EthCriterion;
+import org.onosproject.net.flow.criteria.IPCriterion;
+import org.onosproject.net.flow.criteria.PortCriterion;
+import org.onosproject.net.flow.criteria.VlanIdCriterion;
+import org.onosproject.net.flow.instructions.Instructions;
+import org.onosproject.net.flow.instructions.L2ModificationInstruction;
+import org.onosproject.net.flowobjective.FilteringObjective;
+import org.onosproject.net.flowobjective.ForwardingObjective;
+import org.onosproject.net.flowobjective.ObjectiveError;
+import org.onosproject.net.meter.Band;
+import org.onosproject.net.meter.DefaultBand;
+import org.onosproject.net.meter.DefaultMeterRequest;
+import org.onosproject.net.meter.Meter;
+import org.onosproject.net.meter.MeterId;
+import org.onosproject.net.meter.MeterRequest;
+import org.slf4j.Logger;
+
+import java.util.Collection;
+import java.util.Collections;
+
+import static org.slf4j.LoggerFactory.getLogger;
+
+public class CorsaPipelineV3 extends OVSCorsaPipeline {
+
+ private final Logger log = getLogger(getClass());
+
+ protected static final int PORT_BASED_PROTO_TABLE = 0;
+ protected static final int VLAN_CHECK_TABLE = 1;
+ protected static final int VLAN_MAC_XLATE_TABLE = 2;
+ protected static final int VLAN_CIRCUIT_TABLE = 3;
+ protected static final int PRIORITY_MAP_TABLE = 4;
+ protected static final int L3_IF_MAC_DA_TABLE = 5;
+ protected static final int ETHER_TABLE = 6;
+ protected static final int FIB_TABLE = 7;
+ protected static final int LOCAL_TABLE = 9;
+
+ protected static final byte MAX_VLAN_PCP = 7;
+
+ private MeterId defaultMeterId = null;
+
+ @Override
+ protected TrafficTreatment processNextTreatment(TrafficTreatment treatment) {
+ TrafficTreatment.Builder tb = DefaultTrafficTreatment.builder();
+
+ treatment.immediate().stream()
+ .filter(i -> i instanceof L2ModificationInstruction.ModVlanIdInstruction ||
+ i instanceof L2ModificationInstruction.ModEtherInstruction ||
+ i instanceof Instructions.OutputInstruction)
+ .forEach(i -> tb.add(i));
+ return tb.build();
+ }
+
+ @Override
+ protected TrafficTreatment.Builder processSpecificRoutingTreatment() {
+ return DefaultTrafficTreatment.builder().deferred();
+ }
+
+ @Override
+ protected FlowRule.Builder processSpecificRoutingRule(FlowRule.Builder rb) {
+ return rb.forTable(FIB_TABLE);
+ }
+
+ @Override
+ protected Collection<FlowRule> processSpecificSwitch(ForwardingObjective fwd) {
+ TrafficSelector filteredSelector =
+ DefaultTrafficSelector.builder()
+ .matchInPort(
+ ((PortCriterion) fwd.selector().getCriterion(Criterion.Type.IN_PORT)).port())
+ .matchVlanId(
+ ((VlanIdCriterion) fwd.selector().getCriterion(Criterion.Type.VLAN_VID)).vlanId())
+ .build();
+
+ FlowRule.Builder ruleBuilder = DefaultFlowRule.builder()
+ .fromApp(fwd.appId())
+ .withPriority(fwd.priority())
+ .forDevice(deviceId)
+ .withSelector(filteredSelector)
+ .withTreatment(fwd.treatment())
+ .forTable(VLAN_CIRCUIT_TABLE);
+
+ if (fwd.permanent()) {
+ ruleBuilder.makePermanent();
+ } else {
+ ruleBuilder.makeTemporary(fwd.timeout());
+ }
+
+ return Collections.singletonList(ruleBuilder.build());
+ }
+
+ @Override
+ protected void processFilter(FilteringObjective filt, boolean install,
+ ApplicationId applicationId) {
+ // This driver only processes filtering criteria defined with switch
+ // ports as the key
+ PortCriterion p;
+ if (!filt.key().equals(Criteria.dummy()) &&
+ filt.key().type() == Criterion.Type.IN_PORT) {
+ p = (PortCriterion) filt.key();
+ } else {
+ log.warn("No key defined in filtering objective from app: {}. Not"
+ + "processing filtering objective", applicationId);
+ fail(filt, ObjectiveError.UNKNOWN);
+ return;
+ }
+ // convert filtering conditions for switch-intfs into flowrules
+ FlowRuleOperations.Builder ops = FlowRuleOperations.builder();
+ for (Criterion c : filt.conditions()) {
+ if (c.type() == Criterion.Type.ETH_DST) {
+ EthCriterion e = (EthCriterion) c;
+ log.debug("adding rule for MAC: {}", e.mac());
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
+ selector.matchEthDst(e.mac());
+ selector.matchInPort(p.port());
+ treatment.transition(ETHER_TABLE);
+ FlowRule rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(CONTROLLER_PRIORITY)
+ .fromApp(applicationId)
+ .makePermanent()
+ .forTable(L3_IF_MAC_DA_TABLE).build();
+ ops = install ? ops.add(rule) : ops.remove(rule);
+ } else if (c.type() == Criterion.Type.VLAN_VID) {
+ VlanIdCriterion v = (VlanIdCriterion) c;
+ log.debug("adding rule for VLAN: {}", v.vlanId());
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
+ selector.matchVlanId(v.vlanId());
+ selector.matchInPort(p.port());
+ /* Static treatment for VLAN_CIRCUIT_TABLE */
+ treatment.setVlanPcp(MAX_VLAN_PCP);
+ treatment.setQueue(0);
+ treatment.meter(MeterId.meterId(defaultMeterId.id())); /* use default meter (Green) */
+ treatment.transition(L3_IF_MAC_DA_TABLE);
+ FlowRule rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(CONTROLLER_PRIORITY)
+ .fromApp(applicationId)
+ .makePermanent()
+ .forTable(VLAN_CIRCUIT_TABLE).build();
+ ops = install ? ops.add(rule) : ops.remove(rule);
+ } else if (c.type() == Criterion.Type.IPV4_DST) {
+ IPCriterion ip = (IPCriterion) c;
+ log.debug("adding rule for IP: {}", ip.ip());
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
+ selector.matchEthType(Ethernet.TYPE_IPV4);
+ selector.matchIPDst(ip.ip());
+ treatment.transition(LOCAL_TABLE);
+ FlowRule rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(HIGHEST_PRIORITY)
+ .fromApp(applicationId)
+ .makePermanent()
+ .forTable(FIB_TABLE).build();
+
+ ops = install ? ops.add(rule) : ops.remove(rule);
+ } else {
+ log.warn("Driver does not currently process filtering condition"
+ + " of type: {}", c.type());
+ fail(filt, ObjectiveError.UNSUPPORTED);
+ }
+ }
+ // apply filtering flow rules
+ flowRuleService.apply(ops.build(new FlowRuleOperationsContext() {
+ @Override
+ public void onSuccess(FlowRuleOperations ops) {
+ pass(filt);
+ log.info("Applied filtering rules");
+ }
+
+ @Override
+ public void onError(FlowRuleOperations ops) {
+ fail(filt, ObjectiveError.FLOWINSTALLATIONFAILED);
+ log.info("Failed to apply filtering rules");
+ }
+ }));
+ }
+
+ public void initializePipeline() {
+ processMeterTable(true);
+ processPortBasedProtoTable(true); /* Table 0 */
+ processVlanCheckTable(true); /* Table 1 */
+ processVlanMacXlateTable(true); /* Table 2 */
+ processVlanCircuitTable(true); /* Table 3 */
+ processPriorityMapTable(true); /* Table 4 */
+ processL3IFMacDATable(true); /* Table 5 */
+ processEtherTable(true); /* Table 6 */
+ processFibTable(true); /* Table 7 */
+ processLocalTable(true); /* Table 9 */
+ }
+
+ private void processMeterTable(boolean install) {
+ /* Green meter : Pass all traffic */
+ Band dropBand = DefaultBand.builder()
+ .ofType(Band.Type.DROP)
+ .withRate(0xFFFFFFFF) /* Max Rate */
+ .build();
+ MeterRequest.Builder ops = DefaultMeterRequest.builder()
+ .forDevice(deviceId)
+ .withBands(Collections.singletonList(dropBand))
+ .fromApp(appId);
+
+ Meter meter = meterService.submit(install ? ops.add() : ops.remove());
+ defaultMeterId = meter.id();
+ }
+
+ private void processPortBasedProtoTable(boolean install) {
+ /* Default action */
+ processTableMissGoTo(install, PORT_BASED_PROTO_TABLE, VLAN_CHECK_TABLE);
+ }
+
+ private void processVlanCheckTable(boolean install) {
+ int table = VLAN_CHECK_TABLE;
+
+ /* Default action */
+ processTableMissDrop(install, table);
+
+ /* Tagged packets to VLAN_MAC_XLATE */
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+ selector.matchVlanId(VlanId.ANY);
+
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
+ treatment.transition(VLAN_MAC_XLATE_TABLE);
+
+ FlowRule rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(CONTROLLER_PRIORITY)
+ .fromApp(appId)
+ .makePermanent()
+ .forTable(table).build();
+ processFlowRule(install, rule);
+ }
+
+ private void processVlanMacXlateTable(boolean install) {
+ /* Default action */
+ processTableMissGoTo(install, VLAN_MAC_XLATE_TABLE, VLAN_CIRCUIT_TABLE);
+ }
+
+ private void processVlanCircuitTable(boolean install) {
+ /* Default action */
+ processTableMissDrop(install, VLAN_CIRCUIT_TABLE);
+ }
+
+ private void processPriorityMapTable(boolean install) {
+ /* Not required currently */
+ }
+
+ private void processL3IFMacDATable(boolean install) {
+ int table = L3_IF_MAC_DA_TABLE;
+
+ /* Default action */
+ processTableMissDrop(install, table);
+
+ /* Allow MAC broadcast frames on all ports */
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+ selector.matchEthDst(MacAddress.BROADCAST);
+
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
+ treatment.transition(ETHER_TABLE);
+
+ FlowRule rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(CONTROLLER_PRIORITY)
+ .fromApp(appId)
+ .makePermanent()
+ .forTable(table).build();
+ processFlowRule(install, rule);
+ }
+
+
+ private void processEtherTable(boolean install) {
+ int table = ETHER_TABLE;
+
+ /* Default action */
+ processTableMissDrop(install, table);
+
+ /* Arp to controller */
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+ selector.matchEthType(Ethernet.TYPE_ARP);
+
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
+ treatment.punt();
+
+ FlowRule rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(CONTROLLER_PRIORITY)
+ .fromApp(appId)
+ .makePermanent()
+ .forTable(table).build();
+ processFlowRule(install, rule);
+
+ /* IP to FIB_TABLE */
+ selector = DefaultTrafficSelector.builder();
+ selector.matchEthType(Ethernet.TYPE_IPV4);
+
+ treatment = DefaultTrafficTreatment.builder();
+ treatment.transition(FIB_TABLE);
+
+ rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(CONTROLLER_PRIORITY)
+ .fromApp(appId)
+ .makePermanent()
+ .forTable(table).build();
+ processFlowRule(install, rule);
+ }
+
+ private void processFibTable(boolean install) {
+ /* Default action */
+ processTableMissDrop(install, FIB_TABLE);
+ }
+
+ private void processLocalTable(boolean install) {
+ int table = LOCAL_TABLE;
+ /* Default action */
+ processTableMissDrop(install, table);
+
+ /* Send all protocols to controller */
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
+ treatment.punt();
+
+ FlowRule rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(CONTROLLER_PRIORITY)
+ .fromApp(appId)
+ .makePermanent()
+ .forTable(table).build();
+ processFlowRule(install, rule);
+ }
+
+ /* Init helper: Apply flow rule */
+ private void processFlowRule(boolean install, FlowRule rule) {
+ FlowRuleOperations.Builder ops = FlowRuleOperations.builder();
+ ops = install ? ops.add(rule) : ops.remove(rule);
+
+ flowRuleService.apply(ops.build(new FlowRuleOperationsContext() {
+ @Override
+ public void onSuccess(FlowRuleOperations ops) {
+ log.info("Flow provision success: " + ops.toString() + ", " + rule.toString());
+ }
+
+ @Override
+ public void onError(FlowRuleOperations ops) {
+ log.info("Flow provision error: " + ops.toString() + ", " + rule.toString());
+ }
+ }));
+ }
+
+ /* Init helper: Table Miss = Drop */
+ private void processTableMissDrop(boolean install, int table) {
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
+ treatment.drop();
+
+ FlowRule rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(DROP_PRIORITY)
+ .fromApp(appId)
+ .makePermanent()
+ .forTable(table).build();
+
+ processFlowRule(install, rule);
+ }
+
+ /* Init helper: Table Miss = GoTo */
+ private void processTableMissGoTo(boolean install, int table, int goTo) {
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
+ treatment.transition(goTo);
+
+ FlowRule rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(DROP_PRIORITY)
+ .fromApp(appId)
+ .makePermanent()
+ .forTable(table).build();
+
+ processFlowRule(install, rule);
+ }
+}
diff --git a/drivers/default/src/main/java/org/onosproject/driver/pipeline/CpqdOFDPA2Pipeline.java b/drivers/default/src/main/java/org/onosproject/driver/pipeline/CpqdOFDPA2Pipeline.java
new file mode 100644
index 0000000..cd1ac19
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/pipeline/CpqdOFDPA2Pipeline.java
@@ -0,0 +1,502 @@
+/*
+ * 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 static org.slf4j.LoggerFactory.getLogger;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Deque;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.onlab.packet.Ethernet;
+import org.onlab.packet.VlanId;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.net.Port;
+import org.onosproject.net.PortNumber;
+import org.onosproject.net.behaviour.NextGroup;
+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 org.onosproject.net.flow.FlowRuleOperations;
+import org.onosproject.net.flow.FlowRuleOperationsContext;
+import org.onosproject.net.flow.TrafficSelector;
+import org.onosproject.net.flow.TrafficTreatment;
+import org.onosproject.net.flow.criteria.Criteria;
+import org.onosproject.net.flow.criteria.Criterion;
+import org.onosproject.net.flow.criteria.EthCriterion;
+import org.onosproject.net.flow.criteria.EthTypeCriterion;
+import org.onosproject.net.flow.criteria.IPCriterion;
+import org.onosproject.net.flow.criteria.MplsBosCriterion;
+import org.onosproject.net.flow.criteria.MplsCriterion;
+import org.onosproject.net.flow.criteria.PortCriterion;
+import org.onosproject.net.flow.criteria.VlanIdCriterion;
+import org.onosproject.net.flow.instructions.Instruction;
+import org.onosproject.net.flowobjective.ForwardingObjective;
+import org.onosproject.net.flowobjective.ObjectiveError;
+import org.onosproject.net.group.Group;
+import org.onosproject.net.group.GroupKey;
+import org.slf4j.Logger;
+
+
+/**
+ * Driver for software switch emulation of the OFDPA 2.0 pipeline.
+ * The software switch is the CPqD OF 1.3 switch.
+ */
+public class CpqdOFDPA2Pipeline extends OFDPA2Pipeline {
+
+ private final Logger log = getLogger(getClass());
+
+ /*
+ * Cpqd emulation does not require the non-OF standard rules for
+ * matching untagged packets.
+ *
+ * (non-Javadoc)
+ * @see org.onosproject.driver.pipeline.OFDPA2Pipeline#processVlanIdFilter
+ */
+ @Override
+ protected List<FlowRule> processVlanIdFilter(PortCriterion portCriterion,
+ VlanIdCriterion vidCriterion,
+ VlanId assignedVlan,
+ ApplicationId applicationId) {
+ List<FlowRule> rules = new ArrayList<FlowRule>();
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
+ selector.matchVlanId(vidCriterion.vlanId());
+ treatment.transition(TMAC_TABLE);
+
+ VlanId storeVlan = null;
+ if (vidCriterion.vlanId() == VlanId.NONE) {
+ // untagged packets are assigned vlans
+ treatment.pushVlan().setVlanId(assignedVlan);
+ storeVlan = assignedVlan;
+ } else {
+ storeVlan = vidCriterion.vlanId();
+ }
+
+ // ofdpa cannot match on ALL portnumber, so we need to use separate
+ // rules for each port.
+ List<PortNumber> portnums = new ArrayList<PortNumber>();
+ if (portCriterion.port() == PortNumber.ALL) {
+ for (Port port : deviceService.getPorts(deviceId)) {
+ if (port.number().toLong() > 0 && port.number().toLong() < OFPP_MAX) {
+ portnums.add(port.number());
+ }
+ }
+ } else {
+ portnums.add(portCriterion.port());
+ }
+
+ for (PortNumber pnum : portnums) {
+ // update storage
+ ofdpa2GroupHandler.port2Vlan.put(pnum, storeVlan);
+ Set<PortNumber> vlanPorts = ofdpa2GroupHandler.vlan2Port.get(storeVlan);
+ if (vlanPorts == null) {
+ vlanPorts = Collections.newSetFromMap(
+ new ConcurrentHashMap<PortNumber, Boolean>());
+ vlanPorts.add(pnum);
+ ofdpa2GroupHandler.vlan2Port.put(storeVlan, vlanPorts);
+ } else {
+ vlanPorts.add(pnum);
+ }
+ // create rest of flowrule
+ selector.matchInPort(pnum);
+ FlowRule rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(DEFAULT_PRIORITY)
+ .fromApp(applicationId)
+ .makePermanent()
+ .forTable(VLAN_TABLE).build();
+ rules.add(rule);
+ }
+ return rules;
+ }
+
+ /*
+ * Cpqd emulation does not handle vlan tags and mpls labels correctly.
+ * Workaround requires popping off the VLAN tags in the TMAC table.
+ *
+ * (non-Javadoc)
+ * @see org.onosproject.driver.pipeline.OFDPA2Pipeline#processEthDstFilter
+ */
+ @Override
+ protected List<FlowRule> processEthDstFilter(PortCriterion portCriterion,
+ EthCriterion ethCriterion,
+ VlanIdCriterion vidCriterion,
+ VlanId assignedVlan,
+ ApplicationId applicationId) {
+ //handling untagged packets via assigned VLAN
+ if (vidCriterion.vlanId() == VlanId.NONE) {
+ vidCriterion = (VlanIdCriterion) Criteria.matchVlanId(assignedVlan);
+ }
+ // ofdpa cannot match on ALL portnumber, so we need to use separate
+ // rules for each port.
+ List<PortNumber> portnums = new ArrayList<PortNumber>();
+ if (portCriterion.port() == PortNumber.ALL) {
+ for (Port port : deviceService.getPorts(deviceId)) {
+ if (port.number().toLong() > 0 && port.number().toLong() < OFPP_MAX) {
+ portnums.add(port.number());
+ }
+ }
+ } else {
+ portnums.add(portCriterion.port());
+ }
+
+ List<FlowRule> rules = new ArrayList<FlowRule>();
+ for (PortNumber pnum : portnums) {
+ // for unicast IP packets
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
+ selector.matchInPort(pnum);
+ selector.matchVlanId(vidCriterion.vlanId());
+ selector.matchEthType(Ethernet.TYPE_IPV4);
+ selector.matchEthDst(ethCriterion.mac());
+ /*
+ * Note: CpqD switches do not handle MPLS-related operation properly
+ * for a packet with VLAN tag. We pop VLAN here as a workaround.
+ * Side effect: HostService learns redundant hosts with same MAC but
+ * different VLAN. No known side effect on the network reachability.
+ */
+ treatment.popVlan();
+ treatment.transition(UNICAST_ROUTING_TABLE);
+ FlowRule rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(DEFAULT_PRIORITY)
+ .fromApp(applicationId)
+ .makePermanent()
+ .forTable(TMAC_TABLE).build();
+ rules.add(rule);
+ //for MPLS packets
+ selector = DefaultTrafficSelector.builder();
+ treatment = DefaultTrafficTreatment.builder();
+ selector.matchInPort(pnum);
+ selector.matchVlanId(vidCriterion.vlanId());
+ selector.matchEthType(Ethernet.MPLS_UNICAST);
+ selector.matchEthDst(ethCriterion.mac());
+ // workaround here again
+ treatment.popVlan();
+ treatment.transition(MPLS_TABLE_0);
+ rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(DEFAULT_PRIORITY)
+ .fromApp(applicationId)
+ .makePermanent()
+ .forTable(TMAC_TABLE).build();
+ rules.add(rule);
+ }
+ return rules;
+ }
+
+ /*
+ * Cpqd emulation allows MPLS ecmp.
+ *
+ * (non-Javadoc)
+ * @see org.onosproject.driver.pipeline.OFDPA2Pipeline#processEthTypeSpecific
+ */
+ @Override
+ protected Collection<FlowRule> processEthTypeSpecific(ForwardingObjective fwd) {
+ TrafficSelector selector = fwd.selector();
+ EthTypeCriterion ethType =
+ (EthTypeCriterion) selector.getCriterion(Criterion.Type.ETH_TYPE);
+ if ((ethType == null) ||
+ (ethType.ethType().toShort() != Ethernet.TYPE_IPV4) &&
+ (ethType.ethType().toShort() != Ethernet.MPLS_UNICAST)) {
+ log.warn("processSpecific: Unsupported forwarding objective criteria"
+ + "ethType:{} in dev:{}", ethType, deviceId);
+ fail(fwd, ObjectiveError.UNSUPPORTED);
+ return Collections.emptySet();
+ }
+
+ int forTableId = -1;
+ TrafficSelector.Builder filteredSelector = DefaultTrafficSelector.builder();
+ if (ethType.ethType().toShort() == Ethernet.TYPE_IPV4) {
+ filteredSelector.matchEthType(Ethernet.TYPE_IPV4)
+ .matchIPDst(((IPCriterion)
+ selector.getCriterion(Criterion.Type.IPV4_DST)).ip());
+ forTableId = UNICAST_ROUTING_TABLE;
+ log.debug("processing IPv4 specific forwarding objective {} -> next:{}"
+ + " in dev:{}", fwd.id(), fwd.nextId(), deviceId);
+ } else {
+ filteredSelector
+ .matchEthType(Ethernet.MPLS_UNICAST)
+ .matchMplsLabel(((MplsCriterion)
+ selector.getCriterion(Criterion.Type.MPLS_LABEL)).label());
+ MplsBosCriterion bos = (MplsBosCriterion) selector
+ .getCriterion(Criterion.Type.MPLS_BOS);
+ if (bos != null) {
+ filteredSelector.matchMplsBos(bos.mplsBos());
+ }
+ forTableId = MPLS_TABLE_1;
+ log.debug("processing MPLS specific forwarding objective {} -> next:{}"
+ + " in dev {}", fwd.id(), fwd.nextId(), deviceId);
+ }
+
+ TrafficTreatment.Builder tb = DefaultTrafficTreatment.builder();
+ if (fwd.treatment() != null) {
+ for (Instruction i : fwd.treatment().allInstructions()) {
+ /*
+ * NOTE: OF-DPA does not support immediate instruction in
+ * L3 unicast and MPLS table.
+ */
+ tb.deferred().add(i);
+ }
+ }
+
+ if (fwd.nextId() != null) {
+ NextGroup next = getGroupForNextObjective(fwd.nextId());
+ if (next != null) {
+ List<Deque<GroupKey>> gkeys = appKryo.deserialize(next.data());
+ // we only need the top level group's key to point the flow to it
+ Group group = groupService.getGroup(deviceId, gkeys.get(0).peekFirst());
+ if (group == null) {
+ log.warn("The group left!");
+ fail(fwd, ObjectiveError.GROUPMISSING);
+ return Collections.emptySet();
+ }
+ tb.deferred().group(group.id());
+ }
+ }
+ tb.transition(ACL_TABLE);
+ FlowRule.Builder ruleBuilder = DefaultFlowRule.builder()
+ .fromApp(fwd.appId())
+ .withPriority(fwd.priority())
+ .forDevice(deviceId)
+ .withSelector(filteredSelector.build())
+ .withTreatment(tb.build())
+ .forTable(forTableId);
+
+ if (fwd.permanent()) {
+ ruleBuilder.makePermanent();
+ } else {
+ ruleBuilder.makeTemporary(fwd.timeout());
+ }
+
+ return Collections.singletonList(ruleBuilder.build());
+ }
+
+ @Override
+ protected void initializePipeline() {
+ processPortTable();
+ // vlan table processing not required, as default is to drop packets
+ // which can be accomplished without a table-miss-entry.
+ processTmacTable();
+ processIpTable();
+ processMplsTable();
+ processBridgingTable();
+ processAclTable();
+ }
+
+ protected void processPortTable() {
+ FlowRuleOperations.Builder ops = FlowRuleOperations.builder();
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
+ treatment.transition(VLAN_TABLE);
+ FlowRule tmisse = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(LOWEST_PRIORITY)
+ .fromApp(driverId)
+ .makePermanent()
+ .forTable(PORT_TABLE).build();
+ ops = ops.add(tmisse);
+
+ flowRuleService.apply(ops.build(new FlowRuleOperationsContext() {
+ @Override
+ public void onSuccess(FlowRuleOperations ops) {
+ log.info("Initialized port table");
+ }
+
+ @Override
+ public void onError(FlowRuleOperations ops) {
+ log.info("Failed to initialize port table");
+ }
+ }));
+ }
+
+ protected void processTmacTable() {
+ //table miss entry
+ FlowRuleOperations.Builder ops = FlowRuleOperations.builder();
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
+ selector = DefaultTrafficSelector.builder();
+ treatment = DefaultTrafficTreatment.builder();
+ treatment.transition(BRIDGING_TABLE);
+ FlowRule rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(LOWEST_PRIORITY)
+ .fromApp(driverId)
+ .makePermanent()
+ .forTable(TMAC_TABLE).build();
+ ops = ops.add(rule);
+ flowRuleService.apply(ops.build(new FlowRuleOperationsContext() {
+ @Override
+ public void onSuccess(FlowRuleOperations ops) {
+ log.info("Initialized tmac table");
+ }
+
+ @Override
+ public void onError(FlowRuleOperations ops) {
+ log.info("Failed to initialize tmac table");
+ }
+ }));
+ }
+
+ protected void processIpTable() {
+ //table miss entry
+ FlowRuleOperations.Builder ops = FlowRuleOperations.builder();
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
+ selector = DefaultTrafficSelector.builder();
+ treatment = DefaultTrafficTreatment.builder();
+ treatment.deferred().setOutput(PortNumber.CONTROLLER);
+ treatment.transition(ACL_TABLE);
+ FlowRule rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(LOWEST_PRIORITY)
+ .fromApp(driverId)
+ .makePermanent()
+ .forTable(UNICAST_ROUTING_TABLE).build();
+ ops = ops.add(rule);
+ flowRuleService.apply(ops.build(new FlowRuleOperationsContext() {
+ @Override
+ public void onSuccess(FlowRuleOperations ops) {
+ log.info("Initialized IP table");
+ }
+
+ @Override
+ public void onError(FlowRuleOperations ops) {
+ log.info("Failed to initialize unicast IP table");
+ }
+ }));
+ }
+
+ protected void processMplsTable() {
+ //table miss entry
+ FlowRuleOperations.Builder ops = FlowRuleOperations.builder();
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
+ selector = DefaultTrafficSelector.builder();
+ treatment = DefaultTrafficTreatment.builder();
+ treatment.transition(MPLS_TABLE_1);
+ FlowRule rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(LOWEST_PRIORITY)
+ .fromApp(driverId)
+ .makePermanent()
+ .forTable(MPLS_TABLE_0).build();
+ ops = ops.add(rule);
+
+ treatment.transition(ACL_TABLE);
+ rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(LOWEST_PRIORITY)
+ .fromApp(driverId)
+ .makePermanent()
+ .forTable(MPLS_TABLE_1).build();
+ ops = ops.add(rule);
+
+ flowRuleService.apply(ops.build(new FlowRuleOperationsContext() {
+ @Override
+ public void onSuccess(FlowRuleOperations ops) {
+ log.info("Initialized MPLS tables");
+ }
+
+ @Override
+ public void onError(FlowRuleOperations ops) {
+ log.info("Failed to initialize MPLS tables");
+ }
+ }));
+ }
+
+ private void processBridgingTable() {
+ //table miss entry
+ FlowRuleOperations.Builder ops = FlowRuleOperations.builder();
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
+ selector = DefaultTrafficSelector.builder();
+ treatment = DefaultTrafficTreatment.builder();
+ treatment.transition(ACL_TABLE);
+ FlowRule rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(LOWEST_PRIORITY)
+ .fromApp(driverId)
+ .makePermanent()
+ .forTable(BRIDGING_TABLE).build();
+ ops = ops.add(rule);
+ flowRuleService.apply(ops.build(new FlowRuleOperationsContext() {
+ @Override
+ public void onSuccess(FlowRuleOperations ops) {
+ log.info("Initialized Bridging table");
+ }
+
+ @Override
+ public void onError(FlowRuleOperations ops) {
+ log.info("Failed to initialize Bridging table");
+ }
+ }));
+ }
+
+ protected void processAclTable() {
+ //table miss entry - catch all to executed action-set
+ FlowRuleOperations.Builder ops = FlowRuleOperations.builder();
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
+ selector = DefaultTrafficSelector.builder();
+ treatment = DefaultTrafficTreatment.builder();
+ FlowRule rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(LOWEST_PRIORITY)
+ .fromApp(driverId)
+ .makePermanent()
+ .forTable(ACL_TABLE).build();
+ ops = ops.add(rule);
+ flowRuleService.apply(ops.build(new FlowRuleOperationsContext() {
+ @Override
+ public void onSuccess(FlowRuleOperations ops) {
+ log.info("Initialized Acl table");
+ }
+
+ @Override
+ public void onError(FlowRuleOperations ops) {
+ log.info("Failed to initialize Acl table");
+ }
+ }));
+ }
+
+}
diff --git a/drivers/default/src/main/java/org/onosproject/driver/pipeline/DefaultSingleTablePipeline.java b/drivers/default/src/main/java/org/onosproject/driver/pipeline/DefaultSingleTablePipeline.java
new file mode 100644
index 0000000..d42650f
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/pipeline/DefaultSingleTablePipeline.java
@@ -0,0 +1,129 @@
+/*
+ * 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.onlab.osgi.ServiceDirectory;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.behaviour.Pipeliner;
+import org.onosproject.net.behaviour.PipelinerContext;
+import org.onosproject.net.driver.AbstractHandlerBehaviour;
+import org.onosproject.net.flow.DefaultFlowRule;
+import org.onosproject.net.flow.DefaultTrafficTreatment;
+import org.onosproject.net.flow.FlowRule;
+import org.onosproject.net.flow.FlowRuleOperations;
+import org.onosproject.net.flow.FlowRuleOperationsContext;
+import org.onosproject.net.flow.FlowRuleService;
+import org.onosproject.net.flow.TrafficSelector;
+import org.onosproject.net.flow.TrafficTreatment;
+import org.onosproject.net.flow.instructions.Instructions;
+import org.onosproject.net.flowobjective.FilteringObjective;
+import org.onosproject.net.flowobjective.ForwardingObjective;
+import org.onosproject.net.flowobjective.NextObjective;
+import org.onosproject.net.flowobjective.ObjectiveError;
+import org.slf4j.Logger;
+
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * Simple single table pipeline abstraction.
+ */
+public class DefaultSingleTablePipeline extends AbstractHandlerBehaviour implements Pipeliner {
+
+ private final Logger log = getLogger(getClass());
+
+ private ServiceDirectory serviceDirectory;
+ private FlowRuleService flowRuleService;
+ private DeviceId deviceId;
+
+ @Override
+ public void init(DeviceId deviceId, PipelinerContext context) {
+ this.serviceDirectory = context.directory();
+ this.deviceId = deviceId;
+
+ flowRuleService = serviceDirectory.get(FlowRuleService.class);
+ }
+
+ @Override
+ public void filter(FilteringObjective filter) {}
+
+ @Override
+ public void forward(ForwardingObjective fwd) {
+ FlowRuleOperations.Builder flowBuilder = FlowRuleOperations.builder();
+
+ if (fwd.flag() != ForwardingObjective.Flag.VERSATILE) {
+ throw new UnsupportedOperationException(
+ "Only VERSATILE is supported.");
+ }
+
+ TrafficSelector selector = fwd.selector();
+ TrafficTreatment treatment = fwd.treatment();
+ if ((fwd.treatment().deferred().size() == 0) &&
+ (fwd.treatment().immediate().size() == 0) &&
+ (fwd.treatment().tableTransition() == null) &&
+ (!fwd.treatment().clearedDeferred())) {
+ TrafficTreatment.Builder flowTreatment = DefaultTrafficTreatment.builder();
+ flowTreatment.add(Instructions.createDrop());
+ treatment = flowTreatment.build();
+ }
+
+ FlowRule.Builder ruleBuilder = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector)
+ .withTreatment(treatment)
+ .fromApp(fwd.appId())
+ .withPriority(fwd.priority());
+
+ if (fwd.permanent()) {
+ ruleBuilder.makePermanent();
+ } else {
+ ruleBuilder.makeTemporary(fwd.timeout());
+ }
+
+
+ switch (fwd.op()) {
+
+ case ADD:
+ flowBuilder.add(ruleBuilder.build());
+ break;
+ case REMOVE:
+ flowBuilder.remove(ruleBuilder.build());
+ break;
+ default:
+ log.warn("Unknown operation {}", fwd.op());
+ }
+
+ flowRuleService.apply(flowBuilder.build(new FlowRuleOperationsContext() {
+ @Override
+ public void onSuccess(FlowRuleOperations ops) {
+ if (fwd.context().isPresent()) {
+ fwd.context().get().onSuccess(fwd);
+ }
+ }
+
+ @Override
+ public void onError(FlowRuleOperations ops) {
+ if (fwd.context().isPresent()) {
+ fwd.context().get().onError(fwd, ObjectiveError.FLOWINSTALLATIONFAILED);
+ }
+ }
+ }));
+
+ }
+
+ @Override
+ public void next(NextObjective nextObjective) {}
+
+}
diff --git a/drivers/default/src/main/java/org/onosproject/driver/pipeline/OFDPA2GroupHandler.java b/drivers/default/src/main/java/org/onosproject/driver/pipeline/OFDPA2GroupHandler.java
new file mode 100644
index 0000000..828b778
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/pipeline/OFDPA2GroupHandler.java
@@ -0,0 +1,1167 @@
+package org.onosproject.driver.pipeline;
+
+import com.google.common.base.Objects;
+import com.google.common.cache.Cache;
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.RemovalCause;
+import com.google.common.cache.RemovalNotification;
+import org.onlab.osgi.ServiceDirectory;
+import org.onlab.packet.MplsLabel;
+import org.onlab.packet.VlanId;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.DefaultGroupId;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.PortNumber;
+import org.onosproject.net.behaviour.NextGroup;
+import org.onosproject.net.behaviour.PipelinerContext;
+import org.onosproject.net.flow.DefaultTrafficTreatment;
+import org.onosproject.net.flow.TrafficSelector;
+import org.onosproject.net.flow.TrafficTreatment;
+import org.onosproject.net.flow.criteria.Criterion;
+import org.onosproject.net.flow.criteria.VlanIdCriterion;
+import org.onosproject.net.flow.instructions.Instruction;
+import org.onosproject.net.flow.instructions.Instructions;
+import org.onosproject.net.flow.instructions.L2ModificationInstruction;
+import org.onosproject.net.flowobjective.FlowObjectiveStore;
+import org.onosproject.net.flowobjective.NextObjective;
+import org.onosproject.net.flowobjective.ObjectiveError;
+import org.onosproject.net.group.DefaultGroupBucket;
+import org.onosproject.net.group.DefaultGroupDescription;
+import org.onosproject.net.group.DefaultGroupKey;
+import org.onosproject.net.group.Group;
+import org.onosproject.net.group.GroupBucket;
+import org.onosproject.net.group.GroupBuckets;
+import org.onosproject.net.group.GroupDescription;
+import org.onosproject.net.group.GroupEvent;
+import org.onosproject.net.group.GroupKey;
+import org.onosproject.net.group.GroupListener;
+import org.onosproject.net.group.GroupService;
+import org.slf4j.Logger;
+
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Deque;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
+import static org.onlab.util.Tools.groupedThreads;
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * Group handler for OFDPA2 pipeline.
+ */
+public class OFDPA2GroupHandler {
+ /*
+ * OFDPA requires group-id's to have a certain form.
+ * L2 Interface Groups have <4bits-0><12bits-vlanid><16bits-portid>
+ * L3 Unicast Groups have <4bits-2><28bits-index>
+ * MPLS Interface Groups have <4bits-9><4bits:0><24bits-index>
+ * L3 ECMP Groups have <4bits-7><28bits-index>
+ * L2 Flood Groups have <4bits-4><12bits-vlanid><16bits-index>
+ * L3 VPN Groups have <4bits-9><4bits-2><24bits-index>
+ */
+ private static final int L2_INTERFACE_TYPE = 0x00000000;
+ private static final int L3_UNICAST_TYPE = 0x20000000;
+ private static final int MPLS_INTERFACE_TYPE = 0x90000000;
+ private static final int MPLS_L3VPN_SUBTYPE = 0x92000000;
+ private static final int L3_ECMP_TYPE = 0x70000000;
+ private static final int L2_FLOOD_TYPE = 0x40000000;
+
+ private static final int TYPE_MASK = 0x0fffffff;
+ private static final int SUBTYPE_MASK = 0x00ffffff;
+
+ private static final int PORT_LOWER_BITS_MASK = 0x3f;
+ private static final long PORT_HIGHER_BITS_MASK = ~PORT_LOWER_BITS_MASK;
+
+ private final Logger log = getLogger(getClass());
+ private ServiceDirectory serviceDirectory;
+ protected GroupService groupService;
+
+ private DeviceId deviceId;
+ private FlowObjectiveStore flowObjectiveStore;
+ private Cache<GroupKey, List<OfdpaNextGroup>> pendingNextObjectives;
+ private ConcurrentHashMap<GroupKey, Set<GroupChainElem>> pendingGroups;
+ private ScheduledExecutorService groupChecker =
+ Executors.newScheduledThreadPool(2, groupedThreads("onos/pipeliner", "ofdpa2-%d"));
+
+ // index number for group creation
+ private AtomicInteger l3vpnindex = new AtomicInteger(0);
+
+ // local stores for port-vlan mapping
+ protected Map<PortNumber, VlanId> port2Vlan = new ConcurrentHashMap<>();
+ protected Map<VlanId, Set<PortNumber>> vlan2Port = new ConcurrentHashMap<>();
+
+ // local store for pending bucketAdds - by design there can only be one
+ // pending bucket for a group
+ protected ConcurrentHashMap<Integer, NextObjective> pendingBuckets = new ConcurrentHashMap<>();
+
+ protected void init(DeviceId deviceId, PipelinerContext context) {
+ this.deviceId = deviceId;
+ this.flowObjectiveStore = context.store();
+ this.serviceDirectory = context.directory();
+ this.groupService = serviceDirectory.get(GroupService.class);
+
+ pendingNextObjectives = CacheBuilder.newBuilder()
+ .expireAfterWrite(20, TimeUnit.SECONDS)
+ .removalListener((
+ RemovalNotification<GroupKey, List<OfdpaNextGroup>> notification) -> {
+ if (notification.getCause() == RemovalCause.EXPIRED) {
+ notification.getValue().forEach(ofdpaNextGrp ->
+ OFDPA2Pipeline.fail(ofdpaNextGrp.nextObj,
+ ObjectiveError.GROUPINSTALLATIONFAILED));
+
+ }
+ }).build();
+ pendingGroups = new ConcurrentHashMap<>();
+ groupChecker.scheduleAtFixedRate(new GroupChecker(), 0, 500, TimeUnit.MILLISECONDS);
+
+ groupService.addListener(new InnerGroupListener());
+ }
+
+ protected void addGroup(NextObjective nextObjective) {
+ switch (nextObjective.type()) {
+ case SIMPLE:
+ Collection<TrafficTreatment> treatments = nextObjective.next();
+ if (treatments.size() != 1) {
+ log.error("Next Objectives of type Simple should only have a "
+ + "single Traffic Treatment. Next Objective Id:{}",
+ nextObjective.id());
+ OFDPA2Pipeline.fail(nextObjective, ObjectiveError.BADPARAMS);
+ return;
+ }
+ processSimpleNextObjective(nextObjective);
+ break;
+ case BROADCAST:
+ processBroadcastNextObjective(nextObjective);
+ break;
+ case HASHED:
+ processHashedNextObjective(nextObjective);
+ break;
+ case FAILOVER:
+ OFDPA2Pipeline.fail(nextObjective, ObjectiveError.UNSUPPORTED);
+ log.warn("Unsupported next objective type {}", nextObjective.type());
+ break;
+ default:
+ OFDPA2Pipeline.fail(nextObjective, ObjectiveError.UNKNOWN);
+ log.warn("Unknown next objective type {}", nextObjective.type());
+ }
+ }
+
+ /**
+ * As per the OFDPA 2.0 TTP, packets are sent out of ports by using
+ * a chain of groups. The simple Next Objective passed
+ * in by the application has to be broken up into a group chain
+ * comprising of an L3 Unicast Group that points to an L2 Interface
+ * Group which in-turn points to an output port. In some cases, the simple
+ * next Objective can just be an L2 interface without the need for chaining.
+ *
+ * @param nextObj the nextObjective of type SIMPLE
+ */
+ private void processSimpleNextObjective(NextObjective nextObj) {
+ TrafficTreatment treatment = nextObj.next().iterator().next();
+ // determine if plain L2 or L3->L2
+ boolean plainL2 = true;
+ for (Instruction ins : treatment.allInstructions()) {
+ if (ins.type() == Instruction.Type.L2MODIFICATION) {
+ L2ModificationInstruction l2ins = (L2ModificationInstruction) ins;
+ if (l2ins.subtype() == L2ModificationInstruction.L2SubType.ETH_DST ||
+ l2ins.subtype() == L2ModificationInstruction.L2SubType.ETH_SRC) {
+ plainL2 = false;
+ break;
+ }
+ }
+ }
+
+ if (plainL2) {
+ createL2InterfaceGroup(nextObj);
+ return;
+ }
+
+ // break up simple next objective to GroupChain objects
+ GroupInfo groupInfo = createL2L3Chain(treatment, nextObj.id(),
+ nextObj.appId(), false,
+ nextObj.meta());
+ if (groupInfo == null) {
+ log.error("Could not process nextObj={} in dev:{}", nextObj.id(), deviceId);
+ return;
+ }
+ // create object for local and distributed storage
+ Deque<GroupKey> gkeyChain = new ArrayDeque<>();
+ gkeyChain.addFirst(groupInfo.innerGrpDesc.appCookie());
+ gkeyChain.addFirst(groupInfo.outerGrpDesc.appCookie());
+ OfdpaNextGroup ofdpaGrp = new OfdpaNextGroup(
+ Collections.singletonList(gkeyChain),
+ nextObj);
+
+ // store l3groupkey with the ofdpaNextGroup for the nextObjective that depends on it
+ updatePendingNextObjective(groupInfo.outerGrpDesc.appCookie(), ofdpaGrp);
+
+ // now we are ready to send the l2 groupDescription (inner), as all the stores
+ // that will get async replies have been updated. By waiting to update
+ // the stores, we prevent nasty race conditions.
+ groupService.addGroup(groupInfo.innerGrpDesc);
+ }
+
+ private void updatePendingNextObjective(GroupKey key, OfdpaNextGroup value) {
+ List<OfdpaNextGroup> nextList = new CopyOnWriteArrayList<OfdpaNextGroup>();
+ nextList.add(value);
+ List<OfdpaNextGroup> ret = pendingNextObjectives.asMap()
+ .putIfAbsent(key, nextList);
+ if (ret != null) {
+ ret.add(value);
+ }
+ }
+
+ private void updatePendingGroups(GroupKey gkey, GroupChainElem gce) {
+ Set<GroupChainElem> gceSet = Collections.newSetFromMap(
+ new ConcurrentHashMap<GroupChainElem, Boolean>());
+ gceSet.add(gce);
+ Set<GroupChainElem> retval = pendingGroups.putIfAbsent(gkey, gceSet);
+ if (retval != null) {
+ retval.add(gce);
+ }
+ }
+
+ /**
+ * Creates a simple L2 Interface Group.
+ *
+ * @param nextObj the next Objective
+ */
+ private void createL2InterfaceGroup(NextObjective nextObj) {
+ // only allowed actions are vlan pop and outport
+ TrafficTreatment.Builder ttb = DefaultTrafficTreatment.builder();
+ PortNumber portNum = null;
+ for (Instruction ins : nextObj.next().iterator().next().allInstructions()) {
+ if (ins.type() == Instruction.Type.L2MODIFICATION) {
+ L2ModificationInstruction l2ins = (L2ModificationInstruction) ins;
+ switch (l2ins.subtype()) {
+ case VLAN_POP:
+ ttb.add(l2ins);
+ break;
+ default:
+ break;
+ }
+ } else if (ins.type() == Instruction.Type.OUTPUT) {
+ portNum = ((Instructions.OutputInstruction) ins).port();
+ ttb.add(ins);
+ } else {
+ log.warn("Driver does not handle this type of TrafficTreatment"
+ + " instruction in simple nextObjectives: {}", ins.type());
+ }
+ }
+
+ VlanId vlanId = readVlanFromMeta(nextObj);
+ if (vlanId == null) {
+ log.error("Driver cannot process an L2/L3 group chain without "
+ + "egress vlan information for dev: {} port:{}",
+ deviceId, portNum);
+ return;
+ }
+
+ // assemble information for ofdpa l2interface group
+ int l2groupId = L2_INTERFACE_TYPE | (vlanId.toShort() << 16) | (int) portNum.toLong();
+ // a globally unique groupkey that is different for ports in the same devices
+ // but different for the same portnumber on different devices. Also different
+ // for the various group-types created out of the same next objective.
+ int l2gk = l2InterfaceGroupKey(deviceId, vlanId, portNum.toLong());
+ final GroupKey l2groupkey = new DefaultGroupKey(OFDPA2Pipeline.appKryo.serialize(l2gk));
+
+ // create group description for the l2interfacegroup
+ GroupBucket l2interfaceGroupBucket =
+ DefaultGroupBucket.createIndirectGroupBucket(ttb.build());
+ GroupDescription l2groupDescription =
+ new DefaultGroupDescription(
+ deviceId,
+ GroupDescription.Type.INDIRECT,
+ new GroupBuckets(Collections.singletonList(
+ l2interfaceGroupBucket)),
+ l2groupkey,
+ l2groupId,
+ nextObj.appId());
+ log.debug("Trying L2Interface: device:{} gid:{} gkey:{} nextId:{}",
+ deviceId, Integer.toHexString(l2groupId),
+ l2groupkey, nextObj.id());
+
+ // create object for local and distributed storage
+ Deque<GroupKey> singleKey = new ArrayDeque<>();
+ singleKey.addFirst(l2groupkey);
+ OfdpaNextGroup ofdpaGrp = new OfdpaNextGroup(
+ Collections.singletonList(singleKey),
+ nextObj);
+
+ // store l2groupkey for the nextObjective that depends on it
+ updatePendingNextObjective(l2groupkey, ofdpaGrp);
+ // send the group description to the group service
+ groupService.addGroup(l2groupDescription);
+ }
+
+ /**
+ * Creates one of two possible group-chains from the treatment
+ * passed in. Depending on the MPLS boolean, this method either creates
+ * an L3Unicast Group --> L2Interface Group, if mpls is false;
+ * or MPLSInterface Group --> L2Interface Group, if mpls is true;
+ * The returned 'inner' group description is always the L2 Interface group.
+ *
+ * @param treatment that needs to be broken up to create the group chain
+ * @param nextId of the next objective that needs this group chain
+ * @param appId of the application that sent this next objective
+ * @param mpls determines if L3Unicast or MPLSInterface group is created
+ * @param meta metadata passed in by the application as part of the nextObjective
+ * @return GroupInfo containing the GroupDescription of the
+ * L2Interface group(inner) and the GroupDescription of the (outer)
+ * L3Unicast/MPLSInterface group. May return null if there is an
+ * error in processing the chain
+ */
+ private GroupInfo createL2L3Chain(TrafficTreatment treatment, int nextId,
+ ApplicationId appId, boolean mpls,
+ TrafficSelector meta) {
+ // for the l2interface group, get vlan and port info
+ // for the outer group, get the src/dst mac, and vlan info
+ TrafficTreatment.Builder outerTtb = DefaultTrafficTreatment.builder();
+ TrafficTreatment.Builder innerTtb = DefaultTrafficTreatment.builder();
+ VlanId vlanid = null;
+ long portNum = 0;
+ boolean setVlan = false, popVlan = false;
+ for (Instruction ins : treatment.allInstructions()) {
+ if (ins.type() == Instruction.Type.L2MODIFICATION) {
+ L2ModificationInstruction l2ins = (L2ModificationInstruction) ins;
+ switch (l2ins.subtype()) {
+ case ETH_DST:
+ outerTtb.setEthDst(((L2ModificationInstruction.ModEtherInstruction) l2ins).mac());
+ break;
+ case ETH_SRC:
+ outerTtb.setEthSrc(((L2ModificationInstruction.ModEtherInstruction) l2ins).mac());
+ break;
+ case VLAN_ID:
+ vlanid = ((L2ModificationInstruction.ModVlanIdInstruction) l2ins).vlanId();
+ outerTtb.setVlanId(vlanid);
+ setVlan = true;
+ break;
+ case VLAN_POP:
+ innerTtb.popVlan();
+ popVlan = true;
+ break;
+ case DEC_MPLS_TTL:
+ case MPLS_LABEL:
+ case MPLS_POP:
+ case MPLS_PUSH:
+ case VLAN_PCP:
+ case VLAN_PUSH:
+ default:
+ break;
+ }
+ } else if (ins.type() == Instruction.Type.OUTPUT) {
+ portNum = ((Instructions.OutputInstruction) ins).port().toLong();
+ innerTtb.add(ins);
+ } else {
+ log.warn("Driver does not handle this type of TrafficTreatment"
+ + " instruction in nextObjectives: {}", ins.type());
+ }
+ }
+
+ if (vlanid == null && meta != null) {
+ // use metadata if available
+ Criterion vidCriterion = meta.getCriterion(Criterion.Type.VLAN_VID);
+ if (vidCriterion != null) {
+ vlanid = ((VlanIdCriterion) vidCriterion).vlanId();
+ }
+ // if vlan is not set, use the vlan in metadata for outerTtb
+ if (vlanid != null && !setVlan) {
+ outerTtb.setVlanId(vlanid);
+ }
+ }
+
+ if (vlanid == null) {
+ log.error("Driver cannot process an L2/L3 group chain without "
+ + "egress vlan information for dev: {} port:{}",
+ deviceId, portNum);
+ return null;
+ }
+
+ if (!setVlan && !popVlan) {
+ // untagged outgoing port
+ TrafficTreatment.Builder temp = DefaultTrafficTreatment.builder();
+ temp.popVlan();
+ innerTtb.build().allInstructions().forEach(i -> temp.add(i));
+ innerTtb = temp;
+ }
+
+ // assemble information for ofdpa l2interface group
+ int l2groupId = L2_INTERFACE_TYPE | (vlanid.toShort() << 16) | (int) portNum;
+ // a globally unique groupkey that is different for ports in the same devices
+ // but different for the same portnumber on different devices. Also different
+ // for the various group-types created out of the same next objective.
+ int l2gk = l2InterfaceGroupKey(deviceId, vlanid, portNum);
+ final GroupKey l2groupkey = new DefaultGroupKey(OFDPA2Pipeline.appKryo.serialize(l2gk));
+
+ // assemble information for outer group
+ GroupDescription outerGrpDesc = null;
+ if (mpls) {
+ // outer group is MPLSInteface
+ int mplsgroupId = MPLS_INTERFACE_TYPE | (int) portNum;
+ // using mplsinterfacemask in groupkey to differentiate from l2interface
+ int mplsgk = MPLS_INTERFACE_TYPE | (SUBTYPE_MASK & (deviceId.hashCode() << 8 | (int) portNum));
+ final GroupKey mplsgroupkey = new DefaultGroupKey(OFDPA2Pipeline.appKryo.serialize(mplsgk));
+ outerTtb.group(new DefaultGroupId(l2groupId));
+ // create the mpls-interface group description to wait for the
+ // l2 interface group to be processed
+ GroupBucket mplsinterfaceGroupBucket =
+ DefaultGroupBucket.createIndirectGroupBucket(outerTtb.build());
+ outerGrpDesc = new DefaultGroupDescription(
+ deviceId,
+ GroupDescription.Type.INDIRECT,
+ new GroupBuckets(Collections.singletonList(
+ mplsinterfaceGroupBucket)),
+ mplsgroupkey,
+ mplsgroupId,
+ appId);
+ log.debug("Trying MPLS-Interface: device:{} gid:{} gkey:{} nextid:{}",
+ deviceId, Integer.toHexString(mplsgroupId),
+ mplsgroupkey, nextId);
+ } else {
+ // outer group is L3Unicast
+ int l3groupId = L3_UNICAST_TYPE | (int) portNum;
+ int l3gk = L3_UNICAST_TYPE | (TYPE_MASK & (deviceId.hashCode() << 8 | (int) portNum));
+ final GroupKey l3groupkey = new DefaultGroupKey(OFDPA2Pipeline.appKryo.serialize(l3gk));
+ outerTtb.group(new DefaultGroupId(l2groupId));
+ // create the l3unicast group description to wait for the
+ // l2 interface group to be processed
+ GroupBucket l3unicastGroupBucket =
+ DefaultGroupBucket.createIndirectGroupBucket(outerTtb.build());
+ outerGrpDesc = new DefaultGroupDescription(
+ deviceId,
+ GroupDescription.Type.INDIRECT,
+ new GroupBuckets(Collections.singletonList(
+ l3unicastGroupBucket)),
+ l3groupkey,
+ l3groupId,
+ appId);
+ log.debug("Trying L3Unicast: device:{} gid:{} gkey:{} nextid:{}",
+ deviceId, Integer.toHexString(l3groupId),
+ l3groupkey, nextId);
+ }
+
+ // store l2groupkey with the groupChainElem for the outer-group that depends on it
+ GroupChainElem gce = new GroupChainElem(outerGrpDesc, 1, false);
+ updatePendingGroups(l2groupkey, gce);
+
+ // create group description for the inner l2interfacegroup
+ GroupBucket l2interfaceGroupBucket =
+ DefaultGroupBucket.createIndirectGroupBucket(innerTtb.build());
+ GroupDescription l2groupDescription =
+ new DefaultGroupDescription(
+ deviceId,
+ GroupDescription.Type.INDIRECT,
+ new GroupBuckets(Collections.singletonList(
+ l2interfaceGroupBucket)),
+ l2groupkey,
+ l2groupId,
+ appId);
+ log.debug("Trying L2Interface: device:{} gid:{} gkey:{} nextId:{}",
+ deviceId, Integer.toHexString(l2groupId),
+ l2groupkey, nextId);
+ return new GroupInfo(l2groupDescription, outerGrpDesc);
+
+ }
+
+ /**
+ * As per the OFDPA 2.0 TTP, packets are sent out of ports by using
+ * a chain of groups. The broadcast Next Objective passed in by the application
+ * has to be broken up into a group chain comprising of an
+ * L2 Flood group whose buckets point to L2 Interface groups.
+ *
+ * @param nextObj the nextObjective of type BROADCAST
+ */
+ private void processBroadcastNextObjective(NextObjective nextObj) {
+ // break up broadcast next objective to multiple groups
+ Collection<TrafficTreatment> buckets = nextObj.next();
+
+ VlanId vlanId = readVlanFromMeta(nextObj);
+ if (vlanId == null) {
+ log.warn("Required VLAN ID info in nextObj metadata but not found. Aborting");
+ return;
+ }
+
+ // each treatment is converted to an L2 interface group
+ List<GroupDescription> l2interfaceGroupDescs = new ArrayList<>();
+ List<Deque<GroupKey>> allGroupKeys = new ArrayList<>();
+ for (TrafficTreatment treatment : buckets) {
+ TrafficTreatment.Builder newTreatment = DefaultTrafficTreatment.builder();
+ PortNumber portNum = null;
+ // ensure that the only allowed treatments are pop-vlan and output
+ for (Instruction ins : treatment.allInstructions()) {
+ if (ins.type() == Instruction.Type.L2MODIFICATION) {
+ L2ModificationInstruction l2ins = (L2ModificationInstruction) ins;
+ switch (l2ins.subtype()) {
+ case VLAN_POP:
+ newTreatment.add(l2ins);
+ break;
+ default:
+ log.debug("action {} not permitted for broadcast nextObj",
+ l2ins.subtype());
+ break;
+ }
+ } else if (ins.type() == Instruction.Type.OUTPUT) {
+ portNum = ((Instructions.OutputInstruction) ins).port();
+ newTreatment.add(ins);
+ } else {
+ log.debug("TrafficTreatment of type {} not permitted in " +
+ " broadcast nextObjective", ins.type());
+ }
+ }
+
+ // assemble info for l2 interface group
+ int l2gk = l2InterfaceGroupKey(deviceId, vlanId, portNum.toLong());
+ final GroupKey l2groupkey = new DefaultGroupKey(OFDPA2Pipeline.appKryo.serialize(l2gk));
+ int l2groupId = L2_INTERFACE_TYPE | (vlanId.toShort() << 16) |
+ (int) portNum.toLong();
+ GroupBucket l2interfaceGroupBucket =
+ DefaultGroupBucket.createIndirectGroupBucket(newTreatment.build());
+ GroupDescription l2interfaceGroupDescription =
+ new DefaultGroupDescription(
+ deviceId,
+ GroupDescription.Type.INDIRECT,
+ new GroupBuckets(Collections.singletonList(
+ l2interfaceGroupBucket)),
+ l2groupkey,
+ l2groupId,
+ nextObj.appId());
+ log.debug("Trying L2-Interface: device:{} gid:{} gkey:{} nextid:{}",
+ deviceId, Integer.toHexString(l2groupId),
+ l2groupkey, nextObj.id());
+
+ Deque<GroupKey> gkeyChain = new ArrayDeque<>();
+ gkeyChain.addFirst(l2groupkey);
+
+ // store the info needed to create this group
+ l2interfaceGroupDescs.add(l2interfaceGroupDescription);
+ allGroupKeys.add(gkeyChain);
+ }
+
+ // assemble info for l2 flood group
+ Integer l2floodgroupId = L2_FLOOD_TYPE | (vlanId.toShort() << 16) | nextObj.id();
+ int l2floodgk = L2_FLOOD_TYPE | nextObj.id() << 12;
+ final GroupKey l2floodgroupkey = new DefaultGroupKey(OFDPA2Pipeline.appKryo.serialize(l2floodgk));
+ // collection of group buckets pointing to all the l2 interface groups
+ List<GroupBucket> l2floodBuckets = new ArrayList<>();
+ for (GroupDescription l2intGrpDesc : l2interfaceGroupDescs) {
+ TrafficTreatment.Builder ttb = DefaultTrafficTreatment.builder();
+ ttb.group(new DefaultGroupId(l2intGrpDesc.givenGroupId()));
+ GroupBucket abucket = DefaultGroupBucket.createAllGroupBucket(ttb.build());
+ l2floodBuckets.add(abucket);
+ }
+ // create the l2flood group-description to wait for all the
+ // l2interface groups to be processed
+ GroupDescription l2floodGroupDescription =
+ new DefaultGroupDescription(
+ deviceId,
+ GroupDescription.Type.ALL,
+ new GroupBuckets(l2floodBuckets),
+ l2floodgroupkey,
+ l2floodgroupId,
+ nextObj.appId());
+ GroupChainElem gce = new GroupChainElem(l2floodGroupDescription,
+ l2interfaceGroupDescs.size(),
+ false);
+ log.debug("Trying L2-Flood: device:{} gid:{} gkey:{} nextid:{}",
+ deviceId, Integer.toHexString(l2floodgroupId),
+ l2floodgroupkey, nextObj.id());
+
+ // create objects for local and distributed storage
+ allGroupKeys.forEach(gkeyChain -> gkeyChain.addFirst(l2floodgroupkey));
+ OfdpaNextGroup ofdpaGrp = new OfdpaNextGroup(allGroupKeys, nextObj);
+
+ // store l2floodgroupkey with the ofdpaGroupChain for the nextObjective
+ // that depends on it
+ updatePendingNextObjective(l2floodgroupkey, ofdpaGrp);
+
+ for (GroupDescription l2intGrpDesc : l2interfaceGroupDescs) {
+ // store all l2groupkeys with the groupChainElem for the l2floodgroup
+ // that depends on it
+ updatePendingGroups(l2intGrpDesc.appCookie(), gce);
+ // send groups for all l2 interface groups
+ groupService.addGroup(l2intGrpDesc);
+ }
+ }
+
+ /**
+ * As per the OFDPA 2.0 TTP, packets are sent out of ports by using
+ * a chain of groups. The hashed Next Objective passed in by the application
+ * has to be broken up into a group chain comprising of an
+ * L3 ECMP group as the top level group. Buckets of this group can point
+ * to a variety of groups in a group chain, depending on the whether
+ * MPLS labels are being pushed or not.
+ * <p>
+ * NOTE: We do not create MPLS ECMP groups as they are unimplemented in
+ * OF-DPA 2.0 (even though it is in the spec). Therefore we do not
+ * check the nextObjective meta to see what is matching before being
+ * sent to this nextObjective.
+ *
+ * @param nextObj the nextObjective of type HASHED
+ */
+ private void processHashedNextObjective(NextObjective nextObj) {
+ // storage for all group keys in the chain of groups created
+ List<Deque<GroupKey>> allGroupKeys = new ArrayList<>();
+ List<GroupInfo> unsentGroups = new ArrayList<>();
+ createHashBucketChains(nextObj, allGroupKeys, unsentGroups);
+
+ // now we can create the outermost L3 ECMP group
+ List<GroupBucket> l3ecmpGroupBuckets = new ArrayList<>();
+ for (GroupInfo gi : unsentGroups) {
+ // create ECMP bucket to point to the outer group
+ TrafficTreatment.Builder ttb = DefaultTrafficTreatment.builder();
+ ttb.group(new DefaultGroupId(gi.outerGrpDesc.givenGroupId()));
+ GroupBucket sbucket = DefaultGroupBucket
+ .createSelectGroupBucket(ttb.build());
+ l3ecmpGroupBuckets.add(sbucket);
+ }
+ int l3ecmpGroupId = L3_ECMP_TYPE | nextObj.id() << 12;
+ GroupKey l3ecmpGroupKey = new DefaultGroupKey(OFDPA2Pipeline.appKryo.serialize(l3ecmpGroupId));
+ GroupDescription l3ecmpGroupDesc =
+ new DefaultGroupDescription(
+ deviceId,
+ GroupDescription.Type.SELECT,
+ new GroupBuckets(l3ecmpGroupBuckets),
+ l3ecmpGroupKey,
+ l3ecmpGroupId,
+ nextObj.appId());
+ GroupChainElem l3ecmpGce = new GroupChainElem(l3ecmpGroupDesc,
+ l3ecmpGroupBuckets.size(),
+ false);
+
+ // create objects for local and distributed storage
+ allGroupKeys.forEach(gkeyChain -> gkeyChain.addFirst(l3ecmpGroupKey));
+ OfdpaNextGroup ofdpaGrp = new OfdpaNextGroup(allGroupKeys, nextObj);
+
+ // store l3ecmpGroupKey with the ofdpaGroupChain for the nextObjective
+ // that depends on it
+ updatePendingNextObjective(l3ecmpGroupKey, ofdpaGrp);
+
+ log.debug("Trying L3ECMP: device:{} gid:{} gkey:{} nextId:{}",
+ deviceId, Integer.toHexString(l3ecmpGroupId),
+ l3ecmpGroupKey, nextObj.id());
+ // finally we are ready to send the innermost groups
+ for (GroupInfo gi : unsentGroups) {
+ log.debug("Sending innermost group {} in group chain on device {} ",
+ Integer.toHexString(gi.innerGrpDesc.givenGroupId()), deviceId);
+ updatePendingGroups(gi.outerGrpDesc.appCookie(), l3ecmpGce);
+ groupService.addGroup(gi.innerGrpDesc);
+ }
+
+ }
+
+ /**
+ * Creates group chains for all buckets in a hashed group, and stores the
+ * GroupInfos and GroupKeys for all the groups in the lists passed in, which
+ * should be empty.
+ * <p>
+ * Does not create the top level ECMP group. Does not actually send the
+ * groups to the groupService.
+ *
+ * @param nextObj the Next Objective with buckets that need to be converted
+ * to group chains
+ * @param allGroupKeys a list to store groupKey for each bucket-group-chain
+ * @param unsentGroups a list to store GroupInfo for each bucket-group-chain
+ */
+ private void createHashBucketChains(NextObjective nextObj,
+ List<Deque<GroupKey>> allGroupKeys,
+ List<GroupInfo> unsentGroups) {
+ // break up hashed next objective to multiple groups
+ Collection<TrafficTreatment> buckets = nextObj.next();
+
+ for (TrafficTreatment bucket : buckets) {
+ //figure out how many labels are pushed in each bucket
+ int labelsPushed = 0;
+ MplsLabel innermostLabel = null;
+ for (Instruction ins : bucket.allInstructions()) {
+ if (ins.type() == Instruction.Type.L2MODIFICATION) {
+ L2ModificationInstruction l2ins = (L2ModificationInstruction) ins;
+ if (l2ins.subtype() == L2ModificationInstruction.L2SubType.MPLS_PUSH) {
+ labelsPushed++;
+ }
+ if (l2ins.subtype() == L2ModificationInstruction.L2SubType.MPLS_LABEL) {
+ if (innermostLabel == null) {
+ innermostLabel = ((L2ModificationInstruction.ModMplsLabelInstruction) l2ins).mplsLabel();
+ }
+ }
+ }
+ }
+
+ Deque<GroupKey> gkeyChain = new ArrayDeque<>();
+ // XXX we only deal with 0 and 1 label push right now
+ if (labelsPushed == 0) {
+ GroupInfo nolabelGroupInfo = createL2L3Chain(bucket, nextObj.id(),
+ nextObj.appId(), false,
+ nextObj.meta());
+ if (nolabelGroupInfo == null) {
+ log.error("Could not process nextObj={} in dev:{}",
+ nextObj.id(), deviceId);
+ return;
+ }
+ gkeyChain.addFirst(nolabelGroupInfo.innerGrpDesc.appCookie());
+ gkeyChain.addFirst(nolabelGroupInfo.outerGrpDesc.appCookie());
+
+ // we can't send the inner group description yet, as we have to
+ // create the dependent ECMP group first. So we store..
+ unsentGroups.add(nolabelGroupInfo);
+
+ } else if (labelsPushed == 1) {
+ GroupInfo onelabelGroupInfo = createL2L3Chain(bucket, nextObj.id(),
+ nextObj.appId(), true,
+ nextObj.meta());
+ if (onelabelGroupInfo == null) {
+ log.error("Could not process nextObj={} in dev:{}",
+ nextObj.id(), deviceId);
+ return;
+ }
+ // we need to add another group to this chain - the L3VPN group
+ TrafficTreatment.Builder l3vpnTtb = DefaultTrafficTreatment.builder();
+ l3vpnTtb.pushMpls()
+ .setMpls(innermostLabel)
+ .setMplsBos(true)
+ .copyTtlOut()
+ .group(new DefaultGroupId(
+ onelabelGroupInfo.outerGrpDesc.givenGroupId()));
+ GroupBucket l3vpnGrpBkt =
+ DefaultGroupBucket.createIndirectGroupBucket(l3vpnTtb.build());
+ int l3vpngroupId = MPLS_L3VPN_SUBTYPE | l3vpnindex.incrementAndGet();
+ int l3vpngk = MPLS_L3VPN_SUBTYPE | nextObj.id() << 12 | l3vpnindex.get();
+ GroupKey l3vpngroupkey = new DefaultGroupKey(OFDPA2Pipeline.appKryo.serialize(l3vpngk));
+ GroupDescription l3vpnGroupDesc =
+ new DefaultGroupDescription(
+ deviceId,
+ GroupDescription.Type.INDIRECT,
+ new GroupBuckets(Collections.singletonList(
+ l3vpnGrpBkt)),
+ l3vpngroupkey,
+ l3vpngroupId,
+ nextObj.appId());
+ GroupChainElem l3vpnGce = new GroupChainElem(l3vpnGroupDesc, 1, false);
+ updatePendingGroups(onelabelGroupInfo.outerGrpDesc.appCookie(), l3vpnGce);
+
+ gkeyChain.addFirst(onelabelGroupInfo.innerGrpDesc.appCookie());
+ gkeyChain.addFirst(onelabelGroupInfo.outerGrpDesc.appCookie());
+ gkeyChain.addFirst(l3vpngroupkey);
+
+ //now we can replace the outerGrpDesc with the one we just created
+ onelabelGroupInfo.outerGrpDesc = l3vpnGroupDesc;
+
+ // we can't send the innermost group yet, as we have to create
+ // the dependent ECMP group first. So we store ...
+ unsentGroups.add(onelabelGroupInfo);
+
+ log.debug("Trying L3VPN: device:{} gid:{} gkey:{} nextId:{}",
+ deviceId, Integer.toHexString(l3vpngroupId),
+ l3vpngroupkey, nextObj.id());
+
+ } else {
+ log.warn("Driver currently does not handle more than 1 MPLS "
+ + "labels. Not processing nextObjective {}", nextObj.id());
+ return;
+ }
+
+ // all groups in this chain
+ allGroupKeys.add(gkeyChain);
+ }
+ }
+
+ /**
+ * Adds a bucket to the top level group of a group-chain, and creates the chain.
+ *
+ * @param nextObjective the next group to add a bucket to
+ * @param next the representation of the existing group-chain for this next objective
+ */
+ protected void addBucketToGroup(NextObjective nextObjective, NextGroup next) {
+ if (nextObjective.type() != NextObjective.Type.HASHED) {
+ log.warn("AddBuckets not applied to nextType:{} in dev:{} for next:{}",
+ nextObjective.type(), deviceId, nextObjective.id());
+ return;
+ }
+ if (nextObjective.next().size() > 1) {
+ log.warn("Only one bucket can be added at a time");
+ return;
+ }
+ // storage for all group keys in the chain of groups created
+ List<Deque<GroupKey>> allGroupKeys = new ArrayList<>();
+ List<GroupInfo> unsentGroups = new ArrayList<>();
+ createHashBucketChains(nextObjective, allGroupKeys, unsentGroups);
+
+ // now we can create the outermost L3 ECMP group bucket to add
+ GroupInfo gi = unsentGroups.get(0); // only one bucket, so only one group-chain
+ TrafficTreatment.Builder ttb = DefaultTrafficTreatment.builder();
+ ttb.group(new DefaultGroupId(gi.outerGrpDesc.givenGroupId()));
+ GroupBucket sbucket = DefaultGroupBucket.createSelectGroupBucket(ttb.build());
+
+ // recreate the original L3 ECMP group id and description
+ int l3ecmpGroupId = L3_ECMP_TYPE | nextObjective.id() << 12;
+ GroupKey l3ecmpGroupKey = new DefaultGroupKey(OFDPA2Pipeline.appKryo.serialize(l3ecmpGroupId));
+
+ // Although GroupDescriptions are not necessary for adding buckets to
+ // existing groups, we use one in the GroupChainElem. When the latter is
+ // processed, the info will be extracted for the bucketAdd call to groupService
+ GroupDescription l3ecmpGroupDesc =
+ new DefaultGroupDescription(
+ deviceId,
+ GroupDescription.Type.SELECT,
+ new GroupBuckets(Collections.singletonList(sbucket)),
+ l3ecmpGroupKey,
+ l3ecmpGroupId,
+ nextObjective.appId());
+ GroupChainElem l3ecmpGce = new GroupChainElem(l3ecmpGroupDesc, 1, true);
+
+ // update original NextGroup with new bucket-chain
+ // don't need to update pendingNextObjectives -- group already exists
+ Deque<GroupKey> newBucketChain = allGroupKeys.get(0);
+ newBucketChain.addFirst(l3ecmpGroupKey);
+ List<Deque<GroupKey>> allOriginalKeys = OFDPA2Pipeline.appKryo.deserialize(next.data());
+ allOriginalKeys.add(newBucketChain);
+ flowObjectiveStore.putNextGroup(nextObjective.id(),
+ new OfdpaNextGroup(allOriginalKeys, nextObjective));
+
+ log.debug("Adding to L3ECMP: device:{} gid:{} gkey:{} nextId:{}",
+ deviceId, Integer.toHexString(l3ecmpGroupId),
+ l3ecmpGroupKey, nextObjective.id());
+ // send the innermost group
+ log.debug("Sending innermost group {} in group chain on device {} ",
+ Integer.toHexString(gi.innerGrpDesc.givenGroupId()), deviceId);
+ updatePendingGroups(gi.outerGrpDesc.appCookie(), l3ecmpGce);
+ groupService.addGroup(gi.innerGrpDesc);
+
+ }
+
+ /**
+ * Removes the bucket in the top level group of a possible group-chain. Does
+ * not remove the groups in a group-chain pointed to by this bucket, as they
+ * may be in use (referenced by other groups) elsewhere.
+ *
+ * @param nextObjective the next group to remove a bucket from
+ * @param next the representation of the existing group-chain for this next objective
+ */
+ protected void removeBucketFromGroup(NextObjective nextObjective, NextGroup next) {
+ if (nextObjective.type() != NextObjective.Type.HASHED) {
+ log.warn("RemoveBuckets not applied to nextType:{} in dev:{} for next:{}",
+ nextObjective.type(), deviceId, nextObjective.id());
+ return;
+ }
+ Collection<TrafficTreatment> treatments = nextObjective.next();
+ TrafficTreatment treatment = treatments.iterator().next();
+ // find the bucket to remove by noting the outport, and figuring out the
+ // top-level group in the group-chain that indirectly references the port
+ PortNumber outport = null;
+ for (Instruction ins : treatment.allInstructions()) {
+ if (ins instanceof Instructions.OutputInstruction) {
+ outport = ((Instructions.OutputInstruction) ins).port();
+ break;
+ }
+ }
+ if (outport == null) {
+ log.error("next objective {} has no outport", nextObjective.id());
+ return;
+ }
+
+ List<Deque<GroupKey>> allgkeys = OFDPA2Pipeline.appKryo.deserialize(next.data());
+ Deque<GroupKey> foundChain = null;
+ int index = 0;
+ for (Deque<GroupKey> gkeys : allgkeys) {
+ GroupKey groupWithPort = gkeys.peekLast();
+ Group group = groupService.getGroup(deviceId, groupWithPort);
+ if (group == null) {
+ log.warn("Inconsistent group chain");
+ continue;
+ }
+ // last group in group chain should have a single bucket pointing to port
+ List<Instruction> lastIns = group.buckets().buckets().iterator()
+ .next().treatment().allInstructions();
+ for (Instruction i : lastIns) {
+ if (i instanceof Instructions.OutputInstruction) {
+ PortNumber lastport = ((Instructions.OutputInstruction) i).port();
+ if (lastport.equals(outport)) {
+ foundChain = gkeys;
+ break;
+ }
+ }
+ }
+ if (foundChain != null) {
+ break;
+ }
+ index++;
+ }
+ if (foundChain != null) {
+ //first groupkey is the one we want to modify
+ GroupKey modGroupKey = foundChain.peekFirst();
+ Group modGroup = groupService.getGroup(deviceId, modGroupKey);
+ //second groupkey is the one we wish to remove the reference to
+ GroupKey pointedGroupKey = null;
+ int i = 0;
+ for (GroupKey gk : foundChain) {
+ if (i++ == 1) {
+ pointedGroupKey = gk;
+ break;
+ }
+ }
+ Group pointedGroup = groupService.getGroup(deviceId, pointedGroupKey);
+ GroupBucket bucket = DefaultGroupBucket.createSelectGroupBucket(
+ DefaultTrafficTreatment.builder()
+ .group(pointedGroup.id())
+ .build());
+ GroupBuckets removeBuckets = new GroupBuckets(Collections
+ .singletonList(bucket));
+ log.debug("Removing buckets from group id {} for next id {} in device {}",
+ modGroup.id(), nextObjective.id(), deviceId);
+ groupService.removeBucketsFromGroup(deviceId, modGroupKey,
+ removeBuckets, modGroupKey,
+ nextObjective.appId());
+ //update store
+ allgkeys.remove(index);
+ flowObjectiveStore.putNextGroup(nextObjective.id(),
+ new OfdpaNextGroup(allgkeys, nextObjective));
+ } else {
+ log.warn("Could not find appropriate group-chain for removing bucket"
+ + " for next id {} in dev:{}", nextObjective.id(), deviceId);
+ }
+ }
+
+ /**
+ * Removes all groups in multiple possible group-chains that represent the next
+ * objective.
+ *
+ * @param nextObjective the next objective to remove
+ * @param next the NextGroup that represents the existing group-chain for
+ * this next objective
+ */
+ protected void removeGroup(NextObjective nextObjective, NextGroup next) {
+ List<Deque<GroupKey>> allgkeys = OFDPA2Pipeline.appKryo.deserialize(next.data());
+ allgkeys.forEach(groupChain -> groupChain.forEach(groupKey ->
+ groupService.removeGroup(deviceId, groupKey, nextObjective.appId())));
+ flowObjectiveStore.removeNextGroup(nextObjective.id());
+ }
+
+ /**
+ * Processes next element of a group chain. Assumption is that if this
+ * group points to another group, the latter has already been created
+ * and this driver has received notification for it. A second assumption is
+ * that if there is another group waiting for this group then the appropriate
+ * stores already have the information to act upon the notification for the
+ * creation of this group.
+ * <p>
+ * The processing of the GroupChainElement depends on the number of groups
+ * this element is waiting on. For all group types other than SIMPLE, a
+ * GroupChainElement could be waiting on multiple groups.
+ *
+ * @param gce the group chain element to be processed next
+ */
+ private void processGroupChain(GroupChainElem gce) {
+ int waitOnGroups = gce.decrementAndGetGroupsWaitedOn();
+ if (waitOnGroups != 0) {
+ log.debug("GCE: {} not ready to be processed", gce);
+ return;
+ }
+ log.debug("GCE: {} ready to be processed", gce);
+ if (gce.addBucketToGroup) {
+ groupService.addBucketsToGroup(gce.groupDescription.deviceId(),
+ gce.groupDescription.appCookie(),
+ gce.groupDescription.buckets(),
+ gce.groupDescription.appCookie(),
+ gce.groupDescription.appId());
+ } else {
+ groupService.addGroup(gce.groupDescription);
+ }
+ }
+
+ private class GroupChecker implements Runnable {
+ @Override
+ public void run() {
+ Set<GroupKey> keys = pendingGroups.keySet().stream()
+ .filter(key -> groupService.getGroup(deviceId, key) != null)
+ .collect(Collectors.toSet());
+ Set<GroupKey> otherkeys = pendingNextObjectives.asMap().keySet().stream()
+ .filter(otherkey -> groupService.getGroup(deviceId, otherkey) != null)
+ .collect(Collectors.toSet());
+ keys.addAll(otherkeys);
+
+ keys.stream().forEach(key ->
+ processPendingGroupsOrNextObjectives(key, false));
+ }
+ }
+
+ private void processPendingGroupsOrNextObjectives(GroupKey key, boolean added) {
+ //first check for group chain
+ Set<GroupChainElem> gceSet = pendingGroups.remove(key);
+ if (gceSet != null) {
+ for (GroupChainElem gce : gceSet) {
+ log.info("Group service {} group key {} in device {}. "
+ + "Processing next group in group chain with group id {}",
+ (added) ? "ADDED" : "processed",
+ key, deviceId,
+ Integer.toHexString(gce.groupDescription.givenGroupId()));
+ processGroupChain(gce);
+ }
+ } else {
+ // otherwise chain complete - check for waiting nextObjectives
+ List<OfdpaNextGroup> nextGrpList = pendingNextObjectives.getIfPresent(key);
+ if (nextGrpList != null) {
+ pendingNextObjectives.invalidate(key);
+ nextGrpList.forEach(nextGrp -> {
+ log.info("Group service {} group key {} in device:{}. "
+ + "Done implementing next objective: {} <<-->> gid:{}",
+ (added) ? "ADDED" : "processed",
+ key, deviceId, nextGrp.nextObjective().id(),
+ Integer.toHexString(groupService.getGroup(deviceId, key)
+ .givenGroupId()));
+ OFDPA2Pipeline.pass(nextGrp.nextObjective());
+ flowObjectiveStore.putNextGroup(nextGrp.nextObjective().id(), nextGrp);
+ // check if addBuckets waiting for this completion
+ NextObjective pendBkt = pendingBuckets
+ .remove(nextGrp.nextObjective().id());
+ if (pendBkt != null) {
+ addBucketToGroup(pendBkt, nextGrp);
+ }
+ });
+ }
+ }
+ }
+
+ private VlanId readVlanFromMeta(NextObjective nextObj) {
+ TrafficSelector metadata = nextObj.meta();
+ Criterion criterion = metadata.getCriterion(Criterion.Type.VLAN_VID);
+ return (criterion == null)
+ ? null : ((VlanIdCriterion) criterion).vlanId();
+ }
+
+ /**
+ * Returns a hash as the L2 Interface Group Key.
+ *
+ * Keep the lower 6-bit for port since port number usually smaller than 64.
+ * Hash other information into remaining 28 bits.
+ *
+ * @param deviceId Device ID
+ * @param vlanId VLAN ID
+ * @param portNumber Port number
+ * @return L2 interface group key
+ */
+ private int l2InterfaceGroupKey(
+ DeviceId deviceId, VlanId vlanId, long portNumber) {
+ int portLowerBits = (int) portNumber & PORT_LOWER_BITS_MASK;
+ long portHigherBits = portNumber & PORT_HIGHER_BITS_MASK;
+ int hash = Objects.hashCode(deviceId, vlanId, portHigherBits);
+ return L2_INTERFACE_TYPE | (TYPE_MASK & hash << 6) | portLowerBits;
+ }
+
+ private class InnerGroupListener implements GroupListener {
+ @Override
+ public void event(GroupEvent event) {
+ log.trace("received group event of type {}", event.type());
+ if (event.type() == GroupEvent.Type.GROUP_ADDED) {
+ GroupKey key = event.subject().appCookie();
+ processPendingGroupsOrNextObjectives(key, true);
+ }
+ }
+ }
+
+ /**
+ * Utility class for moving group information around.
+ */
+ private class GroupInfo {
+ private GroupDescription innerGrpDesc;
+ private GroupDescription outerGrpDesc;
+
+ GroupInfo(GroupDescription innerGrpDesc, GroupDescription outerGrpDesc) {
+ this.innerGrpDesc = innerGrpDesc;
+ this.outerGrpDesc = outerGrpDesc;
+ }
+ }
+
+ /**
+ * Represents an entire group-chain that implements a Next-Objective from
+ * the application. The objective is represented as a list of deques, where
+ * each deque is a separate chain of groups.
+ * <p>
+ * For example, an ECMP group with 3 buckets, where each bucket points to
+ * a group chain of L3 Unicast and L2 interface groups will look like this:
+ * <ul>
+ * <li>List[0] is a Deque of GroupKeyECMP(first)-GroupKeyL3(middle)-GroupKeyL2(last)
+ * <li>List[1] is a Deque of GroupKeyECMP(first)-GroupKeyL3(middle)-GroupKeyL2(last)
+ * <li>List[2] is a Deque of GroupKeyECMP(first)-GroupKeyL3(middle)-GroupKeyL2(last)
+ * </ul>
+ * where the first element of each deque is the same, representing the
+ * top level ECMP group, while every other element represents a unique groupKey.
+ * <p>
+ * Also includes information about the next objective that
+ * resulted in this group-chain.
+ *
+ */
+ protected class OfdpaNextGroup implements NextGroup {
+ private final NextObjective nextObj;
+ private final List<Deque<GroupKey>> gkeys;
+
+ public OfdpaNextGroup(List<Deque<GroupKey>> gkeys, NextObjective nextObj) {
+ this.gkeys = gkeys;
+ this.nextObj = nextObj;
+ }
+
+ @SuppressWarnings("unused")
+ public List<Deque<GroupKey>> groupKey() {
+ return gkeys;
+ }
+
+ public NextObjective nextObjective() {
+ return nextObj;
+ }
+
+ @Override
+ public byte[] data() {
+ return OFDPA2Pipeline.appKryo.serialize(gkeys);
+ }
+ }
+
+ /**
+ * Represents a group element that is part of a chain of groups.
+ * Stores enough information to create a Group Description to add the group
+ * to the switch by requesting the Group Service. Objects instantiating this
+ * class are meant to be temporary and live as long as it is needed to wait for
+ * preceding groups in the group chain to be created.
+ */
+ private class GroupChainElem {
+ private GroupDescription groupDescription;
+ private AtomicInteger waitOnGroups;
+ private boolean addBucketToGroup;
+
+ GroupChainElem(GroupDescription groupDescription, int waitOnGroups,
+ boolean addBucketToGroup) {
+ this.groupDescription = groupDescription;
+ this.waitOnGroups = new AtomicInteger(waitOnGroups);
+ this.addBucketToGroup = addBucketToGroup;
+ }
+
+ /**
+ * This methods atomically decrements the counter for the number of
+ * groups this GroupChainElement is waiting on, for notifications from
+ * the Group Service. When this method returns a value of 0, this
+ * GroupChainElement is ready to be processed.
+ *
+ * @return integer indication of the number of notifications being waited on
+ */
+ int decrementAndGetGroupsWaitedOn() {
+ return waitOnGroups.decrementAndGet();
+ }
+
+ @Override
+ public String toString() {
+ return (Integer.toHexString(groupDescription.givenGroupId()) +
+ " groupKey: " + groupDescription.appCookie() +
+ " waiting-on-groups: " + waitOnGroups.get() +
+ " addBucketToGroup: " + addBucketToGroup +
+ " device: " + deviceId);
+ }
+ }
+}
diff --git a/drivers/default/src/main/java/org/onosproject/driver/pipeline/OFDPA2Pipeline.java b/drivers/default/src/main/java/org/onosproject/driver/pipeline/OFDPA2Pipeline.java
new file mode 100644
index 0000000..1cfb937
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/pipeline/OFDPA2Pipeline.java
@@ -0,0 +1,868 @@
+/*
+ * 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 static org.slf4j.LoggerFactory.getLogger;
+
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Deque;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.onlab.osgi.ServiceDirectory;
+import org.onlab.packet.Ethernet;
+import org.onlab.packet.MacAddress;
+import org.onlab.packet.VlanId;
+import org.onlab.util.KryoNamespace;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreService;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.Port;
+import org.onosproject.net.PortNumber;
+import org.onosproject.net.behaviour.NextGroup;
+import org.onosproject.net.behaviour.Pipeliner;
+import org.onosproject.net.behaviour.PipelinerContext;
+import org.onosproject.net.device.DeviceService;
+import org.onosproject.net.driver.AbstractHandlerBehaviour;
+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 org.onosproject.net.flow.FlowRuleOperations;
+import org.onosproject.net.flow.FlowRuleOperationsContext;
+import org.onosproject.net.flow.FlowRuleService;
+import org.onosproject.net.flow.TrafficSelector;
+import org.onosproject.net.flow.TrafficTreatment;
+import org.onosproject.net.flow.criteria.Criteria;
+import org.onosproject.net.flow.criteria.Criterion;
+import org.onosproject.net.flow.criteria.EthCriterion;
+import org.onosproject.net.flow.criteria.EthTypeCriterion;
+import org.onosproject.net.flow.criteria.IPCriterion;
+import org.onosproject.net.flow.criteria.MplsBosCriterion;
+import org.onosproject.net.flow.criteria.MplsCriterion;
+import org.onosproject.net.flow.criteria.PortCriterion;
+import org.onosproject.net.flow.criteria.VlanIdCriterion;
+import org.onosproject.net.flow.instructions.Instruction;
+import org.onosproject.net.flow.instructions.Instructions.OutputInstruction;
+import org.onosproject.net.flow.instructions.L2ModificationInstruction;
+import org.onosproject.net.flow.instructions.L2ModificationInstruction.L2SubType;
+import org.onosproject.net.flow.instructions.L2ModificationInstruction.ModVlanIdInstruction;
+import org.onosproject.net.flowobjective.FilteringObjective;
+import org.onosproject.net.flowobjective.FlowObjectiveStore;
+import org.onosproject.net.flowobjective.ForwardingObjective;
+import org.onosproject.net.flowobjective.NextObjective;
+import org.onosproject.net.flowobjective.Objective;
+import org.onosproject.net.flowobjective.ObjectiveError;
+import org.onosproject.net.group.DefaultGroupKey;
+import org.onosproject.net.group.Group;
+import org.onosproject.net.group.GroupKey;
+import org.onosproject.net.group.GroupService;
+import org.onosproject.store.serializers.KryoNamespaces;
+import org.slf4j.Logger;
+
+/**
+ * Driver for Broadcom's OF-DPA v2.0 TTP.
+ *
+ */
+public class OFDPA2Pipeline extends AbstractHandlerBehaviour implements Pipeliner {
+ protected static final int PORT_TABLE = 0;
+ protected static final int VLAN_TABLE = 10;
+ protected static final int TMAC_TABLE = 20;
+ protected static final int UNICAST_ROUTING_TABLE = 30;
+ protected static final int MULTICAST_ROUTING_TABLE = 40;
+ protected static final int MPLS_TABLE_0 = 23;
+ protected static final int MPLS_TABLE_1 = 24;
+ protected static final int BRIDGING_TABLE = 50;
+ protected static final int ACL_TABLE = 60;
+ protected static final int MAC_LEARNING_TABLE = 254;
+ protected static final long OFPP_MAX = 0xffffff00L;
+
+ private static final int HIGHEST_PRIORITY = 0xffff;
+ protected static final int DEFAULT_PRIORITY = 0x8000;
+ protected static final int LOWEST_PRIORITY = 0x0;
+
+ private final Logger log = getLogger(getClass());
+ private ServiceDirectory serviceDirectory;
+ protected FlowRuleService flowRuleService;
+ private CoreService coreService;
+ protected GroupService groupService;
+ protected FlowObjectiveStore flowObjectiveStore;
+ protected DeviceId deviceId;
+ protected ApplicationId driverId;
+ protected DeviceService deviceService;
+ protected static KryoNamespace appKryo = new KryoNamespace.Builder()
+ .register(KryoNamespaces.API)
+ .register(GroupKey.class)
+ .register(DefaultGroupKey.class)
+ .register(OFDPA2GroupHandler.OfdpaNextGroup.class)
+ .register(byte[].class)
+ .register(ArrayDeque.class)
+ .build();
+
+ protected OFDPA2GroupHandler ofdpa2GroupHandler;
+
+ private Set<IPCriterion> sentIpFilters = Collections.newSetFromMap(
+ new ConcurrentHashMap<>());
+
+ @Override
+ public void init(DeviceId deviceId, PipelinerContext context) {
+ this.serviceDirectory = context.directory();
+ this.deviceId = deviceId;
+
+ // Initialize OFDPA group handler
+ ofdpa2GroupHandler = new OFDPA2GroupHandler();
+ ofdpa2GroupHandler.init(deviceId, context);
+
+ coreService = serviceDirectory.get(CoreService.class);
+ flowRuleService = serviceDirectory.get(FlowRuleService.class);
+ groupService = serviceDirectory.get(GroupService.class);
+ flowObjectiveStore = context.store();
+ deviceService = serviceDirectory.get(DeviceService.class);
+
+ driverId = coreService.registerApplication(
+ "org.onosproject.driver.OFDPA2Pipeline");
+
+ initializePipeline();
+ }
+
+ protected void initializePipeline() {
+ // OF-DPA does not require initializing the pipeline as it puts default
+ // rules automatically in the hardware. However emulation of OFDPA in
+ // software switches does require table-miss-entries.
+ }
+
+ //////////////////////////////////////
+ // Flow Objectives
+ //////////////////////////////////////
+
+ @Override
+ public void filter(FilteringObjective filteringObjective) {
+ if (filteringObjective.type() == FilteringObjective.Type.PERMIT) {
+ processFilter(filteringObjective,
+ filteringObjective.op() == Objective.Operation.ADD,
+ filteringObjective.appId());
+ } else {
+ // Note that packets that don't match the PERMIT filter are
+ // automatically denied. The DENY filter is used to deny packets
+ // that are otherwise permitted by the PERMIT filter.
+ // Use ACL table flow rules here for DENY filtering objectives
+ log.debug("filter objective other than PERMIT currently not supported");
+ fail(filteringObjective, ObjectiveError.UNSUPPORTED);
+ }
+ }
+
+ @Override
+ public void forward(ForwardingObjective fwd) {
+ Collection<FlowRule> rules;
+ FlowRuleOperations.Builder flowOpsBuilder = FlowRuleOperations.builder();
+
+ rules = processForward(fwd);
+ switch (fwd.op()) {
+ case ADD:
+ rules.stream()
+ .filter(Objects::nonNull)
+ .forEach(flowOpsBuilder::add);
+ break;
+ case REMOVE:
+ rules.stream()
+ .filter(Objects::nonNull)
+ .forEach(flowOpsBuilder::remove);
+ break;
+ default:
+ fail(fwd, ObjectiveError.UNKNOWN);
+ log.warn("Unknown forwarding type {}", fwd.op());
+ }
+
+ flowRuleService.apply(flowOpsBuilder.build(new FlowRuleOperationsContext() {
+ @Override
+ public void onSuccess(FlowRuleOperations ops) {
+ pass(fwd);
+ }
+
+ @Override
+ public void onError(FlowRuleOperations ops) {
+ fail(fwd, ObjectiveError.FLOWINSTALLATIONFAILED);
+ }
+ }));
+ }
+
+ @Override
+ public void next(NextObjective nextObjective) {
+ NextGroup nextGroup = flowObjectiveStore.getNextGroup(nextObjective.id());
+ switch (nextObjective.op()) {
+ case ADD:
+ if (nextGroup != null) {
+ log.warn("Cannot add next {} that already exists in device {}",
+ nextObjective.id(), deviceId);
+ return;
+ }
+ log.debug("Processing NextObjective id{} in dev{} - add group",
+ nextObjective.id(), deviceId);
+ ofdpa2GroupHandler.addGroup(nextObjective);
+ break;
+ case ADD_TO_EXISTING:
+ if (nextGroup != null) {
+ log.debug("Processing NextObjective id{} in dev{} - add bucket",
+ nextObjective.id(), deviceId);
+ ofdpa2GroupHandler.addBucketToGroup(nextObjective, nextGroup);
+ } else {
+ // it is possible that group-chain has not been fully created yet
+ log.debug("Waiting to add bucket to group for next-id:{} in dev:{}",
+ nextObjective.id(), deviceId);
+ // by design only one pending bucket is allowed for the group
+ ofdpa2GroupHandler.pendingBuckets.put(nextObjective.id(), nextObjective);
+ }
+ break;
+ case REMOVE:
+ if (nextGroup == null) {
+ log.warn("Cannot remove next {} that does not exist in device {}",
+ nextObjective.id(), deviceId);
+ return;
+ }
+ log.debug("Processing NextObjective id{} in dev{} - remove group",
+ nextObjective.id(), deviceId);
+ ofdpa2GroupHandler.removeGroup(nextObjective, nextGroup);
+ break;
+ case REMOVE_FROM_EXISTING:
+ if (nextGroup == null) {
+ log.warn("Cannot remove from next {} that does not exist in device {}",
+ nextObjective.id(), deviceId);
+ return;
+ }
+ log.debug("Processing NextObjective id{} in dev{} - remove bucket",
+ nextObjective.id(), deviceId);
+ ofdpa2GroupHandler.removeBucketFromGroup(nextObjective, nextGroup);
+ break;
+ default:
+ log.warn("Unsupported operation {}", nextObjective.op());
+ }
+ }
+
+ //////////////////////////////////////
+ // Flow handling
+ //////////////////////////////////////
+
+ /**
+ * As per OFDPA 2.0 TTP, filtering of VLAN ids, MAC addresses (for routing)
+ * and IP addresses configured on switch ports happen in different tables.
+ * Note that IP filtering rules need to be added to the ACL table, as there
+ * is no mechanism to send to controller via IP table.
+ *
+ * @param filt the filtering objective
+ * @param install indicates whether to add or remove the objective
+ * @param applicationId the application that sent this objective
+ */
+ private void processFilter(FilteringObjective filt,
+ boolean install, ApplicationId applicationId) {
+ // This driver only processes filtering criteria defined with switch
+ // ports as the key
+ PortCriterion portCriterion = null;
+ EthCriterion ethCriterion = null;
+ VlanIdCriterion vidCriterion = null;
+ Collection<IPCriterion> ips = new ArrayList<IPCriterion>();
+ if (!filt.key().equals(Criteria.dummy()) &&
+ filt.key().type() == Criterion.Type.IN_PORT) {
+ portCriterion = (PortCriterion) filt.key();
+ } else {
+ log.warn("No key defined in filtering objective from app: {}. Not"
+ + "processing filtering objective", applicationId);
+ fail(filt, ObjectiveError.UNKNOWN);
+ return;
+ }
+ // convert filtering conditions for switch-intfs into flowrules
+ FlowRuleOperations.Builder ops = FlowRuleOperations.builder();
+ for (Criterion criterion : filt.conditions()) {
+ if (criterion.type() == Criterion.Type.ETH_DST) {
+ ethCriterion = (EthCriterion) criterion;
+ } else if (criterion.type() == Criterion.Type.VLAN_VID) {
+ vidCriterion = (VlanIdCriterion) criterion;
+ } else if (criterion.type() == Criterion.Type.IPV4_DST) {
+ ips.add((IPCriterion) criterion);
+ } else {
+ log.error("Unsupported filter {}", criterion);
+ fail(filt, ObjectiveError.UNSUPPORTED);
+ return;
+ }
+ }
+
+ VlanId assignedVlan = null;
+ // For VLAN cross-connect packets, use the configured VLAN
+ if (vidCriterion != null) {
+ if (vidCriterion.vlanId() != VlanId.NONE) {
+ assignedVlan = vidCriterion.vlanId();
+
+ // For untagged packets, assign a VLAN ID
+ } else {
+ if (filt.meta() == null) {
+ log.error("Missing metadata in filtering objective required " +
+ "for vlan assignment in dev {}", deviceId);
+ fail(filt, ObjectiveError.BADPARAMS);
+ return;
+ }
+ for (Instruction i : filt.meta().allInstructions()) {
+ if (i instanceof ModVlanIdInstruction) {
+ assignedVlan = ((ModVlanIdInstruction) i).vlanId();
+ }
+ }
+ if (assignedVlan == null) {
+ log.error("Driver requires an assigned vlan-id to tag incoming "
+ + "untagged packets. Not processing vlan filters on "
+ + "device {}", deviceId);
+ fail(filt, ObjectiveError.BADPARAMS);
+ return;
+ }
+ }
+ }
+
+ if (ethCriterion == null || ethCriterion.mac().equals(MacAddress.NONE)) {
+ log.debug("filtering objective missing dstMac, cannot program TMAC table");
+ } else {
+ for (FlowRule tmacRule : processEthDstFilter(portCriterion, ethCriterion,
+ vidCriterion, assignedVlan,
+ applicationId)) {
+ log.debug("adding MAC filtering rules in TMAC table: {} for dev: {}",
+ tmacRule, deviceId);
+ ops = install ? ops.add(tmacRule) : ops.remove(tmacRule);
+ }
+ }
+
+ if (ethCriterion == null || vidCriterion == null) {
+ log.debug("filtering objective missing dstMac or VLAN, "
+ + "cannot program VLAN Table");
+ } else {
+ for (FlowRule vlanRule : processVlanIdFilter(portCriterion, vidCriterion,
+ assignedVlan,
+ applicationId)) {
+ log.debug("adding VLAN filtering rule in VLAN table: {} for dev: {}",
+ vlanRule, deviceId);
+ ops = install ? ops.add(vlanRule) : ops.remove(vlanRule);
+ }
+ }
+
+ for (IPCriterion ipaddr : ips) {
+ // since we ignore port information for IP rules, and the same (gateway) IP
+ // can be configured on multiple ports, we make sure that we send
+ // only a single rule to the switch.
+ if (!sentIpFilters.contains(ipaddr)) {
+ sentIpFilters.add(ipaddr);
+ log.debug("adding IP filtering rules in ACL table {} for dev: {}",
+ ipaddr, deviceId);
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
+ selector.matchEthType(Ethernet.TYPE_IPV4);
+ selector.matchIPDst(ipaddr.ip());
+ treatment.setOutput(PortNumber.CONTROLLER);
+ FlowRule rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(HIGHEST_PRIORITY)
+ .fromApp(applicationId)
+ .makePermanent()
+ .forTable(ACL_TABLE).build();
+ ops = install ? ops.add(rule) : ops.remove(rule);
+ }
+ }
+
+ // apply filtering flow rules
+ flowRuleService.apply(ops.build(new FlowRuleOperationsContext() {
+ @Override
+ public void onSuccess(FlowRuleOperations ops) {
+ log.info("Applied {} filtering rules in device {}",
+ ops.stages().get(0).size(), deviceId);
+ pass(filt);
+ }
+
+ @Override
+ public void onError(FlowRuleOperations ops) {
+ log.info("Failed to apply all filtering rules in dev {}", deviceId);
+ fail(filt, ObjectiveError.FLOWINSTALLATIONFAILED);
+ }
+ }));
+
+ }
+
+ /**
+ * Allows untagged packets into pipeline by assigning a vlan id.
+ * Vlan assignment is done by the application.
+ * Allows tagged packets into pipeline as per configured port-vlan info.
+ *
+ * @param portCriterion port on device for which this filter is programmed
+ * @param vidCriterion vlan assigned to port, or NONE for untagged
+ * @param assignedVlan assigned vlan-id for untagged packets
+ * @param applicationId for application programming this filter
+ * @return list of FlowRule for port-vlan filters
+ */
+ protected List<FlowRule> processVlanIdFilter(PortCriterion portCriterion,
+ VlanIdCriterion vidCriterion,
+ VlanId assignedVlan,
+ ApplicationId applicationId) {
+ List<FlowRule> rules = new ArrayList<FlowRule>();
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
+ selector.matchVlanId(vidCriterion.vlanId());
+ treatment.transition(TMAC_TABLE);
+
+ VlanId storeVlan = null;
+ if (vidCriterion.vlanId() == VlanId.NONE) {
+ // untagged packets are assigned vlans
+ treatment.pushVlan().setVlanId(assignedVlan);
+ // XXX ofdpa will require an additional vlan match on the assigned vlan
+ // and it may not require the push. This is not in compliance with OF
+ // standard. Waiting on what the exact flows are going to look like.
+ storeVlan = assignedVlan;
+ } else {
+ storeVlan = vidCriterion.vlanId();
+ }
+
+ // ofdpa cannot match on ALL portnumber, so we need to use separate
+ // rules for each port.
+ List<PortNumber> portnums = new ArrayList<PortNumber>();
+ if (portCriterion.port() == PortNumber.ALL) {
+ for (Port port : deviceService.getPorts(deviceId)) {
+ if (port.number().toLong() > 0 && port.number().toLong() < OFPP_MAX) {
+ portnums.add(port.number());
+ }
+ }
+ } else {
+ portnums.add(portCriterion.port());
+ }
+
+ for (PortNumber pnum : portnums) {
+ // update storage
+ ofdpa2GroupHandler.port2Vlan.put(pnum, storeVlan);
+ Set<PortNumber> vlanPorts = ofdpa2GroupHandler.vlan2Port.get(storeVlan);
+ if (vlanPorts == null) {
+ vlanPorts = Collections.newSetFromMap(
+ new ConcurrentHashMap<PortNumber, Boolean>());
+ vlanPorts.add(pnum);
+ ofdpa2GroupHandler.vlan2Port.put(storeVlan, vlanPorts);
+ } else {
+ vlanPorts.add(pnum);
+ }
+ // create rest of flowrule
+ selector.matchInPort(pnum);
+ FlowRule rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(DEFAULT_PRIORITY)
+ .fromApp(applicationId)
+ .makePermanent()
+ .forTable(VLAN_TABLE).build();
+ rules.add(rule);
+ }
+ return rules;
+ }
+
+ /**
+ * Allows routed packets with correct destination MAC to be directed
+ * to unicast-IP routing table or MPLS forwarding table.
+ *
+ * @param portCriterion port on device for which this filter is programmed
+ * @param ethCriterion dstMac of device for which is filter is programmed
+ * @param vidCriterion vlan assigned to port, or NONE for untagged
+ * @param assignedVlan assigned vlan-id for untagged packets
+ * @param applicationId for application programming this filter
+ * @return list of FlowRule for port-vlan filters
+
+ */
+ protected List<FlowRule> processEthDstFilter(PortCriterion portCriterion,
+ EthCriterion ethCriterion,
+ VlanIdCriterion vidCriterion,
+ VlanId assignedVlan,
+ ApplicationId applicationId) {
+ //handling untagged packets via assigned VLAN
+ if (vidCriterion.vlanId() == VlanId.NONE) {
+ vidCriterion = (VlanIdCriterion) Criteria.matchVlanId(assignedVlan);
+ }
+ // ofdpa cannot match on ALL portnumber, so we need to use separate
+ // rules for each port.
+ List<PortNumber> portnums = new ArrayList<PortNumber>();
+ if (portCriterion.port() == PortNumber.ALL) {
+ for (Port port : deviceService.getPorts(deviceId)) {
+ if (port.number().toLong() > 0 && port.number().toLong() < OFPP_MAX) {
+ portnums.add(port.number());
+ }
+ }
+ } else {
+ portnums.add(portCriterion.port());
+ }
+
+ List<FlowRule> rules = new ArrayList<FlowRule>();
+ for (PortNumber pnum : portnums) {
+ // for unicast IP packets
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
+ selector.matchInPort(pnum);
+ selector.matchVlanId(vidCriterion.vlanId());
+ selector.matchEthType(Ethernet.TYPE_IPV4);
+ selector.matchEthDst(ethCriterion.mac());
+ treatment.transition(UNICAST_ROUTING_TABLE);
+ FlowRule rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(DEFAULT_PRIORITY)
+ .fromApp(applicationId)
+ .makePermanent()
+ .forTable(TMAC_TABLE).build();
+ rules.add(rule);
+ //for MPLS packets
+ selector = DefaultTrafficSelector.builder();
+ treatment = DefaultTrafficTreatment.builder();
+ selector.matchInPort(pnum);
+ selector.matchVlanId(vidCriterion.vlanId());
+ selector.matchEthType(Ethernet.MPLS_UNICAST);
+ selector.matchEthDst(ethCriterion.mac());
+ treatment.transition(MPLS_TABLE_0);
+ rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(DEFAULT_PRIORITY)
+ .fromApp(applicationId)
+ .makePermanent()
+ .forTable(TMAC_TABLE).build();
+ rules.add(rule);
+ }
+ return rules;
+ }
+
+ private Collection<FlowRule> processForward(ForwardingObjective fwd) {
+ switch (fwd.flag()) {
+ case SPECIFIC:
+ return processSpecific(fwd);
+ case VERSATILE:
+ return processVersatile(fwd);
+ default:
+ fail(fwd, ObjectiveError.UNKNOWN);
+ log.warn("Unknown forwarding flag {}", fwd.flag());
+ }
+ return Collections.emptySet();
+ }
+
+ /**
+ * In the OF-DPA 2.0 pipeline, versatile forwarding objectives go to the
+ * ACL table.
+ * @param fwd the forwarding objective of type 'versatile'
+ * @return a collection of flow rules to be sent to the switch. An empty
+ * collection may be returned if there is a problem in processing
+ * the flow rule
+ */
+ private Collection<FlowRule> processVersatile(ForwardingObjective fwd) {
+ log.info("Processing versatile forwarding objective");
+ TrafficSelector selector = fwd.selector();
+
+ EthTypeCriterion ethType =
+ (EthTypeCriterion) selector.getCriterion(Criterion.Type.ETH_TYPE);
+ if (ethType == null) {
+ log.error("Versatile forwarding objective must include ethType");
+ fail(fwd, ObjectiveError.BADPARAMS);
+ return Collections.emptySet();
+ }
+ if (fwd.nextId() == null && fwd.treatment() == null) {
+ log.error("Forwarding objective {} from {} must contain "
+ + "nextId or Treatment", fwd.selector(), fwd.appId());
+ return Collections.emptySet();
+ }
+ // XXX driver does not currently do type checking as per Tables 65-67 in
+ // OFDPA 2.0 spec. The only allowed treatment is a punt to the controller.
+ if (fwd.treatment() != null &&
+ fwd.treatment().allInstructions().size() == 1 &&
+ fwd.treatment().allInstructions().get(0).type() == Instruction.Type.OUTPUT) {
+ OutputInstruction o = (OutputInstruction) fwd.treatment().allInstructions().get(0);
+ if (o.port() == PortNumber.CONTROLLER) {
+ FlowRule.Builder ruleBuilder = DefaultFlowRule.builder()
+ .fromApp(fwd.appId())
+ .withPriority(fwd.priority())
+ .forDevice(deviceId)
+ .withSelector(fwd.selector())
+ .withTreatment(fwd.treatment())
+ .makePermanent()
+ .forTable(ACL_TABLE);
+ return Collections.singletonList(ruleBuilder.build());
+ } else {
+ log.warn("Only allowed treatments in versatile forwarding "
+ + "objectives are punts to the controller");
+ return Collections.emptySet();
+ }
+ }
+
+ if (fwd.nextId() != null) {
+ // XXX overide case
+ log.warn("versatile objective --> next Id not yet implemeted");
+ }
+ return Collections.emptySet();
+ }
+
+ /**
+ * In the OF-DPA 2.0 pipeline, specific forwarding refers to the IP table
+ * (unicast or multicast) or the L2 table (mac + vlan) or the MPLS table.
+ *
+ * @param fwd the forwarding objective of type 'specific'
+ * @return a collection of flow rules. Typically there will be only one
+ * for this type of forwarding objective. An empty set may be
+ * returned if there is an issue in processing the objective.
+ */
+ protected Collection<FlowRule> processSpecific(ForwardingObjective fwd) {
+ log.trace("Processing specific fwd objective:{} in dev:{} with next:{}",
+ fwd.id(), deviceId, fwd.nextId());
+ boolean isEthTypeObj = isSupportedEthTypeObjective(fwd);
+ boolean isEthDstObj = isSupportedEthDstObjective(fwd);
+
+ if (isEthTypeObj) {
+ return processEthTypeSpecific(fwd);
+ } else if (isEthDstObj) {
+ return processEthDstSpecific(fwd);
+ } else {
+ log.warn("processSpecific: Unsupported forwarding objective "
+ + "criteria fwd:{} in dev:{}", fwd.nextId(), deviceId);
+ fail(fwd, ObjectiveError.UNSUPPORTED);
+ return Collections.emptySet();
+ }
+ }
+
+ private boolean isSupportedEthTypeObjective(ForwardingObjective fwd) {
+ TrafficSelector selector = fwd.selector();
+ EthTypeCriterion ethType = (EthTypeCriterion) selector
+ .getCriterion(Criterion.Type.ETH_TYPE);
+ return !((ethType == null) ||
+ ((ethType.ethType().toShort() != Ethernet.TYPE_IPV4) &&
+ (ethType.ethType().toShort() != Ethernet.MPLS_UNICAST)));
+ }
+
+ private boolean isSupportedEthDstObjective(ForwardingObjective fwd) {
+ TrafficSelector selector = fwd.selector();
+ EthCriterion ethDst = (EthCriterion) selector
+ .getCriterion(Criterion.Type.ETH_DST);
+ VlanIdCriterion vlanId = (VlanIdCriterion) selector
+ .getCriterion(Criterion.Type.VLAN_VID);
+ return !(ethDst == null && vlanId == null);
+ }
+
+ /**
+ * Handles forwarding rules to the IP and MPLS tables.
+ *
+ * @param fwd the forwarding objective
+ * @return A collection of flow rules, or an empty set
+ */
+ protected Collection<FlowRule> processEthTypeSpecific(ForwardingObjective fwd) {
+ TrafficSelector selector = fwd.selector();
+ EthTypeCriterion ethType =
+ (EthTypeCriterion) selector.getCriterion(Criterion.Type.ETH_TYPE);
+
+ int forTableId;
+ TrafficSelector.Builder filteredSelector = DefaultTrafficSelector.builder();
+ if (ethType.ethType().toShort() == Ethernet.TYPE_IPV4) {
+ filteredSelector.matchEthType(Ethernet.TYPE_IPV4)
+ .matchIPDst(((IPCriterion)
+ selector.getCriterion(Criterion.Type.IPV4_DST)).ip());
+ forTableId = UNICAST_ROUTING_TABLE;
+ log.debug("processing IPv4 specific forwarding objective {} -> next:{}"
+ + " in dev:{}", fwd.id(), fwd.nextId(), deviceId);
+ } else {
+ filteredSelector
+ .matchEthType(Ethernet.MPLS_UNICAST)
+ .matchMplsLabel(((MplsCriterion)
+ selector.getCriterion(Criterion.Type.MPLS_LABEL)).label());
+ MplsBosCriterion bos = (MplsBosCriterion) selector
+ .getCriterion(Criterion.Type.MPLS_BOS);
+ if (bos != null) {
+ filteredSelector.matchMplsBos(bos.mplsBos());
+ }
+ forTableId = MPLS_TABLE_1;
+ log.debug("processing MPLS specific forwarding objective {} -> next:{}"
+ + " in dev {}", fwd.id(), fwd.nextId(), deviceId);
+ }
+
+ TrafficTreatment.Builder tb = DefaultTrafficTreatment.builder();
+ boolean popMpls = false;
+ if (fwd.treatment() != null) {
+ for (Instruction i : fwd.treatment().allInstructions()) {
+ /*
+ * NOTE: OF-DPA does not support immediate instruction in
+ * L3 unicast and MPLS table.
+ */
+ tb.deferred().add(i);
+ if (i instanceof L2ModificationInstruction &&
+ ((L2ModificationInstruction) i).subtype() == L2SubType.MPLS_POP) {
+ popMpls = true;
+ }
+ }
+ }
+
+ if (fwd.nextId() != null) {
+ if (forTableId == MPLS_TABLE_1 && !popMpls) {
+ log.warn("SR CONTINUE case cannot be handled as MPLS ECMP "
+ + "is not implemented in OF-DPA yet. Aborting this flow "
+ + "in this device {}", deviceId);
+ // XXX We could convert to forwarding to a single-port, via a
+ // MPLS interface, or a MPLS SWAP (with-same) but that would
+ // have to be handled in the next-objective. Also the pop-mpls
+ // logic used here won't work in non-BoS case.
+ fail(fwd, ObjectiveError.FLOWINSTALLATIONFAILED);
+ return Collections.emptySet();
+ }
+
+ NextGroup next = getGroupForNextObjective(fwd.nextId());
+ if (next != null) {
+ List<Deque<GroupKey>> gkeys = appKryo.deserialize(next.data());
+ // we only need the top level group's key to point the flow to it
+ Group group = groupService.getGroup(deviceId, gkeys.get(0).peekFirst());
+ if (group == null) {
+ log.warn("Group with key:{} for next-id:{} not found in dev:{}",
+ gkeys.get(0).peekFirst(), fwd.nextId(), deviceId);
+ fail(fwd, ObjectiveError.GROUPMISSING);
+ return Collections.emptySet();
+ }
+ tb.deferred().group(group.id());
+ }
+ }
+ tb.transition(ACL_TABLE);
+ FlowRule.Builder ruleBuilder = DefaultFlowRule.builder()
+ .fromApp(fwd.appId())
+ .withPriority(fwd.priority())
+ .forDevice(deviceId)
+ .withSelector(filteredSelector.build())
+ .withTreatment(tb.build())
+ .forTable(forTableId);
+
+ if (fwd.permanent()) {
+ ruleBuilder.makePermanent();
+ } else {
+ ruleBuilder.makeTemporary(fwd.timeout());
+ }
+
+ return Collections.singletonList(ruleBuilder.build());
+ }
+
+ /**
+ * Handles forwarding rules to the L2 bridging table. Flow actions are not
+ * allowed in the bridging table - instead we use L2 Interface group or
+ * L2 flood group
+ *
+ * @param fwd the forwarding objective
+ * @return A collection of flow rules, or an empty set
+ */
+ protected Collection<FlowRule> processEthDstSpecific(ForwardingObjective fwd) {
+ List<FlowRule> rules = new ArrayList<>();
+
+ // Build filtered selector
+ TrafficSelector selector = fwd.selector();
+ EthCriterion ethCriterion = (EthCriterion) selector
+ .getCriterion(Criterion.Type.ETH_DST);
+ VlanIdCriterion vlanIdCriterion = (VlanIdCriterion) selector
+ .getCriterion(Criterion.Type.VLAN_VID);
+
+ if (vlanIdCriterion == null) {
+ log.warn("Forwarding objective for bridging requires vlan. Not "
+ + "installing fwd:{} in dev:{}", fwd.id(), deviceId);
+ fail(fwd, ObjectiveError.BADPARAMS);
+ return Collections.emptySet();
+ }
+
+ TrafficSelector.Builder filteredSelectorBuilder =
+ DefaultTrafficSelector.builder();
+ // Do not match MacAddress for subnet broadcast entry
+ if (!ethCriterion.mac().equals(MacAddress.NONE)) {
+ filteredSelectorBuilder.matchEthDst(ethCriterion.mac());
+ log.debug("processing L2 forwarding objective:{} -> next:{} in dev:{}",
+ fwd.id(), fwd.nextId(), deviceId);
+ } else {
+ log.debug("processing L2 Broadcast forwarding objective:{} -> next:{} "
+ + "in dev:{} for vlan:{}",
+ fwd.id(), fwd.nextId(), deviceId, vlanIdCriterion.vlanId());
+ }
+ filteredSelectorBuilder.matchVlanId(vlanIdCriterion.vlanId());
+ TrafficSelector filteredSelector = filteredSelectorBuilder.build();
+
+ if (fwd.treatment() != null) {
+ log.warn("Ignoring traffic treatment in fwd rule {} meant for L2 table"
+ + "for dev:{}. Expecting only nextId", fwd.id(), deviceId);
+ }
+
+ TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder();
+ if (fwd.nextId() != null) {
+ NextGroup next = getGroupForNextObjective(fwd.nextId());
+ if (next != null) {
+ List<Deque<GroupKey>> gkeys = appKryo.deserialize(next.data());
+ // we only need the top level group's key to point the flow to it
+ Group group = groupService.getGroup(deviceId, gkeys.get(0).peekFirst());
+ if (group != null) {
+ treatmentBuilder.deferred().group(group.id());
+ } else {
+ log.warn("Group with key:{} for next-id:{} not found in dev:{}",
+ gkeys.get(0).peekFirst(), fwd.nextId(), deviceId);
+ fail(fwd, ObjectiveError.GROUPMISSING);
+ return Collections.emptySet();
+ }
+ }
+ }
+ treatmentBuilder.immediate().transition(ACL_TABLE);
+ TrafficTreatment filteredTreatment = treatmentBuilder.build();
+
+ // Build bridging table entries
+ FlowRule.Builder flowRuleBuilder = DefaultFlowRule.builder();
+ flowRuleBuilder.fromApp(fwd.appId())
+ .withPriority(fwd.priority())
+ .forDevice(deviceId)
+ .withSelector(filteredSelector)
+ .withTreatment(filteredTreatment)
+ .forTable(BRIDGING_TABLE);
+ if (fwd.permanent()) {
+ flowRuleBuilder.makePermanent();
+ } else {
+ flowRuleBuilder.makeTemporary(fwd.timeout());
+ }
+ rules.add(flowRuleBuilder.build());
+ return rules;
+ }
+
+ protected NextGroup getGroupForNextObjective(Integer nextId) {
+ NextGroup next = flowObjectiveStore.getNextGroup(nextId);
+ if (next != null) {
+ List<Deque<GroupKey>> gkeys = appKryo.deserialize(next.data());
+ if (gkeys != null && !gkeys.isEmpty()) {
+ return next;
+ } else {
+ log.warn("Empty next group found in FlowObjective store for "
+ + "next-id:{} in dev:{}", nextId, deviceId);
+ }
+ } else {
+ log.warn("next-id {} not found in Flow objective store for dev:{}",
+ nextId, deviceId);
+ }
+ return null;
+ }
+
+ protected static void pass(Objective obj) {
+ if (obj.context().isPresent()) {
+ obj.context().get().onSuccess(obj);
+ }
+ }
+
+ protected static void fail(Objective obj, ObjectiveError error) {
+ if (obj.context().isPresent()) {
+ obj.context().get().onError(obj, error);
+ }
+ }
+}
diff --git a/drivers/default/src/main/java/org/onosproject/driver/pipeline/OVSCorsaPipeline.java b/drivers/default/src/main/java/org/onosproject/driver/pipeline/OVSCorsaPipeline.java
new file mode 100644
index 0000000..46a360b
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/pipeline/OVSCorsaPipeline.java
@@ -0,0 +1,864 @@
+/*
+ * 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 com.google.common.cache.Cache;
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.RemovalCause;
+import com.google.common.cache.RemovalNotification;
+
+import org.onlab.osgi.ServiceDirectory;
+import org.onlab.packet.Ethernet;
+import org.onlab.packet.IPv4;
+import org.onlab.packet.MacAddress;
+import org.onlab.packet.VlanId;
+import org.onlab.util.KryoNamespace;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreService;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.behaviour.NextGroup;
+import org.onosproject.net.behaviour.Pipeliner;
+import org.onosproject.net.behaviour.PipelinerContext;
+import org.onosproject.net.driver.AbstractHandlerBehaviour;
+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 org.onosproject.net.flow.FlowRuleOperations;
+import org.onosproject.net.flow.FlowRuleOperationsContext;
+import org.onosproject.net.flow.FlowRuleService;
+import org.onosproject.net.flow.TrafficSelector;
+import org.onosproject.net.flow.TrafficTreatment;
+import org.onosproject.net.flow.criteria.Criteria;
+import org.onosproject.net.flow.criteria.Criterion;
+import org.onosproject.net.flow.criteria.EthCriterion;
+import org.onosproject.net.flow.criteria.EthTypeCriterion;
+import org.onosproject.net.flow.criteria.IPCriterion;
+import org.onosproject.net.flow.criteria.IPProtocolCriterion;
+import org.onosproject.net.flow.criteria.PortCriterion;
+import org.onosproject.net.flow.criteria.VlanIdCriterion;
+import org.onosproject.net.flowobjective.FilteringObjective;
+import org.onosproject.net.flowobjective.FlowObjectiveStore;
+import org.onosproject.net.flowobjective.ForwardingObjective;
+import org.onosproject.net.flowobjective.NextObjective;
+import org.onosproject.net.flowobjective.Objective;
+import org.onosproject.net.flowobjective.ObjectiveError;
+import org.onosproject.net.group.DefaultGroupBucket;
+import org.onosproject.net.group.DefaultGroupDescription;
+import org.onosproject.net.group.DefaultGroupKey;
+import org.onosproject.net.group.Group;
+import org.onosproject.net.group.GroupBucket;
+import org.onosproject.net.group.GroupBuckets;
+import org.onosproject.net.group.GroupDescription;
+import org.onosproject.net.group.GroupEvent;
+import org.onosproject.net.group.GroupKey;
+import org.onosproject.net.group.GroupListener;
+import org.onosproject.net.group.GroupService;
+import org.onosproject.net.meter.MeterService;
+import org.slf4j.Logger;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+
+import static org.onlab.util.Tools.groupedThreads;
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * OpenvSwitch emulation of the Corsa pipeline handler.
+ */
+public class OVSCorsaPipeline extends AbstractHandlerBehaviour implements Pipeliner {
+
+ protected static final int MAC_TABLE = 0;
+ protected static final int VLAN_MPLS_TABLE = 1;
+ protected static final int VLAN_TABLE = 2;
+ //protected static final int MPLS_TABLE = 3;
+ protected static final int ETHER_TABLE = 4;
+ protected static final int COS_MAP_TABLE = 5;
+ protected static final int FIB_TABLE = 6;
+ protected static final int LOCAL_TABLE = 9;
+
+
+ protected static final int CONTROLLER_PRIORITY = 255;
+ protected static final int DROP_PRIORITY = 0;
+ protected static final int HIGHEST_PRIORITY = 0xffff;
+
+ private final Logger log = getLogger(getClass());
+
+ private ServiceDirectory serviceDirectory;
+ protected FlowRuleService flowRuleService;
+ private CoreService coreService;
+ private GroupService groupService;
+ protected MeterService meterService;
+ private FlowObjectiveStore flowObjectiveStore;
+ protected DeviceId deviceId;
+ protected ApplicationId appId;
+
+ private KryoNamespace appKryo = new KryoNamespace.Builder()
+ .register(GroupKey.class)
+ .register(DefaultGroupKey.class)
+ .register(CorsaGroup.class)
+ .register(byte[].class)
+ .build();
+
+ private Cache<GroupKey, NextObjective> pendingGroups;
+
+ private ScheduledExecutorService groupChecker =
+ Executors.newScheduledThreadPool(2, groupedThreads("onos/pipeliner",
+ "ovs-corsa-%d"));
+
+ @Override
+ public void init(DeviceId deviceId, PipelinerContext context) {
+ this.serviceDirectory = context.directory();
+ this.deviceId = deviceId;
+
+ pendingGroups = CacheBuilder.newBuilder()
+ .expireAfterWrite(20, TimeUnit.SECONDS)
+ .removalListener((RemovalNotification<GroupKey, NextObjective> notification) -> {
+ if (notification.getCause() == RemovalCause.EXPIRED) {
+ fail(notification.getValue(), ObjectiveError.GROUPINSTALLATIONFAILED);
+ }
+ }).build();
+
+ groupChecker.scheduleAtFixedRate(new GroupChecker(), 0, 500, TimeUnit.MILLISECONDS);
+
+ coreService = serviceDirectory.get(CoreService.class);
+ flowRuleService = serviceDirectory.get(FlowRuleService.class);
+ groupService = serviceDirectory.get(GroupService.class);
+ meterService = serviceDirectory.get(MeterService.class);
+ flowObjectiveStore = context.store();
+
+ groupService.addListener(new InnerGroupListener());
+
+ appId = coreService.registerApplication(
+ "org.onosproject.driver.OVSCorsaPipeline");
+
+ initializePipeline();
+ }
+
+ @Override
+ public void filter(FilteringObjective filteringObjective) {
+ if (filteringObjective.type() == FilteringObjective.Type.PERMIT) {
+ processFilter(filteringObjective,
+ filteringObjective.op() == Objective.Operation.ADD,
+ filteringObjective.appId());
+ } else {
+ fail(filteringObjective, ObjectiveError.UNSUPPORTED);
+ }
+ }
+
+ @Override
+ public void forward(ForwardingObjective fwd) {
+ Collection<FlowRule> rules;
+ FlowRuleOperations.Builder flowBuilder = FlowRuleOperations.builder();
+
+ rules = processForward(fwd);
+ switch (fwd.op()) {
+ case ADD:
+ rules.stream()
+ .filter(Objects::nonNull)
+ .forEach(flowBuilder::add);
+ break;
+ case REMOVE:
+ rules.stream()
+ .filter(Objects::nonNull)
+ .forEach(flowBuilder::remove);
+ break;
+ default:
+ fail(fwd, ObjectiveError.UNKNOWN);
+ log.warn("Unknown forwarding type {}", fwd.op());
+ }
+
+
+ flowRuleService.apply(flowBuilder.build(new FlowRuleOperationsContext() {
+ @Override
+ public void onSuccess(FlowRuleOperations ops) {
+ pass(fwd);
+ }
+
+ @Override
+ public void onError(FlowRuleOperations ops) {
+ fail(fwd, ObjectiveError.FLOWINSTALLATIONFAILED);
+ }
+ }));
+
+ }
+
+ @Override
+ public void next(NextObjective nextObjective) {
+ switch (nextObjective.type()) {
+ case SIMPLE:
+ Collection<TrafficTreatment> treatments = nextObjective.next();
+ if (treatments.size() == 1) {
+ TrafficTreatment treatment = treatments.iterator().next();
+ treatment = processNextTreatment(treatment);
+ GroupBucket bucket =
+ DefaultGroupBucket.createIndirectGroupBucket(treatment);
+ final GroupKey key = new DefaultGroupKey(appKryo.serialize(nextObjective.id()));
+ GroupDescription groupDescription
+ = new DefaultGroupDescription(deviceId,
+ GroupDescription.Type.INDIRECT,
+ new GroupBuckets(Collections
+ .singletonList(bucket)),
+ key,
+ null, // let group service determine group id
+ nextObjective.appId());
+ groupService.addGroup(groupDescription);
+ pendingGroups.put(key, nextObjective);
+ }
+ break;
+ case HASHED:
+ case BROADCAST:
+ case FAILOVER:
+ fail(nextObjective, ObjectiveError.UNSUPPORTED);
+ log.warn("Unsupported next objective type {}", nextObjective.type());
+ break;
+ default:
+ fail(nextObjective, ObjectiveError.UNKNOWN);
+ log.warn("Unknown next objective type {}", nextObjective.type());
+ }
+
+ }
+
+ /* Hook for altering the NextObjective treatment */
+ protected TrafficTreatment processNextTreatment(TrafficTreatment treatment) {
+ return treatment; /* Keep treatment as is for OVSCorsaPipeline */
+ }
+
+ private Collection<FlowRule> processForward(ForwardingObjective fwd) {
+ switch (fwd.flag()) {
+ case SPECIFIC:
+ return processSpecific(fwd);
+ case VERSATILE:
+ return processVersatile(fwd);
+ default:
+ fail(fwd, ObjectiveError.UNKNOWN);
+ log.warn("Unknown forwarding flag {}", fwd.flag());
+ }
+ return Collections.emptySet();
+ }
+
+ private Collection<FlowRule> processVersatile(ForwardingObjective fwd) {
+ log.debug("Processing versatile forwarding objective");
+ TrafficSelector selector = fwd.selector();
+
+ EthTypeCriterion ethType =
+ (EthTypeCriterion) selector.getCriterion(Criterion.Type.ETH_TYPE);
+ if (ethType == null) {
+ log.error("Versatile forwarding objective must include ethType");
+ fail(fwd, ObjectiveError.UNKNOWN);
+ return Collections.emptySet();
+ }
+ if (ethType.ethType().toShort() == Ethernet.TYPE_ARP) {
+ log.warn("Driver automatically handles ARP packets by punting to controller "
+ + " from ETHER table");
+ pass(fwd);
+ return Collections.emptySet();
+ } else if (ethType.ethType().toShort() == Ethernet.TYPE_LLDP ||
+ ethType.ethType().toShort() == Ethernet.TYPE_BSN) {
+ log.warn("Driver currently does not currently handle LLDP packets");
+ fail(fwd, ObjectiveError.UNSUPPORTED);
+ return Collections.emptySet();
+ } else if (ethType.ethType().toShort() == Ethernet.TYPE_IPV4) {
+ IPCriterion ipSrc = (IPCriterion) selector
+ .getCriterion(Criterion.Type.IPV4_SRC);
+ IPCriterion ipDst = (IPCriterion) selector
+ .getCriterion(Criterion.Type.IPV4_DST);
+ IPProtocolCriterion ipProto = (IPProtocolCriterion) selector
+ .getCriterion(Criterion.Type.IP_PROTO);
+ if (ipSrc != null) {
+ log.warn("Driver does not currently handle matching Src IP");
+ fail(fwd, ObjectiveError.UNSUPPORTED);
+ return Collections.emptySet();
+ }
+ if (ipDst != null) {
+ log.error("Driver handles Dst IP matching as specific forwarding "
+ + "objective, not versatile");
+ fail(fwd, ObjectiveError.UNSUPPORTED);
+ return Collections.emptySet();
+ }
+ if (ipProto != null && ipProto.protocol() == IPv4.PROTOCOL_TCP) {
+ log.warn("Driver automatically punts all packets reaching the "
+ + "LOCAL table to the controller");
+ pass(fwd);
+ return Collections.emptySet();
+ }
+ }
+
+ log.warn("Driver does not support given versatile forwarding objective");
+ fail(fwd, ObjectiveError.UNSUPPORTED);
+ return Collections.emptySet();
+ }
+
+ private Collection<FlowRule> processSpecific(ForwardingObjective fwd) {
+ log.debug("Processing specific forwarding objective");
+ TrafficSelector selector = fwd.selector();
+
+ EthTypeCriterion ethType =
+ (EthTypeCriterion) selector.getCriterion(Criterion.Type.ETH_TYPE);
+ if (ethType != null) {
+ short et = ethType.ethType().toShort();
+ if (et == Ethernet.TYPE_IPV4) {
+ return processSpecificRoute(fwd);
+ } else if (et == Ethernet.TYPE_VLAN) {
+ /* The ForwardingObjective must specify VLAN ethtype in order to use the Transit Circuit */
+ return processSpecificSwitch(fwd);
+ }
+ }
+
+ fail(fwd, ObjectiveError.UNSUPPORTED);
+ return Collections.emptySet();
+ }
+
+ private Collection<FlowRule> processSpecificRoute(ForwardingObjective fwd) {
+ TrafficSelector filteredSelector =
+ DefaultTrafficSelector.builder()
+ .matchEthType(Ethernet.TYPE_IPV4)
+ .matchIPDst(
+ ((IPCriterion) fwd.selector().getCriterion(Criterion.Type.IPV4_DST)).ip())
+ .build();
+
+ TrafficTreatment.Builder tb = processSpecificRoutingTreatment();
+
+ if (fwd.nextId() != null) {
+ NextGroup next = flowObjectiveStore.getNextGroup(fwd.nextId());
+ GroupKey key = appKryo.deserialize(next.data());
+ Group group = groupService.getGroup(deviceId, key);
+ if (group == null) {
+ log.warn("The group left!");
+ fail(fwd, ObjectiveError.GROUPMISSING);
+ return Collections.emptySet();
+ }
+ tb.group(group.id());
+ }
+
+ FlowRule.Builder ruleBuilder = DefaultFlowRule.builder()
+ .fromApp(fwd.appId())
+ .withPriority(fwd.priority())
+ .forDevice(deviceId)
+ .withSelector(filteredSelector)
+ .withTreatment(tb.build());
+
+ ruleBuilder = processSpecificRoutingRule(ruleBuilder);
+
+ if (fwd.permanent()) {
+ ruleBuilder.makePermanent();
+ } else {
+ ruleBuilder.makeTemporary(fwd.timeout());
+ }
+
+ return Collections.singletonList(ruleBuilder.build());
+ }
+
+ /* Hook for modifying Route traffic treatment */
+ protected TrafficTreatment.Builder processSpecificRoutingTreatment() {
+ return DefaultTrafficTreatment.builder();
+ }
+
+ /* Hook for modifying Route flow rule */
+ protected FlowRule.Builder processSpecificRoutingRule(FlowRule.Builder rb) {
+ return rb.forTable(FIB_TABLE);
+ }
+
+ protected Collection<FlowRule> processSpecificSwitch(ForwardingObjective fwd) {
+ /* Not supported by until CorsaPipelineV3 */
+ log.warn("Vlan switching not supported in ovs-corsa driver");
+ fail(fwd, ObjectiveError.UNSUPPORTED);
+ return Collections.emptySet();
+ }
+
+ protected void processFilter(FilteringObjective filt, boolean install,
+ ApplicationId applicationId) {
+ // This driver only processes filtering criteria defined with switch
+ // ports as the key
+ PortCriterion p;
+ if (!filt.key().equals(Criteria.dummy()) &&
+ filt.key().type() == Criterion.Type.IN_PORT) {
+ p = (PortCriterion) filt.key();
+ } else {
+ log.warn("No key defined in filtering objective from app: {}. Not"
+ + "processing filtering objective", applicationId);
+ fail(filt, ObjectiveError.UNKNOWN);
+ return;
+ }
+ // convert filtering conditions for switch-intfs into flowrules
+ FlowRuleOperations.Builder ops = FlowRuleOperations.builder();
+ for (Criterion c : filt.conditions()) {
+ if (c.type() == Criterion.Type.ETH_DST) {
+ EthCriterion e = (EthCriterion) c;
+ log.debug("adding rule for MAC: {}", e.mac());
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
+ selector.matchEthDst(e.mac());
+ treatment.transition(VLAN_MPLS_TABLE);
+ FlowRule rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(CONTROLLER_PRIORITY)
+ .fromApp(applicationId)
+ .makePermanent()
+ .forTable(MAC_TABLE).build();
+ ops = install ? ops.add(rule) : ops.remove(rule);
+ } else if (c.type() == Criterion.Type.VLAN_VID) {
+ VlanIdCriterion v = (VlanIdCriterion) c;
+ log.debug("adding rule for VLAN: {}", v.vlanId());
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
+ selector.matchVlanId(v.vlanId());
+ selector.matchInPort(p.port());
+ treatment.transition(ETHER_TABLE);
+ treatment.deferred().popVlan();
+ FlowRule rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(CONTROLLER_PRIORITY)
+ .fromApp(applicationId)
+ .makePermanent()
+ .forTable(VLAN_TABLE).build();
+ ops = install ? ops.add(rule) : ops.remove(rule);
+ } else if (c.type() == Criterion.Type.IPV4_DST) {
+ IPCriterion ip = (IPCriterion) c;
+ log.debug("adding rule for IP: {}", ip.ip());
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
+ selector.matchEthType(Ethernet.TYPE_IPV4);
+ selector.matchIPDst(ip.ip());
+ treatment.transition(LOCAL_TABLE);
+ FlowRule rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(HIGHEST_PRIORITY)
+ .fromApp(applicationId)
+ .makePermanent()
+ .forTable(FIB_TABLE).build();
+
+ ops = install ? ops.add(rule) : ops.remove(rule);
+ } else {
+ log.warn("Driver does not currently process filtering condition"
+ + " of type: {}", c.type());
+ fail(filt, ObjectiveError.UNSUPPORTED);
+ }
+ }
+ // apply filtering flow rules
+ flowRuleService.apply(ops.build(new FlowRuleOperationsContext() {
+ @Override
+ public void onSuccess(FlowRuleOperations ops) {
+ pass(filt);
+ log.info("Applied filtering rules");
+ }
+
+ @Override
+ public void onError(FlowRuleOperations ops) {
+ fail(filt, ObjectiveError.FLOWINSTALLATIONFAILED);
+ log.info("Failed to apply filtering rules");
+ }
+ }));
+ }
+
+ protected void pass(Objective obj) {
+ if (obj.context().isPresent()) {
+ obj.context().get().onSuccess(obj);
+ }
+ }
+
+ protected void fail(Objective obj, ObjectiveError error) {
+ if (obj.context().isPresent()) {
+ obj.context().get().onError(obj, error);
+ }
+ }
+
+ protected void initializePipeline() {
+ processMacTable(true);
+ processVlanMplsTable(true);
+ processVlanTable(true);
+ processEtherTable(true);
+ processCosTable(true);
+ processFibTable(true);
+ processLocalTable(true);
+ }
+
+ private void processMacTable(boolean install) {
+ TrafficSelector.Builder selector;
+ TrafficTreatment.Builder treatment;
+
+ // Bcast rule
+ selector = DefaultTrafficSelector.builder();
+ treatment = DefaultTrafficTreatment.builder();
+
+ selector.matchEthDst(MacAddress.BROADCAST);
+ treatment.transition(VLAN_MPLS_TABLE);
+
+ FlowRule rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(CONTROLLER_PRIORITY)
+ .fromApp(appId)
+ .makePermanent()
+ .forTable(MAC_TABLE).build();
+
+
+ FlowRuleOperations.Builder ops = FlowRuleOperations.builder();
+
+ ops = install ? ops.add(rule) : ops.remove(rule);
+
+
+ //Drop rule
+ selector = DefaultTrafficSelector.builder();
+ treatment = DefaultTrafficTreatment.builder();
+
+ treatment.drop();
+
+ rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(DROP_PRIORITY)
+ .fromApp(appId)
+ .makePermanent()
+ .forTable(MAC_TABLE).build();
+
+
+ ops = install ? ops.add(rule) : ops.remove(rule);
+
+ flowRuleService.apply(ops.build(new FlowRuleOperationsContext() {
+ @Override
+ public void onSuccess(FlowRuleOperations ops) {
+ log.info("Provisioned mac table");
+ }
+
+ @Override
+ public void onError(FlowRuleOperations ops) {
+ log.info("Failed to provision mac table");
+ }
+ }));
+
+ }
+
+ protected void processVlanMplsTable(boolean install) {
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment
+ .builder();
+ FlowRuleOperations.Builder ops = FlowRuleOperations.builder();
+ FlowRule rule;
+
+ selector.matchVlanId(VlanId.ANY);
+ treatment.transition(VLAN_TABLE);
+
+ rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(CONTROLLER_PRIORITY)
+ .fromApp(appId)
+ .makePermanent()
+ .forTable(VLAN_MPLS_TABLE).build();
+
+
+ ops = install ? ops.add(rule) : ops.remove(rule);
+
+ flowRuleService.apply(ops.build(new FlowRuleOperationsContext() {
+ @Override
+ public void onSuccess(FlowRuleOperations ops) {
+ log.info("Provisioned vlan/mpls table");
+ }
+
+ @Override
+ public void onError(FlowRuleOperations ops) {
+ log.info(
+ "Failed to provision vlan/mpls table");
+ }
+ }));
+
+ }
+
+ private void processVlanTable(boolean install) {
+ TrafficSelector.Builder selector;
+ TrafficTreatment.Builder treatment;
+ FlowRuleOperations.Builder ops = FlowRuleOperations.builder();
+ FlowRule rule;
+
+
+ //Drop rule
+ selector = DefaultTrafficSelector.builder();
+ treatment = DefaultTrafficTreatment.builder();
+
+ treatment.drop();
+
+ rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(DROP_PRIORITY)
+ .fromApp(appId)
+ .makePermanent()
+ .forTable(VLAN_TABLE).build();
+
+ ops = install ? ops.add(rule) : ops.remove(rule);
+
+ flowRuleService.apply(ops.build(new FlowRuleOperationsContext() {
+ @Override
+ public void onSuccess(FlowRuleOperations ops) {
+ log.info("Provisioned vlan table");
+ }
+
+ @Override
+ public void onError(FlowRuleOperations ops) {
+ log.info("Failed to provision vlan table");
+ }
+ }));
+ }
+
+ private void processEtherTable(boolean install) {
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment
+ .builder();
+ FlowRuleOperations.Builder ops = FlowRuleOperations.builder();
+ FlowRule rule;
+
+ selector.matchEthType(Ethernet.TYPE_ARP);
+ treatment.punt();
+
+ rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(CONTROLLER_PRIORITY)
+ .fromApp(appId)
+ .makePermanent()
+ .forTable(ETHER_TABLE).build();
+
+ ops = install ? ops.add(rule) : ops.remove(rule);
+
+ selector = DefaultTrafficSelector.builder();
+ treatment = DefaultTrafficTreatment.builder();
+
+ selector.matchEthType(Ethernet.TYPE_IPV4);
+ treatment.transition(COS_MAP_TABLE);
+
+ rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withPriority(CONTROLLER_PRIORITY)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .fromApp(appId)
+ .makePermanent()
+ .forTable(ETHER_TABLE).build();
+
+ ops = install ? ops.add(rule) : ops.remove(rule);
+
+ //Drop rule
+ selector = DefaultTrafficSelector.builder();
+ treatment = DefaultTrafficTreatment.builder();
+
+ treatment.drop();
+
+ rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(DROP_PRIORITY)
+ .fromApp(appId)
+ .makePermanent()
+ .forTable(ETHER_TABLE).build();
+
+
+ ops = install ? ops.add(rule) : ops.remove(rule);
+
+ flowRuleService.apply(ops.build(new FlowRuleOperationsContext() {
+ @Override
+ public void onSuccess(FlowRuleOperations ops) {
+ log.info("Provisioned ether table");
+ }
+
+ @Override
+ public void onError(FlowRuleOperations ops) {
+ log.info("Failed to provision ether table");
+ }
+ }));
+
+ }
+
+ private void processCosTable(boolean install) {
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment
+ .builder();
+ FlowRuleOperations.Builder ops = FlowRuleOperations.builder();
+ FlowRule rule;
+
+ treatment.transition(FIB_TABLE);
+
+ rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(DROP_PRIORITY)
+ .fromApp(appId)
+ .makePermanent()
+ .forTable(COS_MAP_TABLE).build();
+
+ ops = install ? ops.add(rule) : ops.remove(rule);
+
+ flowRuleService.apply(ops.build(new FlowRuleOperationsContext() {
+ @Override
+ public void onSuccess(FlowRuleOperations ops) {
+ log.info("Provisioned cos table");
+ }
+
+ @Override
+ public void onError(FlowRuleOperations ops) {
+ log.info("Failed to provision cos table");
+ }
+ }));
+
+ }
+
+ private void processFibTable(boolean install) {
+ TrafficSelector.Builder selector;
+ TrafficTreatment.Builder treatment;
+ FlowRuleOperations.Builder ops = FlowRuleOperations.builder();
+ FlowRule rule;
+
+ //Drop rule
+ selector = DefaultTrafficSelector.builder();
+ treatment = DefaultTrafficTreatment.builder();
+
+ treatment.drop();
+
+ rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(DROP_PRIORITY)
+ .fromApp(appId)
+ .makePermanent()
+ .forTable(FIB_TABLE).build();
+
+ ops = install ? ops.add(rule) : ops.remove(rule);
+
+ flowRuleService.apply(ops.build(new FlowRuleOperationsContext() {
+ @Override
+ public void onSuccess(FlowRuleOperations ops) {
+ log.info("Provisioned FIB table");
+ }
+
+ @Override
+ public void onError(FlowRuleOperations ops) {
+ log.info("Failed to provision FIB table");
+ }
+ }));
+ }
+
+ private void processLocalTable(boolean install) {
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment
+ .builder();
+ FlowRuleOperations.Builder ops = FlowRuleOperations.builder();
+ FlowRule rule;
+
+ treatment.punt();
+
+ rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(CONTROLLER_PRIORITY)
+ .fromApp(appId)
+ .makePermanent()
+ .forTable(LOCAL_TABLE).build();
+
+ ops = install ? ops.add(rule) : ops.remove(rule);
+
+ flowRuleService.apply(ops.build(new FlowRuleOperationsContext() {
+ @Override
+ public void onSuccess(FlowRuleOperations ops) {
+ log.info("Provisioned Local table");
+ }
+
+ @Override
+ public void onError(FlowRuleOperations ops) {
+ log.info("Failed to provision Local table");
+ }
+ }));
+ }
+
+ private class InnerGroupListener implements GroupListener {
+ @Override
+ public void event(GroupEvent event) {
+ if (event.type() == GroupEvent.Type.GROUP_ADDED) {
+ GroupKey key = event.subject().appCookie();
+
+ NextObjective obj = pendingGroups.getIfPresent(key);
+ if (obj != null) {
+ flowObjectiveStore.putNextGroup(obj.id(), new CorsaGroup(key));
+ pass(obj);
+ pendingGroups.invalidate(key);
+ }
+ }
+ }
+ }
+
+
+ private class GroupChecker implements Runnable {
+
+ @Override
+ public void run() {
+ Set<GroupKey> keys = pendingGroups.asMap().keySet().stream()
+ .filter(key -> groupService.getGroup(deviceId, key) != null)
+ .collect(Collectors.toSet());
+
+ keys.stream().forEach(key -> {
+ NextObjective obj = pendingGroups.getIfPresent(key);
+ if (obj == null) {
+ return;
+ }
+ pass(obj);
+ pendingGroups.invalidate(key);
+ log.info("Heard back from group service for group {}. "
+ + "Applying pending forwarding objectives", obj.id());
+ flowObjectiveStore.putNextGroup(obj.id(), new CorsaGroup(key));
+ });
+ }
+ }
+
+ private class CorsaGroup implements NextGroup {
+
+ private final GroupKey key;
+
+ public CorsaGroup(GroupKey key) {
+ this.key = key;
+ }
+
+ @SuppressWarnings("unused")
+ public GroupKey key() {
+ return key;
+ }
+
+ @Override
+ public byte[] data() {
+ return appKryo.serialize(key);
+ }
+
+ }
+}
diff --git a/drivers/default/src/main/java/org/onosproject/driver/pipeline/OltPipeline.java b/drivers/default/src/main/java/org/onosproject/driver/pipeline/OltPipeline.java
new file mode 100644
index 0000000..8980733
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/pipeline/OltPipeline.java
@@ -0,0 +1,546 @@
+/*
+ * 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 com.google.common.collect.Lists;
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.apache.commons.lang3.tuple.Pair;
+import org.onlab.osgi.ServiceDirectory;
+import org.onlab.packet.EthType;
+import org.onlab.packet.IPv4;
+import org.onlab.packet.VlanId;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreService;
+import org.onosproject.net.DefaultAnnotations;
+import org.onosproject.net.Device;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.MastershipRole;
+import org.onosproject.net.PortNumber;
+import org.onosproject.net.behaviour.Pipeliner;
+import org.onosproject.net.behaviour.PipelinerContext;
+import org.onosproject.net.device.DefaultDeviceDescription;
+import org.onosproject.net.device.DeviceDescription;
+import org.onosproject.net.device.DeviceProvider;
+import org.onosproject.net.device.DeviceProviderRegistry;
+import org.onosproject.net.device.DeviceService;
+import org.onosproject.net.driver.AbstractHandlerBehaviour;
+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 org.onosproject.net.flow.FlowRuleOperations;
+import org.onosproject.net.flow.FlowRuleOperationsContext;
+import org.onosproject.net.flow.FlowRuleService;
+import org.onosproject.net.flow.TrafficSelector;
+import org.onosproject.net.flow.TrafficTreatment;
+import org.onosproject.net.flow.criteria.Criteria;
+import org.onosproject.net.flow.criteria.Criterion;
+import org.onosproject.net.flow.criteria.EthTypeCriterion;
+import org.onosproject.net.flow.criteria.IPProtocolCriterion;
+import org.onosproject.net.flow.criteria.PortCriterion;
+import org.onosproject.net.flow.criteria.VlanIdCriterion;
+import org.onosproject.net.flow.instructions.Instruction;
+import org.onosproject.net.flow.instructions.Instructions;
+import org.onosproject.net.flow.instructions.L2ModificationInstruction;
+import org.onosproject.net.flowobjective.FilteringObjective;
+import org.onosproject.net.flowobjective.ForwardingObjective;
+import org.onosproject.net.flowobjective.NextObjective;
+import org.onosproject.net.flowobjective.Objective;
+import org.onosproject.net.flowobjective.ObjectiveError;
+import org.onosproject.net.provider.AbstractProvider;
+import org.onosproject.net.provider.ProviderId;
+import org.slf4j.Logger;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Optional;
+import java.util.stream.Collectors;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * Pipeliner for OLT device.
+ */
+
+public class OltPipeline extends AbstractHandlerBehaviour implements Pipeliner {
+
+ private static final Integer QQ_TABLE = 1;
+ private final Logger log = getLogger(getClass());
+
+ static final ProviderId PID = new ProviderId("olt", "org.onosproject.olt", true);
+
+ static final String DEVICE = "isAccess";
+ static final String OLT = "true";
+
+ private ServiceDirectory serviceDirectory;
+ private FlowRuleService flowRuleService;
+ private DeviceId deviceId;
+ private CoreService coreService;
+
+ private ApplicationId appId;
+
+ private DeviceProvider provider = new AnnotationProvider();
+
+ @Override
+ public void init(DeviceId deviceId, PipelinerContext context) {
+ log.debug("Initiate OLT pipeline");
+ this.serviceDirectory = context.directory();
+ this.deviceId = deviceId;
+ DeviceProviderRegistry registry =
+ serviceDirectory.get(DeviceProviderRegistry.class);
+ flowRuleService = serviceDirectory.get(FlowRuleService.class);
+ coreService = serviceDirectory.get(CoreService.class);
+
+ appId = coreService.registerApplication(
+ "org.onosproject.driver.OLTPipeline");
+
+ }
+
+ @Override
+ public void filter(FilteringObjective filter) {
+ Instructions.OutputInstruction output;
+
+ if (filter.meta() != null && !filter.meta().immediate().isEmpty()) {
+ output = (Instructions.OutputInstruction) filter.meta().immediate().stream()
+ .filter(t -> t.type().equals(Instruction.Type.OUTPUT))
+ .limit(1)
+ .findFirst().get();
+
+ if (output == null || !output.port().equals(PortNumber.CONTROLLER)) {
+ log.error("OLT can only filter packet to controller");
+ fail(filter, ObjectiveError.UNSUPPORTED);
+ return;
+ }
+ } else {
+ fail(filter, ObjectiveError.BADPARAMS);
+ return;
+ }
+
+ if (filter.key().type() != Criterion.Type.IN_PORT) {
+ fail(filter, ObjectiveError.BADPARAMS);
+ return;
+ }
+
+ EthTypeCriterion ethType = (EthTypeCriterion)
+ filterForCriterion(filter.conditions(), Criterion.Type.ETH_TYPE);
+
+ if (ethType == null) {
+ fail(filter, ObjectiveError.BADPARAMS);
+ return;
+ }
+
+ if (ethType.ethType().equals(EthType.EtherType.EAPOL.ethType())) {
+ provisionEapol(filter, ethType, output);
+ } else if (ethType.ethType().equals(EthType.EtherType.IPV4.ethType())) {
+ IPProtocolCriterion ipProto = (IPProtocolCriterion)
+ filterForCriterion(filter.conditions(), Criterion.Type.IP_PROTO);
+ if (ipProto.protocol() == IPv4.PROTOCOL_IGMP) {
+ provisionIGMP(filter, ethType, ipProto, output);
+ } else {
+ log.error("OLT can only filter igmp");
+ fail(filter, ObjectiveError.UNSUPPORTED);
+ }
+ } else {
+ log.error("OLT can only filter eapol and igmp");
+ fail(filter, ObjectiveError.UNSUPPORTED);
+ }
+
+ }
+
+
+ @Override
+ public void forward(ForwardingObjective fwd) {
+ TrafficTreatment treatment = fwd.treatment();
+
+ List<Instruction> instructions = treatment.allInstructions();
+
+ Optional<Instruction> vlanIntruction = instructions.stream()
+ .filter(i -> i.type() == Instruction.Type.L2MODIFICATION)
+ .filter(i -> ((L2ModificationInstruction) i).subtype() ==
+ L2ModificationInstruction.L2SubType.VLAN_PUSH ||
+ ((L2ModificationInstruction) i).subtype() ==
+ L2ModificationInstruction.L2SubType.VLAN_POP)
+ .findAny();
+
+ if (!vlanIntruction.isPresent()) {
+ fail(fwd, ObjectiveError.BADPARAMS);
+ return;
+ }
+
+ L2ModificationInstruction vlanIns =
+ (L2ModificationInstruction) vlanIntruction.get();
+
+ if (vlanIns.subtype() == L2ModificationInstruction.L2SubType.VLAN_PUSH) {
+ installUpstreamRules(fwd);
+ } else if (vlanIns.subtype() == L2ModificationInstruction.L2SubType.VLAN_POP) {
+ installDownstreamRules(fwd);
+ } else {
+ log.error("Unknown OLT operation: {}", fwd);
+ fail(fwd, ObjectiveError.UNSUPPORTED);
+ return;
+ }
+
+ pass(fwd);
+
+ }
+
+ @Override
+ public void next(NextObjective nextObjective) {
+ throw new UnsupportedOperationException("OLT does not next hop.");
+ }
+
+ private void installDownstreamRules(ForwardingObjective fwd) {
+ List<Pair<Instruction, Instruction>> vlanOps =
+ vlanOps(fwd,
+ L2ModificationInstruction.L2SubType.VLAN_POP);
+
+ if (vlanOps == null) {
+ return;
+ }
+
+ Instruction output = fetchOutput(fwd, "downstream");
+
+ if (output == null) {
+ return;
+ }
+
+ Pair<Instruction, Instruction> popAndRewrite = vlanOps.remove(0);
+
+ TrafficSelector selector = fwd.selector();
+
+ Criterion outerVlan = selector.getCriterion(Criterion.Type.VLAN_VID);
+ Criterion innerVlan = selector.getCriterion(Criterion.Type.INNER_VLAN_VID);
+ Criterion inport = selector.getCriterion(Criterion.Type.IN_PORT);
+
+ if (outerVlan == null || innerVlan == null || inport == null) {
+ log.error("Forwarding objective is underspecified: {}", fwd);
+ fail(fwd, ObjectiveError.BADPARAMS);
+ return;
+ }
+
+ Criterion innerVid = Criteria.matchVlanId(((VlanIdCriterion) innerVlan).vlanId());
+
+ FlowRule.Builder outer = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .fromApp(appId)
+ .makePermanent()
+ .withPriority(fwd.priority())
+ .withSelector(buildSelector(inport, outerVlan))
+ .withTreatment(buildTreatment(popAndRewrite.getLeft(),
+ Instructions.transition(QQ_TABLE)));
+
+ FlowRule.Builder inner = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .fromApp(appId)
+ .forTable(QQ_TABLE)
+ .makePermanent()
+ .withPriority(fwd.priority())
+ .withSelector(buildSelector(inport, innerVid))
+ .withTreatment(buildTreatment(popAndRewrite.getRight(),
+ output));
+
+ applyRules(fwd, inner, outer);
+
+ }
+
+ private void installUpstreamRules(ForwardingObjective fwd) {
+ List<Pair<Instruction, Instruction>> vlanOps =
+ vlanOps(fwd,
+ L2ModificationInstruction.L2SubType.VLAN_PUSH);
+
+ if (vlanOps == null) {
+ return;
+ }
+
+ Instruction output = fetchOutput(fwd, "upstream");
+
+ if (output == null) {
+ return;
+ }
+
+ Pair<Instruction, Instruction> innerPair = vlanOps.remove(0);
+
+ Pair<Instruction, Instruction> outerPair = vlanOps.remove(0);
+
+ FlowRule.Builder inner = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .fromApp(appId)
+ .makePermanent()
+ .withPriority(fwd.priority())
+ .withSelector(fwd.selector())
+ .withTreatment(buildTreatment(innerPair.getRight(),
+ Instructions.transition(QQ_TABLE)));
+
+ PortCriterion inPort = (PortCriterion)
+ fwd.selector().getCriterion(Criterion.Type.IN_PORT);
+
+ VlanId cVlanId = ((L2ModificationInstruction.ModVlanIdInstruction)
+ innerPair.getRight()).vlanId();
+
+ FlowRule.Builder outer = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .fromApp(appId)
+ .forTable(QQ_TABLE)
+ .makePermanent()
+ .withPriority(fwd.priority())
+ .withSelector(buildSelector(inPort,
+ Criteria.matchVlanId(cVlanId)))
+ .withTreatment(buildTreatment(outerPair.getLeft(),
+ outerPair.getRight(),
+ output));
+
+ applyRules(fwd, inner, outer);
+
+ }
+
+ private Instruction fetchOutput(ForwardingObjective fwd, String direction) {
+ Instruction output = fwd.treatment().allInstructions().stream()
+ .filter(i -> i.type() == Instruction.Type.OUTPUT)
+ .findFirst().orElse(null);
+
+ if (output == null) {
+ log.error("OLT {} rule has no output", direction);
+ fail(fwd, ObjectiveError.BADPARAMS);
+ return null;
+ }
+ return output;
+ }
+
+ private List<Pair<Instruction, Instruction>> vlanOps(ForwardingObjective fwd,
+ L2ModificationInstruction.L2SubType type) {
+
+ List<Pair<Instruction, Instruction>> vlanOps = findVlanOps(
+ fwd.treatment().allInstructions(), type);
+
+ if (vlanOps == null) {
+ String direction = type == L2ModificationInstruction.L2SubType.VLAN_POP
+ ? "downstream" : "upstream";
+ log.error("Missing vlan operations in {} forwarding: {}", direction, fwd);
+ fail(fwd, ObjectiveError.BADPARAMS);
+ return null;
+ }
+ return vlanOps;
+ }
+
+
+ private List<Pair<Instruction, Instruction>> findVlanOps(List<Instruction> instructions,
+ L2ModificationInstruction.L2SubType type) {
+
+ List<Instruction> vlanPushs = findL2Instructions(
+ type,
+ instructions);
+ List<Instruction> vlanSets = findL2Instructions(
+ L2ModificationInstruction.L2SubType.VLAN_ID,
+ instructions);
+
+ if (vlanPushs.size() != vlanSets.size()) {
+ return null;
+ }
+
+ List<Pair<Instruction, Instruction>> pairs = Lists.newArrayList();
+
+ for (int i = 0; i < vlanPushs.size(); i++) {
+ pairs.add(new ImmutablePair<>(vlanPushs.get(i), vlanSets.get(i)));
+ }
+ return pairs;
+ }
+
+ private List<Instruction> findL2Instructions(L2ModificationInstruction.L2SubType subType,
+ List<Instruction> actions) {
+ return actions.stream()
+ .filter(i -> i.type() == Instruction.Type.L2MODIFICATION)
+ .filter(i -> ((L2ModificationInstruction) i).subtype() == subType)
+ .collect(Collectors.toList());
+ }
+
+ private void provisionEapol(FilteringObjective filter,
+ EthTypeCriterion ethType,
+ Instructions.OutputInstruction output) {
+
+ TrafficSelector selector = buildSelector(filter.key(), ethType);
+ TrafficTreatment treatment = buildTreatment(output);
+ buildAndApplyRule(filter, selector, treatment);
+
+ }
+
+ private void provisionIGMP(FilteringObjective filter, EthTypeCriterion ethType,
+ IPProtocolCriterion ipProto,
+ Instructions.OutputInstruction output) {
+ TrafficSelector selector = buildSelector(filter.key(), ethType, ipProto);
+ TrafficTreatment treatment = buildTreatment(output);
+ buildAndApplyRule(filter, selector, treatment);
+ }
+
+ private void buildAndApplyRule(FilteringObjective filter, TrafficSelector selector,
+ TrafficTreatment treatment) {
+ FlowRule rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .forTable(0)
+ .fromApp(filter.appId())
+ .makePermanent()
+ .withSelector(selector)
+ .withTreatment(treatment)
+ .withPriority(filter.priority())
+ .build();
+
+ FlowRuleOperations.Builder opsBuilder = FlowRuleOperations.builder();
+
+ switch (filter.type()) {
+ case PERMIT:
+ opsBuilder.add(rule);
+ break;
+ case DENY:
+ opsBuilder.remove(rule);
+ break;
+ default:
+ log.warn("Unknown filter type : {}", filter.type());
+ fail(filter, ObjectiveError.UNSUPPORTED);
+ }
+
+ applyFlowRules(opsBuilder, filter);
+ }
+
+ private void applyRules(ForwardingObjective fwd,
+ FlowRule.Builder inner, FlowRule.Builder outer) {
+ FlowRuleOperations.Builder builder = FlowRuleOperations.builder();
+ switch (fwd.op()) {
+ case ADD:
+ builder.add(inner.build()).add(outer.build());
+ break;
+ case REMOVE:
+ builder.remove(inner.build()).remove(outer.build());
+ break;
+ case ADD_TO_EXISTING:
+ break;
+ case REMOVE_FROM_EXISTING:
+ break;
+ default:
+ log.warn("Unknown forwarding operation: {}", fwd.op());
+ }
+
+ applyFlowRules(builder, fwd);
+ }
+
+ private void applyFlowRules(FlowRuleOperations.Builder builder,
+ Objective objective) {
+ flowRuleService.apply(builder.build(new FlowRuleOperationsContext() {
+ @Override
+ public void onSuccess(FlowRuleOperations ops) {
+ pass(objective);
+ }
+
+ @Override
+ public void onError(FlowRuleOperations ops) {
+ fail(objective, ObjectiveError.FLOWINSTALLATIONFAILED);
+ }
+ }));
+ }
+
+ private Criterion filterForCriterion(Collection<Criterion> criteria, Criterion.Type type) {
+ return criteria.stream()
+ .filter(c -> c.type().equals(type))
+ .limit(1)
+ .findFirst().orElse(null);
+ }
+
+ private TrafficSelector buildSelector(Criterion... criteria) {
+
+
+ TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
+
+ for (Criterion c : criteria) {
+ sBuilder.add(c);
+ }
+
+ return sBuilder.build();
+ }
+
+ private TrafficTreatment buildTreatment(Instruction... instructions) {
+
+
+ TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
+
+ for (Instruction i : instructions) {
+ tBuilder.add(i);
+ }
+
+ return tBuilder.build();
+ }
+
+
+ private void fail(Objective obj, ObjectiveError error) {
+ if (obj.context().isPresent()) {
+ obj.context().get().onError(obj, error);
+ }
+ }
+
+ private void pass(Objective obj) {
+ if (obj.context().isPresent()) {
+ obj.context().get().onSuccess(obj);
+ }
+ }
+
+ /**
+ * Build a device description.
+ *
+ * @param deviceId a deviceId
+ * @param key the key of the annotation
+ * @param value the value for the annotation
+ * @return a device description
+ */
+ private DeviceDescription description(DeviceId deviceId, String key, String value) {
+ DeviceService deviceService = serviceDirectory.get(DeviceService.class);
+ Device device = deviceService.getDevice(deviceId);
+
+ checkNotNull(device, "Device not found in device service.");
+
+ DefaultAnnotations.Builder builder = DefaultAnnotations.builder();
+ if (value != null) {
+ builder.set(key, value);
+ } else {
+ builder.remove(key);
+ }
+ return new DefaultDeviceDescription(device.id().uri(), device.type(),
+ device.manufacturer(), device.hwVersion(),
+ device.swVersion(), device.serialNumber(),
+ device.chassisId(), builder.build());
+ }
+
+ /**
+ * Simple ancillary provider used to annotate device.
+ */
+ private static final class AnnotationProvider
+ extends AbstractProvider implements DeviceProvider {
+ private AnnotationProvider() {
+ super(PID);
+ }
+
+ @Override
+ public void triggerProbe(DeviceId deviceId) {
+ }
+
+ @Override
+ public void roleChanged(DeviceId deviceId, MastershipRole newRole) {
+ }
+
+ @Override
+ public boolean isReachable(DeviceId deviceId) {
+ return false;
+ }
+ }
+
+}
diff --git a/drivers/default/src/main/java/org/onosproject/driver/pipeline/OpenVSwitchPipeline.java b/drivers/default/src/main/java/org/onosproject/driver/pipeline/OpenVSwitchPipeline.java
new file mode 100644
index 0000000..9e24a17
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/pipeline/OpenVSwitchPipeline.java
@@ -0,0 +1,380 @@
+/*
+ * 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 static org.slf4j.LoggerFactory.getLogger;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Objects;
+
+import org.onlab.osgi.ServiceDirectory;
+import org.onlab.packet.EthType.EtherType;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreService;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.behaviour.Pipeliner;
+import org.onosproject.net.behaviour.PipelinerContext;
+import org.onosproject.net.device.DeviceService;
+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 org.onosproject.net.flow.FlowRuleOperations;
+import org.onosproject.net.flow.FlowRuleOperationsContext;
+import org.onosproject.net.flow.FlowRuleService;
+import org.onosproject.net.flow.TrafficSelector;
+import org.onosproject.net.flow.TrafficTreatment;
+import org.onosproject.net.flow.criteria.Criteria;
+import org.onosproject.net.flow.criteria.Criterion.Type;
+import org.onosproject.net.flow.instructions.Instructions;
+import org.onosproject.net.flowobjective.FilteringObjective;
+import org.onosproject.net.flowobjective.FlowObjectiveStore;
+import org.onosproject.net.flowobjective.ForwardingObjective;
+import org.onosproject.net.flowobjective.NextObjective;
+import org.onosproject.net.flowobjective.Objective;
+import org.onosproject.net.flowobjective.ObjectiveError;
+import org.slf4j.Logger;
+
+/**
+ * Driver for standard OpenVSwitch.
+ */
+public class OpenVSwitchPipeline extends DefaultSingleTablePipeline
+ implements Pipeliner {
+
+ private static final String VTN_APP_ID = "org.onosproject.app.vtn";
+ private final Logger log = getLogger(getClass());
+ private CoreService coreService;
+ private ServiceDirectory serviceDirectory;
+ protected FlowObjectiveStore flowObjectiveStore;
+ protected DeviceId deviceId;
+ protected ApplicationId appId;
+ protected FlowRuleService flowRuleService;
+ protected DeviceService deviceService;
+ private static final int TIME_OUT = 0;
+ private static final int CLASSIFIER_TABLE = 0;
+ private static final int ARP_TABLE = 10;
+ private static final int DNAT_TABLE = 20;
+ private static final int L3FWD_TABLE = 30;
+ private static final int SNAT_TABLE = 40;
+ private static final int MAC_TABLE = 50;
+ private static final int TABLE_MISS_PRIORITY = 0;
+
+ @Override
+ public void init(DeviceId deviceId, PipelinerContext context) {
+ super.init(deviceId, context);
+ this.serviceDirectory = context.directory();
+ this.deviceId = deviceId;
+
+ coreService = serviceDirectory.get(CoreService.class);
+ flowRuleService = serviceDirectory.get(FlowRuleService.class);
+ flowObjectiveStore = context.store();
+ appId = coreService
+ .registerApplication("org.onosproject.driver.OpenVSwitchPipeline");
+ initializePipeline();
+ }
+
+ @Override
+ public void filter(FilteringObjective filteringObjective) {
+ super.filter(filteringObjective);
+ }
+
+ @Override
+ public void forward(ForwardingObjective fwd) {
+ if (!VTN_APP_ID.equals(fwd.appId().name())) {
+ super.forward(fwd);
+ return;
+ }
+ Collection<FlowRule> rules;
+ FlowRuleOperations.Builder flowOpsBuilder = FlowRuleOperations
+ .builder();
+
+ rules = processForward(fwd);
+ switch (fwd.op()) {
+ case ADD:
+ rules.stream().filter(Objects::nonNull)
+ .forEach(flowOpsBuilder::add);
+ break;
+ case REMOVE:
+ rules.stream().filter(Objects::nonNull)
+ .forEach(flowOpsBuilder::remove);
+ break;
+ default:
+ fail(fwd, ObjectiveError.UNKNOWN);
+ log.warn("Unknown forwarding type {}", fwd.op());
+ }
+
+ flowRuleService.apply(flowOpsBuilder
+ .build(new FlowRuleOperationsContext() {
+ @Override
+ public void onSuccess(FlowRuleOperations ops) {
+ pass(fwd);
+ }
+
+ @Override
+ public void onError(FlowRuleOperations ops) {
+ fail(fwd, ObjectiveError.FLOWINSTALLATIONFAILED);
+ }
+ }));
+ }
+
+ @Override
+ public void next(NextObjective nextObjective) {
+ super.next(nextObjective);
+ }
+
+ private void initializePipeline() {
+ processClassifierTable(true);
+ processArpTable(true);
+ processDnatTable(true);
+ processL3fwdTable(true);
+ processSnatTable(true);
+ processMacTable(true);
+ }
+
+ private void processClassifierTable(boolean install) {
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
+
+ treatment.transition(MAC_TABLE);
+
+ FlowRule rule;
+ rule = DefaultFlowRule.builder().forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(TABLE_MISS_PRIORITY).fromApp(appId)
+ .makePermanent().forTable(CLASSIFIER_TABLE).build();
+
+ applyRules(install, rule);
+ }
+
+ private void processArpTable(boolean install) {
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
+
+ treatment.transition(MAC_TABLE);
+
+ FlowRule rule;
+ rule = DefaultFlowRule.builder().forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(TABLE_MISS_PRIORITY).fromApp(appId)
+ .makePermanent().forTable(ARP_TABLE).build();
+
+ applyRules(install, rule);
+ }
+
+ private void processDnatTable(boolean install) {
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
+
+ treatment.transition(MAC_TABLE);
+
+ FlowRule rule;
+ rule = DefaultFlowRule.builder().forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(TABLE_MISS_PRIORITY).fromApp(appId)
+ .makePermanent().forTable(DNAT_TABLE).build();
+
+ applyRules(install, rule);
+ }
+
+ private void processL3fwdTable(boolean install) {
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
+
+ treatment.transition(SNAT_TABLE);
+
+ FlowRule rule;
+ rule = DefaultFlowRule.builder().forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(TABLE_MISS_PRIORITY).fromApp(appId)
+ .makePermanent().forTable(L3FWD_TABLE).build();
+
+ applyRules(install, rule);
+ }
+
+ private void processSnatTable(boolean install) {
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
+
+ treatment.transition(MAC_TABLE);
+
+ FlowRule rule;
+ rule = DefaultFlowRule.builder().forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(TABLE_MISS_PRIORITY).fromApp(appId)
+ .makePermanent().forTable(SNAT_TABLE).build();
+
+ applyRules(install, rule);
+ }
+
+ private void processMacTable(boolean install) {
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
+
+ treatment.drop();
+
+ FlowRule rule;
+ rule = DefaultFlowRule.builder().forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(TABLE_MISS_PRIORITY).fromApp(appId)
+ .makePermanent().forTable(MAC_TABLE).build();
+
+ applyRules(install, rule);
+ }
+
+ private void applyRules(boolean install, FlowRule rule) {
+ FlowRuleOperations.Builder ops = FlowRuleOperations.builder();
+
+ ops = install ? ops.add(rule) : ops.remove(rule);
+ flowRuleService.apply(ops.build(new FlowRuleOperationsContext() {
+ @Override
+ public void onSuccess(FlowRuleOperations ops) {
+ log.info("ONOSW provisioned " + rule.tableId() + " table");
+ }
+
+ @Override
+ public void onError(FlowRuleOperations ops) {
+ log.info("ONOSW failed to provision " + rule.tableId() + " table");
+ }
+ }));
+ }
+
+ private Collection<FlowRule> processForward(ForwardingObjective fwd) {
+ switch (fwd.flag()) {
+ case SPECIFIC:
+ return processSpecific(fwd);
+ case VERSATILE:
+ return processVersatile(fwd);
+ default:
+ fail(fwd, ObjectiveError.UNKNOWN);
+ log.warn("Unknown forwarding flag {}", fwd.flag());
+ }
+ return Collections.emptySet();
+ }
+
+ private Collection<FlowRule> processVersatile(ForwardingObjective fwd) {
+ log.debug("Processing versatile forwarding objective");
+ return Collections.emptyList();
+ }
+
+ private Collection<FlowRule> processSpecific(ForwardingObjective fwd) {
+ log.debug("Processing specific forwarding objective");
+ TrafficSelector selector = fwd.selector();
+ TrafficTreatment tb = fwd.treatment();
+ FlowRule.Builder ruleBuilder = DefaultFlowRule.builder()
+ .fromApp(fwd.appId()).withPriority(fwd.priority())
+ .forDevice(deviceId).withSelector(selector)
+ .withTreatment(tb).makeTemporary(TIME_OUT);
+ ruleBuilder.withPriority(fwd.priority());
+ if (fwd.permanent()) {
+ ruleBuilder.makePermanent();
+ }
+ Integer transition = null;
+ Integer forTable = null;
+ // MAC table flow rules
+ if ((selector.getCriterion(Type.TUNNEL_ID) != null && selector
+ .getCriterion(Type.ETH_DST) != null)
+ || tb.allInstructions().contains(Instructions.createDrop())) {
+ forTable = MAC_TABLE;
+ return reassemblyFlowRule(ruleBuilder, tb, transition, forTable);
+ }
+ // CLASSIFIER table flow rules
+ if (selector.getCriterion(Type.IN_PORT) != null) {
+ forTable = CLASSIFIER_TABLE;
+ if (selector.getCriterion(Type.ETH_SRC) != null
+ && selector.getCriterion(Type.ETH_DST) != null) {
+ transition = L3FWD_TABLE;
+ } else if (selector.getCriterion(Type.ETH_SRC) != null
+ || selector.getCriterion(Type.TUNNEL_ID) != null) {
+ transition = MAC_TABLE;
+ } else if (selector.getCriterion(Type.IPV4_DST) != null) {
+ transition = DNAT_TABLE;
+ }
+ return reassemblyFlowRule(ruleBuilder, tb, transition, forTable);
+ }
+ // ARP table flow rules
+ if (selector.getCriterion(Type.ETH_TYPE) != null
+ && selector.getCriterion(Type.ETH_TYPE).equals(Criteria
+ .matchEthType(EtherType.ARP.ethType().toShort()))) {
+ // CLASSIFIER table arp flow rules
+ if (selector.getCriterion(Type.TUNNEL_ID) == null) {
+ transition = ARP_TABLE;
+ forTable = CLASSIFIER_TABLE;
+ return reassemblyFlowRule(ruleBuilder, tb, transition, forTable);
+ }
+ forTable = ARP_TABLE;
+ return reassemblyFlowRule(ruleBuilder, tb, transition, forTable);
+ }
+ // L3FWD table flow rules
+ if (selector.getCriterion(Type.TUNNEL_ID) != null
+ && selector.getCriterion(Type.IPV4_DST) != null) {
+ transition = MAC_TABLE;
+ forTable = L3FWD_TABLE;
+ return reassemblyFlowRule(ruleBuilder, tb, transition, forTable);
+ }
+ // DNAT table flow rules
+ if (selector.getCriterion(Type.IPV4_DST) != null) {
+ transition = L3FWD_TABLE;
+ forTable = DNAT_TABLE;
+ return reassemblyFlowRule(ruleBuilder, tb, transition, forTable);
+ }
+ // SNAT table flow rules
+ if (selector.getCriterion(Type.TUNNEL_ID) != null
+ && selector.getCriterion(Type.IPV4_SRC) != null) {
+ transition = MAC_TABLE;
+ forTable = SNAT_TABLE;
+ return reassemblyFlowRule(ruleBuilder, tb, transition, forTable);
+ }
+ return Collections.singletonList(ruleBuilder.build());
+ }
+
+ private Collection<FlowRule> reassemblyFlowRule(FlowRule.Builder ruleBuilder,
+ TrafficTreatment tb,
+ Integer transition,
+ Integer forTable) {
+ if (transition != null) {
+ TrafficTreatment.Builder newTraffic = DefaultTrafficTreatment
+ .builder();
+ tb.allInstructions().forEach(t -> newTraffic.add(t));
+ newTraffic.transition(transition);
+ ruleBuilder.withTreatment(newTraffic.build());
+ } else {
+ ruleBuilder.withTreatment(tb);
+ }
+ if (forTable != null) {
+ ruleBuilder.forTable(forTable);
+ }
+ return Collections.singletonList(ruleBuilder.build());
+ }
+
+ private void fail(Objective obj, ObjectiveError error) {
+ if (obj.context().isPresent()) {
+ obj.context().get().onError(obj, error);
+ }
+ }
+
+ private void pass(Objective obj) {
+ if (obj.context().isPresent()) {
+ obj.context().get().onSuccess(obj);
+ }
+ }
+}
diff --git a/drivers/default/src/main/java/org/onosproject/driver/pipeline/OpenstackPipeline.java b/drivers/default/src/main/java/org/onosproject/driver/pipeline/OpenstackPipeline.java
new file mode 100644
index 0000000..058283d
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/pipeline/OpenstackPipeline.java
@@ -0,0 +1,287 @@
+/*
+ * 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.onlab.osgi.ServiceDirectory;
+import org.onlab.packet.Ethernet;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreService;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.behaviour.Pipeliner;
+import org.onosproject.net.behaviour.PipelinerContext;
+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 org.onosproject.net.flow.FlowRuleOperations;
+import org.onosproject.net.flow.FlowRuleOperationsContext;
+import org.onosproject.net.flow.FlowRuleService;
+import org.onosproject.net.flow.TrafficSelector;
+import org.onosproject.net.flow.TrafficTreatment;
+import org.onosproject.net.flow.criteria.Criterion;
+import org.onosproject.net.flow.criteria.EthTypeCriterion;
+import org.onosproject.net.flow.criteria.UdpPortCriterion;
+import org.onosproject.net.flowobjective.FilteringObjective;
+import org.onosproject.net.flowobjective.FlowObjectiveStore;
+import org.onosproject.net.flowobjective.ForwardingObjective;
+import org.onosproject.net.flowobjective.NextObjective;
+import org.onosproject.net.flowobjective.Objective;
+import org.onosproject.net.flowobjective.ObjectiveError;
+import org.slf4j.Logger;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Objects;
+
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * Driver for OpenstackSwitching.
+ */
+public class OpenstackPipeline extends DefaultSingleTablePipeline
+ implements Pipeliner {
+
+ private final Logger log = getLogger(getClass());
+ private CoreService coreService;
+ private ServiceDirectory serviceDirectory;
+ protected FlowObjectiveStore flowObjectiveStore;
+ protected DeviceId deviceId;
+ protected ApplicationId appId;
+ protected FlowRuleService flowRuleService;
+
+ protected static final int VNI_TABLE = 0;
+ protected static final int FORWARDING_TABLE = 1;
+
+ private static final int DROP_PRIORITY = 0;
+ private static final int TIME_OUT = 0;
+ private static final int DHCP_SERVER_PORT = 67;
+ private static final int DHCP_CLIENT_PORT = 68;
+
+
+ @Override
+ public void init(DeviceId deviceId, PipelinerContext context) {
+ super.init(deviceId, context);
+ this.serviceDirectory = context.directory();
+ this.deviceId = deviceId;
+
+ coreService = serviceDirectory.get(CoreService.class);
+ flowRuleService = serviceDirectory.get(FlowRuleService.class);
+ flowObjectiveStore = context.store();
+
+ appId = coreService.registerApplication(
+ "org.onosproject.driver.OpenstackPipeline");
+
+ initializePipeline();
+ }
+
+ @Override
+ public void filter(FilteringObjective filteringObjective) {
+ super.filter(filteringObjective);
+ }
+
+ @Override
+ public void next(NextObjective nextObjective) {
+ super.next(nextObjective);
+ }
+
+ @Override
+ public void forward(ForwardingObjective forwardingObjective) {
+ Collection<FlowRule> rules;
+ FlowRuleOperations.Builder flowOpsBuilder = FlowRuleOperations.builder();
+
+ rules = processForward(forwardingObjective);
+
+ switch (forwardingObjective.op()) {
+ case ADD:
+ rules.stream()
+ .filter(Objects::nonNull)
+ .forEach(flowOpsBuilder::add);
+ break;
+ case REMOVE:
+ rules.stream()
+ .filter(Objects::nonNull)
+ .forEach(flowOpsBuilder::remove);
+ break;
+ default:
+ fail(forwardingObjective, ObjectiveError.UNKNOWN);
+ log.warn("Unknown forwarding type {}");
+ }
+
+ flowRuleService.apply(flowOpsBuilder.build(new FlowRuleOperationsContext() {
+ @Override
+ public void onSuccess(FlowRuleOperations ops) {
+ pass(forwardingObjective);
+ }
+
+ @Override
+ public void onError(FlowRuleOperations ops) {
+ fail(forwardingObjective, ObjectiveError.FLOWINSTALLATIONFAILED);
+ }
+ }));
+ }
+
+ private void initializePipeline() {
+ processVNITable(true);
+ processForwardingTable(true);
+ }
+
+ private void processVNITable(boolean install) {
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
+
+ treatment.transition(FORWARDING_TABLE);
+
+ FlowRule flowRule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(DROP_PRIORITY)
+ .fromApp(appId)
+ .makePermanent()
+ .forTable(VNI_TABLE)
+ .build();
+
+ applyRules(install, flowRule);
+ }
+
+ private void processForwardingTable(boolean install) {
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
+
+ treatment.drop();
+
+ FlowRule flowRule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(DROP_PRIORITY)
+ .fromApp(appId)
+ .makePermanent()
+ .forTable(FORWARDING_TABLE)
+ .build();
+
+ applyRules(install, flowRule);
+ }
+
+ private void applyRules(boolean install, FlowRule flowRule) {
+ FlowRuleOperations.Builder flowOpsBuilder = FlowRuleOperations.builder();
+
+ flowOpsBuilder = install ? flowOpsBuilder.add(flowRule) : flowOpsBuilder.remove(flowRule);
+
+ flowRuleService.apply(flowOpsBuilder.build(new FlowRuleOperationsContext() {
+ @Override
+ public void onSuccess(FlowRuleOperations ops) {
+ log.debug("Provisioned vni or forwarding table");
+ }
+
+ @Override
+ public void onError(FlowRuleOperations ops) {
+ log.debug("Failed to privision vni or forwarding table");
+ }
+ }));
+ }
+
+ private Collection<FlowRule> processForward(ForwardingObjective forwardingObjective) {
+ switch (forwardingObjective.flag()) {
+ case SPECIFIC:
+ return processSpecific(forwardingObjective);
+ case VERSATILE:
+ return processVersatile(forwardingObjective);
+ default:
+ fail(forwardingObjective, ObjectiveError.UNKNOWN);
+ log.warn("Unknown forwarding flag {}", forwardingObjective.flag());
+ }
+ return Collections.emptySet();
+ }
+
+ private Collection<FlowRule> processVersatile(ForwardingObjective forwardingObjective) {
+ log.debug("Processing versatile forwarding objective");
+
+ FlowRule.Builder ruleBuilder = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(forwardingObjective.selector())
+ .withTreatment(forwardingObjective.treatment())
+ .withPriority(forwardingObjective.priority())
+ .fromApp(forwardingObjective.appId());
+
+ if (forwardingObjective.permanent()) {
+ ruleBuilder.makePermanent();
+ } else {
+ ruleBuilder.makeTemporary(TIME_OUT);
+ }
+
+ //ARP & DHCP Rule
+ EthTypeCriterion ethCriterion =
+ (EthTypeCriterion) forwardingObjective.selector().getCriterion(Criterion.Type.ETH_TYPE);
+ UdpPortCriterion udpPortCriterion = (UdpPortCriterion) forwardingObjective
+ .selector().getCriterion(Criterion.Type.UDP_DST);
+ if (ethCriterion != null) {
+ if (ethCriterion.ethType().toShort() == Ethernet.TYPE_ARP ||
+ ethCriterion.ethType().toShort() == Ethernet.TYPE_LLDP) {
+ ruleBuilder.forTable(VNI_TABLE);
+ return Collections.singletonList(ruleBuilder.build());
+ } else if (udpPortCriterion != null && udpPortCriterion.udpPort().toInt() == DHCP_SERVER_PORT) {
+ ruleBuilder.forTable(VNI_TABLE);
+ return Collections.singletonList(ruleBuilder.build());
+ }
+ }
+ return Collections.emptySet();
+ }
+
+ private Collection<FlowRule> processSpecific(ForwardingObjective forwardingObjective) {
+ log.debug("Processing specific forwarding objective");
+
+ FlowRule.Builder ruleBuilder = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(forwardingObjective.selector())
+ .withTreatment(forwardingObjective.treatment())
+ .withPriority(forwardingObjective.priority())
+ .fromApp(forwardingObjective.appId());
+
+ if (forwardingObjective.permanent()) {
+ ruleBuilder.makePermanent();
+ } else {
+ ruleBuilder.makeTemporary(TIME_OUT);
+ }
+
+ //VNI Table Rule
+ if (forwardingObjective.selector().getCriterion(Criterion.Type.IN_PORT) != null) {
+ TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
+ forwardingObjective.treatment().allInstructions().forEach(tBuilder::add);
+ tBuilder.transition(FORWARDING_TABLE);
+ ruleBuilder.withTreatment(tBuilder.build());
+ ruleBuilder.forTable(VNI_TABLE);
+ } else {
+ ruleBuilder.forTable(FORWARDING_TABLE);
+ }
+
+ return Collections.singletonList(ruleBuilder.build());
+ }
+
+
+ private void pass(Objective obj) {
+ if (obj.context().isPresent()) {
+ obj.context().get().onSuccess(obj);
+ }
+ }
+
+ private void fail(Objective obj, ObjectiveError error) {
+ if (obj.context().isPresent()) {
+ obj.context().get().onError(obj, error);
+ }
+ }
+}
+
diff --git a/drivers/default/src/main/java/org/onosproject/driver/pipeline/PicaPipeline.java b/drivers/default/src/main/java/org/onosproject/driver/pipeline/PicaPipeline.java
new file mode 100644
index 0000000..6cb5b82
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/pipeline/PicaPipeline.java
@@ -0,0 +1,544 @@
+/*
+ * 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.onlab.osgi.ServiceDirectory;
+import org.onlab.packet.Ethernet;
+import org.onlab.packet.MacAddress;
+import org.onlab.packet.VlanId;
+import org.onlab.util.KryoNamespace;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreService;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.PortNumber;
+import org.onosproject.net.behaviour.NextGroup;
+import org.onosproject.net.behaviour.Pipeliner;
+import org.onosproject.net.behaviour.PipelinerContext;
+import org.onosproject.net.driver.AbstractHandlerBehaviour;
+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 org.onosproject.net.flow.FlowRuleOperations;
+import org.onosproject.net.flow.FlowRuleOperationsContext;
+import org.onosproject.net.flow.FlowRuleService;
+import org.onosproject.net.flow.TrafficSelector;
+import org.onosproject.net.flow.TrafficTreatment;
+import org.onosproject.net.flow.criteria.Criteria;
+import org.onosproject.net.flow.criteria.Criterion;
+import org.onosproject.net.flow.criteria.EthCriterion;
+import org.onosproject.net.flow.criteria.EthTypeCriterion;
+import org.onosproject.net.flow.criteria.IPCriterion;
+import org.onosproject.net.flow.criteria.PortCriterion;
+import org.onosproject.net.flow.criteria.VlanIdCriterion;
+import org.onosproject.net.flow.instructions.Instruction;
+import org.onosproject.net.flow.instructions.L2ModificationInstruction;
+import org.onosproject.net.flowobjective.FilteringObjective;
+import org.onosproject.net.flowobjective.FlowObjectiveStore;
+import org.onosproject.net.flowobjective.ForwardingObjective;
+import org.onosproject.net.flowobjective.NextObjective;
+import org.onosproject.net.flowobjective.Objective;
+import org.onosproject.net.flowobjective.ObjectiveError;
+import org.onosproject.store.serializers.KryoNamespaces;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+import java.util.concurrent.ConcurrentHashMap;
+
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * Pica pipeline handler.
+ */
+public class PicaPipeline extends AbstractHandlerBehaviour implements Pipeliner {
+
+ protected static final int IP_UNICAST_TABLE = 252;
+ protected static final int ACL_TABLE = 0;
+
+ //private static final int CONTROLLER_PRIORITY = 255;
+ private static final int DROP_PRIORITY = 0;
+ private static final int HIGHEST_PRIORITY = 0xffff;
+
+ private final Logger log = getLogger(getClass());
+
+ private ServiceDirectory serviceDirectory;
+ private FlowRuleService flowRuleService;
+ private CoreService coreService;
+ private FlowObjectiveStore flowObjectiveStore;
+ private DeviceId deviceId;
+ private ApplicationId appId;
+ private Collection<Filter> filters;
+ private Collection<ForwardingObjective> pendingVersatiles;
+
+ private KryoNamespace appKryo = new KryoNamespace.Builder()
+ .register(KryoNamespaces.API)
+ .register(PicaGroup.class)
+ .register(byte[].class)
+ .build();
+
+ @Override
+ public void init(DeviceId deviceId, PipelinerContext context) {
+ this.serviceDirectory = context.directory();
+ this.deviceId = deviceId;
+
+ coreService = serviceDirectory.get(CoreService.class);
+ flowRuleService = serviceDirectory.get(FlowRuleService.class);
+ flowObjectiveStore = context.store();
+ filters = Collections.newSetFromMap(new ConcurrentHashMap<Filter, Boolean>());
+ pendingVersatiles = Collections.newSetFromMap(
+ new ConcurrentHashMap<ForwardingObjective, Boolean>());
+ appId = coreService.registerApplication(
+ "org.onosproject.driver.OVSPicaPipeline");
+
+ initializePipeline();
+ }
+
+ @Override
+ public void filter(FilteringObjective filteringObjective) {
+ if (filteringObjective.type() == FilteringObjective.Type.PERMIT) {
+ processFilter(filteringObjective,
+ filteringObjective.op() == Objective.Operation.ADD,
+ filteringObjective.appId());
+ } else {
+ fail(filteringObjective, ObjectiveError.UNSUPPORTED);
+ }
+ }
+
+ @Override
+ public void forward(ForwardingObjective fwd) {
+ Collection<FlowRule> rules;
+ FlowRuleOperations.Builder flowBuilder = FlowRuleOperations.builder();
+
+ rules = processForward(fwd);
+ switch (fwd.op()) {
+ case ADD:
+ rules.stream()
+ .filter(Objects::nonNull)
+ .forEach(flowBuilder::add);
+ break;
+ case REMOVE:
+ rules.stream()
+ .filter(Objects::nonNull)
+ .forEach(flowBuilder::remove);
+ break;
+ default:
+ fail(fwd, ObjectiveError.UNKNOWN);
+ log.warn("Unknown forwarding type {}", fwd.op());
+ }
+
+
+ flowRuleService.apply(flowBuilder.build(new FlowRuleOperationsContext() {
+ @Override
+ public void onSuccess(FlowRuleOperations ops) {
+ pass(fwd);
+ }
+
+ @Override
+ public void onError(FlowRuleOperations ops) {
+ fail(fwd, ObjectiveError.FLOWINSTALLATIONFAILED);
+ }
+ }));
+
+ }
+
+ @Override
+ public void next(NextObjective nextObjective) {
+ switch (nextObjective.type()) {
+ case SIMPLE:
+ Collection<TrafficTreatment> treatments = nextObjective.next();
+ if (treatments.size() != 1) {
+ log.error("Next Objectives of type Simple should only have a "
+ + "single Traffic Treatment. Next Objective Id:{}", nextObjective.id());
+ fail(nextObjective, ObjectiveError.BADPARAMS);
+ return;
+ }
+ TrafficTreatment treatment = treatments.iterator().next();
+ TrafficTreatment.Builder filteredTreatment = DefaultTrafficTreatment.builder();
+ VlanId modVlanId;
+ for (Instruction ins : treatment.allInstructions()) {
+ if (ins.type() == Instruction.Type.L2MODIFICATION) {
+ L2ModificationInstruction l2ins = (L2ModificationInstruction) ins;
+ switch (l2ins.subtype()) {
+ case ETH_DST:
+ filteredTreatment.setEthDst(
+ ((L2ModificationInstruction.ModEtherInstruction) l2ins).mac());
+ break;
+ case ETH_SRC:
+ filteredTreatment.setEthSrc(
+ ((L2ModificationInstruction.ModEtherInstruction) l2ins).mac());
+ break;
+ case VLAN_ID:
+ modVlanId = ((L2ModificationInstruction.ModVlanIdInstruction) l2ins).vlanId();
+ filteredTreatment.setVlanId(modVlanId);
+ break;
+ default:
+ break;
+ }
+ } else if (ins.type() == Instruction.Type.OUTPUT) {
+ //long portNum = ((Instructions.OutputInstruction) ins).port().toLong();
+ filteredTreatment.add(ins);
+ } else {
+ // Ignore the vlan_pcp action since it's does matter much.
+ log.warn("Driver does not handle this type of TrafficTreatment"
+ + " instruction in nextObjectives: {}", ins.type());
+ }
+ }
+ // store for future use
+ flowObjectiveStore.putNextGroup(nextObjective.id(),
+ new PicaGroup(filteredTreatment.build()));
+ break;
+ case HASHED:
+ case BROADCAST:
+ case FAILOVER:
+ fail(nextObjective, ObjectiveError.UNSUPPORTED);
+ log.warn("Unsupported next objective type {}", nextObjective.type());
+ break;
+ default:
+ fail(nextObjective, ObjectiveError.UNKNOWN);
+ log.warn("Unknown next objective type {}", nextObjective.type());
+ }
+
+ }
+
+ private Collection<FlowRule> processForward(ForwardingObjective fwd) {
+ switch (fwd.flag()) {
+ case SPECIFIC:
+ return processSpecific(fwd);
+ case VERSATILE:
+ return processVersatile(fwd);
+ default:
+ fail(fwd, ObjectiveError.UNKNOWN);
+ log.warn("Unknown forwarding flag {}", fwd.flag());
+ }
+ return Collections.emptySet();
+ }
+
+ private Collection<FlowRule> processVersatile(ForwardingObjective fwd) {
+ log.debug("Processing versatile forwarding objective");
+ TrafficSelector selector = fwd.selector();
+ TrafficTreatment treatment = fwd.treatment();
+ Collection<FlowRule> flowrules = new ArrayList<FlowRule>();
+
+ // first add this rule for basic single-table operation
+ // or non-ARP related multi-table operation
+ FlowRule rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector)
+ .withTreatment(treatment)
+ .withPriority(fwd.priority())
+ .fromApp(fwd.appId())
+ .makePermanent()
+ .forTable(ACL_TABLE).build();
+ flowrules.add(rule);
+
+ EthTypeCriterion ethType =
+ (EthTypeCriterion) selector.getCriterion(Criterion.Type.ETH_TYPE);
+ if (ethType == null) {
+ log.warn("No ethType in versatile forwarding obj. Not processing further.");
+ return flowrules;
+ }
+
+ // now deal with possible mix of ARP with filtering objectives
+ // in multi-table scenarios
+ if (ethType.ethType().toShort() == Ethernet.TYPE_ARP) {
+ if (filters.isEmpty()) {
+ pendingVersatiles.add(fwd);
+ return flowrules;
+ }
+ for (Filter filter : filters) {
+ flowrules.addAll(processVersatilesWithFilters(filter, fwd));
+ }
+ }
+ return flowrules;
+ }
+
+ private Collection<FlowRule> processVersatilesWithFilters(
+ Filter filt, ForwardingObjective fwd) {
+ Collection<FlowRule> flows = new ArrayList<FlowRule>();
+
+ // rule for ARP replies
+ log.debug("adding ARP rule in ACL table");
+ TrafficSelector.Builder sel = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder treat = DefaultTrafficTreatment.builder();
+ sel.matchInPort(filt.port());
+ sel.matchVlanId(filt.vlanId());
+ sel.matchEthDst(filt.mac());
+ sel.matchEthType(Ethernet.TYPE_ARP);
+ treat.setOutput(PortNumber.CONTROLLER);
+ FlowRule rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(sel.build())
+ .withTreatment(treat.build())
+ .withPriority(HIGHEST_PRIORITY)
+ .fromApp(appId)
+ .makePermanent()
+ .forTable(ACL_TABLE).build();
+ flows.add(rule);
+
+ // rule for ARP Broadcast
+ sel = DefaultTrafficSelector.builder();
+ treat = DefaultTrafficTreatment.builder();
+ sel.matchInPort(filt.port());
+ sel.matchVlanId(filt.vlanId());
+ sel.matchEthDst(MacAddress.BROADCAST);
+ sel.matchEthType(Ethernet.TYPE_ARP);
+ treat.setOutput(PortNumber.CONTROLLER);
+ rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(sel.build())
+ .withTreatment(treat.build())
+ .withPriority(HIGHEST_PRIORITY)
+ .fromApp(appId)
+ .makePermanent()
+ .forTable(ACL_TABLE).build();
+ flows.add(rule);
+
+ return flows;
+ }
+
+
+ private Collection<FlowRule> processSpecific(ForwardingObjective fwd) {
+ log.debug("Processing specific forwarding objective");
+ TrafficSelector selector = fwd.selector();
+ EthTypeCriterion ethType =
+ (EthTypeCriterion) selector.getCriterion(Criterion.Type.ETH_TYPE);
+ if (ethType == null || ethType.ethType().toShort() != Ethernet.TYPE_IPV4) {
+ fail(fwd, ObjectiveError.UNSUPPORTED);
+ return Collections.emptySet();
+ }
+
+ List<FlowRule> ipflows = new ArrayList<FlowRule>();
+ for (Filter f: filters) {
+ TrafficSelector filteredSelector =
+ DefaultTrafficSelector.builder()
+ .matchEthType(Ethernet.TYPE_IPV4)
+ .matchIPDst(
+ ((IPCriterion)
+ selector.getCriterion(Criterion.Type.IPV4_DST)).ip())
+ .matchEthDst(f.mac())
+ .matchVlanId(f.vlanId())
+ .build();
+ TrafficTreatment tt = null;
+ if (fwd.nextId() != null) {
+ NextGroup next = flowObjectiveStore.getNextGroup(fwd.nextId());
+ if (next == null) {
+ log.error("next-id {} does not exist in store", fwd.nextId());
+ return Collections.emptySet();
+ }
+ tt = appKryo.deserialize(next.data());
+ if (tt == null) {
+ log.error("Error in deserializing next-id {}", fwd.nextId());
+ return Collections.emptySet();
+ }
+ }
+
+ FlowRule.Builder ruleBuilder = DefaultFlowRule.builder()
+ .fromApp(fwd.appId())
+ .withPriority(fwd.priority())
+ .forDevice(deviceId)
+ .withSelector(filteredSelector)
+ .withTreatment(tt);
+ if (fwd.permanent()) {
+ ruleBuilder.makePermanent();
+ } else {
+ ruleBuilder.makeTemporary(fwd.timeout());
+ }
+ ruleBuilder.forTable(IP_UNICAST_TABLE);
+ ipflows.add(ruleBuilder.build());
+ }
+
+ return ipflows;
+ }
+
+ private void processFilter(FilteringObjective filt, boolean install,
+ ApplicationId applicationId) {
+ // This driver only processes filtering criteria defined with switch
+ // ports as the key
+ PortCriterion p;
+ if (!filt.key().equals(Criteria.dummy()) &&
+ filt.key().type() == Criterion.Type.IN_PORT) {
+ p = (PortCriterion) filt.key();
+ } else {
+ log.warn("No key defined in filtering objective from app: {}. Not"
+ + "processing filtering objective", applicationId);
+ fail(filt, ObjectiveError.UNKNOWN);
+ return;
+ }
+
+ EthCriterion e = null; VlanIdCriterion v = null;
+ Collection<IPCriterion> ips = new ArrayList<IPCriterion>();
+ // convert filtering conditions for switch-intfs into flowrules
+ FlowRuleOperations.Builder ops = FlowRuleOperations.builder();
+ for (Criterion c : filt.conditions()) {
+ if (c.type() == Criterion.Type.ETH_DST) {
+ e = (EthCriterion) c;
+ } else if (c.type() == Criterion.Type.VLAN_VID) {
+ v = (VlanIdCriterion) c;
+ } else if (c.type() == Criterion.Type.IPV4_DST) {
+ ips.add((IPCriterion) c);
+ } else {
+ log.error("Unsupported filter {}", c);
+ fail(filt, ObjectiveError.UNSUPPORTED);
+ return;
+ }
+ }
+
+ // cache for later use
+ Filter filter = new Filter(p, e, v, ips);
+ filters.add(filter);
+
+ // apply any pending versatile forwarding objectives
+ for (ForwardingObjective fwd : pendingVersatiles) {
+ Collection<FlowRule> ret = processVersatilesWithFilters(filter, fwd);
+ for (FlowRule fr : ret) {
+ ops.add(fr);
+ }
+ }
+
+ for (IPCriterion ipaddr : ips) {
+ log.debug("adding IP filtering rules in ACL table: {}", ipaddr.ip());
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
+ selector.matchInPort(p.port());
+ selector.matchVlanId(v.vlanId());
+ selector.matchEthDst(e.mac());
+ selector.matchEthType(Ethernet.TYPE_IPV4);
+ selector.matchIPDst(ipaddr.ip()); // router IPs to the controller
+ treatment.setOutput(PortNumber.CONTROLLER);
+ FlowRule rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(HIGHEST_PRIORITY)
+ .fromApp(applicationId)
+ .makePermanent()
+ .forTable(ACL_TABLE).build();
+ ops = ops.add(rule);
+ }
+
+ // apply filtering flow rules
+ flowRuleService.apply(ops.build(new FlowRuleOperationsContext() {
+ @Override
+ public void onSuccess(FlowRuleOperations ops) {
+ pass(filt);
+ log.info("Applied filtering rules");
+ }
+
+ @Override
+ public void onError(FlowRuleOperations ops) {
+ fail(filt, ObjectiveError.FLOWINSTALLATIONFAILED);
+ log.info("Failed to apply filtering rules");
+ }
+ }));
+ }
+
+ private void pass(Objective obj) {
+ if (obj.context().isPresent()) {
+ obj.context().get().onSuccess(obj);
+ }
+ }
+
+ private void fail(Objective obj, ObjectiveError error) {
+ if (obj.context().isPresent()) {
+ obj.context().get().onError(obj, error);
+ }
+ }
+
+ private void initializePipeline() {
+ //processIpUnicastTable(true);
+ processAclTable(true);
+ }
+
+ private void processAclTable(boolean install) {
+ TrafficSelector.Builder selector;
+ TrafficTreatment.Builder treatment;
+ FlowRuleOperations.Builder ops = FlowRuleOperations.builder();
+ FlowRule rule;
+
+ //Drop rule
+ selector = DefaultTrafficSelector.builder();
+ treatment = DefaultTrafficTreatment.builder();
+
+ rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(DROP_PRIORITY)
+ .fromApp(appId)
+ .makePermanent()
+ .forTable(ACL_TABLE).build();
+
+ ops = install ? ops.add(rule) : ops.remove(rule);
+
+ flowRuleService.apply(ops.build(new FlowRuleOperationsContext() {
+ @Override
+ public void onSuccess(FlowRuleOperations ops) {
+ log.info("Provisioned ACL table");
+ }
+
+ @Override
+ public void onError(FlowRuleOperations ops) {
+ log.info("Failed to provision ACL table");
+ }
+ }));
+ }
+
+ private class Filter {
+ private PortCriterion port;
+ private VlanIdCriterion vlan;
+ private EthCriterion eth;
+
+ @SuppressWarnings("unused")
+ private Collection<IPCriterion> ips;
+
+ public Filter(PortCriterion p, EthCriterion e, VlanIdCriterion v,
+ Collection<IPCriterion> ips) {
+ this.eth = e;
+ this.port = p;
+ this.vlan = v;
+ this.ips = ips;
+ }
+
+ public PortNumber port() {
+ return port.port();
+ }
+
+ public VlanId vlanId() {
+ return vlan.vlanId();
+ }
+
+ public MacAddress mac() {
+ return eth.mac();
+ }
+ }
+
+ private class PicaGroup implements NextGroup {
+ TrafficTreatment nextActions;
+
+ public PicaGroup(TrafficTreatment next) {
+ this.nextActions = next;
+ }
+
+ @Override
+ public byte[] data() {
+ return appKryo.serialize(nextActions);
+ }
+ }
+}
diff --git a/drivers/default/src/main/java/org/onosproject/driver/pipeline/SoftRouterPipeline.java b/drivers/default/src/main/java/org/onosproject/driver/pipeline/SoftRouterPipeline.java
new file mode 100644
index 0000000..8e5ce91
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/pipeline/SoftRouterPipeline.java
@@ -0,0 +1,433 @@
+/*
+ * 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.onlab.osgi.ServiceDirectory;
+import org.onlab.packet.Ethernet;
+import org.onlab.packet.VlanId;
+import org.onlab.util.KryoNamespace;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreService;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.behaviour.NextGroup;
+import org.onosproject.net.behaviour.Pipeliner;
+import org.onosproject.net.behaviour.PipelinerContext;
+import org.onosproject.net.driver.AbstractHandlerBehaviour;
+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 org.onosproject.net.flow.FlowRuleOperations;
+import org.onosproject.net.flow.FlowRuleOperationsContext;
+import org.onosproject.net.flow.FlowRuleService;
+import org.onosproject.net.flow.TrafficSelector;
+import org.onosproject.net.flow.TrafficTreatment;
+import org.onosproject.net.flow.criteria.Criteria;
+import org.onosproject.net.flow.criteria.Criterion;
+import org.onosproject.net.flow.criteria.EthCriterion;
+import org.onosproject.net.flow.criteria.EthTypeCriterion;
+import org.onosproject.net.flow.criteria.IPCriterion;
+import org.onosproject.net.flow.criteria.PortCriterion;
+import org.onosproject.net.flow.criteria.VlanIdCriterion;
+import org.onosproject.net.flowobjective.FilteringObjective;
+import org.onosproject.net.flowobjective.FlowObjectiveStore;
+import org.onosproject.net.flowobjective.ForwardingObjective;
+import org.onosproject.net.flowobjective.NextObjective;
+import org.onosproject.net.flowobjective.Objective;
+import org.onosproject.net.flowobjective.ObjectiveError;
+import org.onosproject.store.serializers.KryoNamespaces;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Objects;
+
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * Simple 2-Table Pipeline for Software/NPU based routers. This pipeline
+ * does not forward IP traffic to next-hop groups. Instead it forwards traffic
+ * using OF FlowMod actions.
+ */
+public class SoftRouterPipeline extends AbstractHandlerBehaviour implements Pipeliner {
+
+ protected static final int FILTER_TABLE = 0;
+ protected static final int FIB_TABLE = 1;
+
+ private static final int DROP_PRIORITY = 0;
+ private static final int DEFAULT_PRIORITY = 0x8000;
+ private static final int HIGHEST_PRIORITY = 0xffff;
+
+ private ServiceDirectory serviceDirectory;
+ protected FlowRuleService flowRuleService;
+ private CoreService coreService;
+ private FlowObjectiveStore flowObjectiveStore;
+ protected DeviceId deviceId;
+ protected ApplicationId appId;
+ private ApplicationId driverId;
+
+ private KryoNamespace appKryo = new KryoNamespace.Builder()
+ .register(DummyGroup.class)
+ .register(KryoNamespaces.API)
+ .register(byte[].class)
+ .build();
+
+ private final Logger log = getLogger(getClass());
+
+ @Override
+ public void init(DeviceId deviceId, PipelinerContext context) {
+ this.serviceDirectory = context.directory();
+ this.deviceId = deviceId;
+ coreService = serviceDirectory.get(CoreService.class);
+ flowRuleService = serviceDirectory.get(FlowRuleService.class);
+ flowObjectiveStore = context.store();
+ driverId = coreService.registerApplication(
+ "org.onosproject.driver.SoftRouterPipeline");
+
+ initializePipeline();
+ }
+
+ @Override
+ public void filter(FilteringObjective filteringObjective) {
+ if (filteringObjective.type() == FilteringObjective.Type.PERMIT) {
+ processFilter(filteringObjective,
+ filteringObjective.op() == Objective.Operation.ADD,
+ filteringObjective.appId());
+ } else {
+ fail(filteringObjective, ObjectiveError.UNSUPPORTED);
+ }
+ }
+
+ @Override
+ public void forward(ForwardingObjective fwd) {
+ Collection<FlowRule> rules;
+ FlowRuleOperations.Builder flowOpsBuilder = FlowRuleOperations.builder();
+
+ rules = processForward(fwd);
+ switch (fwd.op()) {
+ case ADD:
+ rules.stream()
+ .filter(Objects::nonNull)
+ .forEach(flowOpsBuilder::add);
+ break;
+ case REMOVE:
+ rules.stream()
+ .filter(Objects::nonNull)
+ .forEach(flowOpsBuilder::remove);
+ break;
+ default:
+ fail(fwd, ObjectiveError.UNKNOWN);
+ log.warn("Unknown forwarding type {}", fwd.op());
+ }
+
+
+ flowRuleService.apply(flowOpsBuilder.build(new FlowRuleOperationsContext() {
+ @Override
+ public void onSuccess(FlowRuleOperations ops) {
+ pass(fwd);
+ }
+
+ @Override
+ public void onError(FlowRuleOperations ops) {
+ fail(fwd, ObjectiveError.FLOWINSTALLATIONFAILED);
+ }
+ }));
+
+ }
+
+ @Override
+ public void next(NextObjective nextObjective) {
+ switch (nextObjective.type()) {
+ case SIMPLE:
+ Collection<TrafficTreatment> treatments = nextObjective.next();
+ if (treatments.size() != 1) {
+ log.error("Next Objectives of type Simple should only have a "
+ + "single Traffic Treatment. Next Objective Id:{}", nextObjective.id());
+ fail(nextObjective, ObjectiveError.BADPARAMS);
+ return;
+ }
+ processSimpleNextObjective(nextObjective);
+ break;
+ case HASHED:
+ case BROADCAST:
+ case FAILOVER:
+ fail(nextObjective, ObjectiveError.UNSUPPORTED);
+ log.warn("Unsupported next objective type {}", nextObjective.type());
+ break;
+ default:
+ fail(nextObjective, ObjectiveError.UNKNOWN);
+ log.warn("Unknown next objective type {}", nextObjective.type());
+ }
+ }
+
+ private void pass(Objective obj) {
+ if (obj.context().isPresent()) {
+ obj.context().get().onSuccess(obj);
+ }
+ }
+
+ private void fail(Objective obj, ObjectiveError error) {
+ if (obj.context().isPresent()) {
+ obj.context().get().onError(obj, error);
+ }
+ }
+
+ private void initializePipeline() {
+ //Drop rules for both tables
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
+ FlowRuleOperations.Builder ops = FlowRuleOperations.builder();
+
+ treatment.drop();
+
+ FlowRule rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(DROP_PRIORITY)
+ .fromApp(driverId)
+ .makePermanent()
+ .forTable(FILTER_TABLE)
+ .build();
+ ops = ops.add(rule);
+
+ rule = DefaultFlowRule.builder().forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(DROP_PRIORITY)
+ .fromApp(driverId)
+ .makePermanent()
+ .forTable(FIB_TABLE)
+ .build();
+ ops = ops.add(rule);
+
+ flowRuleService.apply(ops.build(new FlowRuleOperationsContext() {
+ @Override
+ public void onSuccess(FlowRuleOperations ops) {
+ log.info("Provisioned drop rules in both tables");
+ }
+
+ @Override
+ public void onError(FlowRuleOperations ops) {
+ log.info("Failed to provision drop rules");
+ }
+ }));
+ }
+
+ private void processFilter(FilteringObjective filt, boolean install,
+ ApplicationId applicationId) {
+ // This driver only processes filtering criteria defined with switch
+ // ports as the key
+ PortCriterion p;
+ EthCriterion e = null;
+ VlanIdCriterion v = null;
+
+ if (!filt.key().equals(Criteria.dummy()) &&
+ filt.key().type() == Criterion.Type.IN_PORT) {
+ p = (PortCriterion) filt.key();
+ } else {
+ log.warn("No key defined in filtering objective from app: {}. Not"
+ + "processing filtering objective", applicationId);
+ fail(filt, ObjectiveError.UNKNOWN);
+ return;
+ }
+
+ // convert filtering conditions for switch-intfs into flowrules
+ FlowRuleOperations.Builder ops = FlowRuleOperations.builder();
+ for (Criterion c : filt.conditions()) {
+ if (c.type() == Criterion.Type.ETH_DST) {
+ e = (EthCriterion) c;
+ } else if (c.type() == Criterion.Type.VLAN_VID) {
+ v = (VlanIdCriterion) c;
+ } else {
+ log.error("Unsupported filter {}", c);
+ fail(filt, ObjectiveError.UNSUPPORTED);
+ return;
+ }
+ }
+
+ log.debug("adding Port/VLAN/MAC filtering rules in filter table: {}/{}/{}",
+ p.port(), v.vlanId(), e.mac());
+ TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
+ selector.matchInPort(p.port());
+
+ selector.matchEthDst(e.mac());
+ selector.matchVlanId(v.vlanId());
+ selector.matchEthType(Ethernet.TYPE_IPV4);
+ if (!v.vlanId().equals(VlanId.NONE)) {
+ treatment.popVlan();
+ }
+ treatment.transition(FIB_TABLE);
+ FlowRule rule = DefaultFlowRule.builder()
+ .forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(DEFAULT_PRIORITY)
+ .fromApp(applicationId)
+ .makePermanent()
+ .forTable(FILTER_TABLE).build();
+ ops = ops.add(rule);
+
+ ops = install ? ops.add(rule) : ops.remove(rule);
+ // apply filtering flow rules
+ flowRuleService.apply(ops.build(new FlowRuleOperationsContext() {
+ @Override
+ public void onSuccess(FlowRuleOperations ops) {
+ log.info("Applied filtering rules");
+ pass(filt);
+ }
+
+ @Override
+ public void onError(FlowRuleOperations ops) {
+ log.info("Failed to apply filtering rules");
+ fail(filt, ObjectiveError.FLOWINSTALLATIONFAILED);
+ }
+ }));
+ }
+
+ private Collection<FlowRule> processForward(ForwardingObjective fwd) {
+ switch (fwd.flag()) {
+ case SPECIFIC:
+ return processSpecific(fwd);
+ case VERSATILE:
+ return processVersatile(fwd);
+ default:
+ fail(fwd, ObjectiveError.UNKNOWN);
+ log.warn("Unknown forwarding flag {}", fwd.flag());
+ }
+ return Collections.emptySet();
+ }
+
+ /**
+ * SoftRouter has a single versatile table - the filter table. All versatile
+ * flow rules must include the filtering rules.
+ *
+ * @param fwd The forwarding objective of type versatile
+ * @return A collection of flow rules meant to be delivered to the flowrule
+ * subsystem. May return empty collection in case of failures.
+ */
+ private Collection<FlowRule> processVersatile(ForwardingObjective fwd) {
+ Collection<FlowRule> flowrules = new ArrayList<>();
+
+ FlowRule rule = DefaultFlowRule.builder()
+ .withSelector(fwd.selector())
+ .withTreatment(fwd.treatment())
+ .makePermanent()
+ .forDevice(deviceId)
+ .fromApp(fwd.appId())
+ .withPriority(fwd.priority())
+ .build();
+
+ flowrules.add(rule);
+
+ return flowrules;
+ }
+
+ /**
+ * SoftRouter has a single specific table - the FIB Table. It emulates
+ * LPM matching of dstIP by using higher priority flows for longer prefixes.
+ * Flows are forwarded using flow-actions
+ *
+ * @param fwd The forwarding objective of type simple
+ * @return A collection of flow rules meant to be delivered to the flowrule
+ * subsystem. Typically the returned collection has a single flowrule.
+ * May return empty collection in case of failures.
+ *
+ */
+ private Collection<FlowRule> processSpecific(ForwardingObjective fwd) {
+ log.debug("Processing specific forwarding objective");
+ TrafficSelector selector = fwd.selector();
+ EthTypeCriterion ethType =
+ (EthTypeCriterion) selector.getCriterion(Criterion.Type.ETH_TYPE);
+ // XXX currently supporting only the L3 unicast table
+ if (ethType == null || ethType.ethType().toShort() != Ethernet.TYPE_IPV4) {
+ fail(fwd, ObjectiveError.UNSUPPORTED);
+ return Collections.emptySet();
+ }
+
+ TrafficSelector filteredSelector =
+ DefaultTrafficSelector.builder()
+ .matchEthType(Ethernet.TYPE_IPV4)
+ .matchIPDst(((IPCriterion)
+ selector.getCriterion(Criterion.Type.IPV4_DST)).ip())
+ .build();
+
+ TrafficTreatment tt = null;
+ if (fwd.nextId() != null) {
+ NextGroup next = flowObjectiveStore.getNextGroup(fwd.nextId());
+ if (next == null) {
+ log.error("next-id {} does not exist in store", fwd.nextId());
+ return Collections.emptySet();
+ }
+ tt = appKryo.deserialize(next.data());
+ if (tt == null) {
+ log.error("Error in deserializing next-id {}", fwd.nextId());
+ return Collections.emptySet();
+ }
+ }
+
+ FlowRule.Builder ruleBuilder = DefaultFlowRule.builder()
+ .fromApp(fwd.appId())
+ .withPriority(fwd.priority())
+ .forDevice(deviceId)
+ .withSelector(filteredSelector);
+
+ if (tt != null) {
+ ruleBuilder.withTreatment(tt);
+ }
+
+ if (fwd.permanent()) {
+ ruleBuilder.makePermanent();
+ } else {
+ ruleBuilder.makeTemporary(fwd.timeout());
+ }
+
+ ruleBuilder.forTable(FIB_TABLE);
+ return Collections.singletonList(ruleBuilder.build());
+ }
+
+ /**
+ * Next Objectives are stored as dummy groups for retrieval later
+ * when Forwarding Objectives reference the next objective id. At that point
+ * the dummy group is fetched from the distributed store and the enclosed
+ * treatment is applied as a flow rule action.
+ *
+ * @param nextObj the next objective of type simple
+ */
+ private void processSimpleNextObjective(NextObjective nextObj) {
+ // Simple next objective has a single treatment (not a collection)
+ TrafficTreatment treatment = nextObj.next().iterator().next();
+ flowObjectiveStore.putNextGroup(nextObj.id(),
+ new DummyGroup(treatment));
+ }
+
+ private class DummyGroup implements NextGroup {
+ TrafficTreatment nextActions;
+
+ public DummyGroup(TrafficTreatment next) {
+ this.nextActions = next;
+ }
+
+ @Override
+ public byte[] data() {
+ return appKryo.serialize(nextActions);
+ }
+
+ }
+
+}
diff --git a/drivers/default/src/main/java/org/onosproject/driver/pipeline/SpringOpenTTP.java b/drivers/default/src/main/java/org/onosproject/driver/pipeline/SpringOpenTTP.java
new file mode 100644
index 0000000..1277c75
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/pipeline/SpringOpenTTP.java
@@ -0,0 +1,1109 @@
+/*
+ * 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 static org.onlab.util.Tools.groupedThreads;
+import static org.slf4j.LoggerFactory.getLogger;
+
+import com.google.common.cache.Cache;
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.RemovalCause;
+import com.google.common.cache.RemovalNotification;
+
+import org.onlab.osgi.ServiceDirectory;
+import org.onlab.packet.Ethernet;
+import org.onlab.packet.MacAddress;
+import org.onlab.packet.VlanId;
+import org.onlab.util.KryoNamespace;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreService;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.PortNumber;
+import org.onosproject.net.behaviour.NextGroup;
+import org.onosproject.net.behaviour.Pipeliner;
+import org.onosproject.net.behaviour.PipelinerContext;
+import org.onosproject.net.driver.AbstractHandlerBehaviour;
+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 org.onosproject.net.flow.FlowRuleOperations;
+import org.onosproject.net.flow.FlowRuleOperationsContext;
+import org.onosproject.net.flow.FlowRuleService;
+import org.onosproject.net.flow.TrafficSelector;
+import org.onosproject.net.flow.TrafficTreatment;
+import org.onosproject.net.flow.criteria.Criteria;
+import org.onosproject.net.flow.criteria.Criterion;
+import org.onosproject.net.flow.criteria.Criterion.Type;
+import org.onosproject.net.flow.criteria.EthCriterion;
+import org.onosproject.net.flow.criteria.EthTypeCriterion;
+import org.onosproject.net.flow.criteria.IPCriterion;
+import org.onosproject.net.flow.criteria.MplsBosCriterion;
+import org.onosproject.net.flow.criteria.MplsCriterion;
+import org.onosproject.net.flow.criteria.PortCriterion;
+import org.onosproject.net.flow.criteria.VlanIdCriterion;
+import org.onosproject.net.flow.instructions.Instruction;
+import org.onosproject.net.flow.instructions.Instructions.OutputInstruction;
+import org.onosproject.net.flow.instructions.L2ModificationInstruction.ModVlanIdInstruction;
+import org.onosproject.net.flowobjective.FilteringObjective;
+import org.onosproject.net.flowobjective.FlowObjectiveStore;
+import org.onosproject.net.flowobjective.ForwardingObjective;
+import org.onosproject.net.flowobjective.NextObjective;
+import org.onosproject.net.flowobjective.Objective;
+import org.onosproject.net.flowobjective.ObjectiveError;
+import org.onosproject.net.group.DefaultGroupBucket;
+import org.onosproject.net.group.DefaultGroupDescription;
+import org.onosproject.net.group.DefaultGroupKey;
+import org.onosproject.net.group.Group;
+import org.onosproject.net.group.GroupBucket;
+import org.onosproject.net.group.GroupBuckets;
+import org.onosproject.net.group.GroupDescription;
+import org.onosproject.net.group.GroupEvent;
+import org.onosproject.net.group.GroupKey;
+import org.onosproject.net.group.GroupListener;
+import org.onosproject.net.group.GroupService;
+import org.onosproject.store.serializers.KryoNamespaces;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+
+/**
+ * Driver for SPRING-OPEN pipeline.
+ */
+public class SpringOpenTTP extends AbstractHandlerBehaviour
+ implements Pipeliner {
+
+ // Default table ID - compatible with CpqD switch
+ private static final int TABLE_VLAN = 0;
+ private static final int TABLE_TMAC = 1;
+ private static final int TABLE_IPV4_UNICAST = 2;
+ private static final int TABLE_MPLS = 3;
+ private static final int TABLE_DMAC = 4;
+ private static final int TABLE_ACL = 5;
+ private static final int TABLE_SMAC = 6;
+
+ /**
+ * Set the default values. These variables will get overwritten based on the
+ * switch vendor type
+ */
+ protected int vlanTableId = TABLE_VLAN;
+ protected int tmacTableId = TABLE_TMAC;
+ protected int ipv4UnicastTableId = TABLE_IPV4_UNICAST;
+ protected int mplsTableId = TABLE_MPLS;
+ protected int dstMacTableId = TABLE_DMAC;
+ protected int aclTableId = TABLE_ACL;
+ protected int srcMacTableId = TABLE_SMAC;
+
+ protected final Logger log = getLogger(getClass());
+
+ private ServiceDirectory serviceDirectory;
+ private FlowRuleService flowRuleService;
+ private CoreService coreService;
+ protected GroupService groupService;
+ protected FlowObjectiveStore flowObjectiveStore;
+ protected DeviceId deviceId;
+ private ApplicationId appId;
+
+ private Cache<GroupKey, NextObjective> pendingGroups;
+
+ private ScheduledExecutorService groupChecker = Executors
+ .newScheduledThreadPool(2,
+ groupedThreads("onos/pipeliner",
+ "spring-open-%d"));
+ protected KryoNamespace appKryo = new KryoNamespace.Builder()
+ .register(KryoNamespaces.API)
+ .register(GroupKey.class)
+ .register(DefaultGroupKey.class)
+ .register(TrafficTreatment.class)
+ .register(SpringOpenGroup.class)
+ .register(byte[].class)
+ .build();
+
+ @Override
+ public void init(DeviceId deviceId, PipelinerContext context) {
+ this.serviceDirectory = context.directory();
+ this.deviceId = deviceId;
+
+ pendingGroups = CacheBuilder
+ .newBuilder()
+ .expireAfterWrite(20, TimeUnit.SECONDS)
+ .removalListener((RemovalNotification<GroupKey, NextObjective> notification) -> {
+ if (notification.getCause() == RemovalCause.EXPIRED) {
+ fail(notification.getValue(),
+ ObjectiveError.GROUPINSTALLATIONFAILED);
+ }
+ }).build();
+
+ groupChecker.scheduleAtFixedRate(new GroupChecker(), 0, 500,
+ TimeUnit.MILLISECONDS);
+
+ coreService = serviceDirectory.get(CoreService.class);
+ flowRuleService = serviceDirectory.get(FlowRuleService.class);
+ groupService = serviceDirectory.get(GroupService.class);
+ flowObjectiveStore = context.store();
+
+ groupService.addListener(new InnerGroupListener());
+
+ appId = coreService
+ .registerApplication("org.onosproject.driver.SpringOpenTTP");
+
+ setTableMissEntries();
+ log.info("Spring Open TTP driver initialized");
+ }
+
+ @Override
+ public void filter(FilteringObjective filteringObjective) {
+ if (filteringObjective.type() == FilteringObjective.Type.PERMIT) {
+ log.debug("processing PERMIT filter objective");
+ processFilter(filteringObjective,
+ filteringObjective.op() == Objective.Operation.ADD,
+ filteringObjective.appId());
+ } else {
+ log.debug("filter objective other than PERMIT not supported");
+ fail(filteringObjective, ObjectiveError.UNSUPPORTED);
+ }
+ }
+
+ @Override
+ public void forward(ForwardingObjective fwd) {
+ Collection<FlowRule> rules;
+ FlowRuleOperations.Builder flowBuilder = FlowRuleOperations.builder();
+
+ rules = processForward(fwd);
+ switch (fwd.op()) {
+ case ADD:
+ rules.stream().filter(Objects::nonNull)
+ .forEach(flowBuilder::add);
+ break;
+ case REMOVE:
+ rules.stream().filter(Objects::nonNull)
+ .forEach(flowBuilder::remove);
+ break;
+ default:
+ fail(fwd, ObjectiveError.UNKNOWN);
+ log.warn("Unknown forwarding type {}", fwd.op());
+ }
+
+ flowRuleService.apply(flowBuilder
+ .build(new FlowRuleOperationsContext() {
+ @Override
+ public void onSuccess(FlowRuleOperations ops) {
+ pass(fwd);
+ log.debug("Provisioned tables in {} successfully with "
+ + "forwarding rules", deviceId);
+ }
+
+ @Override
+ public void onError(FlowRuleOperations ops) {
+ fail(fwd, ObjectiveError.FLOWINSTALLATIONFAILED);
+ log.warn("Failed to provision tables in {} with "
+ + "forwarding rules", deviceId);
+ }
+ }));
+
+ }
+
+ @Override
+ public void next(NextObjective nextObjective) {
+ NextGroup nextGroup = flowObjectiveStore.getNextGroup(nextObjective.id());
+ switch (nextObjective.op()) {
+ case ADD:
+ if (nextGroup != null) {
+ log.warn("Cannot add next {} that already exists in device {}",
+ nextObjective.id(), deviceId);
+ return;
+ }
+ log.debug("Processing NextObjective id{} in dev{} - add group",
+ nextObjective.id(), deviceId);
+ addGroup(nextObjective);
+ break;
+ case ADD_TO_EXISTING:
+ if (nextGroup != null) {
+ log.debug("Processing NextObjective id{} in dev{} - add bucket",
+ nextObjective.id(), deviceId);
+ addBucketToGroup(nextObjective);
+ } else {
+ log.warn("Cannot add to group that does not exist");
+ }
+ break;
+ case REMOVE:
+ if (nextGroup == null) {
+ log.warn("Cannot remove next {} that does not exist in device {}",
+ nextObjective.id(), deviceId);
+ return;
+ }
+ log.debug("Processing NextObjective id{} in dev{} - remove group",
+ nextObjective.id(), deviceId);
+ removeGroup(nextObjective);
+ break;
+ case REMOVE_FROM_EXISTING:
+ if (nextGroup == null) {
+ log.warn("Cannot remove from next {} that does not exist in device {}",
+ nextObjective.id(), deviceId);
+ return;
+ }
+ log.debug("Processing NextObjective id{} in dev{} - remove bucket",
+ nextObjective.id(), deviceId);
+ removeBucketFromGroup(nextObjective);
+ break;
+ default:
+ log.warn("Unsupported operation {}", nextObjective.op());
+ }
+ }
+
+ private void removeGroup(NextObjective nextObjective) {
+ log.debug("removeGroup in {}: for next objective id {}",
+ deviceId, nextObjective.id());
+ final GroupKey key = new DefaultGroupKey(
+ appKryo.serialize(nextObjective.id()));
+ groupService.removeGroup(deviceId, key, appId);
+ }
+
+ private void addGroup(NextObjective nextObjective) {
+ log.debug("addGroup with type{} for nextObjective id {}",
+ nextObjective.type(), nextObjective.id());
+ List<GroupBucket> buckets;
+ switch (nextObjective.type()) {
+ case SIMPLE:
+ Collection<TrafficTreatment> treatments = nextObjective.next();
+ if (treatments.size() == 1) {
+ // Spring Open TTP converts simple nextObjective to flow-actions
+ // in a dummy group
+ TrafficTreatment treatment = nextObjective.next().iterator().next();
+ log.debug("Converting SIMPLE group for next objective id {} " +
+ "to {} flow-actions in device:{}", nextObjective.id(),
+ treatment.allInstructions().size(), deviceId);
+ flowObjectiveStore.putNextGroup(nextObjective.id(),
+ new SpringOpenGroup(null, treatment));
+ }
+ break;
+ case HASHED:
+ // we convert MPLS ECMP groups to flow-actions for a single
+ // bucket(output port).
+ boolean mplsEcmp = false;
+ if (nextObjective.meta() != null) {
+ for (Criterion c : nextObjective.meta().criteria()) {
+ if (c.type() == Type.MPLS_LABEL) {
+ mplsEcmp = true;
+ }
+ }
+ }
+ if (mplsEcmp) {
+ // covert to flow-actions in a dummy group by choosing the first bucket
+ log.debug("Converting HASHED group for next objective id {} " +
+ "to flow-actions in device:{}", nextObjective.id(),
+ deviceId);
+ TrafficTreatment treatment = nextObjective.next().iterator().next();
+ flowObjectiveStore.putNextGroup(nextObjective.id(),
+ new SpringOpenGroup(null, treatment));
+ } else {
+ // process as ECMP group
+ buckets = nextObjective
+ .next()
+ .stream()
+ .map((treatment) -> DefaultGroupBucket
+ .createSelectGroupBucket(treatment))
+ .collect(Collectors.toList());
+ if (!buckets.isEmpty()) {
+ final GroupKey key = new DefaultGroupKey(
+ appKryo.serialize(nextObjective.id()));
+ GroupDescription groupDescription = new DefaultGroupDescription(
+ deviceId,
+ GroupDescription.Type.SELECT,
+ new GroupBuckets(buckets),
+ key,
+ null,
+ nextObjective.appId());
+ log.debug("Creating HASHED group for next objective id {}"
+ + " in dev:{}", nextObjective.id(), deviceId);
+ pendingGroups.put(key, nextObjective);
+ groupService.addGroup(groupDescription);
+ }
+ }
+ break;
+ case BROADCAST:
+ buckets = nextObjective
+ .next()
+ .stream()
+ .map((treatment) -> DefaultGroupBucket
+ .createAllGroupBucket(treatment))
+ .collect(Collectors.toList());
+ if (!buckets.isEmpty()) {
+ final GroupKey key = new DefaultGroupKey(
+ appKryo.serialize(nextObjective
+ .id()));
+ GroupDescription groupDescription = new DefaultGroupDescription(
+ deviceId,
+ GroupDescription.Type.ALL,
+ new GroupBuckets(buckets),
+ key,
+ null,
+ nextObjective.appId());
+ log.debug("Creating BROADCAST group for next objective id {} "
+ + "in device {}", nextObjective.id(), deviceId);
+ pendingGroups.put(key, nextObjective);
+ groupService.addGroup(groupDescription);
+ }
+ break;
+ case FAILOVER:
+ log.debug("FAILOVER next objectives not supported");
+ fail(nextObjective, ObjectiveError.UNSUPPORTED);
+ log.warn("Unsupported next objective type {}", nextObjective.type());
+ break;
+ default:
+ fail(nextObjective, ObjectiveError.UNKNOWN);
+ log.warn("Unknown next objective type {}", nextObjective.type());
+ }
+ }
+
+ private void addBucketToGroup(NextObjective nextObjective) {
+ log.debug("addBucketToGroup in {}: for next objective id {}",
+ deviceId, nextObjective.id());
+ Collection<TrafficTreatment> treatments = nextObjective.next();
+ TrafficTreatment treatment = treatments.iterator().next();
+ final GroupKey key = new DefaultGroupKey(
+ appKryo.serialize(nextObjective
+ .id()));
+ Group group = groupService.getGroup(deviceId, key);
+ if (group == null) {
+ log.warn("Group is not found in {} for {}", deviceId, key);
+ return;
+ }
+ GroupBucket bucket;
+ if (group.type() == GroupDescription.Type.INDIRECT) {
+ bucket = DefaultGroupBucket.createIndirectGroupBucket(treatment);
+ } else if (group.type() == GroupDescription.Type.SELECT) {
+ bucket = DefaultGroupBucket.createSelectGroupBucket(treatment);
+ } else if (group.type() == GroupDescription.Type.ALL) {
+ bucket = DefaultGroupBucket.createAllGroupBucket(treatment);
+ } else {
+ log.warn("Unsupported Group type {}", group.type());
+ return;
+ }
+ GroupBuckets bucketsToAdd = new GroupBuckets(Collections.singletonList(bucket));
+ log.debug("Adding buckets to group id {} of next objective id {} in device {}",
+ group.id(), nextObjective.id(), deviceId);
+ groupService.addBucketsToGroup(deviceId, key, bucketsToAdd, key, appId);
+ }
+
+ private void removeBucketFromGroup(NextObjective nextObjective) {
+ log.debug("removeBucketFromGroup in {}: for next objective id {}",
+ deviceId, nextObjective.id());
+ NextGroup nextGroup = flowObjectiveStore.getNextGroup(nextObjective.id());
+ if (nextGroup != null) {
+ Collection<TrafficTreatment> treatments = nextObjective.next();
+ TrafficTreatment treatment = treatments.iterator().next();
+ final GroupKey key = new DefaultGroupKey(
+ appKryo.serialize(nextObjective
+ .id()));
+ Group group = groupService.getGroup(deviceId, key);
+ if (group == null) {
+ log.warn("Group is not found in {} for {}", deviceId, key);
+ return;
+ }
+ GroupBucket bucket;
+ if (group.type() == GroupDescription.Type.INDIRECT) {
+ bucket = DefaultGroupBucket.createIndirectGroupBucket(treatment);
+ } else if (group.type() == GroupDescription.Type.SELECT) {
+ bucket = DefaultGroupBucket.createSelectGroupBucket(treatment);
+ } else if (group.type() == GroupDescription.Type.ALL) {
+ bucket = DefaultGroupBucket.createAllGroupBucket(treatment);
+ } else {
+ log.warn("Unsupported Group type {}", group.type());
+ return;
+ }
+ GroupBuckets removeBuckets = new GroupBuckets(Collections.singletonList(bucket));
+ log.debug("Removing buckets from group id {} of next objective id {} in device {}",
+ group.id(), nextObjective.id(), deviceId);
+ groupService.removeBucketsFromGroup(deviceId, key, removeBuckets, key, appId);
+ }
+ }
+
+ private Collection<FlowRule> processForward(ForwardingObjective fwd) {
+ switch (fwd.flag()) {
+ case SPECIFIC:
+ return processSpecific(fwd);
+ case VERSATILE:
+ return processVersatile(fwd);
+ default:
+ fail(fwd, ObjectiveError.UNKNOWN);
+ log.warn("Unknown forwarding flag {}", fwd.flag());
+ }
+ return Collections.emptySet();
+ }
+
+ private Collection<FlowRule> processVersatile(ForwardingObjective fwd) {
+ log.debug("Processing versatile forwarding objective in dev:{}", deviceId);
+ TrafficSelector selector = fwd.selector();
+ EthTypeCriterion ethType =
+ (EthTypeCriterion) selector.getCriterion(Criterion.Type.ETH_TYPE);
+ if (ethType == null) {
+ log.error("Versatile forwarding objective must include ethType");
+ fail(fwd, ObjectiveError.UNKNOWN);
+ return Collections.emptySet();
+ }
+
+ if (fwd.treatment() == null && fwd.nextId() == null) {
+ log.error("VERSATILE forwarding objective needs next objective ID "
+ + "or treatment.");
+ return Collections.emptySet();
+ }
+ // emulation of ACL table (for versatile fwd objective) requires
+ // overriding any previous instructions
+ TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment
+ .builder();
+ treatmentBuilder.wipeDeferred();
+
+ if (fwd.nextId() != null) {
+ NextGroup next = flowObjectiveStore.getNextGroup(fwd.nextId());
+ if (next != null) {
+ SpringOpenGroup soGroup = appKryo.deserialize(next.data());
+ if (soGroup.dummy) {
+ // need to convert to flow-actions
+ for (Instruction ins : soGroup.treatment.allInstructions()) {
+ treatmentBuilder.add(ins);
+ }
+ } else {
+ GroupKey key = soGroup.key;
+ Group group = groupService.getGroup(deviceId, key);
+ if (group == null) {
+ log.warn("The group left!");
+ fail(fwd, ObjectiveError.GROUPMISSING);
+ return Collections.emptySet();
+ }
+ treatmentBuilder.deferred().group(group.id());
+ log.debug("Adding OUTGROUP action");
+ }
+ }
+ }
+
+ if (fwd.treatment() != null) {
+ if (fwd.treatment().allInstructions().size() == 1 &&
+ fwd.treatment().allInstructions().get(0).type() == Instruction.Type.OUTPUT) {
+ OutputInstruction o = (OutputInstruction) fwd.treatment().allInstructions().get(0);
+ if (o.port() == PortNumber.CONTROLLER) {
+ treatmentBuilder.punt();
+ } else {
+ treatmentBuilder.add(o);
+ }
+ } else {
+ for (Instruction ins : fwd.treatment().allInstructions()) {
+ treatmentBuilder.add(ins);
+ }
+ }
+ }
+
+ FlowRule.Builder ruleBuilder = DefaultFlowRule.builder()
+ .fromApp(fwd.appId()).withPriority(fwd.priority())
+ .forDevice(deviceId).withSelector(fwd.selector())
+ .withTreatment(treatmentBuilder.build());
+
+ if (fwd.permanent()) {
+ ruleBuilder.makePermanent();
+ } else {
+ ruleBuilder.makeTemporary(fwd.timeout());
+ }
+
+ ruleBuilder.forTable(aclTableId);
+ return Collections.singletonList(ruleBuilder.build());
+ }
+
+ private boolean isSupportedEthTypeObjective(ForwardingObjective fwd) {
+ TrafficSelector selector = fwd.selector();
+ EthTypeCriterion ethType = (EthTypeCriterion) selector
+ .getCriterion(Criterion.Type.ETH_TYPE);
+ if ((ethType == null) ||
+ ((ethType.ethType().toShort() != Ethernet.TYPE_IPV4) &&
+ (ethType.ethType().toShort() != Ethernet.MPLS_UNICAST))) {
+ return false;
+ }
+ return true;
+ }
+
+ private boolean isSupportedEthDstObjective(ForwardingObjective fwd) {
+ TrafficSelector selector = fwd.selector();
+ EthCriterion ethDst = (EthCriterion) selector
+ .getCriterion(Criterion.Type.ETH_DST);
+ VlanIdCriterion vlanId = (VlanIdCriterion) selector
+ .getCriterion(Criterion.Type.VLAN_VID);
+ if (ethDst == null && vlanId == null) {
+ return false;
+ }
+ return true;
+ }
+
+ protected Collection<FlowRule> processSpecific(ForwardingObjective fwd) {
+ log.debug("Processing specific fwd objective:{} in dev:{} with next:{}",
+ fwd.id(), deviceId, fwd.nextId());
+ boolean isEthTypeObj = isSupportedEthTypeObjective(fwd);
+ boolean isEthDstObj = isSupportedEthDstObjective(fwd);
+
+ if (isEthTypeObj) {
+ return processEthTypeSpecificObjective(fwd);
+ } else if (isEthDstObj) {
+ return processEthDstSpecificObjective(fwd);
+ } else {
+ log.warn("processSpecific: Unsupported "
+ + "forwarding objective criteria");
+ fail(fwd, ObjectiveError.UNSUPPORTED);
+ return Collections.emptySet();
+ }
+ }
+
+ protected Collection<FlowRule>
+ processEthTypeSpecificObjective(ForwardingObjective fwd) {
+ TrafficSelector selector = fwd.selector();
+ EthTypeCriterion ethType = (EthTypeCriterion) selector
+ .getCriterion(Criterion.Type.ETH_TYPE);
+
+ TrafficSelector.Builder filteredSelectorBuilder =
+ DefaultTrafficSelector.builder();
+ int forTableId = -1;
+ if (ethType.ethType().toShort() == Ethernet.TYPE_IPV4) {
+ filteredSelectorBuilder = filteredSelectorBuilder
+ .matchEthType(Ethernet.TYPE_IPV4)
+ .matchIPDst(((IPCriterion) selector
+ .getCriterion(Criterion.Type.IPV4_DST))
+ .ip());
+ forTableId = ipv4UnicastTableId;
+ log.debug("processing IPv4 specific forwarding objective:{} in dev:{}",
+ fwd.id(), deviceId);
+ } else {
+ filteredSelectorBuilder = filteredSelectorBuilder
+ .matchEthType(Ethernet.MPLS_UNICAST)
+ .matchMplsLabel(((MplsCriterion)
+ selector.getCriterion(Criterion.Type.MPLS_LABEL)).label());
+ if (selector.getCriterion(Criterion.Type.MPLS_BOS) != null) {
+ filteredSelectorBuilder.matchMplsBos(((MplsBosCriterion)
+ selector.getCriterion(Type.MPLS_BOS)).mplsBos());
+ }
+ forTableId = mplsTableId;
+ log.debug("processing MPLS specific forwarding objective:{} in dev:{}",
+ fwd.id(), deviceId);
+ }
+
+ TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment
+ .builder();
+ if (fwd.treatment() != null) {
+ for (Instruction i : fwd.treatment().allInstructions()) {
+ treatmentBuilder.add(i);
+ }
+ }
+
+ if (fwd.nextId() != null) {
+ NextGroup next = flowObjectiveStore.getNextGroup(fwd.nextId());
+ if (next != null) {
+ SpringOpenGroup soGroup = appKryo.deserialize(next.data());
+ if (soGroup.dummy) {
+ log.debug("Adding {} flow-actions for fwd. obj. {} -> next:{} "
+ + "in dev: {}", soGroup.treatment.allInstructions().size(),
+ fwd.id(), fwd.nextId(), deviceId);
+ for (Instruction ins : soGroup.treatment.allInstructions()) {
+ treatmentBuilder.add(ins);
+ }
+ } else {
+ GroupKey key = soGroup.key;
+ Group group = groupService.getGroup(deviceId, key);
+ if (group == null) {
+ log.warn("The group left!");
+ fail(fwd, ObjectiveError.GROUPMISSING);
+ return Collections.emptySet();
+ }
+ treatmentBuilder.deferred().group(group.id());
+ log.debug("Adding OUTGROUP action to group:{} for fwd. obj. {} "
+ + "for next:{} in dev: {}", group.id(), fwd.id(),
+ fwd.nextId(), deviceId);
+ }
+ } else {
+ log.warn("processSpecific: No associated next objective object");
+ fail(fwd, ObjectiveError.GROUPMISSING);
+ return Collections.emptySet();
+ }
+ }
+
+ TrafficSelector filteredSelector = filteredSelectorBuilder.build();
+ TrafficTreatment treatment = treatmentBuilder.transition(aclTableId)
+ .build();
+
+ FlowRule.Builder ruleBuilder = DefaultFlowRule.builder()
+ .fromApp(fwd.appId()).withPriority(fwd.priority())
+ .forDevice(deviceId).withSelector(filteredSelector)
+ .withTreatment(treatment);
+
+ if (fwd.permanent()) {
+ ruleBuilder.makePermanent();
+ } else {
+ ruleBuilder.makeTemporary(fwd.timeout());
+ }
+
+ ruleBuilder.forTable(forTableId);
+ return Collections.singletonList(ruleBuilder.build());
+
+ }
+
+ protected Collection<FlowRule>
+ processEthDstSpecificObjective(ForwardingObjective fwd) {
+ List<FlowRule> rules = new ArrayList<>();
+
+ // Build filtered selector
+ TrafficSelector selector = fwd.selector();
+ EthCriterion ethCriterion = (EthCriterion) selector
+ .getCriterion(Criterion.Type.ETH_DST);
+ VlanIdCriterion vlanIdCriterion = (VlanIdCriterion) selector
+ .getCriterion(Criterion.Type.VLAN_VID);
+ TrafficSelector.Builder filteredSelectorBuilder =
+ DefaultTrafficSelector.builder();
+ // Do not match MacAddress for subnet broadcast entry
+ if (!ethCriterion.mac().equals(MacAddress.NONE)) {
+ filteredSelectorBuilder.matchEthDst(ethCriterion.mac());
+ log.debug("processing L2 forwarding objective:{} in dev:{}",
+ fwd.id(), deviceId);
+ } else {
+ log.debug("processing L2 Broadcast forwarding objective:{} "
+ + "in dev:{} for vlan:{}",
+ fwd.id(), deviceId, vlanIdCriterion.vlanId());
+ }
+ filteredSelectorBuilder.matchVlanId(vlanIdCriterion.vlanId());
+ TrafficSelector filteredSelector = filteredSelectorBuilder.build();
+
+ // Build filtered treatment
+ TrafficTreatment.Builder treatmentBuilder =
+ DefaultTrafficTreatment.builder();
+ if (fwd.treatment() != null) {
+ treatmentBuilder.deferred();
+ fwd.treatment().allInstructions().forEach(treatmentBuilder::add);
+ }
+ if (fwd.nextId() != null) {
+ NextGroup next = flowObjectiveStore.getNextGroup(fwd.nextId());
+ if (next != null) {
+ SpringOpenGroup soGrp = appKryo.deserialize(next.data());
+ if (soGrp.dummy) {
+ log.debug("Adding {} flow-actions for fwd. obj. {} "
+ + "in dev: {}", soGrp.treatment.allInstructions().size(),
+ fwd.id(), deviceId);
+ for (Instruction ins : soGrp.treatment.allInstructions()) {
+ treatmentBuilder.deferred().add(ins);
+ }
+ } else {
+ GroupKey key = soGrp.key;
+ Group group = groupService.getGroup(deviceId, key);
+ if (group == null) {
+ log.warn("The group left!");
+ fail(fwd, ObjectiveError.GROUPMISSING);
+ return Collections.emptySet();
+ }
+ treatmentBuilder.deferred().group(group.id());
+ log.debug("Adding OUTGROUP action to group:{} for fwd. obj. {} "
+ + "in dev: {}", group.id(), fwd.id(), deviceId);
+ }
+ }
+ }
+ treatmentBuilder.immediate().transition(aclTableId);
+ TrafficTreatment filteredTreatment = treatmentBuilder.build();
+
+ // Build bridging table entries
+ FlowRule.Builder flowRuleBuilder = DefaultFlowRule.builder();
+ flowRuleBuilder.fromApp(fwd.appId())
+ .withPriority(fwd.priority())
+ .forDevice(deviceId)
+ .withSelector(filteredSelector)
+ .withTreatment(filteredTreatment)
+ .forTable(dstMacTableId);
+ if (fwd.permanent()) {
+ flowRuleBuilder.makePermanent();
+ } else {
+ flowRuleBuilder.makeTemporary(fwd.timeout());
+ }
+ rules.add(flowRuleBuilder.build());
+
+ /*
+ // TODO Emulate source MAC table behavior
+ // Do not install source MAC table entry for subnet broadcast
+ if (!ethCriterion.mac().equals(MacAddress.NONE)) {
+ // Build filtered selector
+ selector = fwd.selector();
+ ethCriterion = (EthCriterion) selector.getCriterion(Criterion.Type.ETH_DST);
+ filteredSelectorBuilder = DefaultTrafficSelector.builder();
+ filteredSelectorBuilder.matchEthSrc(ethCriterion.mac());
+ filteredSelector = filteredSelectorBuilder.build();
+
+ // Build empty treatment. Apply existing instruction if match.
+ treatmentBuilder = DefaultTrafficTreatment.builder();
+ filteredTreatment = treatmentBuilder.build();
+
+ // Build bridging table entries
+ flowRuleBuilder = DefaultFlowRule.builder();
+ flowRuleBuilder.fromApp(fwd.appId())
+ .withPriority(fwd.priority())
+ .forDevice(deviceId)
+ .withSelector(filteredSelector)
+ .withTreatment(filteredTreatment)
+ .forTable(srcMacTableId)
+ .makePermanent();
+ rules.add(flowRuleBuilder.build());
+ }
+ */
+
+ return rules;
+ }
+
+ /*
+ * Note: CpqD switches do not handle MPLS-related operation properly
+ * for a packet with VLAN tag. We pop VLAN here as a workaround.
+ * Side effect: HostService learns redundant hosts with same MAC but
+ * different VLAN. No known side effect on the network reachability.
+ */
+ protected List<FlowRule> processEthDstFilter(EthCriterion ethCriterion,
+ VlanIdCriterion vlanIdCriterion,
+ FilteringObjective filt,
+ VlanId assignedVlan,
+ ApplicationId applicationId) {
+ //handling untagged packets via assigned VLAN
+ if (vlanIdCriterion.vlanId() == VlanId.NONE) {
+ vlanIdCriterion = (VlanIdCriterion) Criteria.matchVlanId(assignedVlan);
+ }
+
+ List<FlowRule> rules = new ArrayList<>();
+ TrafficSelector.Builder selectorIp = DefaultTrafficSelector
+ .builder();
+ TrafficTreatment.Builder treatmentIp = DefaultTrafficTreatment
+ .builder();
+ selectorIp.matchEthDst(ethCriterion.mac());
+ selectorIp.matchEthType(Ethernet.TYPE_IPV4);
+ selectorIp.matchVlanId(vlanIdCriterion.vlanId());
+ treatmentIp.popVlan();
+ treatmentIp.transition(ipv4UnicastTableId);
+ FlowRule ruleIp = DefaultFlowRule.builder().forDevice(deviceId)
+ .withSelector(selectorIp.build())
+ .withTreatment(treatmentIp.build())
+ .withPriority(filt.priority()).fromApp(applicationId)
+ .makePermanent().forTable(tmacTableId).build();
+ log.debug("adding IP ETH rule for MAC: {}", ethCriterion.mac());
+ rules.add(ruleIp);
+
+ TrafficSelector.Builder selectorMpls = DefaultTrafficSelector
+ .builder();
+ TrafficTreatment.Builder treatmentMpls = DefaultTrafficTreatment
+ .builder();
+ selectorMpls.matchEthDst(ethCriterion.mac());
+ selectorMpls.matchEthType(Ethernet.MPLS_UNICAST);
+ selectorMpls.matchVlanId(vlanIdCriterion.vlanId());
+ treatmentMpls.popVlan();
+ treatmentMpls.transition(mplsTableId);
+ FlowRule ruleMpls = DefaultFlowRule.builder()
+ .forDevice(deviceId).withSelector(selectorMpls.build())
+ .withTreatment(treatmentMpls.build())
+ .withPriority(filt.priority()).fromApp(applicationId)
+ .makePermanent().forTable(tmacTableId).build();
+ log.debug("adding MPLS ETH rule for MAC: {}", ethCriterion.mac());
+ rules.add(ruleMpls);
+
+ return rules;
+ }
+
+ protected List<FlowRule> processVlanIdFilter(VlanIdCriterion vlanIdCriterion,
+ FilteringObjective filt,
+ VlanId assignedVlan,
+ ApplicationId applicationId) {
+ List<FlowRule> rules = new ArrayList<>();
+ log.debug("adding rule for VLAN: {}", vlanIdCriterion.vlanId());
+ TrafficSelector.Builder selector = DefaultTrafficSelector
+ .builder();
+ TrafficTreatment.Builder treatment = DefaultTrafficTreatment
+ .builder();
+ PortCriterion p = (PortCriterion) filt.key();
+ if (vlanIdCriterion.vlanId() != VlanId.NONE) {
+ selector.matchVlanId(vlanIdCriterion.vlanId());
+ selector.matchInPort(p.port());
+ } else {
+ selector.matchInPort(p.port());
+ treatment.immediate().pushVlan().setVlanId(assignedVlan);
+ }
+ treatment.transition(tmacTableId);
+ FlowRule rule = DefaultFlowRule.builder().forDevice(deviceId)
+ .withSelector(selector.build())
+ .withTreatment(treatment.build())
+ .withPriority(filt.priority()).fromApp(applicationId)
+ .makePermanent().forTable(vlanTableId).build();
+ rules.add(rule);
+
+ return rules;
+ }
+
+ private void processFilter(FilteringObjective filt, boolean install,
+ ApplicationId applicationId) {
+ // This driver only processes filtering criteria defined with switch
+ // ports as the key
+ if (filt.key().equals(Criteria.dummy())
+ || filt.key().type() != Criterion.Type.IN_PORT) {
+ log.warn("No key defined in filtering objective from app: {}. Not"
+ + "processing filtering objective", applicationId);
+ fail(filt, ObjectiveError.UNKNOWN);
+ return;
+ }
+
+ EthCriterion ethCriterion = null;
+ VlanIdCriterion vlanIdCriterion = null;
+
+ // convert filtering conditions for switch-intfs into flowrules
+ FlowRuleOperations.Builder ops = FlowRuleOperations.builder();
+
+ for (Criterion criterion : filt.conditions()) {
+ if (criterion.type() == Criterion.Type.ETH_DST) {
+ ethCriterion = (EthCriterion) criterion;
+ } else if (criterion.type() == Criterion.Type.VLAN_VID) {
+ vlanIdCriterion = (VlanIdCriterion) criterion;
+ } else if (criterion.type() == Criterion.Type.IPV4_DST) {
+ log.debug("driver does not process IP filtering rules as it " +
+ "sends all misses in the IP table to the controller");
+ } else {
+ log.warn("Driver does not currently process filtering condition"
+ + " of type: {}", criterion.type());
+ fail(filt, ObjectiveError.UNSUPPORTED);
+ }
+ }
+
+ VlanId assignedVlan = null;
+ if (vlanIdCriterion != null) {
+ // For VLAN cross-connect packets, use the configured VLAN
+ if (vlanIdCriterion.vlanId() != VlanId.NONE) {
+ assignedVlan = vlanIdCriterion.vlanId();
+
+ // For untagged packets, assign a VLAN ID
+ } else {
+ if (filt.meta() == null) {
+ log.error("Missing metadata in filtering objective required " +
+ "for vlan assignment in dev {}", deviceId);
+ fail(filt, ObjectiveError.BADPARAMS);
+ return;
+ }
+ for (Instruction i : filt.meta().allInstructions()) {
+ if (i instanceof ModVlanIdInstruction) {
+ assignedVlan = ((ModVlanIdInstruction) i).vlanId();
+ }
+ }
+ if (assignedVlan == null) {
+ log.error("Driver requires an assigned vlan-id to tag incoming "
+ + "untagged packets. Not processing vlan filters on "
+ + "device {}", deviceId);
+ fail(filt, ObjectiveError.BADPARAMS);
+ return;
+ }
+ }
+ }
+
+ if (ethCriterion == null) {
+ log.debug("filtering objective missing dstMac, cannot program TMAC table");
+ } else {
+ for (FlowRule tmacRule : processEthDstFilter(ethCriterion,
+ vlanIdCriterion,
+ filt,
+ assignedVlan,
+ applicationId)) {
+ log.debug("adding MAC filtering rules in TMAC table: {} for dev: {}",
+ tmacRule, deviceId);
+ ops = install ? ops.add(tmacRule) : ops.remove(tmacRule);
+ }
+ }
+
+ if (vlanIdCriterion == null) {
+ log.debug("filtering objective missing VLAN ID criterion, "
+ + "cannot program VLAN Table");
+ } else {
+ for (FlowRule vlanRule : processVlanIdFilter(vlanIdCriterion,
+ filt,
+ assignedVlan,
+ applicationId)) {
+ log.debug("adding VLAN filtering rule in VLAN table: {} for dev: {}",
+ vlanRule, deviceId);
+ ops = install ? ops.add(vlanRule) : ops.remove(vlanRule);
+ }
+ }
+
+ // apply filtering flow rules
+ flowRuleService.apply(ops.build(new FlowRuleOperationsContext() {
+ @Override
+ public void onSuccess(FlowRuleOperations ops) {
+ pass(filt);
+ log.debug("Provisioned tables in {} with fitering "
+ + "rules", deviceId);
+ }
+
+ @Override
+ public void onError(FlowRuleOperations ops) {
+ fail(filt, ObjectiveError.FLOWINSTALLATIONFAILED);
+ log.warn("Failed to provision tables in {} with "
+ + "fitering rules", deviceId);
+ }
+ }));
+ }
+
+ protected void setTableMissEntries() {
+ // set all table-miss-entries
+ populateTableMissEntry(vlanTableId, true, false, false, -1);
+ populateTableMissEntry(tmacTableId, false, false, true, dstMacTableId);
+ populateTableMissEntry(ipv4UnicastTableId, false, true, true, aclTableId);
+ populateTableMissEntry(mplsTableId, false, true, true, aclTableId);
+ populateTableMissEntry(dstMacTableId, false, false, true, aclTableId);
+ populateTableMissEntry(aclTableId, false, false, false, -1);
+ }
+
+ protected void populateTableMissEntry(int tableToAdd,
+ boolean toControllerNow,
+ boolean toControllerWrite,
+ boolean toTable, int tableToSend) {
+ TrafficSelector selector = DefaultTrafficSelector.builder().build();
+ TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
+
+ if (toControllerNow) {
+ tBuilder.setOutput(PortNumber.CONTROLLER);
+ }
+
+ if (toControllerWrite) {
+ tBuilder.deferred().setOutput(PortNumber.CONTROLLER);
+ }
+
+ if (toTable) {
+ tBuilder.transition(tableToSend);
+ }
+
+ FlowRule flow = DefaultFlowRule.builder().forDevice(deviceId)
+ .withSelector(selector).withTreatment(tBuilder.build())
+ .withPriority(0).fromApp(appId).makePermanent()
+ .forTable(tableToAdd).build();
+
+ flowRuleService.applyFlowRules(flow);
+ }
+
+ private void pass(Objective obj) {
+ if (obj.context().isPresent()) {
+ obj.context().get().onSuccess(obj);
+ }
+ }
+
+ protected void fail(Objective obj, ObjectiveError error) {
+ if (obj.context().isPresent()) {
+ obj.context().get().onError(obj, error);
+ }
+ }
+
+ private class InnerGroupListener implements GroupListener {
+ @Override
+ public void event(GroupEvent event) {
+ if (event.type() == GroupEvent.Type.GROUP_ADDED) {
+ log.trace("InnerGroupListener: Group ADDED "
+ + "event received in device {}", deviceId);
+ GroupKey key = event.subject().appCookie();
+
+ NextObjective obj = pendingGroups.getIfPresent(key);
+ if (obj != null) {
+ log.debug("Group verified: dev:{} gid:{} <<->> nextId:{}",
+ deviceId, event.subject().id(), obj.id());
+ flowObjectiveStore
+ .putNextGroup(obj.id(),
+ new SpringOpenGroup(key, null));
+ pass(obj);
+ pendingGroups.invalidate(key);
+ }
+ } else if (event.type() == GroupEvent.Type.GROUP_ADD_FAILED) {
+ log.warn("InnerGroupListener: Group ADD "
+ + "failed event received in device {}", deviceId);
+ }
+ }
+ }
+
+ private class GroupChecker implements Runnable {
+
+ @Override
+ public void run() {
+ Set<GroupKey> keys = pendingGroups
+ .asMap()
+ .keySet()
+ .stream()
+ .filter(key -> groupService.getGroup(deviceId, key) != null)
+ .collect(Collectors.toSet());
+
+ keys.stream()
+ .forEach(key -> {
+ NextObjective obj = pendingGroups
+ .getIfPresent(key);
+ if (obj == null) {
+ return;
+ }
+ log.debug("Group verified: dev:{} gid:{} <<->> nextId:{}",
+ deviceId,
+ groupService.getGroup(deviceId, key).id(),
+ obj.id());
+ pass(obj);
+ pendingGroups.invalidate(key);
+ flowObjectiveStore.putNextGroup(
+ obj.id(),
+ new SpringOpenGroup(key, null));
+ });
+ }
+ }
+
+ /**
+ * SpringOpenGroup can either serve as storage for a GroupKey which can be
+ * used to fetch the group from the Group Service, or it can be serve as storage
+ * for Traffic Treatments which can be used as flow actions. In the latter
+ * case, we refer to this as a dummy group.
+ *
+ */
+ private class SpringOpenGroup implements NextGroup {
+ private final boolean dummy;
+ private final GroupKey key;
+ private final TrafficTreatment treatment;
+
+ /**
+ * Storage for a GroupKey or a TrafficTreatment. One of the params
+ * to this constructor must be null.
+ * @param key represents a GroupKey
+ * @param treatment represents flow actions in a dummy group
+ */
+ public SpringOpenGroup(GroupKey key, TrafficTreatment treatment) {
+ if (key == null) {
+ this.key = new DefaultGroupKey(new byte[]{0});
+ this.treatment = treatment;
+ this.dummy = true;
+ } else {
+ this.key = key;
+ this.treatment = DefaultTrafficTreatment.builder().build();
+ this.dummy = false;
+ }
+ }
+
+ @SuppressWarnings("unused")
+ public GroupKey key() {
+ return key;
+ }
+
+ @Override
+ public byte[] data() {
+ return appKryo.serialize(this);
+ }
+
+ }
+}
diff --git a/drivers/default/src/main/java/org/onosproject/driver/pipeline/SpringOpenTTPDell.java b/drivers/default/src/main/java/org/onosproject/driver/pipeline/SpringOpenTTPDell.java
new file mode 100644
index 0000000..2b71ff7
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/pipeline/SpringOpenTTPDell.java
@@ -0,0 +1,206 @@
+/*
+ * 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 java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+
+import org.onlab.packet.Ethernet;
+import org.onlab.packet.MacAddress;
+import org.onlab.packet.VlanId;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.net.behaviour.NextGroup;
+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 org.onosproject.net.flow.TrafficSelector;
+import org.onosproject.net.flow.TrafficTreatment;
+import org.onosproject.net.flow.criteria.Criterion;
+import org.onosproject.net.flow.criteria.EthCriterion;
+import org.onosproject.net.flow.criteria.EthTypeCriterion;
+import org.onosproject.net.flow.criteria.IPCriterion;
+import org.onosproject.net.flow.criteria.MplsBosCriterion;
+import org.onosproject.net.flow.criteria.MplsCriterion;
+import org.onosproject.net.flow.criteria.VlanIdCriterion;
+import org.onosproject.net.flow.instructions.Instruction;
+import org.onosproject.net.flowobjective.FilteringObjective;
+import org.onosproject.net.flowobjective.ForwardingObjective;
+import org.onosproject.net.flowobjective.ObjectiveError;
+import org.onosproject.net.group.Group;
+import org.onosproject.net.group.GroupKey;
+
+/**
+ * Spring-open driver implementation for Dell hardware switches.
+ */
+public class SpringOpenTTPDell extends SpringOpenTTP {
+
+ /* Table IDs to be used for Dell Open Segment Routers*/
+ private static final int DELL_TABLE_VLAN = 17;
+ private static final int DELL_TABLE_TMAC = 18;
+ private static final int DELL_TABLE_IPV4_UNICAST = 30;
+ private static final int DELL_TABLE_MPLS = 25;
+ private static final int DELL_TABLE_ACL = 40;
+
+ //TODO: Store this info in the distributed store.
+ private MacAddress deviceTMac = null;
+
+ public SpringOpenTTPDell() {
+ super();
+ vlanTableId = DELL_TABLE_VLAN;
+ tmacTableId = DELL_TABLE_TMAC;
+ ipv4UnicastTableId = DELL_TABLE_IPV4_UNICAST;
+ mplsTableId = DELL_TABLE_MPLS;
+ aclTableId = DELL_TABLE_ACL;
+ }
+
+ @Override
+ protected void setTableMissEntries() {
+ // No need to set table-miss-entries in Dell switches
+ return;
+ }
+
+ @Override
+ //Dell switches need ETH_DST based match condition in all IP table entries.
+ //So this method overrides the default spring-open behavior and adds
+ //ETH_DST match condition while pushing IP table flow rules
+ protected Collection<FlowRule> processSpecific(ForwardingObjective fwd) {
+ log.debug("Processing specific");
+ TrafficSelector selector = fwd.selector();
+ EthTypeCriterion ethType = (EthTypeCriterion) selector
+ .getCriterion(Criterion.Type.ETH_TYPE);
+ if ((ethType == null) ||
+ (ethType.ethType().toShort() != Ethernet.TYPE_IPV4) &&
+ (ethType.ethType().toShort() != Ethernet.MPLS_UNICAST)) {
+ log.debug("processSpecific: Unsupported "
+ + "forwarding objective criteraia");
+ fail(fwd, ObjectiveError.UNSUPPORTED);
+ return Collections.emptySet();
+ }
+
+ TrafficSelector.Builder filteredSelectorBuilder =
+ DefaultTrafficSelector.builder();
+ int forTableId = -1;
+ if (ethType.ethType().toShort() == Ethernet.TYPE_IPV4) {
+ if (deviceTMac == null) {
+ log.debug("processSpecific: ETH_DST filtering "
+ + "objective is not set which is required "
+ + "before sending a IPv4 forwarding objective");
+ //TODO: Map the error to more appropriate error code.
+ fail(fwd, ObjectiveError.DEVICEMISSING);
+ return Collections.emptySet();
+ }
+ filteredSelectorBuilder = filteredSelectorBuilder
+ .matchEthType(Ethernet.TYPE_IPV4)
+ .matchEthDst(deviceTMac)
+ .matchIPDst(((IPCriterion) selector
+ .getCriterion(Criterion.Type.IPV4_DST))
+ .ip());
+ forTableId = ipv4UnicastTableId;
+ log.debug("processing IPv4 specific forwarding objective");
+ } else {
+ filteredSelectorBuilder = filteredSelectorBuilder
+ .matchEthType(Ethernet.MPLS_UNICAST)
+ .matchMplsLabel(((MplsCriterion)
+ selector.getCriterion(Criterion.Type.MPLS_LABEL)).label());
+ if (selector.getCriterion(Criterion.Type.MPLS_BOS) != null) {
+ filteredSelectorBuilder.matchMplsBos(((MplsBosCriterion)
+ selector.getCriterion(Criterion.Type.MPLS_BOS)).mplsBos());
+ }
+ forTableId = mplsTableId;
+ log.debug("processing MPLS specific forwarding objective");
+ }
+
+ TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment
+ .builder();
+ if (fwd.treatment() != null) {
+ for (Instruction i : fwd.treatment().allInstructions()) {
+ treatmentBuilder.add(i);
+ }
+ }
+
+ if (fwd.nextId() != null) {
+ NextGroup next = flowObjectiveStore.getNextGroup(fwd.nextId());
+
+ if (next != null) {
+ GroupKey key = appKryo.deserialize(next.data());
+
+ Group group = groupService.getGroup(deviceId, key);
+
+ if (group == null) {
+ log.warn("The group left!");
+ fail(fwd, ObjectiveError.GROUPMISSING);
+ return Collections.emptySet();
+ }
+ treatmentBuilder.group(group.id());
+ log.debug("Adding OUTGROUP action");
+ } else {
+ log.warn("processSpecific: No associated next objective object");
+ fail(fwd, ObjectiveError.GROUPMISSING);
+ return Collections.emptySet();
+ }
+ }
+
+ TrafficSelector filteredSelector = filteredSelectorBuilder.build();
+ TrafficTreatment treatment = treatmentBuilder.transition(aclTableId)
+ .build();
+
+ FlowRule.Builder ruleBuilder = DefaultFlowRule.builder()
+ .fromApp(fwd.appId()).withPriority(fwd.priority())
+ .forDevice(deviceId).withSelector(filteredSelector)
+ .withTreatment(treatment);
+
+ if (fwd.permanent()) {
+ ruleBuilder.makePermanent();
+ } else {
+ ruleBuilder.makeTemporary(fwd.timeout());
+ }
+
+ ruleBuilder.forTable(forTableId);
+ return Collections.singletonList(ruleBuilder.build());
+
+ }
+
+ @Override
+ //Dell switches need ETH_DST based match condition in all IP table entries.
+ //So while processing the ETH_DST based filtering objective, store
+ //the device MAC to be used locally to use it while pushing the IP rules.
+ protected List<FlowRule> processEthDstFilter(EthCriterion ethCriterion,
+ VlanIdCriterion vlanIdCriterion,
+ FilteringObjective filt,
+ VlanId assignedVlan,
+ ApplicationId applicationId) {
+ // Store device termination Mac to be used in IP flow entries
+ deviceTMac = ethCriterion.mac();
+
+ log.debug("For now not adding any TMAC rules "
+ + "into Dell switches as it is ignoring");
+
+ return Collections.emptyList();
+ }
+
+ @Override
+ protected List<FlowRule> processVlanIdFilter(VlanIdCriterion vlanIdCriterion,
+ FilteringObjective filt,
+ VlanId assignedVlan,
+ ApplicationId applicationId) {
+ log.debug("For now not adding any VLAN rules "
+ + "into Dell switches as it is ignoring");
+
+ return Collections.emptyList();
+ }
+}
\ No newline at end of file
diff --git a/drivers/default/src/main/java/org/onosproject/driver/pipeline/package-info.java b/drivers/default/src/main/java/org/onosproject/driver/pipeline/package-info.java
new file mode 100644
index 0000000..880acf5
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/pipeline/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * 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.
+ */
+
+/**
+ * Implementations of the pipeline driver behaviours.
+ */
+package org.onosproject.driver.pipeline;
\ No newline at end of file
diff --git a/drivers/default/src/main/java/org/onosproject/driver/query/CalientLambdaQuery.java b/drivers/default/src/main/java/org/onosproject/driver/query/CalientLambdaQuery.java
new file mode 100644
index 0000000..cb43e54
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/query/CalientLambdaQuery.java
@@ -0,0 +1,53 @@
+/*
+ * 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.query;
+
+import org.onlab.util.Spectrum;
+import org.onosproject.net.ChannelSpacing;
+import org.onosproject.net.GridType;
+import org.onosproject.net.OchSignal;
+import org.onosproject.net.PortNumber;
+import org.onosproject.net.behaviour.LambdaQuery;
+import org.onosproject.net.driver.AbstractHandlerBehaviour;
+
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+/**
+ * Lambda query implementation for Calient S160 and S320 Optical Circuit Switch.
+ *
+ * The device consists of OMS ports only, and each port exposes lambda resources covering the whole
+ * usable optical spectrum (U to O band, see {@link Spectrum} for spectrum definitions).
+ */
+public class CalientLambdaQuery extends AbstractHandlerBehaviour implements LambdaQuery {
+
+ @Override
+ public Set<OchSignal> queryLambdas(PortNumber port) {
+ // S160 data sheet
+ // Wavelength range: 1260 - 1630 nm
+ long startSpacingMultiplier = Spectrum.U_BAND_MIN.subtract(Spectrum.CENTER_FREQUENCY).asHz() /
+ ChannelSpacing.CHL_12P5GHZ.frequency().asHz();
+ long stopSpacingMultiplier = Spectrum.O_BAND_MAX.subtract(Spectrum.CENTER_FREQUENCY).asHz() /
+ ChannelSpacing.CHL_12P5GHZ.frequency().asHz();
+
+ // Only consider odd values for the multiplier (for easy mapping to fixed grid)
+ return IntStream.rangeClosed((int) startSpacingMultiplier, (int) stopSpacingMultiplier)
+ .filter(i -> i % 2 == 1)
+ .mapToObj(i -> new OchSignal(GridType.FLEX, ChannelSpacing.CHL_6P25GHZ, i, 1))
+ .collect(Collectors.toSet());
+ }
+}
diff --git a/drivers/default/src/main/java/org/onosproject/driver/query/DefaultTributarySlotQuery.java b/drivers/default/src/main/java/org/onosproject/driver/query/DefaultTributarySlotQuery.java
new file mode 100644
index 0000000..b5f0f48
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/query/DefaultTributarySlotQuery.java
@@ -0,0 +1,79 @@
+/*
+ * 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.query;
+
+import org.onlab.util.GuavaCollectors;
+import org.onosproject.net.OchPort;
+import org.onosproject.net.OduSignalType;
+import org.onosproject.net.Port;
+import org.onosproject.net.PortNumber;
+import org.onosproject.net.TributarySlot;
+import org.onosproject.net.device.DeviceService;
+import org.onosproject.net.driver.AbstractHandlerBehaviour;
+import org.onosproject.net.behaviour.TributarySlotQuery;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Collections;
+import java.util.Set;
+import java.util.stream.IntStream;
+
+/**
+ * TributarySlotQuery implementation which responds that all slots of ODU2 or ODU4 are available for the port.
+ */
+public class DefaultTributarySlotQuery extends AbstractHandlerBehaviour implements TributarySlotQuery {
+
+ private static final Logger log = LoggerFactory.getLogger(DefaultTributarySlotQuery.class);
+
+ private static final int TOTAL_ODU2_TRIBUTARY_SLOTS = 8;
+ private static final int TOTAL_ODU4_TRIBUTARY_SLOTS = 80;
+
+ private static Set<TributarySlot> getEntireOdu2TributarySlots() {
+ return IntStream.rangeClosed(1, TOTAL_ODU2_TRIBUTARY_SLOTS)
+ .mapToObj(TributarySlot::of)
+ .collect(GuavaCollectors.toImmutableSet());
+ }
+
+ private static Set<TributarySlot> getEntireOdu4TributarySlots() {
+ return IntStream.rangeClosed(1, TOTAL_ODU4_TRIBUTARY_SLOTS)
+ .mapToObj(TributarySlot::of)
+ .collect(GuavaCollectors.toImmutableSet());
+ }
+
+ private static final Set<TributarySlot> ENTIRE_ODU2_TRIBUTARY_SLOTS = getEntireOdu2TributarySlots();
+ private static final Set<TributarySlot> ENTIRE_ODU4_TRIBUTARY_SLOTS = getEntireOdu4TributarySlots();
+
+ @Override
+ public Set<TributarySlot> queryTributarySlots(PortNumber port) {
+ // currently return all slots by default.
+ DeviceService deviceService = this.handler().get(DeviceService.class);
+ Port p = deviceService.getPort(this.data().deviceId(), port);
+
+ if (!(p instanceof OchPort)) {
+ return Collections.emptySet();
+ }
+ OduSignalType signalType = ((OchPort) p).signalType();
+ switch (signalType) {
+ case ODU2:
+ return ENTIRE_ODU2_TRIBUTARY_SLOTS;
+ case ODU4:
+ return ENTIRE_ODU4_TRIBUTARY_SLOTS;
+ default:
+ log.error("Unsupported signal type {}", signalType);
+ return Collections.emptySet();
+ }
+ }
+}
\ No newline at end of file
diff --git a/drivers/default/src/main/java/org/onosproject/driver/query/FullMplsAvailable.java b/drivers/default/src/main/java/org/onosproject/driver/query/FullMplsAvailable.java
new file mode 100644
index 0000000..efe1912
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/query/FullMplsAvailable.java
@@ -0,0 +1,53 @@
+/*
+ * 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.query;
+
+import java.util.Set;
+import java.util.stream.IntStream;
+
+import org.onlab.packet.MplsLabel;
+import org.onlab.util.GuavaCollectors;
+import org.onosproject.net.PortNumber;
+import org.onosproject.net.behaviour.MplsQuery;
+import org.onosproject.net.driver.AbstractHandlerBehaviour;
+
+/**
+ * Driver which always responds that all MPLS Labels are available for the Device.
+ */
+public class FullMplsAvailable
+ extends AbstractHandlerBehaviour
+ implements MplsQuery {
+
+ // Ref: http://www.iana.org/assignments/mpls-label-values/mpls-label-values.xhtml
+ // Smallest non-reserved MPLS label
+ private static final int MIN_UNRESERVED_LABEL = 0x10;
+ // Max non-reserved MPLS label = 239
+ private static final int MAX_UNRESERVED_LABEL = 0xEF;
+ private static final Set<MplsLabel> ENTIRE_MPLS_LABELS = getEntireMplsLabels();
+
+
+ @Override
+ public Set<MplsLabel> queryMplsLabels(PortNumber port) {
+ return ENTIRE_MPLS_LABELS;
+ }
+
+ private static Set<MplsLabel> getEntireMplsLabels() {
+ return IntStream.range(MIN_UNRESERVED_LABEL, MAX_UNRESERVED_LABEL + 1)
+ .mapToObj(MplsLabel::mplsLabel)
+ .collect(GuavaCollectors.toImmutableSet());
+ }
+
+}
diff --git a/drivers/default/src/main/java/org/onosproject/driver/query/FullVlanAvailable.java b/drivers/default/src/main/java/org/onosproject/driver/query/FullVlanAvailable.java
new file mode 100644
index 0000000..292192a
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/query/FullVlanAvailable.java
@@ -0,0 +1,51 @@
+/*
+ * 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.query;
+
+import java.util.Set;
+import java.util.stream.IntStream;
+
+import org.onlab.packet.VlanId;
+import org.onlab.util.GuavaCollectors;
+import org.onosproject.net.PortNumber;
+import org.onosproject.net.behaviour.VlanQuery;
+import org.onosproject.net.driver.AbstractHandlerBehaviour;
+
+import com.google.common.annotations.Beta;
+
+/**
+ * Driver which always responds that all VLAN IDs are available for the Device.
+ */
+@Beta
+public class FullVlanAvailable
+ extends AbstractHandlerBehaviour
+ implements VlanQuery {
+
+ private static final int MAX_VLAN_ID = VlanId.MAX_VLAN;
+ private static final Set<VlanId> ENTIRE_VLAN = getEntireVlans();
+
+ @Override
+ public Set<VlanId> queryVlanIds(PortNumber port) {
+ return ENTIRE_VLAN;
+ }
+
+ private static Set<VlanId> getEntireVlans() {
+ return IntStream.range(0, MAX_VLAN_ID)
+ .mapToObj(x -> VlanId.vlanId((short) x))
+ .collect(GuavaCollectors.toImmutableSet());
+ }
+
+}
diff --git a/drivers/default/src/main/java/org/onosproject/driver/query/LincOELambdaQuery.java b/drivers/default/src/main/java/org/onosproject/driver/query/LincOELambdaQuery.java
new file mode 100644
index 0000000..b180f32
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/query/LincOELambdaQuery.java
@@ -0,0 +1,60 @@
+/*
+ * 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.query;
+
+import org.onosproject.net.ChannelSpacing;
+import org.onosproject.net.GridType;
+import org.onosproject.net.OchSignal;
+import org.onosproject.net.Port;
+import org.onosproject.net.PortNumber;
+import org.onosproject.net.behaviour.LambdaQuery;
+import org.onosproject.net.device.DeviceService;
+import org.onosproject.net.driver.AbstractHandlerBehaviour;
+
+import java.util.Collections;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+/**
+ * Lambda query implementation for LINC-OE Optical Emulator switch.
+ *
+ * The LINC ROADM emulator exposes two types of ports: OCh ports connect to ports in the packet layer,
+ * while OMS ports connect to an OMS port on a neighbouring ROADM.
+ *
+ * LINC exposes OchSignal resources: 80 lambdas of 50 GHz (fixed grid) around ITU-T G.694.1 center frequency 193.1 GHz.
+ */
+
+public class LincOELambdaQuery extends AbstractHandlerBehaviour implements LambdaQuery {
+
+ private static final int LAMBDA_COUNT = 80;
+
+ @Override
+ public Set<OchSignal> queryLambdas(PortNumber port) {
+ DeviceService deviceService = this.handler().get(DeviceService.class);
+ Port p = deviceService.getPort(this.data().deviceId(), port);
+
+ // OCh ports don't expose lambda resources
+ if (!p.type().equals(Port.Type.OMS)) {
+ return Collections.emptySet();
+ }
+
+ // OMS ports expose 80 fixed grid lambdas of 50GHz width, centered around the ITU-T center frequency 193.1 THz.
+ return IntStream.range(0, LAMBDA_COUNT)
+ .mapToObj(x -> new OchSignal(GridType.DWDM, ChannelSpacing.CHL_50GHZ, x - (LAMBDA_COUNT / 2), 4))
+ .collect(Collectors.toSet());
+ }
+}
diff --git a/drivers/default/src/main/java/org/onosproject/driver/query/OFOpticalSwitch13LambdaQuery.java b/drivers/default/src/main/java/org/onosproject/driver/query/OFOpticalSwitch13LambdaQuery.java
new file mode 100644
index 0000000..f01a266
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/query/OFOpticalSwitch13LambdaQuery.java
@@ -0,0 +1,63 @@
+/*
+ * 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.driver.query;
+
+import org.onosproject.net.ChannelSpacing;
+import org.onosproject.net.OchSignal;
+import org.onosproject.net.OmsPort;
+import org.onosproject.net.Port;
+import org.onosproject.net.PortNumber;
+import org.onosproject.net.behaviour.LambdaQuery;
+import org.onosproject.net.device.DeviceService;
+import org.onosproject.net.driver.AbstractHandlerBehaviour;
+
+import java.util.Collections;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+/**
+ * Lambda query implementation for OFOpticalSwitch13.
+ *
+ * Note: Standard (ONF TS-022, March 15, 2015) does not support negative values for spacingMultiplier in exp_OCH_sigid.
+ * Thus, Lambda values cannot be calculated using center and spacingMultiplier of +/- values.
+ * Therefore, Lambda values are calculated with positive values only: starting from min-frequency of 191.7 THz.
+ *
+ * TODO: When standard is fixed - modify queryLambdas accordingly.
+ *
+ * OFOpticalSwitch13 exposes OchSignal resources: 'lambdaCount' lambdas with 50GHz width (fixed grid)
+ * starting from min-frequency of 191.7 THz.
+ */
+
+public class OFOpticalSwitch13LambdaQuery extends AbstractHandlerBehaviour implements LambdaQuery {
+
+ @Override
+ public Set<OchSignal> queryLambdas(PortNumber port) {
+ DeviceService deviceService = this.handler().get(DeviceService.class);
+ Port p = deviceService.getPort(this.data().deviceId(), port);
+
+ // Only OMS ports expose lambda resources
+ if (!p.type().equals(Port.Type.OMS)) {
+ return Collections.emptySet();
+ }
+
+ short lambdaCount = ((OmsPort) p).totalChannels();
+ // OMS ports expose 'lambdaCount' fixed grid lambdas of 50GHz width, starting from min-frequency 191.7 THz.
+ return IntStream.rangeClosed(1, lambdaCount)
+ .mapToObj(x -> OchSignal.newDwdmSlot(ChannelSpacing.CHL_50GHZ, x))
+ .collect(Collectors.toSet());
+ }
+}
diff --git a/drivers/default/src/main/java/org/onosproject/driver/query/package-info.java b/drivers/default/src/main/java/org/onosproject/driver/query/package-info.java
new file mode 100644
index 0000000..84f34e4
--- /dev/null
+++ b/drivers/default/src/main/java/org/onosproject/driver/query/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * 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.
+ */
+
+/**
+ * Implementations of the resource query behaviours.
+ */
+package org.onosproject.driver.query;
diff --git a/drivers/default/src/main/resources/onos-drivers.xml b/drivers/default/src/main/resources/onos-drivers.xml
new file mode 100644
index 0000000..eb6075d
--- /dev/null
+++ b/drivers/default/src/main/resources/onos-drivers.xml
@@ -0,0 +1,181 @@
+<?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"/>
+ <behaviour api="org.onosproject.openflow.controller.driver.OpenFlowSwitchDriver"
+ impl="org.onosproject.driver.handshaker.DefaultSwitchHandshaker"/>
+ </driver>
+ <driver name="ovs" extends="default"
+ manufacturer="Nicira, Inc\." hwVersion="Open vSwitch" swVersion="2\..*">
+ <behaviour api="org.onosproject.openflow.controller.driver.OpenFlowSwitchDriver"
+ impl="org.onosproject.driver.handshaker.NiciraSwitchHandshaker"/>
+ <behaviour api="org.onosproject.openflow.controller.ExtensionTreatmentInterpreter"
+ impl="org.onosproject.driver.extensions.NiciraExtensionTreatmentInterpreter" />
+ <behaviour api="org.onosproject.net.behaviour.ExtensionTreatmentResolver"
+ impl="org.onosproject.driver.extensions.NiciraExtensionTreatmentInterpreter" />
+ <behaviour api="org.onosproject.openflow.controller.ExtensionSelectorInterpreter"
+ impl="org.onosproject.driver.extensions.NiciraExtensionSelectorInterpreter" />
+ <behaviour api="org.onosproject.net.behaviour.ExtensionSelectorResolver"
+ impl="org.onosproject.driver.extensions.NiciraExtensionSelectorInterpreter" />
+ <behaviour api="org.onosproject.net.behaviour.VlanQuery"
+ impl="org.onosproject.driver.query.FullVlanAvailable" />
+ <behaviour api="org.onosproject.net.behaviour.MplsQuery"
+ impl="org.onosproject.driver.query.FullMplsAvailable" />
+ </driver>
+ <driver name="ovs-corsa" extends="ovs"
+ manufacturer="Corsa" hwVersion="emulation" swVersion="0.0.0">
+ <behaviour api="org.onosproject.net.behaviour.Pipeliner"
+ impl="org.onosproject.driver.pipeline.OVSCorsaPipeline"/>
+ </driver>
+ <!-- Emulation of the spring-open pipeline using a CPqD OF 1.3 software switch.
+ ~ This driver is the default driver assigned to the CPqD switch.
+ -->
+ <driver name="spring-open-cpqd" extends="default"
+ manufacturer="Stanford University, Ericsson Research and CPqD Research"
+ hwVersion="OpenFlow 1.3 Reference Userspace Switch" swVersion=".*">
+ <behaviour api="org.onosproject.net.behaviour.Pipeliner"
+ impl="org.onosproject.driver.pipeline.SpringOpenTTP"/>
+ </driver>
+ <driver name="spring-open" extends="default"
+ manufacturer="Dell " hwVersion="OpenFlow switch HW ver. 1.0"
+ swVersion="OpenFlow switch SW ver. 1.0 and 1.3">
+ <behaviour api="org.onosproject.net.behaviour.Pipeliner"
+ impl="org.onosproject.driver.pipeline.SpringOpenTTPDell"/>
+ </driver>
+ <driver name="linc-oe" extends="default"
+ manufacturer="FlowForwarding.org" hwVersion="Unknown"
+ swVersion="LINC-OE OpenFlow Software Switch 1.1">
+ <behaviour api="org.onosproject.openflow.controller.driver.OpenFlowSwitchDriver"
+ impl="org.onosproject.driver.handshaker.OfOpticalSwitchImplLinc13"/>
+ <behaviour api="org.onosproject.net.behaviour.LambdaQuery"
+ impl="org.onosproject.driver.query.LincOELambdaQuery"/>
+ </driver>
+ <driver name="corsa"
+ manufacturer="Corsa" hwVersion="Corsa Element" swVersion="2.3.1">
+ <behaviour api="org.onosproject.net.behaviour.Pipeliner"
+ impl="org.onosproject.driver.pipeline.CorsaPipeline"/>
+ <behaviour api="org.onosproject.openflow.controller.driver.OpenFlowSwitchDriver"
+ impl="org.onosproject.driver.handshaker.CorsaSwitchHandshaker"/>
+ </driver>
+ <driver name="corsa-v1"
+ manufacturer="Corsa" hwVersion="Corsa Element" swVersion="2.3.1">
+ <behaviour api="org.onosproject.net.behaviour.Pipeliner"
+ impl="org.onosproject.driver.pipeline.CorsaPipeline"/>
+ <behaviour api="org.onosproject.openflow.controller.driver.OpenFlowSwitchDriver"
+ impl="org.onosproject.driver.handshaker.CorsaSwitchHandshaker"/>
+ </driver>
+ <driver name="corsa-v3"
+ manufacturer="Corsa" hwVersion="Corsa Element" swVersion="2.3.1">
+ <behaviour api="org.onosproject.net.behaviour.Pipeliner"
+ impl="org.onosproject.driver.pipeline.CorsaPipelineV3"/>
+ <behaviour api="org.onosproject.openflow.controller.driver.OpenFlowSwitchDriver"
+ impl="org.onosproject.driver.handshaker.CorsaSwitchHandshaker"/>
+ </driver>
+ <driver name="ofdpa" extends="default"
+ manufacturer="Broadcom Corp." hwVersion="OF-DPA.*" swVersion="OF-DPA.*">
+ <behaviour api="org.onosproject.net.behaviour.Pipeliner"
+ impl="org.onosproject.driver.pipeline.OFDPA2Pipeline"/>
+ </driver>
+ <driver name="pmc-olt" extends="default"
+ manufacturer="PMC GPON Networks" hwVersion="PASffffffff v-1" swVersion="vOLT.*">
+ <behaviour api="org.onosproject.net.behaviour.Pipeliner"
+ impl="org.onosproject.driver.pipeline.OltPipeline"/>
+ </driver>
+ <driver name="fj-olt" extends="default"
+ manufacturer="Fujitsu" hwVersion="svkOLT" swVersion="v1.0">
+ <behaviour api="org.onosproject.net.behaviour.Pipeliner"
+ impl="org.onosproject.driver.pipeline.OltPipeline"/>
+ </driver>
+ <driver name="g.fast" extends="default"
+ manufacturer="TEST1" hwVersion="TEST2" swVersion="TEST3">
+ <behaviour api="org.onosproject.net.behaviour.Pipeliner"
+ impl="org.onosproject.driver.pipeline.OltPipeline"/>
+ </driver>
+ <!-- The SoftRouter driver is meant to be used by any software/NPU based
+ ~ switch that wishes to implement a simple 2-table router. To use this
+ ~ driver, configure ONOS with the dpid of the device, or extend the
+ ~ driver declaration with the manufacturer/hwVersion/swVersion of the
+ ~ device (see 'noviflow' example).
+ -->
+ <driver name="softrouter" extends="default"
+ manufacturer="Various" hwVersion="various" swVersion="0.0.0">
+ <behaviour api="org.onosproject.net.behaviour.Pipeliner"
+ impl="org.onosproject.driver.pipeline.SoftRouterPipeline"/>
+ </driver>
+ <driver name="centec-V350" extends="default"
+ manufacturer=".*Centec.*" hwVersion=".*" swVersion="3.1.*">
+ <behaviour api="org.onosproject.net.behaviour.Pipeliner"
+ impl="org.onosproject.driver.pipeline.CentecV350Pipeline"/>
+ </driver>
+ <driver name="pica" extends="default"
+ manufacturer="Pica8, Inc." hwVersion=".*" swVersion="PicOS 2.6">
+ <behaviour api="org.onosproject.net.behaviour.Pipeliner"
+ impl="org.onosproject.driver.pipeline.PicaPipeline"/>
+ </driver>
+ <driver name="noviflow" extends="softrouter"
+ manufacturer="NoviFlow Inc" hwVersion="NS.*" swVersion="NW.*">
+ </driver>
+ <!-- Emulation of the ofdpa pipeline using a CPqD OF 1.3 software switch.
+ ~ To use this driver, configure ONOS with the dpid of the device.
+ -->
+ <driver name="ofdpa-cpqd" extends="default"
+ manufacturer="ONF"
+ hwVersion="OF1.3 Software Switch from CPqD" swVersion="for Group Chaining">
+ <behaviour api="org.onosproject.net.behaviour.Pipeliner"
+ impl="org.onosproject.driver.pipeline.CpqdOFDPA2Pipeline"/>
+ </driver>
+ <driver name="calient" extends="default"
+ manufacturer="calient inc" hwVersion="calient hardware"
+ swVersion="ocs switch">
+ <behaviour api="org.onosproject.openflow.controller.driver.OpenFlowSwitchDriver"
+ impl="org.onosproject.driver.handshaker.CalientFiberSwitchHandshaker"/>
+ <behaviour api="org.onosproject.net.behaviour.LambdaQuery"
+ impl="org.onosproject.driver.query.CalientLambdaQuery"/>
+ </driver>
+ <driver name="onosfw" extends="ovs"
+ manufacturer="" hwVersion="" swVersion="">
+ <behaviour api="org.onosproject.net.behaviour.Pipeliner"
+ impl="org.onosproject.driver.pipeline.OpenVSwitchPipeline"/>
+ </driver>
+ <driver name="eci" extends="default"
+ manufacturer="ECI Telecom" hwVersion="Optical.*" swVersion="V_1_0">
+ <behaviour api="org.onosproject.openflow.controller.driver.OpenFlowSwitchDriver"
+ impl="org.onosproject.driver.handshaker.OFOpticalSwitch13"/>
+ <behaviour api="org.onosproject.net.behaviour.TributarySlotQuery"
+ impl="org.onosproject.driver.query.DefaultTributarySlotQuery" />
+ <behaviour api="org.onosproject.net.behaviour.LambdaQuery"
+ impl="org.onosproject.driver.query.OFOpticalSwitch13LambdaQuery"/>
+ </driver>
+ <driver name="aos" extends="ofdpa"
+ manufacturer="Accton" hwVersion=".*" swVersion="1.*">
+ </driver>
+ <driver name="sona" extends="ovs"
+ manufacturer="" hwVersion="" swVersion="">
+ <behaviour api="org.onosproject.net.behaviour.Pipeliner"
+ impl="org.onosproject.driver.pipeline.OpenstackPipeline"/>
+ </driver>
+ <driver name="oplk-roadm" extends="default"
+ manufacturer="Oplink a Molex company" hwVersion="ROADM"
+ swVersion="of-agent">
+ <behaviour api="org.onosproject.openflow.controller.driver.OpenFlowSwitchDriver"
+ impl="org.onosproject.driver.handshaker.OplinkRoadmHandshaker"/>
+ </driver>
+</drivers>
+
diff --git a/drivers/default/src/test/java/org/onosproject/driver/extensions/NiciraSetNshContextHeaderTest.java b/drivers/default/src/test/java/org/onosproject/driver/extensions/NiciraSetNshContextHeaderTest.java
new file mode 100644
index 0000000..5993acf
--- /dev/null
+++ b/drivers/default/src/test/java/org/onosproject/driver/extensions/NiciraSetNshContextHeaderTest.java
@@ -0,0 +1,69 @@
+/*
+ * 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.extensions;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.is;
+import static org.hamcrest.Matchers.notNullValue;
+
+import org.junit.Test;
+import org.onosproject.net.NshContextHeader;
+import org.onosproject.net.flow.instructions.ExtensionTreatmentType;
+
+import com.google.common.testing.EqualsTester;
+
+/**
+ * Unit tests for NiciraSetNshContextHeader class.
+ */
+public class NiciraSetNshContextHeaderTest {
+
+ final NiciraSetNshContextHeader nshCh1 = new NiciraSetNshContextHeader(NshContextHeader.of(10),
+ ExtensionTreatmentType.
+ ExtensionTreatmentTypes.
+ NICIRA_SET_NSH_CH1.type());
+ final NiciraSetNshContextHeader sameAsNshCh1 = new NiciraSetNshContextHeader(NshContextHeader.of(10),
+ ExtensionTreatmentType.
+ ExtensionTreatmentTypes.
+ NICIRA_SET_NSH_CH1.type());
+ final NiciraSetNshContextHeader nshCh2 = new NiciraSetNshContextHeader(NshContextHeader.of(20),
+ ExtensionTreatmentType.
+ ExtensionTreatmentTypes.
+ NICIRA_SET_NSH_CH1.type());
+
+ /**
+ * Checks the operation of equals() methods.
+ */
+ @Test
+ public void testEquals() {
+ new EqualsTester().addEqualityGroup(nshCh1, sameAsNshCh1).addEqualityGroup(nshCh2).testEquals();
+ }
+
+ /**
+ * Checks the construction of a NiciraSetNshSi object.
+ */
+ @Test
+ public void testConstruction() {
+ final NiciraSetNshContextHeader niciraSetNshCh = new NiciraSetNshContextHeader(NshContextHeader.of(10),
+ ExtensionTreatmentType.
+ ExtensionTreatmentTypes.
+ NICIRA_SET_NSH_CH1.type());
+ assertThat(niciraSetNshCh, is(notNullValue()));
+ assertThat(niciraSetNshCh.nshCh().nshContextHeader(), is(10));
+ assertThat(niciraSetNshCh.type(), is(ExtensionTreatmentType.
+ ExtensionTreatmentTypes.
+ NICIRA_SET_NSH_CH1.type()));
+ }
+}
diff --git a/drivers/default/src/test/java/org/onosproject/driver/extensions/NiciraSetNshSiTest.java b/drivers/default/src/test/java/org/onosproject/driver/extensions/NiciraSetNshSiTest.java
new file mode 100644
index 0000000..7113417
--- /dev/null
+++ b/drivers/default/src/test/java/org/onosproject/driver/extensions/NiciraSetNshSiTest.java
@@ -0,0 +1,53 @@
+/*
+ * 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.extensions;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.is;
+import static org.hamcrest.Matchers.notNullValue;
+
+import org.junit.Test;
+import org.onosproject.net.NshServiceIndex;
+
+import com.google.common.testing.EqualsTester;
+
+/**
+ * Unit tests for NiciraSetNshSi class.
+ */
+public class NiciraSetNshSiTest {
+
+ final NiciraSetNshSi nshSi1 = new NiciraSetNshSi(NshServiceIndex.of((short) 10));
+ final NiciraSetNshSi sameAsNshSi1 = new NiciraSetNshSi(NshServiceIndex.of((short) 10));
+ final NiciraSetNshSi nshSi2 = new NiciraSetNshSi(NshServiceIndex.of((short) 20));
+
+ /**
+ * Checks the operation of equals() methods.
+ */
+ @Test
+ public void testEquals() {
+ new EqualsTester().addEqualityGroup(nshSi1, sameAsNshSi1).addEqualityGroup(nshSi2).testEquals();
+ }
+
+ /**
+ * Checks the construction of a NiciraSetNshSi object.
+ */
+ @Test
+ public void testConstruction() {
+ final NiciraSetNshSi niciraSetNshSi = new NiciraSetNshSi(NshServiceIndex.of((short) 15));
+ assertThat(niciraSetNshSi, is(notNullValue()));
+ assertThat(niciraSetNshSi.nshSi().serviceIndex(), is((short) 15));
+ }
+}
diff --git a/drivers/default/src/test/java/org/onosproject/driver/extensions/NiciraSetNshSpiTest.java b/drivers/default/src/test/java/org/onosproject/driver/extensions/NiciraSetNshSpiTest.java
new file mode 100644
index 0000000..5650c82
--- /dev/null
+++ b/drivers/default/src/test/java/org/onosproject/driver/extensions/NiciraSetNshSpiTest.java
@@ -0,0 +1,53 @@
+/*
+ * 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.extensions;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.is;
+import static org.hamcrest.Matchers.notNullValue;
+
+import org.junit.Test;
+import org.onosproject.net.NshServicePathId;
+
+import com.google.common.testing.EqualsTester;
+
+/**
+ * Unit tests for NiciraSetNshSpi class.
+ */
+public class NiciraSetNshSpiTest {
+
+ final NiciraSetNshSpi nshSpi1 = new NiciraSetNshSpi(NshServicePathId.of(10));
+ final NiciraSetNshSpi sameAsNshSpi1 = new NiciraSetNshSpi(NshServicePathId.of(10));
+ final NiciraSetNshSpi nshSpi2 = new NiciraSetNshSpi(NshServicePathId.of(20));
+
+ /**
+ * Checks the operation of equals() methods.
+ */
+ @Test
+ public void testEquals() {
+ new EqualsTester().addEqualityGroup(nshSpi1, sameAsNshSpi1).addEqualityGroup(nshSpi2).testEquals();
+ }
+
+ /**
+ * Checks the construction of a NiciraSetNshSpi object.
+ */
+ @Test
+ public void testConstruction() {
+ final NiciraSetNshSpi niciraSetNshSpi = new NiciraSetNshSpi(NshServicePathId.of(10));
+ assertThat(niciraSetNshSpi, is(notNullValue()));
+ assertThat(niciraSetNshSpi.nshSpi().servicePathId(), is(10));
+ }
+}