blob: 26ec75ad849845f0ddf46fc7371d700eadfad939 [file] [log] [blame]
Carmelo Casconef7aa3f92017-07-06 23:56:50 -04001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2017-present Open Networking Foundation
Carmelo Casconef7aa3f92017-07-06 23:56:50 -04003 *
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;
Carmelo Cascone8d99b172017-07-18 17:26:31 -040047import p4.P4RuntimeOuterClass.Update;
48import p4.P4RuntimeOuterClass.WriteRequest;
Andrea Campanellafc1d34c2017-07-18 17:01:41 +020049import p4.config.P4InfoOuterClass.P4Info;
Carmelo Casconef7aa3f92017-07-06 23:56:50 -040050import p4.tmp.P4Config;
51
52import java.io.IOException;
53import java.io.InputStream;
Carmelo Casconef7aa3f92017-07-06 23:56:50 -040054import java.util.Collection;
Carmelo Cascone8d99b172017-07-18 17:26:31 -040055import java.util.Collections;
56import java.util.Iterator;
57import java.util.List;
58import java.util.Map;
Carmelo Casconef7aa3f92017-07-06 23:56:50 -040059import java.util.concurrent.CompletableFuture;
Carmelo Cascone8d99b172017-07-18 17:26:31 -040060import java.util.concurrent.Executor;
Carmelo Casconef7aa3f92017-07-06 23:56:50 -040061import java.util.concurrent.ExecutorService;
Carmelo Cascone8d99b172017-07-18 17:26:31 -040062import java.util.concurrent.Executors;
Carmelo Casconef7aa3f92017-07-06 23:56:50 -040063import java.util.concurrent.TimeUnit;
Carmelo Cascone8d99b172017-07-18 17:26:31 -040064import java.util.concurrent.locks.Lock;
65import java.util.concurrent.locks.ReentrantLock;
66import java.util.function.Supplier;
67import java.util.stream.Collectors;
68import java.util.stream.StreamSupport;
Carmelo Casconef7aa3f92017-07-06 23:56:50 -040069
Carmelo Cascone8d99b172017-07-18 17:26:31 -040070import static org.onlab.util.Tools.groupedThreads;
71import static org.onosproject.net.pi.model.PiPipeconf.ExtensionType;
Carmelo Casconef7aa3f92017-07-06 23:56:50 -040072import static org.slf4j.LoggerFactory.getLogger;
Carmelo Cascone8d99b172017-07-18 17:26:31 -040073import static p4.P4RuntimeOuterClass.Entity.EntityCase.TABLE_ENTRY;
Andrea Campanellafc1d34c2017-07-18 17:01:41 +020074import static p4.P4RuntimeOuterClass.PacketOut;
Carmelo Casconef7aa3f92017-07-06 23:56:50 -040075import static p4.P4RuntimeOuterClass.SetForwardingPipelineConfigRequest.Action.VERIFY_AND_COMMIT;
76
77/**
78 * Implementation of a P4Runtime client.
79 */
Carmelo Cascone8d99b172017-07-18 17:26:31 -040080public final class P4RuntimeClientImpl implements P4RuntimeClient {
Carmelo Casconef7aa3f92017-07-06 23:56:50 -040081
82 private static final int DEADLINE_SECONDS = 15;
83
Carmelo Cascone8d99b172017-07-18 17:26:31 -040084 // FIXME: use static election ID, since mastership arbitration is not yet support on BMv2 or Tofino.
85 private static final int ELECTION_ID = 1;
86
87 private static final Map<WriteOperationType, Update.Type> UPDATE_TYPES = ImmutableMap.of(
88 WriteOperationType.UNSPECIFIED, Update.Type.UNSPECIFIED,
89 WriteOperationType.INSERT, Update.Type.INSERT,
90 WriteOperationType.MODIFY, Update.Type.MODIFY,
91 WriteOperationType.DELETE, Update.Type.DELETE
92 );
93
Carmelo Casconef7aa3f92017-07-06 23:56:50 -040094 private final Logger log = getLogger(getClass());
95
96 private final DeviceId deviceId;
Carmelo Casconef423bec2017-08-30 01:56:25 +020097 private final long p4DeviceId;
Carmelo Casconef7aa3f92017-07-06 23:56:50 -040098 private final P4RuntimeControllerImpl controller;
99 private final P4RuntimeGrpc.P4RuntimeBlockingStub blockingStub;
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400100 private final Context.CancellableContext cancellableContext;
101 private final ExecutorService executorService;
102 private final Executor contextExecutor;
103 private final Lock writeLock = new ReentrantLock();
104 private final StreamObserver<StreamMessageRequest> streamRequestObserver;
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400105
106
Carmelo Casconef423bec2017-08-30 01:56:25 +0200107 P4RuntimeClientImpl(DeviceId deviceId, long p4DeviceId, ManagedChannel channel,
108 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 Cascone2cad9ef2017-08-01 21:52:07 +0200117 //TODO Investigate deadline or timeout in supplyInContext Method
118 this.blockingStub = P4RuntimeGrpc.newBlockingStub(channel);
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 */
Carmelo Cascone2cad9ef2017-08-01 21:52:07 +0200130 private <U> CompletableFuture<U> supplyInContext(Supplier<U> supplier, String opDescription) {
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400131 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) {
Carmelo Cascone2cad9ef2017-08-01 21:52:07 +0200137 log.error("Exception in P4Runtime client of {}, executing {}", deviceId, opDescription, ex);
Carmelo Casconea966c342017-07-30 01:56:30 -0400138 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 Cascone2cad9ef2017-08-01 21:52:07 +0200147 return supplyInContext(this::doInitStreamChannel, "initStreamChannel");
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) {
Carmelo Cascone2cad9ef2017-08-01 21:52:07 +0200152 return supplyInContext(() -> doSetPipelineConfig(pipeconf, targetConfigExtType), "setPipelineConfig");
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) {
Carmelo Cascone2cad9ef2017-08-01 21:52:07 +0200158 return supplyInContext(() -> doWriteTableEntries(piTableEntries, opType, pipeconf),
159 "writeTableEntries-" + opType.name());
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400160 }
161
162 @Override
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400163 public CompletableFuture<Collection<PiTableEntry>> dumpTable(PiTableId piTableId, PiPipeconf pipeconf) {
Carmelo Cascone2cad9ef2017-08-01 21:52:07 +0200164 return supplyInContext(() -> doDumpTable(piTableId, pipeconf), "dumpTable-" + piTableId);
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400165 }
166
167 @Override
Andrea Campanella432f7182017-07-14 18:43:27 +0200168 public CompletableFuture<Boolean> packetOut(PiPacketOperation packet, PiPipeconf pipeconf) {
Carmelo Cascone2cad9ef2017-08-01 21:52:07 +0200169 return supplyInContext(() -> doPacketOut(packet, pipeconf), "packetOut");
Andrea Campanella432f7182017-07-14 18:43:27 +0200170 }
171
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400172 /* Blocking method implementations below */
173
174 private boolean doInitStreamChannel() {
175 // To listen for packets and other events, we need to start the RPC.
176 // Here we do it by sending a master arbitration update.
177 log.info("initializing stream chanel on {}...", deviceId);
178 if (!doArbitrationUpdate()) {
179 log.warn("Unable to initialize stream channel for {}", deviceId);
180 return false;
181 } else {
182 return true;
183 }
184 }
185
186 private boolean doArbitrationUpdate() {
187 log.info("Sending arbitration update to {}...", deviceId);
188 StreamMessageRequest requestMsg = StreamMessageRequest.newBuilder()
189 .setArbitration(MasterArbitrationUpdate.newBuilder()
190 .setDeviceId(p4DeviceId)
191 .build())
192 .build();
193 try {
194 streamRequestObserver.onNext(requestMsg);
195 return true;
196 } catch (StatusRuntimeException e) {
197 log.warn("Arbitration update failed for {}: {}", deviceId, e);
198 return false;
199 }
200 }
201
202 private boolean doSetPipelineConfig(PiPipeconf pipeconf, ExtensionType targetConfigExtType) {
203
204 log.info("Setting pipeline config for {} to {} using {}...", deviceId, pipeconf.id(), targetConfigExtType);
205
206 P4Info p4Info = PipeconfHelper.getP4Info(pipeconf);
207 if (p4Info == null) {
208 // Problem logged by PipeconfHelper.
209 return false;
210 }
211
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400212
Andrea Campanella0288c872017-08-07 18:32:51 +0200213 ForwardingPipelineConfig.Builder pipelineConfigBuilder = ForwardingPipelineConfig
214 .newBuilder()
215 .setDeviceId(p4DeviceId)
216 .setP4Info(p4Info);
217
218 //if the target config extension is null we don't want to add the config.
219 if (targetConfigExtType != null) {
220 if (!pipeconf.extension(targetConfigExtType).isPresent()) {
221 log.warn("Missing extension {} in pipeconf {}", targetConfigExtType, pipeconf.id());
222 return false;
223 }
224 InputStream targetConfig = pipeconf.extension(targetConfigExtType).get();
225 P4Config.P4DeviceConfig p4DeviceConfigMsg;
226 try {
227 p4DeviceConfigMsg = P4Config.P4DeviceConfig
228 .newBuilder()
229 .setExtras(P4Config.P4DeviceConfig.Extras.getDefaultInstance())
230 .setReassign(true)
231 .setDeviceData(ByteString.readFrom(targetConfig))
232 .build();
233
234 pipelineConfigBuilder.setP4DeviceConfig(p4DeviceConfigMsg.toByteString());
235
236 } catch (IOException ex) {
237 log.warn("Unable to load target-specific config for {}: {}", deviceId, ex.getMessage());
238 return false;
239 }
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400240 }
241
242 SetForwardingPipelineConfigRequest request = SetForwardingPipelineConfigRequest
243 .newBuilder()
244 .setAction(VERIFY_AND_COMMIT)
Andrea Campanella0288c872017-08-07 18:32:51 +0200245 .addConfigs(pipelineConfigBuilder.build())
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400246 .build();
247
248 try {
249 this.blockingStub.setForwardingPipelineConfig(request);
250
251 } catch (StatusRuntimeException ex) {
252 log.warn("Unable to set pipeline config for {}: {}", deviceId, ex.getMessage());
253 return false;
254 }
255
256 return true;
257 }
258
259 private boolean doWriteTableEntries(Collection<PiTableEntry> piTableEntries, WriteOperationType opType,
260 PiPipeconf pipeconf) {
261
262 WriteRequest.Builder writeRequestBuilder = WriteRequest.newBuilder();
263
264 Collection<Update> updateMsgs = TableEntryEncoder.encode(piTableEntries, pipeconf)
265 .stream()
266 .map(tableEntryMsg ->
267 Update.newBuilder()
268 .setEntity(Entity.newBuilder()
269 .setTableEntry(tableEntryMsg)
270 .build())
271 .setType(UPDATE_TYPES.get(opType))
272 .build())
273 .collect(Collectors.toList());
274
275 if (updateMsgs.size() == 0) {
276 return true;
277 }
278
279 writeRequestBuilder
280 .setDeviceId(p4DeviceId)
Carmelo Cascone2cad9ef2017-08-01 21:52:07 +0200281 /* PI ignores this ElectionId, commenting out for now.
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400282 .setElectionId(Uint128.newBuilder()
283 .setHigh(0)
284 .setLow(ELECTION_ID)
Carmelo Cascone2cad9ef2017-08-01 21:52:07 +0200285 .build()) */
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400286 .addAllUpdates(updateMsgs)
287 .build();
288
289 try {
290 blockingStub.write(writeRequestBuilder.build());
291 return true;
292 } catch (StatusRuntimeException e) {
293 log.warn("Unable to write table entries ({}): {}", opType, e.getMessage());
294 return false;
295 }
296 }
297
298 private Collection<PiTableEntry> doDumpTable(PiTableId piTableId, PiPipeconf pipeconf) {
299
Carmelo Cascone9f007702017-08-24 13:30:51 +0200300 log.debug("Dumping table {} from {} (pipeconf {})...", piTableId, deviceId, pipeconf.id());
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400301
302 P4InfoBrowser browser = PipeconfHelper.getP4InfoBrowser(pipeconf);
303 int tableId;
304 try {
305 tableId = browser.tables().getByName(piTableId.id()).getPreamble().getId();
306 } catch (P4InfoBrowser.NotFoundException e) {
307 log.warn("Unable to dump table: {}", e.getMessage());
308 return Collections.emptyList();
309 }
310
311 ReadRequest requestMsg = ReadRequest.newBuilder()
312 .setDeviceId(p4DeviceId)
313 .addEntities(Entity.newBuilder()
314 .setTableEntry(TableEntry.newBuilder()
315 .setTableId(tableId)
316 .build())
317 .build())
318 .build();
319
320 Iterator<ReadResponse> responses;
321 try {
322 responses = blockingStub.read(requestMsg);
323 } catch (StatusRuntimeException e) {
324 log.warn("Unable to dump table: {}", e.getMessage());
325 return Collections.emptyList();
326 }
327
328 Iterable<ReadResponse> responseIterable = () -> responses;
329 List<TableEntry> tableEntryMsgs = StreamSupport
330 .stream(responseIterable.spliterator(), false)
331 .map(ReadResponse::getEntitiesList)
332 .flatMap(List::stream)
333 .filter(entity -> entity.getEntityCase() == TABLE_ENTRY)
334 .map(Entity::getTableEntry)
335 .collect(Collectors.toList());
336
Carmelo Cascone9f007702017-08-24 13:30:51 +0200337 log.debug("Retrieved {} entries from table {} on {}...", tableEntryMsgs.size(), piTableId, deviceId);
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400338
339 return TableEntryEncoder.decode(tableEntryMsgs, pipeconf);
340 }
341
Andrea Campanellafc1d34c2017-07-18 17:01:41 +0200342 private boolean doPacketOut(PiPacketOperation packet, PiPipeconf pipeconf) {
343 try {
344 //encode the PiPacketOperation into a PacketOut
345 PacketOut packetOut = PacketIOCodec.encodePacketOut(packet, pipeconf);
346
347 //Build the request
348 StreamMessageRequest packetOutRequest = StreamMessageRequest
349 .newBuilder().setPacket(packetOut).build();
350
351 //Send the request
352 streamRequestObserver.onNext(packetOutRequest);
353
354 } catch (P4InfoBrowser.NotFoundException e) {
355 log.error("Cant find expected metadata in p4Info file. {}", e.getMessage());
356 log.debug("Exception", e);
357 return false;
358 }
359 return true;
360 }
361
Carmelo Casconea966c342017-07-30 01:56:30 -0400362 private void doPacketIn(PacketIn packetInMsg) {
363
364 // Retrieve the pipeconf for this client's device.
365 PiPipeconfService pipeconfService = DefaultServiceDirectory.getService(PiPipeconfService.class);
366 if (pipeconfService == null) {
367 throw new IllegalStateException("PiPipeconfService is null. Can't handle packet in.");
368 }
369 final PiPipeconf pipeconf;
370 if (pipeconfService.ofDevice(deviceId).isPresent() &&
371 pipeconfService.getPipeconf(pipeconfService.ofDevice(deviceId).get()).isPresent()) {
372 pipeconf = pipeconfService.getPipeconf(pipeconfService.ofDevice(deviceId).get()).get();
373 } else {
374 log.warn("Unable to get pipeconf of {}. Can't handle packet in", deviceId);
375 return;
376 }
377 // Decode packet message and post event.
Carmelo Cascone2cad9ef2017-08-01 21:52:07 +0200378 PiPacketOperation packetOperation = PacketIOCodec.decodePacketIn(packetInMsg, pipeconf);
379 DefaultPacketIn packetInEventSubject = new DefaultPacketIn(deviceId, packetOperation);
380 P4RuntimeEvent event = new P4RuntimeEvent(P4RuntimeEvent.Type.PACKET_IN, packetInEventSubject);
Carmelo Casconea966c342017-07-30 01:56:30 -0400381 log.debug("Received packet in: {}", event);
382 controller.postEvent(event);
383 }
384
385 private void doArbitrationUpdateFromDevice(MasterArbitrationUpdate arbitrationMsg) {
386
387 log.warn("Received arbitration update from {} (NOT IMPLEMENTED YET): {}", deviceId, arbitrationMsg);
388 }
389
Carmelo Casconeb2e3dba2017-07-27 12:07:09 -0400390 /**
391 * Returns the internal P4 device ID associated with this client.
392 *
393 * @return P4 device ID
394 */
Carmelo Casconef423bec2017-08-30 01:56:25 +0200395 public long p4DeviceId() {
Carmelo Casconeb2e3dba2017-07-27 12:07:09 -0400396 return p4DeviceId;
397 }
398
399 /**
400 * For testing purpose only. TODO: remove before release.
401 *
402 * @return blocking stub
403 */
404 public P4RuntimeGrpc.P4RuntimeBlockingStub blockingStub() {
405 return this.blockingStub;
406 }
407
Andrea Campanellafc1d34c2017-07-18 17:01:41 +0200408
Andrea Campanella432f7182017-07-14 18:43:27 +0200409 @Override
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400410 public void shutdown() {
411
Carmelo Cascone59f57de2017-07-11 19:55:09 -0400412 log.info("Shutting down client for {}...", deviceId);
413
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400414 writeLock.lock();
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400415 try {
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400416 if (streamRequestObserver != null) {
417 streamRequestObserver.onCompleted();
418 cancellableContext.cancel(new InterruptedException("Requested client shutdown"));
419 }
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400420
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400421 this.executorService.shutdown();
422 try {
423 executorService.awaitTermination(5, TimeUnit.SECONDS);
424 } catch (InterruptedException e) {
425 log.warn("Executor service didn't shutdown in time.");
426 }
427 } finally {
428 writeLock.unlock();
429 }
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400430 }
431
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400432 /**
433 * Handles messages received from the device on the stream channel.
434 */
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400435 private class StreamChannelResponseObserver implements StreamObserver<StreamMessageResponse> {
436
437 @Override
438 public void onNext(StreamMessageResponse message) {
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400439 executorService.submit(() -> doNext(message));
440 }
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400441
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400442 private void doNext(StreamMessageResponse message) {
Carmelo Casconea966c342017-07-30 01:56:30 -0400443 try {
Andrea Campanella0288c872017-08-07 18:32:51 +0200444 log.debug("Received message on stream channel from {}: {}", deviceId, message.getUpdateCase());
Carmelo Casconea966c342017-07-30 01:56:30 -0400445 switch (message.getUpdateCase()) {
446 case PACKET:
447 // Packet-in
448 doPacketIn(message.getPacket());
Andrea Campanella288b2732017-07-28 14:16:16 +0200449 return;
Carmelo Casconea966c342017-07-30 01:56:30 -0400450 case ARBITRATION:
451 doArbitrationUpdateFromDevice(message.getArbitration());
452 return;
453 default:
454 log.warn("Unrecognized stream message from {}: {}", deviceId, message.getUpdateCase());
455 }
456 } catch (Throwable ex) {
457 log.error("Exception while processing stream channel message from {}", deviceId, ex);
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400458 }
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400459 }
460
461 @Override
462 public void onError(Throwable throwable) {
Carmelo Cascone59f57de2017-07-11 19:55:09 -0400463 log.warn("Error on stream channel for {}: {}", deviceId, Status.fromThrowable(throwable));
464 // FIXME: we might want to recreate the channel.
465 // In general, we want to be robust against any transient error and, if the channel is open, make sure the
466 // stream channel is always on.
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400467 }
468
469 @Override
470 public void onCompleted() {
Carmelo Cascone59f57de2017-07-11 19:55:09 -0400471 log.warn("Stream channel for {} has completed", deviceId);
472 // FIXME: same concern as before.
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400473 }
474 }
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400475}