blob: 60295908fa7c1d723d48c2c84c301e261057e797 [file] [log] [blame]
Carmelo Casconea62ac3d2017-08-30 03:19:00 +02001/*
2 * Copyright 2017-present Open Networking Foundation
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package org.onosproject.drivers.p4runtime;
18
19import com.google.common.collect.ImmutableBiMap;
20import com.google.common.collect.ImmutableList;
21import org.onlab.packet.Ethernet;
22import org.onlab.util.ImmutableByteSequence;
23import org.onosproject.net.ConnectPoint;
24import org.onosproject.net.DeviceId;
25import org.onosproject.net.Port;
26import org.onosproject.net.PortNumber;
27import org.onosproject.net.device.DeviceService;
28import org.onosproject.net.driver.AbstractHandlerBehaviour;
29import org.onosproject.net.flow.TrafficTreatment;
30import org.onosproject.net.flow.criteria.Criterion;
31import org.onosproject.net.flow.instructions.Instruction;
32import org.onosproject.net.flow.instructions.Instructions;
33import org.onosproject.net.packet.DefaultInboundPacket;
34import org.onosproject.net.packet.InboundPacket;
35import org.onosproject.net.packet.OutboundPacket;
36import org.onosproject.net.pi.model.PiHeaderFieldModel;
37import org.onosproject.net.pi.model.PiPipeconf;
38import org.onosproject.net.pi.model.PiPipeconfId;
39import org.onosproject.net.pi.model.PiPipelineInterpreter;
40import org.onosproject.net.pi.model.PiPipelineModel;
41import org.onosproject.net.pi.model.PiTableModel;
42import org.onosproject.net.pi.runtime.PiAction;
43import org.onosproject.net.pi.runtime.PiActionId;
44import org.onosproject.net.pi.runtime.PiActionParam;
45import org.onosproject.net.pi.runtime.PiActionParamId;
46import org.onosproject.net.pi.runtime.PiHeaderFieldId;
47import org.onosproject.net.pi.runtime.PiPacketMetadata;
48import org.onosproject.net.pi.runtime.PiPacketMetadataId;
49import org.onosproject.net.pi.runtime.PiPacketOperation;
50import org.onosproject.net.pi.runtime.PiPipeconfService;
51import org.onosproject.net.pi.runtime.PiTableId;
52
53import java.nio.ByteBuffer;
54import java.util.Collection;
55import java.util.List;
56import java.util.Optional;
57
58import static java.lang.String.format;
59import static java.util.stream.Collectors.toList;
60import static org.onlab.util.ImmutableByteSequence.copyFrom;
61import static org.onlab.util.ImmutableByteSequence.fit;
62import static org.onosproject.net.PortNumber.CONTROLLER;
63import static org.onosproject.net.PortNumber.FLOOD;
64import static org.onosproject.net.flow.instructions.Instruction.Type.OUTPUT;
65import static org.onosproject.net.pi.runtime.PiPacketOperation.Type.PACKET_OUT;
66
67/**
68 * Implementation of an interpreter that can be used for any P4 program based on default.p4 (i.e. those under
69 * onos/tools/test/p4src).
70 */
71public class DefaultP4Interpreter extends AbstractHandlerBehaviour implements PiPipelineInterpreter {
72
73 // FIXME: Should move this class out of the p4runtime drivers.
74 // e.g. in a dedicated onos/pipeconf directory, along with any related P4 source code.
75
76 public static final String TABLE0 = "table0";
77 public static final String SEND_TO_CPU = "send_to_cpu";
78 public static final String PORT = "port";
Carmelo Casconeeb018122017-09-06 13:16:03 +020079 public static final String DROP = "_drop";
Carmelo Casconea62ac3d2017-08-30 03:19:00 +020080 public static final String SET_EGRESS_PORT = "set_egress_port";
81 public static final String EGRESS_PORT = "egress_port";
82 public static final String INGRESS_PORT = "ingress_port";
83
84 protected static final PiHeaderFieldId ETH_DST_ID = PiHeaderFieldId.of("ethernet", "dstAddr");
85 protected static final PiHeaderFieldId ETH_SRC_ID = PiHeaderFieldId.of("ethernet", "srcAddr");
86 protected static final PiHeaderFieldId ETH_TYPE_ID = PiHeaderFieldId.of("ethernet", "etherType");
87
88 private static final ImmutableBiMap<Integer, PiTableId> TABLE_MAP = ImmutableBiMap.of(
89 0, PiTableId.of(TABLE0));
90
91 private boolean targetAttributesInitialized = false;
92
93 /*
94 The following attributes are target-specific, i.e. they might change from one target to another.
95 */
96 private ImmutableBiMap<Criterion.Type, PiHeaderFieldId> criterionMap;
97 private int portFieldBitWidth;
98
99 /**
100 * Populates target-specific attributes based on this device's pipeline model.
101 */
102 private synchronized void initTargetSpecificAttributes() {
103 if (targetAttributesInitialized) {
104 return;
105 }
106
107 DeviceId deviceId = this.handler().data().deviceId();
108 PiPipeconfService pipeconfService = this.handler().get(PiPipeconfService.class);
109 PiPipeconfId pipeconfId = pipeconfService.ofDevice(deviceId)
110 .orElseThrow(() -> new RuntimeException(format(
111 "Unable to get current pipeconf for device %s", this.data().deviceId())));
112 PiPipeconf pipeconf = pipeconfService.getPipeconf(pipeconfId)
113 .orElseThrow(() -> new RuntimeException(format(
114 "Pipeconf %s is not registered", pipeconfId)));
115 PiPipelineModel model = pipeconf.pipelineModel();
116
117 this.portFieldBitWidth = extractPortFieldBitWidth(model);
118 this.criterionMap = new ImmutableBiMap.Builder<Criterion.Type, PiHeaderFieldId>()
119 .put(Criterion.Type.IN_PORT, extractInPortFieldId(model))
120 .put(Criterion.Type.ETH_DST, ETH_DST_ID)
121 .put(Criterion.Type.ETH_SRC, ETH_SRC_ID)
122 .put(Criterion.Type.ETH_TYPE, ETH_TYPE_ID)
123 .build();
124
125 this.targetAttributesInitialized = true;
126 }
127
128 private static PiHeaderFieldId extractInPortFieldId(PiPipelineModel model) {
129 /*
130 For the targets we currently support, the field name is "ingress_port", but we miss the header name, which is
131 target-specific. We know table0 defines that field as a match key, we look for it and we get the header name.
132 */
133 PiTableModel tableModel = model.table(TABLE0).orElseThrow(() -> new RuntimeException(format(
134 "No such table '%s' in pipeline model", TABLE0)));
135 PiHeaderFieldModel fieldModel = tableModel.matchFields().stream()
136 .filter(m -> m.field().type().name().equals(INGRESS_PORT))
137 .findFirst()
138 .orElseThrow(() -> new RuntimeException(format(
139 "No such match field in table '%s' with name '%s'", TABLE0, INGRESS_PORT)))
140 .field();
141 return PiHeaderFieldId.of(fieldModel.header().name(), INGRESS_PORT);
142 }
143
144 private static int extractPortFieldBitWidth(PiPipelineModel model) {
145 /*
146 Get it form the set_egress_port action parameters.
147 */
148 return model
149 .action(SET_EGRESS_PORT).orElseThrow(() -> new RuntimeException(format(
150 "No such action '%s' in pipeline model", SET_EGRESS_PORT)))
151 .param(PORT).orElseThrow(() -> new RuntimeException(format(
152 "No such parameter '%s' of action '%s' in pipeline model", PORT, SET_EGRESS_PORT)))
153 .bitWidth();
154 }
155
156
157 @Override
158 public PiAction mapTreatment(TrafficTreatment treatment, PiTableId piTableId) throws PiInterpreterException {
159
160 if (treatment.allInstructions().size() == 0) {
161 // No instructions means drop for us.
162 return actionWithName(DROP);
163 } else if (treatment.allInstructions().size() > 1) {
164 // Otherwise, we understand treatments with only 1 instruction.
165 throw new PiPipelineInterpreter.PiInterpreterException("Treatment has multiple instructions");
166 }
167
168 Instruction instruction = treatment.allInstructions().get(0);
169
170 switch (instruction.type()) {
171 case OUTPUT:
172 Instructions.OutputInstruction outInstruction = (Instructions.OutputInstruction) instruction;
173 PortNumber port = outInstruction.port();
174 if (!port.isLogical()) {
175 return PiAction.builder()
176 .withId(PiActionId.of(SET_EGRESS_PORT))
177 .withParameter(new PiActionParam(PiActionParamId.of(PORT), copyFrom(port.toLong())))
178 .build();
179 } else if (port.equals(CONTROLLER)) {
180 return actionWithName(SEND_TO_CPU);
181 } else {
182 throw new PiInterpreterException(format("Egress on logical port '%s' not supported", port));
183 }
184 case NOACTION:
185 return actionWithName(DROP);
186 default:
187 throw new PiInterpreterException(format("Instruction type '%s' not supported", instruction.type()));
188 }
189 }
190
191 @Override
192 public Collection<PiPacketOperation> mapOutboundPacket(OutboundPacket packet)
193 throws PiInterpreterException {
194 TrafficTreatment treatment = packet.treatment();
195
196 // default.p4 supports only OUTPUT instructions.
197 List<Instructions.OutputInstruction> outInstructions = treatment.allInstructions()
198 .stream()
199 .filter(i -> i.type().equals(OUTPUT))
200 .map(i -> (Instructions.OutputInstruction) i)
201 .collect(toList());
202
203 if (treatment.allInstructions().size() != outInstructions.size()) {
204 // There are other instructions that are not of type OUTPUT.
205 throw new PiInterpreterException("Treatment not supported: " + treatment);
206 }
207
208 ImmutableList.Builder<PiPacketOperation> builder = ImmutableList.builder();
209 for (Instructions.OutputInstruction outInst : outInstructions) {
210 if (outInst.port().isLogical() && !outInst.port().equals(FLOOD)) {
211 throw new PiInterpreterException(format("Output on logical port '%s' not supported", outInst.port()));
212 } else if (outInst.port().equals(FLOOD)) {
213 // Since default.p4 does not support flooding, we create a packet operation for each switch port.
214 for (Port port : handler().get(DeviceService.class).getPorts(packet.sendThrough())) {
215 builder.add(createPiPacketOperation(packet.data(), port.number().toLong()));
216 }
217 } else {
218 builder.add(createPiPacketOperation(packet.data(), outInst.port().toLong()));
219 }
220 }
221 return builder.build();
222 }
223
224 @Override
225 public InboundPacket mapInboundPacket(DeviceId deviceId, PiPacketOperation packetIn)
226 throws PiInterpreterException {
227 // Assuming that the packet is ethernet, which is fine since default.p4 can deparse only ethernet packets.
228 Ethernet ethPkt = new Ethernet();
229
230 ethPkt.deserialize(packetIn.data().asArray(), 0, packetIn.data().size());
231
232 // Returns the ingress port packet metadata.
233 Optional<PiPacketMetadata> packetMetadata = packetIn.metadatas()
234 .stream().filter(metadata -> metadata.id().name().equals(INGRESS_PORT))
235 .findFirst();
236
237 if (packetMetadata.isPresent()) {
238 ImmutableByteSequence portByteSequence = packetMetadata.get().value();
239 short s = portByteSequence.asReadOnlyBuffer().getShort();
240 ConnectPoint receivedFrom = new ConnectPoint(deviceId, PortNumber.portNumber(s));
241 ByteBuffer rawData = ByteBuffer.wrap(packetIn.data().asArray());
242 return new DefaultInboundPacket(receivedFrom, ethPkt, rawData);
243 } else {
244 throw new PiInterpreterException(format(
245 "Missing metadata '%s' in packet-in received from '%s': %s", INGRESS_PORT, deviceId, packetIn));
246 }
247 }
248
249 private PiPacketOperation createPiPacketOperation(ByteBuffer data, long portNumber) throws PiInterpreterException {
250 PiPacketMetadata metadata = createPacketMetadata(portNumber);
251 return PiPacketOperation.builder()
252 .withType(PACKET_OUT)
253 .withData(copyFrom(data))
254 .withMetadatas(ImmutableList.of(metadata))
255 .build();
256 }
257
258 private PiPacketMetadata createPacketMetadata(long portNumber) throws PiInterpreterException {
259 initTargetSpecificAttributes();
260 try {
261 return PiPacketMetadata.builder()
262 .withId(PiPacketMetadataId.of(EGRESS_PORT))
263 .withValue(fit(copyFrom(portNumber), portFieldBitWidth))
264 .build();
265 } catch (ImmutableByteSequence.ByteSequenceTrimException e) {
266 throw new PiInterpreterException(format("Port number %d too big, %s", portNumber, e.getMessage()));
267 }
268 }
269
270 /**
271 * Returns an action instance with no runtime parameters.
272 */
273 private PiAction actionWithName(String name) {
274 return PiAction.builder().withId(PiActionId.of(name)).build();
275 }
276
277 @Override
278 public Optional<PiHeaderFieldId> mapCriterionType(Criterion.Type type) {
279 initTargetSpecificAttributes();
280 return Optional.ofNullable(criterionMap.get(type));
281 }
282
283 @Override
284 public Optional<Criterion.Type> mapPiHeaderFieldId(PiHeaderFieldId headerFieldId) {
285 initTargetSpecificAttributes();
286 return Optional.ofNullable(criterionMap.inverse().get(headerFieldId));
287 }
288
289 @Override
290 public Optional<PiTableId> mapFlowRuleTableId(int flowRuleTableId) {
291 return Optional.ofNullable(TABLE_MAP.get(flowRuleTableId));
292 }
293
294 @Override
295 public Optional<Integer> mapPiTableId(PiTableId piTableId) {
296 return Optional.ofNullable(TABLE_MAP.inverse().get(piTableId));
297 }
298}