Reusable implementation of default P4 interpreter

That can be shared among many targets running a program equivalent to
default.p4.

Change-Id: Ic13fc4e416f4ad77f71fbd3202277aac9088b3b1
diff --git a/apps/p4runtime-test/src/test/java/org/onosproject/p4runtime/test/P4RuntimeTest.java b/apps/p4runtime-test/src/test/java/org/onosproject/p4runtime/test/P4RuntimeTest.java
index 9e7e9f8..74e6845 100644
--- a/apps/p4runtime-test/src/test/java/org/onosproject/p4runtime/test/P4RuntimeTest.java
+++ b/apps/p4runtime-test/src/test/java/org/onosproject/p4runtime/test/P4RuntimeTest.java
@@ -23,13 +23,10 @@
 import org.junit.Ignore;
 import org.junit.Test;
 import org.onlab.util.ImmutableByteSequence;
-import org.onosproject.bmv2.model.Bmv2PipelineModelParser;
-import org.onosproject.drivers.bmv2.Bmv2DefaultInterpreter;
+import org.onosproject.drivers.bmv2.Bmv2DefaultPipeconfFactory;
 import org.onosproject.grpc.ctl.GrpcControllerImpl;
 import org.onosproject.net.DeviceId;
-import org.onosproject.net.pi.model.DefaultPiPipeconf;
 import org.onosproject.net.pi.model.PiPipeconf;
-import org.onosproject.net.pi.model.PiPipeconfId;
 import org.onosproject.net.pi.model.PiPipelineInterpreter;
 import org.onosproject.net.pi.runtime.PiAction;
 import org.onosproject.net.pi.runtime.PiActionId;
@@ -54,7 +51,6 @@
 
 import static org.onlab.util.ImmutableByteSequence.*;
 import static org.onosproject.net.pi.model.PiPipeconf.ExtensionType.BMV2_JSON;
-import static org.onosproject.net.pi.model.PiPipeconf.ExtensionType.P4_INFO_TEXT;
 import static org.onosproject.net.pi.runtime.PiPacketOperation.Type.PACKET_OUT;
 import static p4.P4RuntimeOuterClass.ActionProfileGroup.Type.SELECT;
 import static p4.P4RuntimeOuterClass.Update.Type.INSERT;
@@ -81,13 +77,7 @@
     private final URL p4InfoUrl = this.getClass().getResource("/bmv2/default.p4info");
     private final URL jsonUrl = this.getClass().getResource("/bmv2/default.json");
 
-    private final PiPipeconf bmv2DefaultPipeconf = DefaultPiPipeconf.builder()
-            .withId(new PiPipeconfId("mock-p4runtime"))
-            .withPipelineModel(Bmv2PipelineModelParser.parse(jsonUrl))
-            .addBehaviour(PiPipelineInterpreter.class, Bmv2DefaultInterpreter.class)
-            .addExtension(P4_INFO_TEXT, p4InfoUrl)
-            .addExtension(BMV2_JSON, jsonUrl)
-            .build();
+    private final PiPipeconf bmv2DefaultPipeconf = Bmv2DefaultPipeconfFactory.get();
     private final P4RuntimeControllerImpl controller = new P4RuntimeControllerImpl();
     private final GrpcControllerImpl grpcController = new GrpcControllerImpl();
     private final DeviceId deviceId = DeviceId.deviceId("dummy:1");
diff --git a/apps/pi-demo/ecmp/BUCK b/apps/pi-demo/ecmp/BUCK
index ebe97de..7c6a9af 100644
--- a/apps/pi-demo/ecmp/BUCK
+++ b/apps/pi-demo/ecmp/BUCK
@@ -4,6 +4,7 @@
     '//incubator/bmv2/model:onos-incubator-bmv2-model',
     '//apps/pi-demo/common:onos-apps-pi-demo-common',
     '//drivers/default:onos-drivers-default',
