blob: d8a76d47231f5cfd34e2def747a8e3b5fb8fb509 [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();
Carmelo Casconea966c342017-07-30 01:56:30 -0400113 this.executorService = Executors.newFixedThreadPool(15, groupedThreads(
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400114 "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();
Carmelo Casconea966c342017-07-30 01:56:30 -0400136 } catch (Throwable ex) {
137 log.error("Exception in P4Runtime client of {}", deviceId, ex);
138 throw ex;
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400139 } finally {
140 writeLock.unlock();
141 }
142 }, contextExecutor);
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400143 }
144
145 @Override
146 public CompletableFuture<Boolean> initStreamChannel() {
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400147 return supplyInContext(this::doInitStreamChannel);
Carmelo Cascone59f57de2017-07-11 19:55:09 -0400148 }
149
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400150 @Override
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400151 public CompletableFuture<Boolean> setPipelineConfig(PiPipeconf pipeconf, ExtensionType targetConfigExtType) {
152 return supplyInContext(() -> doSetPipelineConfig(pipeconf, targetConfigExtType));
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400153 }
154
155 @Override
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400156 public CompletableFuture<Boolean> writeTableEntries(Collection<PiTableEntry> piTableEntries,
157 WriteOperationType opType, PiPipeconf pipeconf) {
158 return supplyInContext(() -> doWriteTableEntries(piTableEntries, opType, pipeconf));
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400159 }
160
161 @Override
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400162 public CompletableFuture<Collection<PiTableEntry>> dumpTable(PiTableId piTableId, PiPipeconf pipeconf) {
163 return supplyInContext(() -> doDumpTable(piTableId, pipeconf));
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400164 }
165
166 @Override
Andrea Campanella432f7182017-07-14 18:43:27 +0200167 public CompletableFuture<Boolean> packetOut(PiPacketOperation packet, PiPipeconf pipeconf) {
Andrea Campanellafc1d34c2017-07-18 17:01:41 +0200168 return supplyInContext(() -> doPacketOut(packet, pipeconf));
Andrea Campanella432f7182017-07-14 18:43:27 +0200169 }
170
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400171 /* Blocking method implementations below */
172
173 private boolean doInitStreamChannel() {
174 // To listen for packets and other events, we need to start the RPC.
175 // Here we do it by sending a master arbitration update.
176 log.info("initializing stream chanel on {}...", deviceId);
177 if (!doArbitrationUpdate()) {
178 log.warn("Unable to initialize stream channel for {}", deviceId);
179 return false;
180 } else {
181 return true;
182 }
183 }
184
185 private boolean doArbitrationUpdate() {
186 log.info("Sending arbitration update to {}...", deviceId);
187 StreamMessageRequest requestMsg = StreamMessageRequest.newBuilder()
188 .setArbitration(MasterArbitrationUpdate.newBuilder()
189 .setDeviceId(p4DeviceId)
190 .build())
191 .build();
192 try {
193 streamRequestObserver.onNext(requestMsg);
194 return true;
195 } catch (StatusRuntimeException e) {
196 log.warn("Arbitration update failed for {}: {}", deviceId, e);
197 return false;
198 }
199 }
200
201 private boolean doSetPipelineConfig(PiPipeconf pipeconf, ExtensionType targetConfigExtType) {
202
203 log.info("Setting pipeline config for {} to {} using {}...", deviceId, pipeconf.id(), targetConfigExtType);
204
205 P4Info p4Info = PipeconfHelper.getP4Info(pipeconf);
206 if (p4Info == null) {
207 // Problem logged by PipeconfHelper.
208 return false;
209 }
210
211 if (!pipeconf.extension(targetConfigExtType).isPresent()) {
212 log.warn("Missing extension {} in pipeconf {}", targetConfigExtType, pipeconf.id());
213 return false;
214 }
215
216 InputStream targetConfig = pipeconf.extension(targetConfigExtType).get();
217 P4Config.P4DeviceConfig p4DeviceConfigMsg;
218 try {
219 p4DeviceConfigMsg = P4Config.P4DeviceConfig
220 .newBuilder()
221 .setExtras(P4Config.P4DeviceConfig.Extras.getDefaultInstance())
222 .setReassign(true)
223 .setDeviceData(ByteString.readFrom(targetConfig))
224 .build();
225 } catch (IOException ex) {
226 log.warn("Unable to load target-specific config for {}: {}", deviceId, ex.getMessage());
227 return false;
228 }
229
230 SetForwardingPipelineConfigRequest request = SetForwardingPipelineConfigRequest
231 .newBuilder()
232 .setAction(VERIFY_AND_COMMIT)
233 .addConfigs(ForwardingPipelineConfig
234 .newBuilder()
235 .setDeviceId(p4DeviceId)
236 .setP4Info(p4Info)
237 .setP4DeviceConfig(p4DeviceConfigMsg.toByteString())
238 .build())
239 .build();
240
241 try {
242 this.blockingStub.setForwardingPipelineConfig(request);
243
244 } catch (StatusRuntimeException ex) {
245 log.warn("Unable to set pipeline config for {}: {}", deviceId, ex.getMessage());
246 return false;
247 }
248
249 return true;
250 }
251
252 private boolean doWriteTableEntries(Collection<PiTableEntry> piTableEntries, WriteOperationType opType,
253 PiPipeconf pipeconf) {
254
255 WriteRequest.Builder writeRequestBuilder = WriteRequest.newBuilder();
256
257 Collection<Update> updateMsgs = TableEntryEncoder.encode(piTableEntries, pipeconf)
258 .stream()
259 .map(tableEntryMsg ->
260 Update.newBuilder()
261 .setEntity(Entity.newBuilder()
262 .setTableEntry(tableEntryMsg)
263 .build())
264 .setType(UPDATE_TYPES.get(opType))
265 .build())
266 .collect(Collectors.toList());
267
268 if (updateMsgs.size() == 0) {
269 return true;
270 }
271
272 writeRequestBuilder
273 .setDeviceId(p4DeviceId)
274 .setElectionId(Uint128.newBuilder()
275 .setHigh(0)
276 .setLow(ELECTION_ID)
277 .build())
278 .addAllUpdates(updateMsgs)
279 .build();
280
281 try {
282 blockingStub.write(writeRequestBuilder.build());
283 return true;
284 } catch (StatusRuntimeException e) {
285 log.warn("Unable to write table entries ({}): {}", opType, e.getMessage());
286 return false;
287 }
288 }
289
290 private Collection<PiTableEntry> doDumpTable(PiTableId piTableId, PiPipeconf pipeconf) {
291
292 log.info("Dumping table {} from {} (pipeconf {})...", piTableId, deviceId, pipeconf.id());
293
294 P4InfoBrowser browser = PipeconfHelper.getP4InfoBrowser(pipeconf);
295 int tableId;
296 try {
297 tableId = browser.tables().getByName(piTableId.id()).getPreamble().getId();
298 } catch (P4InfoBrowser.NotFoundException e) {
299 log.warn("Unable to dump table: {}", e.getMessage());
300 return Collections.emptyList();
301 }
302
303 ReadRequest requestMsg = ReadRequest.newBuilder()
304 .setDeviceId(p4DeviceId)
305 .addEntities(Entity.newBuilder()
306 .setTableEntry(TableEntry.newBuilder()
307 .setTableId(tableId)
308 .build())
309 .build())
310 .build();
311
312 Iterator<ReadResponse> responses;
313 try {
314 responses = blockingStub.read(requestMsg);
315 } catch (StatusRuntimeException e) {
316 log.warn("Unable to dump table: {}", e.getMessage());
317 return Collections.emptyList();
318 }
319
320 Iterable<ReadResponse> responseIterable = () -> responses;
321 List<TableEntry> tableEntryMsgs = StreamSupport
322 .stream(responseIterable.spliterator(), false)
323 .map(ReadResponse::getEntitiesList)
324 .flatMap(List::stream)
325 .filter(entity -> entity.getEntityCase() == TABLE_ENTRY)
326 .map(Entity::getTableEntry)
327 .collect(Collectors.toList());
328
329 log.info("Retrieved {} entries from table {} on {}...", tableEntryMsgs.size(), piTableId, deviceId);
330
331 return TableEntryEncoder.decode(tableEntryMsgs, pipeconf);
332 }
333
Andrea Campanellafc1d34c2017-07-18 17:01:41 +0200334 private boolean doPacketOut(PiPacketOperation packet, PiPipeconf pipeconf) {
335 try {
336 //encode the PiPacketOperation into a PacketOut
337 PacketOut packetOut = PacketIOCodec.encodePacketOut(packet, pipeconf);
338
339 //Build the request
340 StreamMessageRequest packetOutRequest = StreamMessageRequest
341 .newBuilder().setPacket(packetOut).build();
342
343 //Send the request
344 streamRequestObserver.onNext(packetOutRequest);
345
346 } catch (P4InfoBrowser.NotFoundException e) {
347 log.error("Cant find expected metadata in p4Info file. {}", e.getMessage());
348 log.debug("Exception", e);
349 return false;
350 }
351 return true;
352 }
353
Carmelo Casconea966c342017-07-30 01:56:30 -0400354 private void doPacketIn(PacketIn packetInMsg) {
355
356 // Retrieve the pipeconf for this client's device.
357 PiPipeconfService pipeconfService = DefaultServiceDirectory.getService(PiPipeconfService.class);
358 if (pipeconfService == null) {
359 throw new IllegalStateException("PiPipeconfService is null. Can't handle packet in.");
360 }
361 final PiPipeconf pipeconf;
362 if (pipeconfService.ofDevice(deviceId).isPresent() &&
363 pipeconfService.getPipeconf(pipeconfService.ofDevice(deviceId).get()).isPresent()) {
364 pipeconf = pipeconfService.getPipeconf(pipeconfService.ofDevice(deviceId).get()).get();
365 } else {
366 log.warn("Unable to get pipeconf of {}. Can't handle packet in", deviceId);
367 return;
368 }
369 // Decode packet message and post event.
370 P4RuntimeEvent event = new DefaultPacketInEvent(deviceId, PacketIOCodec.decodePacketIn(packetInMsg, pipeconf));
371 log.debug("Received packet in: {}", event);
372 controller.postEvent(event);
373 }
374
375 private void doArbitrationUpdateFromDevice(MasterArbitrationUpdate arbitrationMsg) {
376
377 log.warn("Received arbitration update from {} (NOT IMPLEMENTED YET): {}", deviceId, arbitrationMsg);
378 }
379
Carmelo Casconeb2e3dba2017-07-27 12:07:09 -0400380 /**
381 * Returns the internal P4 device ID associated with this client.
382 *
383 * @return P4 device ID
384 */
385 public int p4DeviceId() {
386 return p4DeviceId;
387 }
388
389 /**
390 * For testing purpose only. TODO: remove before release.
391 *
392 * @return blocking stub
393 */
394 public P4RuntimeGrpc.P4RuntimeBlockingStub blockingStub() {
395 return this.blockingStub;
396 }
397
Andrea Campanellafc1d34c2017-07-18 17:01:41 +0200398
Andrea Campanella432f7182017-07-14 18:43:27 +0200399 @Override
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400400 public void shutdown() {
401
Carmelo Cascone59f57de2017-07-11 19:55:09 -0400402 log.info("Shutting down client for {}...", deviceId);
403
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400404 writeLock.lock();
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400405 try {
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400406 if (streamRequestObserver != null) {
407 streamRequestObserver.onCompleted();
408 cancellableContext.cancel(new InterruptedException("Requested client shutdown"));
409 }
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400410
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400411 this.executorService.shutdown();
412 try {
413 executorService.awaitTermination(5, TimeUnit.SECONDS);
414 } catch (InterruptedException e) {
415 log.warn("Executor service didn't shutdown in time.");
416 }
417 } finally {
418 writeLock.unlock();
419 }
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400420 }
421
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400422 /**
423 * Handles messages received from the device on the stream channel.
424 */
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400425 private class StreamChannelResponseObserver implements StreamObserver<StreamMessageResponse> {
426
427 @Override
428 public void onNext(StreamMessageResponse message) {
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400429 executorService.submit(() -> doNext(message));
430 }
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400431
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400432 private void doNext(StreamMessageResponse message) {
Carmelo Casconea966c342017-07-30 01:56:30 -0400433 try {
434 log.info("Received message on stream channel from {}: {}", deviceId, message.getUpdateCase());
435 switch (message.getUpdateCase()) {
436 case PACKET:
437 // Packet-in
438 doPacketIn(message.getPacket());
Andrea Campanella288b2732017-07-28 14:16:16 +0200439 return;
Carmelo Casconea966c342017-07-30 01:56:30 -0400440 case ARBITRATION:
441 doArbitrationUpdateFromDevice(message.getArbitration());
442 return;
443 default:
444 log.warn("Unrecognized stream message from {}: {}", deviceId, message.getUpdateCase());
445 }
446 } catch (Throwable ex) {
447 log.error("Exception while processing stream channel message from {}", deviceId, ex);
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400448 }
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400449 }
450
451 @Override
452 public void onError(Throwable throwable) {
Carmelo Cascone59f57de2017-07-11 19:55:09 -0400453 log.warn("Error on stream channel for {}: {}", deviceId, Status.fromThrowable(throwable));
454 // FIXME: we might want to recreate the channel.
455 // In general, we want to be robust against any transient error and, if the channel is open, make sure the
456 // stream channel is always on.
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400457 }
458
459 @Override
460 public void onCompleted() {
Carmelo Cascone59f57de2017-07-11 19:55:09 -0400461 log.warn("Stream channel for {} has completed", deviceId);
462 // FIXME: same concern as before.
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400463 }
464 }
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400465}