MyTunnel P4 tutorial app and pipeconf

Change-Id: I0549276fc7f6c8d0d244d6c52b1b9e85b9c3e13c
diff --git a/apps/p4-tutorial/pipeconf/src/main/java/org/onosproject/p4tutorial/pipeconf/PipeconfFactory.java b/apps/p4-tutorial/pipeconf/src/main/java/org/onosproject/p4tutorial/pipeconf/PipeconfFactory.java
index 5d37bd1..47fad41 100644
--- a/apps/p4-tutorial/pipeconf/src/main/java/org/onosproject/p4tutorial/pipeconf/PipeconfFactory.java
+++ b/apps/p4-tutorial/pipeconf/src/main/java/org/onosproject/p4tutorial/pipeconf/PipeconfFactory.java
@@ -45,8 +45,8 @@
 public final class PipeconfFactory {
 
     public static final PiPipeconfId PIPECONF_ID = new PiPipeconfId("p4-tutorial-pipeconf");
-    private static final URL P4INFO_URL = PipeconfFactory.class.getResource("/main.p4info");
-    private static final URL BMV2_JSON_URL = PipeconfFactory.class.getResource("/main.json");
+    private static final URL P4INFO_URL = PipeconfFactory.class.getResource("/mytunnel.p4info");
+    private static final URL BMV2_JSON_URL = PipeconfFactory.class.getResource("/mytunnel.json");
 
     @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
     private PiPipeconfService piPipeconfService;
@@ -75,7 +75,7 @@
                 .withPipelineModel(pipelineModel)
                 .addBehaviour(PiPipelineInterpreter.class, PipelineInterpreterImpl.class)
                 .addBehaviour(PortStatisticsDiscovery.class, PortStatisticsDiscoveryImpl.class)
-                // Since main.p4 defines only 1 table, we re-use the existing single-table pipeliner.
+                // Since mytunnel.p4 defines only 1 table, we re-use the existing single-table pipeliner.
                 .addBehaviour(Pipeliner.class, DefaultSingleTablePipeline.class)
                 .addExtension(P4_INFO_TEXT, P4INFO_URL)
                 .addExtension(BMV2_JSON, BMV2_JSON_URL)
diff --git a/apps/p4-tutorial/pipeconf/src/main/java/org/onosproject/p4tutorial/pipeconf/PipelineInterpreterImpl.java b/apps/p4-tutorial/pipeconf/src/main/java/org/onosproject/p4tutorial/pipeconf/PipelineInterpreterImpl.java
index a34cada..58afa10 100644
--- a/apps/p4-tutorial/pipeconf/src/main/java/org/onosproject/p4tutorial/pipeconf/PipelineInterpreterImpl.java
+++ b/apps/p4-tutorial/pipeconf/src/main/java/org/onosproject/p4tutorial/pipeconf/PipelineInterpreterImpl.java
@@ -19,10 +19,12 @@
 import com.google.common.collect.BiMap;
 import com.google.common.collect.ImmutableBiMap;
 import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
 import org.onlab.packet.DeserializationException;
 import org.onlab.packet.Ethernet;
 import org.onlab.util.ImmutableByteSequence;
 import org.onosproject.net.ConnectPoint;
+import org.onosproject.net.DeviceId;
 import org.onosproject.net.Port;
 import org.onosproject.net.PortNumber;
 import org.onosproject.net.device.DeviceService;
@@ -30,7 +32,7 @@
 import org.onosproject.net.flow.TrafficTreatment;
 import org.onosproject.net.flow.criteria.Criterion;
 import org.onosproject.net.flow.instructions.Instruction;
-import org.onosproject.net.flow.instructions.Instructions;
+import org.onosproject.net.flow.instructions.Instructions.OutputInstruction;
 import org.onosproject.net.packet.DefaultInboundPacket;
 import org.onosproject.net.packet.InboundPacket;
 import org.onosproject.net.packet.OutboundPacket;
@@ -51,7 +53,6 @@
 import java.util.Optional;
 
 import static java.lang.String.format;
-import static java.util.stream.Collectors.toList;
 import static org.onlab.util.ImmutableByteSequence.copyFrom;
 import static org.onosproject.net.PortNumber.CONTROLLER;
 import static org.onosproject.net.PortNumber.FLOOD;
@@ -59,34 +60,48 @@
 import static org.onosproject.net.pi.model.PiPacketOperationType.PACKET_OUT;
 
 /**
- * Implementation of a PI interpreter for the main.p4 program.
+ * Implementation of a pipeline interpreter for the mytunnel.p4 program.
  */
-public final class PipelineInterpreterImpl extends AbstractHandlerBehaviour implements PiPipelineInterpreter {
+public final class PipelineInterpreterImpl
+        extends AbstractHandlerBehaviour
+        implements PiPipelineInterpreter {
 
-    private static final String DOT =  ".";
+    private static final String DOT = ".";
     private static final String HDR = "hdr";
-    private static final String TABLE0 = "table0";
-    private static final String IP_PROTO_FILTER_TABLE = "ip_proto_filter_table";
-    private static final String SEND_TO_CPU = "send_to_cpu";
-    private static final String PORT = "port";
-    private static final String DROP = "_drop";
-    private static final String SET_EGRESS_PORT = "set_egress_port";
+    private static final String C_INGRESS = "c_ingress";
+    private static final String T_L2_FWD = "t_l2_fwd";
     private static final String EGRESS_PORT = "egress_port";
     private static final String INGRESS_PORT = "ingress_port";
     private static final String ETHERNET = "ethernet";
     private static final String STANDARD_METADATA = "standard_metadata";
     private static final int PORT_FIELD_BITWIDTH = 9;
 
-    private static final PiMatchFieldId INGRESS_PORT_ID = PiMatchFieldId.of(STANDARD_METADATA + DOT + "ingress_port");
-    private static final PiMatchFieldId ETH_DST_ID = PiMatchFieldId.of(HDR + DOT + ETHERNET + DOT + "dst_addr");
-    private static final PiMatchFieldId ETH_SRC_ID = PiMatchFieldId.of(HDR + DOT + ETHERNET + DOT + "src_addr");
-    private static final PiMatchFieldId ETH_TYPE_ID = PiMatchFieldId.of(HDR + DOT + ETHERNET + DOT + "ether_type");
-    private static final PiTableId TABLE0_ID = PiTableId.of(TABLE0);
-    private static final PiTableId IP_PROTO_FILTER_TABLE_ID = PiTableId.of(IP_PROTO_FILTER_TABLE);
+    private static final PiMatchFieldId INGRESS_PORT_ID =
+            PiMatchFieldId.of(STANDARD_METADATA + DOT + "ingress_port");
+    private static final PiMatchFieldId ETH_DST_ID =
+            PiMatchFieldId.of(HDR + DOT + ETHERNET + DOT + "dst_addr");
+    private static final PiMatchFieldId ETH_SRC_ID =
+            PiMatchFieldId.of(HDR + DOT + ETHERNET + DOT + "src_addr");
+    private static final PiMatchFieldId ETH_TYPE_ID =
+            PiMatchFieldId.of(HDR + DOT + ETHERNET + DOT + "ether_type");
 
-    private static final BiMap<Integer, PiTableId> TABLE_MAP = ImmutableBiMap.of(
-            0, TABLE0_ID,
-            1, IP_PROTO_FILTER_TABLE_ID);
+    private static final PiTableId TABLE_L2_FWD_ID =
+            PiTableId.of(C_INGRESS + DOT + T_L2_FWD);
+
+    private static final PiActionId ACT_ID_NOP =
+            PiActionId.of("NoAction");
+    private static final PiActionId ACT_ID_SEND_TO_CPU =
+            PiActionId.of(C_INGRESS + DOT + "send_to_cpu");
+    private static final PiActionId ACT_ID_SET_EGRESS_PORT =
+            PiActionId.of(C_INGRESS + DOT + "set_egress_port");
+
+    private static final PiActionParamId ACT_PARAM_ID_PORT =
+            PiActionParamId.of("port");
+
+    private static final BiMap<Integer, PiTableId> TABLE_MAP =
+            new ImmutableBiMap.Builder<Integer, PiTableId>()
+                    .put(0, TABLE_L2_FWD_ID)
+                    .build();
 
     private static final BiMap<Criterion.Type, PiMatchFieldId> CRITERION_MAP =
             new ImmutableBiMap.Builder<Criterion.Type, PiMatchFieldId>()
@@ -97,129 +112,6 @@
                     .build();
 
     @Override
-    public PiAction mapTreatment(TrafficTreatment treatment, PiTableId piTableId)
-            throws PiInterpreterException {
-
-        if (treatment.allInstructions().size() == 0) {
-            // No instructions means drop for us.
-            return PiAction.builder()
-                    .withId(PiActionId.of(DROP))
-                    .build();
-        } else if (treatment.allInstructions().size() > 1) {
-            // We understand treatments with only 1 instruction.
-            throw new PiInterpreterException("Treatment has multiple instructions");
-        }
-
-        // Get the first and only instruction.
-        Instruction instruction = treatment.allInstructions().get(0);
-
-        switch (instruction.type()) {
-            case OUTPUT:
-                // We understand only instructions of type OUTPUT.
-                Instructions.OutputInstruction outInstruction = (Instructions.OutputInstruction) instruction;
-                PortNumber port = outInstruction.port();
-                if (!port.isLogical()) {
-                    return PiAction.builder()
-                            .withId(PiActionId.of(SET_EGRESS_PORT))
-                            .withParameter(new PiActionParam(PiActionParamId.of(PORT), copyFrom(port.toLong())))
-                            .build();
-                } else if (port.equals(CONTROLLER)) {
-                    return PiAction.builder()
-                            .withId(PiActionId.of(SEND_TO_CPU))
-                            .build();
-                } else {
-                    throw new PiInterpreterException(format("Output on logical port '%s' not supported", port));
-                }
-            default:
-                throw new PiInterpreterException(format("Instruction of type '%s' not supported", instruction.type()));
-        }
-    }
-
-    @Override
-    public Collection<PiPacketOperation> mapOutboundPacket(OutboundPacket packet)
-            throws PiInterpreterException {
-
-        TrafficTreatment treatment = packet.treatment();
-
-        // We support only packet-out with OUTPUT instructions.
-        List<Instructions.OutputInstruction> outInstructions = treatment.allInstructions().stream()
-                .filter(i -> i.type().equals(OUTPUT))
-                .map(i -> (Instructions.OutputInstruction) i)
-                .collect(toList());
-
-        if (treatment.allInstructions().size() != outInstructions.size()) {
-            // There are other instructions that are not of type OUTPUT.
-            throw new PiInterpreterException("Treatment not supported: " + treatment);
-        }
-
-        ImmutableList.Builder<PiPacketOperation> builder = ImmutableList.builder();
-
-        for (Instructions.OutputInstruction outInst : outInstructions) {
-            if (outInst.port().isLogical() && !outInst.port().equals(FLOOD)) {
-                throw new PiInterpreterException(format("Output on logical port '%s' not supported", outInst.port()));
-            } else if (outInst.port().equals(FLOOD)) {
-                // Since main.p4 does not support flooding, we create a packet operation for each switch port.
-                DeviceService deviceService = handler().get(DeviceService.class);
-                for (Port port : deviceService.getPorts(packet.sendThrough())) {
-                    builder.add(createPiPacketOperation(packet.data(), port.number().toLong()));
-                }
-            } else {
-                builder.add(createPiPacketOperation(packet.data(), outInst.port().toLong()));
-            }
-        }
-        return builder.build();
-    }
-
-    @Override
-    public InboundPacket mapInboundPacket(PiPacketOperation packetIn)
-            throws PiInterpreterException {
-        // We assume that the packet is ethernet, which is fine since default.p4 can deparse only ethernet packets.
-        Ethernet ethPkt;
-        try {
-            ethPkt = Ethernet.deserializer().deserialize(packetIn.data().asArray(), 0, packetIn.data().size());
-        } catch (DeserializationException dex) {
-            throw new PiInterpreterException(dex.getMessage());
-        }
-
-        // Returns the ingress port packet metadata.
-        Optional<PiControlMetadata> packetMetadata = packetIn.metadatas().stream()
-                .filter(metadata -> metadata.id().toString().equals(INGRESS_PORT))
-                .findFirst();
-
-        if (packetMetadata.isPresent()) {
-            ImmutableByteSequence portByteSequence = packetMetadata.get().value();
-            short s = portByteSequence.asReadOnlyBuffer().getShort();
-            ConnectPoint receivedFrom = new ConnectPoint(packetIn.deviceId(), PortNumber.portNumber(s));
-            return new DefaultInboundPacket(receivedFrom, ethPkt, packetIn.data().asReadOnlyBuffer());
-        } else {
-            throw new PiInterpreterException(format(
-                    "Missing metadata '%s' in packet-in received from '%s': %s",
-                    INGRESS_PORT, packetIn.deviceId(), packetIn));
-        }
-    }
-
-    private PiPacketOperation createPiPacketOperation(ByteBuffer data, long portNumber) throws PiInterpreterException {
-        PiControlMetadata metadata = createControlMetadata(portNumber);
-        return PiPacketOperation.builder()
-                .forDevice(this.data().deviceId())
-                .withType(PACKET_OUT)
-                .withData(copyFrom(data))
-                .withMetadatas(ImmutableList.of(metadata))
-                .build();
-    }
-
-    private PiControlMetadata createControlMetadata(long portNumber) throws PiInterpreterException {
-        try {
-            return PiControlMetadata.builder()
-                    .withId(PiControlMetadataId.of(EGRESS_PORT))
-                    .withValue(copyFrom(portNumber).fit(PORT_FIELD_BITWIDTH))
-                    .build();
-        } catch (ImmutableByteSequence.ByteSequenceTrimException e) {
-            throw new PiInterpreterException(format("Port number %d too big, %s", portNumber, e.getMessage()));
-        }
-    }
-
-    @Override
     public Optional<PiMatchFieldId> mapCriterionType(Criterion.Type type) {
         return Optional.ofNullable(CRITERION_MAP.get(type));
     }
@@ -238,4 +130,139 @@
     public Optional<Integer> mapPiTableId(PiTableId piTableId) {
         return Optional.ofNullable(TABLE_MAP.inverse().get(piTableId));
     }
+
+    @Override
+    public PiAction mapTreatment(TrafficTreatment treatment, PiTableId piTableId)
+            throws PiInterpreterException {
+
+        if (piTableId != TABLE_L2_FWD_ID) {
+            throw new PiInterpreterException(
+                    "Can map treatments only for 't_l2_fwd' table");
+        }
+
+        if (treatment.allInstructions().size() == 0) {
+            // 0 instructions means "NoAction"
+            return PiAction.builder().withId(ACT_ID_NOP).build();
+        } else if (treatment.allInstructions().size() > 1) {
+            // We understand treatments with only 1 instruction.
+            throw new PiInterpreterException("Treatment has multiple instructions");
+        }
+
+        // Get the first and only instruction.
+        Instruction instruction = treatment.allInstructions().get(0);
+
+        if (instruction.type() != OUTPUT) {
+            // We can map only instructions of type OUTPUT.
+            throw new PiInterpreterException(format(
+                    "Instruction of type '%s' not supported", instruction.type()));
+        }
+
+        OutputInstruction outInstruction = (OutputInstruction) instruction;
+        PortNumber port = outInstruction.port();
+        if (!port.isLogical()) {
+            return PiAction.builder()
+                    .withId(ACT_ID_SET_EGRESS_PORT)
+                    .withParameter(new PiActionParam(
+                            ACT_PARAM_ID_PORT, copyFrom(port.toLong())))
+                    .build();
+        } else if (port.equals(CONTROLLER)) {
+            return PiAction.builder()
+                    .withId(ACT_ID_SEND_TO_CPU)
+                    .build();
+        } else {
+            throw new PiInterpreterException(format(
+                    "Output on logical port '%s' not supported", port));
+        }
+    }
+
+    @Override
+    public Collection<PiPacketOperation> mapOutboundPacket(OutboundPacket packet)
+            throws PiInterpreterException {
+
+        TrafficTreatment treatment = packet.treatment();
+
+        // We support only packet-out with OUTPUT instructions.
+        if (treatment.allInstructions().size() != 1 &&
+                treatment.allInstructions().get(0).type() != OUTPUT) {
+            throw new PiInterpreterException(
+                    "Treatment not supported: " + treatment.toString());
+        }
+
+        Instruction instruction = treatment.allInstructions().get(0);
+        PortNumber port = ((OutputInstruction) instruction).port();
+        List<PiPacketOperation> piPacketOps = Lists.newArrayList();
+
+        if (!port.isLogical()) {
+            piPacketOps.add(createPiPacketOp(packet.data(), port.toLong()));
+        } else if (port.equals(FLOOD)) {
+            // Since mytunnel.p4 does not support flooding, we create a packet
+            // operation for each switch port.
+            DeviceService deviceService = handler().get(DeviceService.class);
+            DeviceId deviceId = packet.sendThrough();
+            for (Port p : deviceService.getPorts(deviceId)) {
+                piPacketOps.add(createPiPacketOp(packet.data(), p.number().toLong()));
+            }
+        } else {
+            throw new PiInterpreterException(format(
+                    "Output on logical port '%s' not supported", port));
+        }
+
+        return piPacketOps;
+    }
+
+    @Override
+    public InboundPacket mapInboundPacket(PiPacketOperation packetIn)
+            throws PiInterpreterException {
+        // We assume that the packet is ethernet, which is fine since mytunnel.p4
+        // can deparse only ethernet packets.
+        Ethernet ethPkt;
+
+        try {
+            ethPkt = Ethernet.deserializer().deserialize(
+                    packetIn.data().asArray(), 0, packetIn.data().size());
+        } catch (DeserializationException dex) {
+            throw new PiInterpreterException(dex.getMessage());
+        }
+
+        // Returns the ingress port packet metadata.
+        Optional<PiControlMetadata> packetMetadata = packetIn.metadatas().stream()
+                .filter(metadata -> metadata.id().toString().equals(INGRESS_PORT))
+                .findFirst();
+
+        if (packetMetadata.isPresent()) {
+            short s = packetMetadata.get().value().asReadOnlyBuffer().getShort();
+            ConnectPoint receivedFrom = new ConnectPoint(
+                    packetIn.deviceId(), PortNumber.portNumber(s));
+            return new DefaultInboundPacket(
+                    receivedFrom, ethPkt, packetIn.data().asReadOnlyBuffer());
+        } else {
+            throw new PiInterpreterException(format(
+                    "Missing metadata '%s' in packet-in received from '%s': %s",
+                    INGRESS_PORT, packetIn.deviceId(), packetIn));
+        }
+    }
+
+    private PiPacketOperation createPiPacketOp(ByteBuffer data, long portNumber)
+            throws PiInterpreterException {
+        PiControlMetadata metadata = createControlMetadata(portNumber);
+        return PiPacketOperation.builder()
+                .forDevice(this.data().deviceId())
+                .withType(PACKET_OUT)
+                .withData(copyFrom(data))
+                .withMetadatas(ImmutableList.of(metadata))
+                .build();
+    }
+
+    private PiControlMetadata createControlMetadata(long portNumber)
+            throws PiInterpreterException {
+        try {
+            return PiControlMetadata.builder()
+                    .withId(PiControlMetadataId.of(EGRESS_PORT))
+                    .withValue(copyFrom(portNumber).fit(PORT_FIELD_BITWIDTH))
+                    .build();
+        } catch (ImmutableByteSequence.ByteSequenceTrimException e) {
+            throw new PiInterpreterException(format(
+                    "Port number %d too big, %s", portNumber, e.getMessage()));
+        }
+    }
 }
diff --git a/apps/p4-tutorial/pipeconf/src/main/java/org/onosproject/p4tutorial/pipeconf/PortStatisticsDiscoveryImpl.java b/apps/p4-tutorial/pipeconf/src/main/java/org/onosproject/p4tutorial/pipeconf/PortStatisticsDiscoveryImpl.java
index 1f204e2..f5fd70c 100644
--- a/apps/p4-tutorial/pipeconf/src/main/java/org/onosproject/p4tutorial/pipeconf/PortStatisticsDiscoveryImpl.java
+++ b/apps/p4-tutorial/pipeconf/src/main/java/org/onosproject/p4tutorial/pipeconf/PortStatisticsDiscoveryImpl.java
@@ -44,15 +44,15 @@
 import static org.onosproject.net.pi.model.PiCounterType.INDIRECT;
 
 /**
- * Implementation of the PortStatisticsDiscovery behaviour for the main.p4 program. This behaviour works by using a
+ * Implementation of the PortStatisticsDiscovery behaviour for the mytunnel.p4 program. This behaviour works by using a
  * P4Runtime client to read the values of the ingress/egress port counters defined in the P4 program.
  */
 public final class PortStatisticsDiscoveryImpl extends AbstractHandlerBehaviour implements PortStatisticsDiscovery {
 
     private static final Logger log = LoggerFactory.getLogger(PortStatisticsDiscoveryImpl.class);
 
-    private static final PiCounterId INGRESS_COUNTER_ID = PiCounterId.of("igr_port_counter");
-    private static final PiCounterId EGRESS_COUNTER_ID = PiCounterId.of("egr_port_counter");
+    private static final PiCounterId INGRESS_COUNTER_ID = PiCounterId.of("c_ingress.rx_port_counter");
+    private static final PiCounterId EGRESS_COUNTER_ID = PiCounterId.of("c_ingress.tx_port_counter");
 
     @Override
     public Collection<PortStatistics> discoverPortStatistics() {