+    '//drivers/p4runtime:onos-drivers-p4runtime',
 ]
 
 osgi_jar (
diff --git a/apps/pi-demo/ecmp/src/main/java/org/onosproject/pi/demo/app/ecmp/EcmpFabricApp.java b/apps/pi-demo/ecmp/src/main/java/org/onosproject/pi/demo/app/ecmp/EcmpFabricApp.java
index 3aabca8..1b6d48b 100644
--- a/apps/pi-demo/ecmp/src/main/java/org/onosproject/pi/demo/app/ecmp/EcmpFabricApp.java
+++ b/apps/pi-demo/ecmp/src/main/java/org/onosproject/pi/demo/app/ecmp/EcmpFabricApp.java
@@ -21,35 +21,35 @@
 import org.apache.commons.lang3.tuple.Pair;
 import org.apache.felix.scr.annotations.Component;
 import org.onlab.util.ImmutableByteSequence;
+import org.onosproject.bmv2.model.Bmv2PipelineModelParser;
 import org.onosproject.driver.pipeline.DefaultSingleTablePipeline;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.Host;
+import org.onosproject.net.Path;
+import org.onosproject.net.Port;
+import org.onosproject.net.PortNumber;
 import org.onosproject.net.behaviour.Pipeliner;
+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.PiCriterion;
+import org.onosproject.net.pi.model.DefaultPiPipeconf;
+import org.onosproject.net.pi.model.PiPipeconf;
+import org.onosproject.net.pi.model.PiPipeconfId;
+import org.onosproject.net.pi.model.PiPipelineInterpreter;
 import org.onosproject.net.pi.runtime.PiAction;
 import org.onosproject.net.pi.runtime.PiActionId;
 import org.onosproject.net.pi.runtime.PiActionParam;
 import org.onosproject.net.pi.runtime.PiActionParamId;
 import org.onosproject.net.pi.runtime.PiHeaderFieldId;
 import org.onosproject.net.pi.runtime.PiTableAction;
-import org.onosproject.pi.demo.app.common.AbstractUpgradableFabricApp;
-import org.onosproject.net.DeviceId;
-import org.onosproject.net.Host;
-import org.onosproject.net.Path;
-import org.onosproject.net.Port;
-import org.onosproject.net.PortNumber;
-import org.onosproject.net.flow.DefaultTrafficSelector;
-import org.onosproject.net.flow.DefaultTrafficTreatment;
-import org.onosproject.net.flow.FlowRule;
-import org.onosproject.net.flow.TrafficTreatment;
-import org.onosproject.net.pi.model.DefaultPiPipeconf;
-import org.onosproject.net.pi.model.PiPipeconf;
-import org.onosproject.net.pi.model.PiPipeconfId;
-import org.onosproject.net.pi.model.PiPipelineInterpreter;
 import org.onosproject.net.topology.DefaultTopologyVertex;
 import org.onosproject.net.topology.Topology;
 import org.onosproject.net.topology.TopologyGraph;
-import org.onosproject.bmv2.model.Bmv2PipelineModelParser;
+import org.onosproject.pi.demo.app.common.AbstractUpgradableFabricApp;
 
 import java.net.URL;
 import java.util.Collection;
diff --git a/apps/pi-demo/ecmp/src/main/java/org/onosproject/pi/demo/app/ecmp/EcmpInterpreter.java b/apps/pi-demo/ecmp/src/main/java/org/onosproject/pi/demo/app/ecmp/EcmpInterpreter.java
index d58ff16..6b302f6 100644
--- a/apps/pi-demo/ecmp/src/main/java/org/onosproject/pi/demo/app/ecmp/EcmpInterpreter.java
+++ b/apps/pi-demo/ecmp/src/main/java/org/onosproject/pi/demo/app/ecmp/EcmpInterpreter.java
@@ -17,48 +17,15 @@
 package org.onosproject.pi.demo.app.ecmp;
 
 import com.google.common.collect.ImmutableBiMap;
-import com.google.common.collect.ImmutableList;
-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;
-import org.onosproject.net.driver.AbstractHandlerBehaviour;
-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.packet.DefaultInboundPacket;
-import org.onosproject.net.packet.InboundPacket;
-import org.onosproject.net.packet.OutboundPacket;
-import org.onosproject.net.pi.model.PiPipelineInterpreter;
-import org.onosproject.net.pi.runtime.PiAction;
-import org.onosproject.net.pi.runtime.PiActionId;
-import org.onosproject.net.pi.runtime.PiActionParam;
-import org.onosproject.net.pi.runtime.PiActionParamId;
-import org.onosproject.net.pi.runtime.PiHeaderFieldId;
-import org.onosproject.net.pi.runtime.PiPacketMetadata;
-import org.onosproject.net.pi.runtime.PiPacketMetadataId;
-import org.onosproject.net.pi.runtime.PiPacketOperation;
+import org.onosproject.drivers.p4runtime.DefaultP4Interpreter;
 import org.onosproject.net.pi.runtime.PiTableId;
 
-import java.nio.ByteBuffer;
-import java.util.Collection;
-import java.util.List;
 import java.util.Optional;
 
-import static java.util.stream.Collectors.toList;
-import static org.onosproject.net.PortNumber.CONTROLLER;
-import static org.onosproject.net.PortNumber.FLOOD;
-import static org.onosproject.net.flow.instructions.Instruction.Type.OUTPUT;
-import static org.onosproject.net.pi.runtime.PiPacketOperation.Type.PACKET_OUT;
-
 /**
  * Implementation of a PiPipeline interpreter for the ecmp.json configuration.
  */
-public class EcmpInterpreter extends AbstractHandlerBehaviour implements PiPipelineInterpreter {
+public class EcmpInterpreter extends DefaultP4Interpreter {
 
     protected static final String ECMP_METADATA_HEADER_NAME = "ecmp_metadata_t";
     protected static final String ECMP_GROUP_ACTION_NAME = "ecmp_group";
@@ -66,32 +33,11 @@
     protected static final String SELECTOR = "selector";
     protected static final String GROUP_SIZE = "groupSize";
     protected static final String ECMP_GROUP_TABLE = "ecmp_group_table";
-    protected static final String TABLE0 = "table0";
-    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 EGRESS_PORT = "egress_port";
-    private static final int PORT_NUMBER_BIT_WIDTH = 9;
 
-    private static final PiHeaderFieldId IN_PORT_ID = PiHeaderFieldId.of("standard_metadata", "ingress_port");
-    private static final PiHeaderFieldId ETH_DST_ID = PiHeaderFieldId.of("ethernet", "dstAddr");
-    private static final PiHeaderFieldId ETH_SRC_ID = PiHeaderFieldId.of("ethernet", "srcAddr");
-    private static final PiHeaderFieldId ETH_TYPE_ID = PiHeaderFieldId.of("ethernet", "etherType");
-
-    private static final ImmutableBiMap<Criterion.Type, PiHeaderFieldId> CRITERION_MAP =
-            new ImmutableBiMap.Builder<Criterion.Type, PiHeaderFieldId>()
-                    .put(Criterion.Type.IN_PORT, IN_PORT_ID)
-                    .put(Criterion.Type.ETH_DST, ETH_DST_ID)
-                    .put(Criterion.Type.ETH_SRC, ETH_SRC_ID)
-                    .put(Criterion.Type.ETH_TYPE, ETH_TYPE_ID)
-                    .build();
-
-    private static final ImmutableBiMap<Integer, PiTableId> TABLE_MAP = ImmutableBiMap.of(
-            0, PiTableId.of(TABLE0),
-            1, PiTableId.of(ECMP_GROUP_TABLE));
-
-    public static final String INGRESS_PORT = "ingress_port";
+    private static final ImmutableBiMap<Integer, PiTableId> TABLE_MAP = new ImmutableBiMap.Builder<Integer, PiTableId>()
+            .put(0, PiTableId.of(TABLE0))
+            .put(1, PiTableId.of(ECMP_GROUP_TABLE))
+            .build();
 
     @Override
     public Optional<Integer> mapPiTableId(PiTableId piTableId) {
@@ -99,151 +45,7 @@
     }
 
     @Override
-    public PiAction mapTreatment(TrafficTreatment treatment, PiTableId piTableId)
-            throws PiInterpreterException {
-
-        if (treatment.allInstructions().size() == 0) {
-            // No instructions means drop for us.
-            return actionWithName(DROP);
-        } else if (treatment.allInstructions().size() > 1) {
-            // Otherwise, we understand treatments with only 1 instruction.
-            throw new PiPipelineInterpreter.PiInterpreterException("Treatment has multiple instructions");
-        }
-
-        Instruction instruction = treatment.allInstructions().get(0);
-
-        switch (instruction.type()) {
-            case OUTPUT:
-                Instructions.OutputInstruction outInstruction = (Instructions.OutputInstruction) instruction;
-                PortNumber port = outInstruction.port();
-                if (!port.isLogical()) {
-                    PiAction.builder()
-                            .withId(PiActionId.of(SET_EGRESS_PORT))
-                            .withParameter(new PiActionParam(PiActionParamId.of(PORT),
-                                                             ImmutableByteSequence.copyFrom(port.toLong())))
-                            .build();
-                } else if (port.equals(CONTROLLER)) {
-                    return actionWithName(SEND_TO_CPU);
-                } else {
-                    throw new PiInterpreterException("Egress on logical port not supported: " + port);
-                }
-            case NOACTION:
-                return actionWithName(DROP);
-            default:
-                throw new PiInterpreterException("Instruction type not supported: " + instruction.type().name());
-        }
-    }
-
-    private static PiAction actionWithName(String name) {
-        return PiAction.builder().withId(PiActionId.of(name)).build();
-    }
-
-    @Override
-    public Optional<PiHeaderFieldId> mapCriterionType(Criterion.Type type) {
-        return Optional.ofNullable(CRITERION_MAP.get(type));
-    }
-
-    @Override
-    public Optional<Criterion.Type> mapPiHeaderFieldId(PiHeaderFieldId headerFieldId) {
-        return Optional.ofNullable(CRITERION_MAP.inverse().get(headerFieldId));
-    }
-
-    @Override
     public Optional<PiTableId> mapFlowRuleTableId(int flowRuleTableId) {
         return Optional.ofNullable(TABLE_MAP.get(flowRuleTableId));
     }
-
-    @Override
-    public Collection<PiPacketOperation> mapOutboundPacket(OutboundPacket packet)
-            throws PiInterpreterException {
-        TrafficTreatment treatment = packet.treatment();
-
-        // ecmp.p4 supports only 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("Logical port not supported: " +
-                                                         outInst.port());
-            } else if (outInst.port().equals(FLOOD)) {
-                //Since ecmp.p4 does not support flood for each port of the device
-                // create a packet operation to send the packet out of that specific port
-                for (Port port : handler().get(DeviceService.class).getPorts(packet.sendThrough())) {
-                    builder.add(createPiPacketOperation(packet.data(), port.number().toLong()));
-                }
-            } else {
-                builder.add(createPiPacketOperation(packet.data(), outInst.port().toLong()));
-            }
-        }
-        return builder.build();
-    }
-
-    private PiPacketOperation createPiPacketOperation(ByteBuffer data, long portNumber) throws PiInterpreterException {
-        //create the metadata
-        PiPacketMetadata metadata = createPacketMetadata(portNumber);
-
-        //Create the Packet operation
-        return PiPacketOperation.builder()
-                .withType(PACKET_OUT)
-                .withData(ImmutableByteSequence.copyFrom(data))
-                .withMetadatas(ImmutableList.of(metadata))
-                .build();
-    }
-
-    private PiPacketMetadata createPacketMetadata(long portNumber) throws PiInterpreterException {
-        ImmutableByteSequence portValue = ImmutableByteSequence.copyFrom(portNumber);
-        //FIXME remove hardcoded bitWidth and retrieve it from pipelineModel
-        try {
-            portValue = ImmutableByteSequence.fit(portValue, PORT_NUMBER_BIT_WIDTH);
-        } catch (ImmutableByteSequence.ByteSequenceTrimException e) {
-            throw new PiInterpreterException("Port number too big: {}" +
-                                                     portNumber + " causes " + e.getMessage());
-        }
-        return PiPacketMetadata.builder()
-                .withId(PiPacketMetadataId.of(EGRESS_PORT))
-                .withValue(portValue)
-                .build();
-    }
-
-    @Override
-    public InboundPacket mapInboundPacket(DeviceId deviceId, PiPacketOperation packetInOperation)
-            throws PiInterpreterException {
-        //We are assuming that the packet is ethernet type
-        Ethernet ethPkt = new Ethernet();
-
-        ethPkt.deserialize(packetInOperation.data().asArray(), 0, packetInOperation.data().size());
-
-        //Returns the ingress port packet metadata
-        Optional<PiPacketMetadata> packetMetadata = packetInOperation.metadatas()
-                .stream().filter(metadata -> metadata.id().name().equals(INGRESS_PORT))
-                .findFirst();
-
-        if (packetMetadata.isPresent()) {
-
-            //Obtaining the ingress port as an immutable byte sequence
-            ImmutableByteSequence portByteSequence = packetMetadata.get().value();
-
-            //Converting immutableByteSequence to short
-            short s = portByteSequence.asReadOnlyBuffer().getShort();
-
-            ConnectPoint receivedFrom = new ConnectPoint(deviceId, PortNumber.portNumber(s));
-
-            //FIXME should be optimizable with .asReadOnlyBytebuffer
-            ByteBuffer rawData = ByteBuffer.wrap(packetInOperation.data().asArray());
-            return new DefaultInboundPacket(receivedFrom, ethPkt, rawData);
-
-        } else {
-            throw new PiInterpreterException("Can't get packet metadata for" + INGRESS_PORT);
-        }
-    }
 }
