blob: a7d77266a5cd552ab5058257fb052267745c56d0 [file] [log] [blame]
Carmelo Casconef7aa3f92017-07-06 23:56:50 -04001/*
2 * Copyright 2017-present Open Networking Laboratory
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.p4runtime.ctl;
18
Carmelo Cascone8d99b172017-07-18 17:26:31 -040019import com.google.common.collect.ImmutableMap;
Carmelo Casconef7aa3f92017-07-06 23:56:50 -040020import com.google.protobuf.ByteString;
Carmelo Cascone59f57de2017-07-11 19:55:09 -040021import io.grpc.Context;
Carmelo Casconef7aa3f92017-07-06 23:56:50 -040022import io.grpc.ManagedChannel;
23import io.grpc.Status;
24import io.grpc.StatusRuntimeException;
25import io.grpc.stub.StreamObserver;
Andrea Campanella288b2732017-07-28 14:16:16 +020026import org.onlab.osgi.DefaultServiceDirectory;
Carmelo Casconef7aa3f92017-07-06 23:56:50 -040027import org.onosproject.net.DeviceId;
Andrea Campanella432f7182017-07-14 18:43:27 +020028import org.onosproject.net.pi.model.PiPipeconf;
29import org.onosproject.net.pi.runtime.PiPacketOperation;
Andrea Campanella288b2732017-07-28 14:16:16 +020030import org.onosproject.net.pi.runtime.PiPipeconfService;
Carmelo Casconef7aa3f92017-07-06 23:56:50 -040031import org.onosproject.net.pi.runtime.PiTableEntry;
32import org.onosproject.net.pi.runtime.PiTableId;
33import org.onosproject.p4runtime.api.P4RuntimeClient;
34import org.onosproject.p4runtime.api.P4RuntimeEvent;
35import org.slf4j.Logger;
36import p4.P4RuntimeGrpc;
Carmelo Cascone8d99b172017-07-18 17:26:31 -040037import p4.P4RuntimeOuterClass.Entity;
38import p4.P4RuntimeOuterClass.ForwardingPipelineConfig;
39import p4.P4RuntimeOuterClass.MasterArbitrationUpdate;
40import p4.P4RuntimeOuterClass.PacketIn;
41import p4.P4RuntimeOuterClass.ReadRequest;
42import p4.P4RuntimeOuterClass.ReadResponse;
43import p4.P4RuntimeOuterClass.SetForwardingPipelineConfigRequest;
44import p4.P4RuntimeOuterClass.StreamMessageRequest;
45import p4.P4RuntimeOuterClass.StreamMessageResponse;
46import p4.P4RuntimeOuterClass.TableEntry;
47import p4.P4RuntimeOuterClass.Uint128;
48import p4.P4RuntimeOuterClass.Update;
49import p4.P4RuntimeOuterClass.WriteRequest;
Andrea Campanellafc1d34c2017-07-18 17:01:41 +020050import p4.config.P4InfoOuterClass.P4Info;
Carmelo Casconef7aa3f92017-07-06 23:56:50 -040051import p4.tmp.P4Config;
52
53import java.io.IOException;
54import java.io.InputStream;
Carmelo Casconef7aa3f92017-07-06 23:56:50 -040055import java.util.Collection;
Carmelo Cascone8d99b172017-07-18 17:26:31 -040056import java.util.Collections;
57import java.util.Iterator;
58import java.util.List;
59import java.util.Map;
Carmelo Casconef7aa3f92017-07-06 23:56:50 -040060import java.util.concurrent.CompletableFuture;
Carmelo Cascone8d99b172017-07-18 17:26:31 -040061import java.util.concurrent.Executor;
Carmelo Casconef7aa3f92017-07-06 23:56:50 -040062import java.util.concurrent.ExecutorService;
Carmelo Cascone8d99b172017-07-18 17:26:31 -040063import java.util.concurrent.Executors;
Carmelo Casconef7aa3f92017-07-06 23:56:50 -040064import java.util.concurrent.TimeUnit;
Carmelo Cascone8d99b172017-07-18 17:26:31 -040065import java.util.concurrent.locks.Lock;
66import java.util.concurrent.locks.ReentrantLock;
67import java.util.function.Supplier;
68import java.util.stream.Collectors;
69import java.util.stream.StreamSupport;
Carmelo Casconef7aa3f92017-07-06 23:56:50 -040070
Carmelo Cascone8d99b172017-07-18 17:26:31 -040071import static org.onlab.util.Tools.groupedThreads;
72import static org.onosproject.net.pi.model.PiPipeconf.ExtensionType;
Carmelo Casconef7aa3f92017-07-06 23:56:50 -040073import static org.slf4j.LoggerFactory.getLogger;
Carmelo Cascone8d99b172017-07-18 17:26:31 -040074import static p4.P4RuntimeOuterClass.Entity.EntityCase.TABLE_ENTRY;
Andrea Campanellafc1d34c2017-07-18 17:01:41 +020075import static p4.P4RuntimeOuterClass.PacketOut;
Carmelo Casconef7aa3f92017-07-06 23:56:50 -040076import static p4.P4RuntimeOuterClass.SetForwardingPipelineConfigRequest.Action.VERIFY_AND_COMMIT;
77
78/**
79 * Implementation of a P4Runtime client.
80 */
Carmelo Cascone8d99b172017-07-18 17:26:31 -040081public final class P4RuntimeClientImpl implements P4RuntimeClient {
Carmelo Casconef7aa3f92017-07-06 23:56:50 -040082
83 private static final int DEADLINE_SECONDS = 15;
84
Carmelo Cascone8d99b172017-07-18 17:26:31 -040085 // FIXME: use static election ID, since mastership arbitration is not yet support on BMv2 or Tofino.
86 private static final int ELECTION_ID = 1;
87
88 private static final Map<WriteOperationType, Update.Type> UPDATE_TYPES = ImmutableMap.of(
89 WriteOperationType.UNSPECIFIED, Update.Type.UNSPECIFIED,
90 WriteOperationType.INSERT, Update.Type.INSERT,
91 WriteOperationType.MODIFY, Update.Type.MODIFY,
92 WriteOperationType.DELETE, Update.Type.DELETE
93 );
94
Carmelo Casconef7aa3f92017-07-06 23:56:50 -040095 private final Logger log = getLogger(getClass());
96
97 private final DeviceId deviceId;
98 private final int p4DeviceId;
99 private final P4RuntimeControllerImpl controller;
100 private final P4RuntimeGrpc.P4RuntimeBlockingStub blockingStub;
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400101 private final Context.CancellableContext cancellableContext;
102 private final ExecutorService executorService;
103 private final Executor contextExecutor;
104 private final Lock writeLock = new ReentrantLock();
105 private final StreamObserver<StreamMessageRequest> streamRequestObserver;
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400106
107
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400108 P4RuntimeClientImpl(DeviceId deviceId, int p4DeviceId, ManagedChannel channel, P4RuntimeControllerImpl controller) {
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400109 this.deviceId = deviceId;
110 this.p4DeviceId = p4DeviceId;
111 this.controller = controller;
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400112 this.cancellableContext = Context.current().withCancellation();
113 this.executorService = Executors.newFixedThreadPool(5, groupedThreads(
114 "onos/p4runtime-client-" + deviceId.toString(),
115 deviceId.toString() + "-%d"));
116 this.contextExecutor = this.cancellableContext.fixedContextExecutor(executorService);
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400117 this.blockingStub = P4RuntimeGrpc.newBlockingStub(channel)
118 .withDeadlineAfter(DEADLINE_SECONDS, TimeUnit.SECONDS);
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400119 P4RuntimeGrpc.P4RuntimeStub asyncStub = P4RuntimeGrpc.newStub(channel);
120 this.streamRequestObserver = asyncStub.streamChannel(new StreamChannelResponseObserver());
121 }
122
123 /**
124 * Executes the given task (supplier) in the gRPC context executor of this client, such that if the context is
125 * cancelled (e.g. client shutdown) the RPC is automatically cancelled.
126 * <p>
127 * Important: Tasks submitted in parallel by different threads are forced executed sequentially.
128 * <p>
129 */
130 private <U> CompletableFuture<U> supplyInContext(Supplier<U> supplier) {
131 return CompletableFuture.supplyAsync(() -> {
132 // TODO: explore a more relaxed locking strategy.
133 writeLock.lock();
134 try {
135 return supplier.get();
136 } finally {
137 writeLock.unlock();
138 }
139 }, contextExecutor);
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400140 }
141
142 @Override
143 public CompletableFuture<Boolean> initStreamChannel() {
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400144 return supplyInContext(this::doInitStreamChannel);
Carmelo Cascone59f57de2017-07-11 19:55:09 -0400145 }
146
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400147 @Override
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400148 public CompletableFuture<Boolean> setPipelineConfig(PiPipeconf pipeconf, ExtensionType targetConfigExtType) {
149 return supplyInContext(() -> doSetPipelineConfig(pipeconf, targetConfigExtType));
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400150 }
151
152 @Override
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400153 public CompletableFuture<Boolean> writeTableEntries(Collection<PiTableEntry> piTableEntries,
154 WriteOperationType opType, PiPipeconf pipeconf) {
155 return supplyInContext(() -> doWriteTableEntries(piTableEntries, opType, pipeconf));
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400156 }
157
158 @Override
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400159 public CompletableFuture<Collection<PiTableEntry>> dumpTable(PiTableId piTableId, PiPipeconf pipeconf) {
160 return supplyInContext(() -> doDumpTable(piTableId, pipeconf));
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400161 }
162
163 @Override
Andrea Campanella432f7182017-07-14 18:43:27 +0200164 public CompletableFuture<Boolean> packetOut(PiPacketOperation packet, PiPipeconf pipeconf) {
Andrea Campanellafc1d34c2017-07-18 17:01:41 +0200165 return supplyInContext(() -> doPacketOut(packet, pipeconf));
Andrea Campanella432f7182017-07-14 18:43:27 +0200166 }
167
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400168 /* Blocking method implementations below */
169
170 private boolean doInitStreamChannel() {
171 // To listen for packets and other events, we need to start the RPC.
172 // Here we do it by sending a master arbitration update.
173 log.info("initializing stream chanel on {}...", deviceId);
174 if (!doArbitrationUpdate()) {
175 log.warn("Unable to initialize stream channel for {}", deviceId);
176 return false;
177 } else {
178 return true;
179 }
180 }
181
182 private boolean doArbitrationUpdate() {
183 log.info("Sending arbitration update to {}...", deviceId);
184 StreamMessageRequest requestMsg = StreamMessageRequest.newBuilder()
185 .setArbitration(MasterArbitrationUpdate.newBuilder()
186 .setDeviceId(p4DeviceId)
187 .build())
188 .build();
189 try {
190 streamRequestObserver.onNext(requestMsg);
191 return true;
192 } catch (StatusRuntimeException e) {
193 log.warn("Arbitration update failed for {}: {}", deviceId, e);
194 return false;
195 }
196 }
197
198 private boolean doSetPipelineConfig(PiPipeconf pipeconf, ExtensionType targetConfigExtType) {
199
200 log.info("Setting pipeline config for {} to {} using {}...", deviceId, pipeconf.id(), targetConfigExtType);
201
202 P4Info p4Info = PipeconfHelper.getP4Info(pipeconf);
203 if (p4Info == null) {
204 // Problem logged by PipeconfHelper.
205 return false;
206 }
207
208 if (!pipeconf.extension(targetConfigExtType).isPresent()) {
209 log.warn("Missing extension {} in pipeconf {}", targetConfigExtType, pipeconf.id());
210 return false;
211 }
212
213 InputStream targetConfig = pipeconf.extension(targetConfigExtType).get();
214 P4Config.P4DeviceConfig p4DeviceConfigMsg;
215 try {
216 p4DeviceConfigMsg = P4Config.P4DeviceConfig
217 .newBuilder()
218 .setExtras(P4Config.P4DeviceConfig.Extras.getDefaultInstance())
219 .setReassign(true)
220 .setDeviceData(ByteString.readFrom(targetConfig))
221 .build();
222 } catch (IOException ex) {
223 log.warn("Unable to load target-specific config for {}: {}", deviceId, ex.getMessage());
224 return false;
225 }
226
227 SetForwardingPipelineConfigRequest request = SetForwardingPipelineConfigRequest
228 .newBuilder()
229 .setAction(VERIFY_AND_COMMIT)
230 .addConfigs(ForwardingPipelineConfig
231 .newBuilder()
232 .setDeviceId(p4DeviceId)
233 .setP4Info(p4Info)
234 .setP4DeviceConfig(p4DeviceConfigMsg.toByteString())
235 .build())
236 .build();
237
238 try {
239 this.blockingStub.setForwardingPipelineConfig(request);
240
241 } catch (StatusRuntimeException ex) {
242 log.warn("Unable to set pipeline config for {}: {}", deviceId, ex.getMessage());
243 return false;
244 }
245
246 return true;
247 }
248
249 private boolean doWriteTableEntries(Collection<PiTableEntry> piTableEntries, WriteOperationType opType,
250 PiPipeconf pipeconf) {
251
252 WriteRequest.Builder writeRequestBuilder = WriteRequest.newBuilder();
253
254 Collection<Update> updateMsgs = TableEntryEncoder.encode(piTableEntries, pipeconf)
255 .stream()
256 .map(tableEntryMsg ->
257 Update.newBuilder()
258 .setEntity(Entity.newBuilder()
259 .setTableEntry(tableEntryMsg)
260 .build())
261 .setType(UPDATE_TYPES.get(opType))
262 .build())
263 .collect(Collectors.toList());
264
265 if (updateMsgs.size() == 0) {
266 return true;
267 }
268
269 writeRequestBuilder
270 .setDeviceId(p4DeviceId)
271 .setElectionId(Uint128.newBuilder()
272 .setHigh(0)
273 .setLow(ELECTION_ID)
274 .build())
275 .addAllUpdates(updateMsgs)
276 .build();
277
278 try {
279 blockingStub.write(writeRequestBuilder.build());
280 return true;
281 } catch (StatusRuntimeException e) {
282 log.warn("Unable to write table entries ({}): {}", opType, e.getMessage());
283 return false;
284 }
285 }
286
287 private Collection<PiTableEntry> doDumpTable(PiTableId piTableId, PiPipeconf pipeconf) {
288
289 log.info("Dumping table {} from {} (pipeconf {})...", piTableId, deviceId, pipeconf.id());
290
291 P4InfoBrowser browser = PipeconfHelper.getP4InfoBrowser(pipeconf);
292 int tableId;
293 try {
294 tableId = browser.tables().getByName(piTableId.id()).getPreamble().getId();
295 } catch (P4InfoBrowser.NotFoundException e) {
296 log.warn("Unable to dump table: {}", e.getMessage());
297 return Collections.emptyList();
298 }
299
300 ReadRequest requestMsg = ReadRequest.newBuilder()
301 .setDeviceId(p4DeviceId)
302 .addEntities(Entity.newBuilder()
303 .setTableEntry(TableEntry.newBuilder()
304 .setTableId(tableId)
305 .build())
306 .build())
307 .build();
308
309 Iterator<ReadResponse> responses;
310 try {
311 responses = blockingStub.read(requestMsg);
312 } catch (StatusRuntimeException e) {
313 log.warn("Unable to dump table: {}", e.getMessage());
314 return Collections.emptyList();
315 }
316
317 Iterable<ReadResponse> responseIterable = () -> responses;
318 List<TableEntry> tableEntryMsgs = StreamSupport
319 .stream(responseIterable.spliterator(), false)
320 .map(ReadResponse::getEntitiesList)
321 .flatMap(List::stream)
322 .filter(entity -> entity.getEntityCase() == TABLE_ENTRY)
323 .map(Entity::getTableEntry)
324 .collect(Collectors.toList());
325
326 log.info("Retrieved {} entries from table {} on {}...", tableEntryMsgs.size(), piTableId, deviceId);
327
328 return TableEntryEncoder.decode(tableEntryMsgs, pipeconf);
329 }
330
Andrea Campanellafc1d34c2017-07-18 17:01:41 +0200331 private boolean doPacketOut(PiPacketOperation packet, PiPipeconf pipeconf) {
332 try {
333 //encode the PiPacketOperation into a PacketOut
334 PacketOut packetOut = PacketIOCodec.encodePacketOut(packet, pipeconf);
335
336 //Build the request
337 StreamMessageRequest packetOutRequest = StreamMessageRequest
338 .newBuilder().setPacket(packetOut).build();
339
340 //Send the request
341 streamRequestObserver.onNext(packetOutRequest);
342
343 } catch (P4InfoBrowser.NotFoundException e) {
344 log.error("Cant find expected metadata in p4Info file. {}", e.getMessage());
345 log.debug("Exception", e);
346 return false;
347 }
348 return true;
349 }
350
Carmelo Casconeb2e3dba2017-07-27 12:07:09 -0400351 /**
352 * Returns the internal P4 device ID associated with this client.
353 *
354 * @return P4 device ID
355 */
356 public int p4DeviceId() {
357 return p4DeviceId;
358 }
359
360 /**
361 * For testing purpose only. TODO: remove before release.
362 *
363 * @return blocking stub
364 */
365 public P4RuntimeGrpc.P4RuntimeBlockingStub blockingStub() {
366 return this.blockingStub;
367 }
368
Andrea Campanellafc1d34c2017-07-18 17:01:41 +0200369
Andrea Campanella432f7182017-07-14 18:43:27 +0200370 @Override
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400371 public void shutdown() {
372
Carmelo Cascone59f57de2017-07-11 19:55:09 -0400373 log.info("Shutting down client for {}...", deviceId);
374
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400375 writeLock.lock();
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400376 try {
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400377 if (streamRequestObserver != null) {
378 streamRequestObserver.onCompleted();
379 cancellableContext.cancel(new InterruptedException("Requested client shutdown"));
380 }
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400381
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400382 this.executorService.shutdown();
383 try {
384 executorService.awaitTermination(5, TimeUnit.SECONDS);
385 } catch (InterruptedException e) {
386 log.warn("Executor service didn't shutdown in time.");
387 }
388 } finally {
389 writeLock.unlock();
390 }
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400391 }
392
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400393 /**
394 * Handles messages received from the device on the stream channel.
395 */
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400396 private class StreamChannelResponseObserver implements StreamObserver<StreamMessageResponse> {
397
398 @Override
399 public void onNext(StreamMessageResponse message) {
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400400 executorService.submit(() -> doNext(message));
401 }
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400402
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400403 private void doNext(StreamMessageResponse message) {
404 log.info("Received message on stream channel from {}: {}", deviceId, message.getUpdateCase());
405 switch (message.getUpdateCase()) {
406 case PACKET:
407 // Packet-in
408 PacketIn packetIn = message.getPacket();
Andrea Campanella288b2732017-07-28 14:16:16 +0200409
410 // Retrieve the pipeconf for the specific device
411 PiPipeconfService pipeconfService = DefaultServiceDirectory.getService(PiPipeconfService.class);
412 if (pipeconfService == null) {
413 throw new IllegalStateException("PiPipeconfService is null. Can't handle packet in.");
414 }
415
416 final PiPipeconf pipeconf;
417 if (pipeconfService.ofDevice(deviceId).isPresent() &&
418 pipeconfService.getPipeconf(pipeconfService.ofDevice(deviceId).get()).isPresent()) {
419 pipeconf = pipeconfService.getPipeconf(pipeconfService.ofDevice(deviceId).get()).get();
420 } else {
421 log.warn("Unable to get the pipeconf of the {}. Can't handle packet in", deviceId);
422 return;
423 }
424 //decode the packet and generate a corresponding p4Runtime event containing the PiPacketOperation
425 P4RuntimeEvent event =
426 new DefaultPacketInEvent(deviceId, PacketIOCodec.decodePacketIn(packetIn, pipeconf));
427
428 //posting the event upwards
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400429 controller.postEvent(event);
430 return;
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400431
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400432 case ARBITRATION:
433 throw new UnsupportedOperationException("Arbitration not implemented.");
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400434
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400435 default:
436 log.warn("Unrecognized stream message from {}: {}", deviceId, message.getUpdateCase());
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400437 }
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400438 }
439
440 @Override
441 public void onError(Throwable throwable) {
Carmelo Cascone59f57de2017-07-11 19:55:09 -0400442 log.warn("Error on stream channel for {}: {}", deviceId, Status.fromThrowable(throwable));
443 // FIXME: we might want to recreate the channel.
444 // In general, we want to be robust against any transient error and, if the channel is open, make sure the
445 // stream channel is always on.
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400446 }
447
448 @Override
449 public void onCompleted() {
Carmelo Cascone59f57de2017-07-11 19:55:09 -0400450 log.warn("Stream channel for {} has completed", deviceId);
451 // FIXME: same concern as before.
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400452 }
453 }
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400454}