\ No newline at end of file
diff --git a/core/net/src/main/java/org/onosproject/net/pi/impl/PiFlowRuleTranslationServiceImpl.java b/core/net/src/main/java/org/onosproject/net/pi/impl/PiFlowRuleTranslationServiceImpl.java
index b999197..c55a57c 100644
--- a/core/net/src/main/java/org/onosproject/net/pi/impl/PiFlowRuleTranslationServiceImpl.java
+++ b/core/net/src/main/java/org/onosproject/net/pi/impl/PiFlowRuleTranslationServiceImpl.java
@@ -61,7 +61,7 @@
     public PiTableEntry translate(FlowRule rule, PiPipeconf pipeconf)
             throws PiFlowRuleTranslationException {
 
-        Device device = deviceService.getDevice(rule.deviceId());
+        final Device device = deviceService.getDevice(rule.deviceId());
         if (device == null) {
             throw new PiFlowRuleTranslationException("Unable to get device " + rule.deviceId());
         }
diff --git a/core/net/src/main/java/org/onosproject/net/pi/impl/PiFlowRuleTranslator.java b/core/net/src/main/java/org/onosproject/net/pi/impl/PiFlowRuleTranslator.java
index 8d8d3c1..dc6d1c5 100644
--- a/core/net/src/main/java/org/onosproject/net/pi/impl/PiFlowRuleTranslator.java
+++ b/core/net/src/main/java/org/onosproject/net/pi/impl/PiFlowRuleTranslator.java
@@ -81,18 +81,24 @@
         PiPipelineModel pipelineModel = pipeconf.pipelineModel();
 
         // Retrieve interpreter, if any.
-        // FIXME: get interpreter via driver once implemented.
-        // final PiPipelineInterpreter interpreter = device.is(PiPipelineInterpreter.class)
-        //        ? device.as(PiPipelineInterpreter.class) : null;
-
         final PiPipelineInterpreter interpreter;
-        try {
-            interpreter = (PiPipelineInterpreter) pipeconf.implementation(PiPipelineInterpreter.class)
-                    .orElse(null)
-                    .newInstance();
-        } catch (InstantiationException | IllegalAccessException e) {
-            throw new PiFlowRuleTranslationException(format(
-                    "Unable to instantiate interpreter of pipeconf %s", pipeconf.id()));
+
+        if (device != null) {
+            interpreter = device.is(PiPipelineInterpreter.class) ? device.as(PiPipelineInterpreter.class) : null;
+        } else {
+            // The case of device == null should be admitted only during unit testing.
+            // In any other case, the interpreter should be constructed using the device.as() method to make sure that
+            // behaviour's handler/data attributes are correctly populated.
+            // FIXME: modify test class PiFlowRuleTranslatorTest to avoid passing null device
+            // I.e. we need to create a device object that supports is/as method for obtaining the interpreter.
+            log.warn("translateFlowRule() called with device == null, is this a unit test?");
+            try {
+                interpreter = (PiPipelineInterpreter) pipeconf.implementation(PiPipelineInterpreter.class)
+                        .orElse(null)
+                        .newInstance();
+            } catch (InstantiationException | IllegalAccessException e) {
+                throw new RuntimeException(format("Unable to instantiate interpreter of pipeconf %s", pipeconf.id()));
+            }
         }
 
         PiTableId piTableId;
diff --git a/drivers/bmv2/BUCK b/drivers/bmv2/BUCK
index 8938d7a..b13a673 100644
--- a/drivers/bmv2/BUCK
+++ b/drivers/bmv2/BUCK
@@ -6,6 +6,7 @@
     '//protocols/p4runtime/api:onos-protocols-p4runtime-api',
     '//incubator/bmv2/model:onos-incubator-bmv2-model',
     '//drivers/default:onos-drivers-default',
+    '//drivers/p4runtime:onos-drivers-p4runtime',
     '//incubator/grpc-dependencies:grpc-core-repkg-' + GRPC_VER,
     '//lib:grpc-netty-' + GRPC_VER,
 ]
diff --git a/drivers/bmv2/src/main/java/org/onosproject/drivers/bmv2/Bmv2DefaultInterpreter.java b/drivers/bmv2/src/main/java/org/onosproject/drivers/bmv2/Bmv2DefaultInterpreter.java
deleted file mode 100644
index fa6a8ea..0000000
--- a/drivers/bmv2/src/main/java/org/onosproject/drivers/bmv2/Bmv2DefaultInterpreter.java
+++ /dev/null
@@ -1,244 +0,0 @@
-/*
- * Copyright 2017-present Open Networking Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.onosproject.drivers.bmv2;
-
-import com.google.common.collect.ImmutableBiMap;
-import com.google.common.collect.ImmutableList;
-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;
-import org.onosproject.net.driver.AbstractHandlerBehaviour;
-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.packet.DefaultInboundPacket;
-import org.onosproject.net.packet.InboundPacket;
-import org.onosproject.net.packet.OutboundPacket;
-import org.onosproject.net.pi.model.PiPipelineInterpreter;
-import org.onosproject.net.pi.runtime.PiAction;
-import org.onosproject.net.pi.runtime.PiActionId;
-import org.onosproject.net.pi.runtime.PiActionParam;
-import org.onosproject.net.pi.runtime.PiActionParamId;
-import org.onosproject.net.pi.runtime.PiHeaderFieldId;
-import org.onosproject.net.pi.runtime.PiPacketMetadata;
-import org.onosproject.net.pi.runtime.PiPacketMetadataId;
-import org.onosproject.net.pi.runtime.PiPacketOperation;
-import org.onosproject.net.pi.runtime.PiTableId;
-
-import java.nio.ByteBuffer;
-import java.util.Collection;
-import java.util.List;
-import java.util.Optional;
-
-import static java.util.stream.Collectors.toList;
-import static org.onosproject.net.PortNumber.CONTROLLER;
-import static org.onosproject.net.PortNumber.FLOOD;
-import static org.onosproject.net.flow.instructions.Instruction.Type.OUTPUT;
-import static org.onosproject.net.pi.runtime.PiPacketOperation.Type.PACKET_OUT;
-
-/**
- * Interpreter implementation for the default pipeconf.
- */
-public class Bmv2DefaultInterpreter extends AbstractHandlerBehaviour implements PiPipelineInterpreter {
-    private static final String TABLE0 = "table0";
-    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 EGRESS_PORT = "egress_port";
-    private static final int PORT_NUMBER_BIT_WIDTH = 9;
-
-    private static final PiHeaderFieldId IN_PORT_ID = PiHeaderFieldId.of("standard_metadata", "ingress_port");
-    private static final PiHeaderFieldId ETH_DST_ID = PiHeaderFieldId.of("ethernet", "dstAddr");
-    private static final PiHeaderFieldId ETH_SRC_ID = PiHeaderFieldId.of("ethernet", "srcAddr");
-    private static final PiHeaderFieldId ETH_TYPE_ID = PiHeaderFieldId.of("ethernet", "etherType");
-
-    private static final ImmutableBiMap<Criterion.Type, PiHeaderFieldId> CRITERION_MAP =
-            new ImmutableBiMap.Builder<Criterion.Type, PiHeaderFieldId>()
-                    .put(Criterion.Type.IN_PORT, IN_PORT_ID)
-                    .put(Criterion.Type.ETH_DST, ETH_DST_ID)
-                    .put(Criterion.Type.ETH_SRC, ETH_SRC_ID)
-                    .put(Criterion.Type.ETH_TYPE, ETH_TYPE_ID)
-                    .build();
-
-    private static final ImmutableBiMap<Integer, PiTableId> TABLE_MAP = ImmutableBiMap.of(
-            0, PiTableId.of(TABLE0));
-    public static final String INGRESS_PORT = "ingress_port";
-
-
-    @Override
-    public PiAction mapTreatment(TrafficTreatment treatment, PiTableId piTableId) throws PiInterpreterException {
-
-        if (treatment.allInstructions().size() == 0) {
-            // No instructions means drop for us.
-            return actionWithName(DROP);
-        } else if (treatment.allInstructions().size() > 1) {
-            // Otherwise, we understand treatments with only 1 instruction.
-            throw new PiPipelineInterpreter.PiInterpreterException("Treatment has multiple instructions");
-        }
-
-        Instruction instruction = treatment.allInstructions().get(0);
-
-        switch (instruction.type()) {
-            case 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),
-                                    ImmutableByteSequence.copyFrom(port.toLong())))
-                            .build();
-                } else if (port.equals(CONTROLLER)) {
-                    return actionWithName(SEND_TO_CPU);
-                } else {
-                    throw new PiInterpreterException("Egress on logical port not supported: " + port);
-                }
-            case NOACTION:
-                return actionWithName(DROP);
-            default:
-                throw new PiInterpreterException("Instruction type not supported: " + instruction.type().name());
-        }
-    }
-
-    @Override
-    public Collection<PiPacketOperation> mapOutboundPacket(OutboundPacket packet)
-            throws PiInterpreterException {
-        TrafficTreatment treatment = packet.treatment();
-
-        // default.p4 supports only 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("Logical port not supported: " +
-                        outInst.port());
-            } else if (outInst.port().equals(FLOOD)) {
-                //Since default.p4 does not support flood for each port of the device
-                // create a packet operation to send the packet out of that specific port
-                for (Port port : handler().get(DeviceService.class).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(DeviceId deviceId, PiPacketOperation packetIn)
-            throws PiInterpreterException {
-
-        //We are assuming that the packet is ethernet type
-        Ethernet ethPkt = new Ethernet();
-
-        ethPkt.deserialize(packetIn.data().asArray(), 0, packetIn.data().size());
-
-        //Returns the ingress port packet metadata
-        Optional<PiPacketMetadata> packetMetadata = packetIn.metadatas()
-                .stream().filter(metadata -> metadata.id().name().equals(INGRESS_PORT))
-                .findFirst();
-
-        if (packetMetadata.isPresent()) {
-
-            //Obtaining the ingress port as an immutable byte sequence
-            ImmutableByteSequence portByteSequence = packetMetadata.get().value();
-
-            //Converting immutableByteSequence to short
-            short s = portByteSequence.asReadOnlyBuffer().getShort();
-
-            ConnectPoint receivedFrom = new ConnectPoint(deviceId, PortNumber.portNumber(s));
-
-            //FIXME should be optimizable with .asReadOnlyBytebuffer
-            ByteBuffer rawData = ByteBuffer.wrap(packetIn.data().asArray());
-            return new DefaultInboundPacket(receivedFrom, ethPkt, rawData);
-
-        } else {
-            throw new PiInterpreterException("Can't get packet metadata for" + INGRESS_PORT);
-        }
-    }
-
-    private PiPacketOperation createPiPacketOperation(ByteBuffer data, long portNumber) throws PiInterpreterException {
-        //create the metadata
-        PiPacketMetadata metadata = createPacketMetadata(portNumber);
-
-        //Create the Packet operation
-        return PiPacketOperation.builder()
-                .withType(PACKET_OUT)
-                .withData(ImmutableByteSequence.copyFrom(data))
-                .withMetadatas(ImmutableList.of(metadata))
-                .build();
-    }
-
-    private PiPacketMetadata createPacketMetadata(long portNumber) throws PiInterpreterException {
-        ImmutableByteSequence portValue = ImmutableByteSequence.copyFrom(portNumber);
-        //FIXME remove hardcoded bitWidth and retrieve it from pipelineModel
-        try {
-            portValue = ImmutableByteSequence.fit(portValue, PORT_NUMBER_BIT_WIDTH);
-        } catch (ImmutableByteSequence.ByteSequenceTrimException e) {
-            throw new PiInterpreterException("Port number too big: {}" +
-                    portNumber + " causes " + e.getMessage());
-        }
-        return PiPacketMetadata.builder()
-                .withId(PiPacketMetadataId.of(EGRESS_PORT))
-                .withValue(portValue)
-                .build();
-    }
-
-    /**
-     * Returns an action instance with no runtime parameters.
-     */
-    private PiAction actionWithName(String name) {
-        return PiAction.builder().withId(PiActionId.of(name)).build();
-    }
-
-    @Override
-    public Optional<PiHeaderFieldId> mapCriterionType(Criterion.Type type) {
-        return Optional.ofNullable(CRITERION_MAP.get(type));
-    }
-
-    @Override
-    public Optional<Criterion.Type> mapPiHeaderFieldId(PiHeaderFieldId headerFieldId) {
-        return Optional.ofNullable(CRITERION_MAP.inverse().get(headerFieldId));
-    }
-
-    @Override
-    public Optional<PiTableId> mapFlowRuleTableId(int flowRuleTableId) {
-        return Optional.ofNullable(TABLE_MAP.get(flowRuleTableId));
-    }
-
-    @Override
-    public Optional<Integer> mapPiTableId(PiTableId piTableId) {
-        return Optional.ofNullable(TABLE_MAP.inverse().get(piTableId));
-    }
-}
diff --git a/drivers/bmv2/src/main/java/org/onosproject/drivers/bmv2/Bmv2DefaultPipeconfFactory.java b/drivers/bmv2/src/main/java/org/onosproject/drivers/bmv2/Bmv2DefaultPipeconfFactory.java
index e04e8b3..3dba8b6 100644
--- a/drivers/bmv2/src/main/java/org/onosproject/drivers/bmv2/Bmv2DefaultPipeconfFactory.java
+++ b/drivers/bmv2/src/main/java/org/onosproject/drivers/bmv2/Bmv2DefaultPipeconfFactory.java
@@ -18,6 +18,7 @@
 
 import org.onosproject.bmv2.model.Bmv2PipelineModelParser;
 import org.onosproject.driver.pipeline.DefaultSingleTablePipeline;
+import org.onosproject.drivers.p4runtime.DefaultP4Interpreter;
 import org.onosproject.net.behaviour.Pipeliner;
 import org.onosproject.net.device.PortStatisticsDiscovery;
 import org.onosproject.net.pi.model.DefaultPiPipeconf;
@@ -33,7 +34,7 @@
 /**
  * Factory of pipeconf implementation for the default.p4 program on BMv2.
  */
-final class Bmv2DefaultPipeconfFactory {
+public final class Bmv2DefaultPipeconfFactory {
 
     private static final String PIPECONF_ID = "bmv2-default-pipeconf";
     private static final String JSON_PATH = "/default.json";
@@ -45,7 +46,7 @@
         // Hides constructor.
     }
 
-    static PiPipeconf get() {
+    public static PiPipeconf get() {
         return PIPECONF;
     }
 
@@ -57,7 +58,7 @@
         return DefaultPiPipeconf.builder()
                 .withId(new PiPipeconfId(PIPECONF_ID))
                 .withPipelineModel(Bmv2PipelineModelParser.parse(jsonUrl))
-                .addBehaviour(PiPipelineInterpreter.class, Bmv2DefaultInterpreter.class)
+                .addBehaviour(PiPipelineInterpreter.class, DefaultP4Interpreter.class)
                 .addBehaviour(Pipeliner.class, DefaultSingleTablePipeline.class)
                 .addBehaviour(PortStatisticsDiscovery.class, Bmv2DefaultPortStatisticsDiscovery.class)
                 .addExtension(P4_INFO_TEXT, p4InfoUrl)
diff --git a/drivers/p4runtime/src/main/java/org/onosproject/drivers/p4runtime/DefaultP4Interpreter.java b/drivers/p4runtime/src/main/java/org/onosproject/drivers/p4runtime/DefaultP4Interpreter.java
new file mode 100644
index 0000000..85167eb
--- /dev/null
+++ b/drivers/p4runtime/src/main/java/org/onosproject/drivers/p4runtime/DefaultP4Interpreter.java
@@ -0,0 +1,298 @@
+/*
+ * Copyright 2017-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.drivers.p4runtime;
+
+import com.google.common.collect.ImmutableBiMap;
+import com.google.common.collect.ImmutableList;
+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;
+import org.onosproject.net.driver.AbstractHandlerBehaviour;
+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.packet.DefaultInboundPacket;
+import org.onosproject.net.packet.InboundPacket;
+import org.onosproject.net.packet.OutboundPacket;
+import org.onosproject.net.pi.model.PiHeaderFieldModel;
+import org.onosproject.net.pi.model.PiPipeconf;
+import org.onosproject.net.pi.model.PiPipeconfId;
+import org.onosproject.net.pi.model.PiPipelineInterpreter;
+import org.onosproject.net.pi.model.PiPipelineModel;
+import org.onosproject.net.pi.model.PiTableModel;
+import org.onosproject.net.pi.runtime.PiAction;
+import org.onosproject.net.pi.runtime.PiActionId;
+import org.onosproject.net.pi.runtime.PiActionParam;
+import org.onosproject.net.pi.runtime.PiActionParamId;
+import org.onosproject.net.pi.runtime.PiHeaderFieldId;
+import org.onosproject.net.pi.runtime.PiPacketMetadata;
+import org.onosproject.net.pi.runtime.PiPacketMetadataId;
+import org.onosproject.net.pi.runtime.PiPacketOperation;
+import org.onosproject.net.pi.runtime.PiPipeconfService;
+import org.onosproject.net.pi.runtime.PiTableId;
+
+import java.nio.ByteBuffer;
+import java.util.Collection;
+import java.util.List;
+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.onlab.util.ImmutableByteSequence.fit;
+import static org.onosproject.net.PortNumber.CONTROLLER;
+import static org.onosproject.net.PortNumber.FLOOD;
+import static org.onosproject.net.flow.instructions.Instruction.Type.OUTPUT;
+import static org.onosproject.net.pi.runtime.PiPacketOperation.Type.PACKET_OUT;
+
+/**
+ * Implementation of an interpreter that can be used for any P4 program based on default.p4 (i.e. those under
+ * onos/tools/test/p4src).
+ */
+public class DefaultP4Interpreter extends AbstractHandlerBehaviour implements PiPipelineInterpreter {
+
+    // FIXME: Should move this class out of the p4runtime drivers.
+    // e.g. in a dedicated onos/pipeconf directory, along with any related P4 source code.
+
+    public static final String TABLE0 = "table0";
+    public static final String SEND_TO_CPU = "send_to_cpu";
+    public static final String PORT = "port";
+    public static final String DROP = "drop";
+    public static final String SET_EGRESS_PORT = "set_egress_port";
+    public static final String EGRESS_PORT = "egress_port";
+    public static final String INGRESS_PORT = "ingress_port";
+
+    protected static final PiHeaderFieldId ETH_DST_ID = PiHeaderFieldId.of("ethernet", "dstAddr");
+    protected static final PiHeaderFieldId ETH_SRC_ID = PiHeaderFieldId.of("ethernet", "srcAddr");
+    protected static final PiHeaderFieldId ETH_TYPE_ID = PiHeaderFieldId.of("ethernet", "etherType");
+
+    private static final ImmutableBiMap<Integer, PiTableId> TABLE_MAP = ImmutableBiMap.of(
+            0, PiTableId.of(TABLE0));
+
+    private boolean targetAttributesInitialized = false;
+
+    /*
+    The following attributes are target-specific, i.e. they might change from one target to another.
+     */
+    private ImmutableBiMap<Criterion.Type, PiHeaderFieldId> criterionMap;
+    private int portFieldBitWidth;
+
+    /**
+     * Populates target-specific attributes based on this device's pipeline model.
+     */
+    private synchronized void initTargetSpecificAttributes() {
+        if (targetAttributesInitialized) {
+            return;
+        }
+
+        DeviceId deviceId = this.handler().data().deviceId();
+        PiPipeconfService pipeconfService = this.handler().get(PiPipeconfService.class);
+        PiPipeconfId pipeconfId = pipeconfService.ofDevice(deviceId)
+                .orElseThrow(() -> new RuntimeException(format(
+                        "Unable to get current pipeconf for device %s", this.data().deviceId())));
+        PiPipeconf pipeconf = pipeconfService.getPipeconf(pipeconfId)
+                .orElseThrow(() -> new RuntimeException(format(
+                        "Pipeconf %s is not registered", pipeconfId)));
+        PiPipelineModel model = pipeconf.pipelineModel();
+
+        this.portFieldBitWidth = extractPortFieldBitWidth(model);
+        this.criterionMap = new ImmutableBiMap.Builder<Criterion.Type, PiHeaderFieldId>()
+                .put(Criterion.Type.IN_PORT, extractInPortFieldId(model))
+                .put(Criterion.Type.ETH_DST, ETH_DST_ID)
+                .put(Criterion.Type.ETH_SRC, ETH_SRC_ID)
+                .put(Criterion.Type.ETH_TYPE, ETH_TYPE_ID)
+                .build();
+
+        this.targetAttributesInitialized = true;
+    }
+
+    private static PiHeaderFieldId extractInPortFieldId(PiPipelineModel model) {
+        /*
+        For the targets we currently support, the field name is "ingress_port", but we miss the header name, which is
+        target-specific. We know table0 defines that field as a match key, we look for it and we get the header name.
+         */
+        PiTableModel tableModel = model.table(TABLE0).orElseThrow(() -> new RuntimeException(format(
+                "No such table '%s' in pipeline model", TABLE0)));
+        PiHeaderFieldModel fieldModel = tableModel.matchFields().stream()
+                .filter(m -> m.field().type().name().equals(INGRESS_PORT))
+                .findFirst()
+                .orElseThrow(() -> new RuntimeException(format(
+                        "No such match field in table '%s' with name '%s'", TABLE0, INGRESS_PORT)))
+                .field();
+        return PiHeaderFieldId.of(fieldModel.header().name(), INGRESS_PORT);
+    }
+
+    private static int extractPortFieldBitWidth(PiPipelineModel model) {
+        /*
+        Get it form the set_egress_port action parameters.
+         */
+        return model
+                .action(SET_EGRESS_PORT).orElseThrow(() -> new RuntimeException(format(
+                        "No such action '%s' in pipeline model", SET_EGRESS_PORT)))
+                .param(PORT).orElseThrow(() -> new RuntimeException(format(
+                        "No such parameter '%s' of action '%s' in pipeline model", PORT, SET_EGRESS_PORT)))
+                .bitWidth();
+    }
+
+
+    @Override
+    public PiAction mapTreatment(TrafficTreatment treatment, PiTableId piTableId) throws PiInterpreterException {
+
+        if (treatment.allInstructions().size() == 0) {
+            // No instructions means drop for us.
+            return actionWithName(DROP);
+        } else if (treatment.allInstructions().size() > 1) {
+            // Otherwise, we understand treatments with only 1 instruction.
+            throw new PiPipelineInterpreter.PiInterpreterException("Treatment has multiple instructions");
+        }
+
+        Instruction instruction = treatment.allInstructions().get(0);
+
+        switch (instruction.type()) {
+            case 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 actionWithName(SEND_TO_CPU);
+                } else {
+                    throw new PiInterpreterException(format("Egress on logical port '%s' not supported", port));
+                }
+            case NOACTION:
+                return actionWithName(DROP);
+            default:
+                throw new PiInterpreterException(format("Instruction type '%s' not supported", instruction.type()));
+        }
+    }
+
+    @Override
+    public Collection<PiPacketOperation> mapOutboundPacket(OutboundPacket packet)
+            throws PiInterpreterException {
+        TrafficTreatment treatment = packet.treatment();
+
+        // default.p4 supports only 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 default.p4 does not support flooding, we create a packet operation for each switch port.
+                for (Port port : handler().get(DeviceService.class).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(DeviceId deviceId, PiPacketOperation packetIn)
+            throws PiInterpreterException {
+        // Assuming that the packet is ethernet, which is fine since default.p4 can deparse only ethernet packets.
+        Ethernet ethPkt = new Ethernet();
+
+        ethPkt.deserialize(packetIn.data().asArray(), 0, packetIn.data().size());
+
+        // Returns the ingress port packet metadata.
+        Optional<PiPacketMetadata> packetMetadata = packetIn.metadatas()
+                .stream().filter(metadata -> metadata.id().name().equals(INGRESS_PORT))
+                .findFirst();
+
+        if (packetMetadata.isPresent()) {
+            ImmutableByteSequence portByteSequence = packetMetadata.get().value();
+            short s = portByteSequence.asReadOnlyBuffer().getShort();
+            ConnectPoint receivedFrom = new ConnectPoint(deviceId, PortNumber.portNumber(s));
+            ByteBuffer rawData = ByteBuffer.wrap(packetIn.data().asArray());
+            return new DefaultInboundPacket(receivedFrom, ethPkt, rawData);
+        } else {
+            throw new PiInterpreterException(format(
+                    "Missing metadata '%s' in packet-in received from '%s': %s", INGRESS_PORT, deviceId, packetIn));
+        }
+    }
+
+    private PiPacketOperation createPiPacketOperation(ByteBuffer data, long portNumber) throws PiInterpreterException {
+        PiPacketMetadata metadata = createPacketMetadata(portNumber);
+        return PiPacketOperation.builder()
+                .withType(PACKET_OUT)
+                .withData(copyFrom(data))
+                .withMetadatas(ImmutableList.of(metadata))
+                .build();
+    }
+
+    private PiPacketMetadata createPacketMetadata(long portNumber) throws PiInterpreterException {
+        initTargetSpecificAttributes();
+        try {
+            return PiPacketMetadata.builder()
+                    .withId(PiPacketMetadataId.of(EGRESS_PORT))
+                    .withValue(fit(copyFrom(portNumber), portFieldBitWidth))
+                    .build();
+        } catch (ImmutableByteSequence.ByteSequenceTrimException e) {
+            throw new PiInterpreterException(format("Port number %d too big, %s", portNumber, e.getMessage()));
+        }
+    }
+
+    /**
+     * Returns an action instance with no runtime parameters.
+     */
+    private PiAction actionWithName(String name) {
+        return PiAction.builder().withId(PiActionId.of(name)).build();
+    }
+
+    @Override
+    public Optional<PiHeaderFieldId> mapCriterionType(Criterion.Type type) {
+        initTargetSpecificAttributes();
+        return Optional.ofNullable(criterionMap.get(type));
+    }
+
+    @Override
+    public Optional<Criterion.Type> mapPiHeaderFieldId(PiHeaderFieldId headerFieldId) {
+        initTargetSpecificAttributes();
+        return Optional.ofNullable(criterionMap.inverse().get(headerFieldId));
+    }
+
+    @Override
+    public Optional<PiTableId> mapFlowRuleTableId(int flowRuleTableId) {
+        return Optional.ofNullable(TABLE_MAP.get(flowRuleTableId));
+    }
+
+    @Override
+    public Optional<Integer> mapPiTableId(PiTableId piTableId) {
+        return Optional.ofNullable(TABLE_MAP.inverse().get(piTableId));
+    }
+}