blob: e8b4e21850d20760de60ca5b42c48a1e00a35f00 [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 Cascone87b9b392017-10-02 18:33:20 +020019import com.google.common.collect.HashMultimap;
Carmelo Cascone8d99b172017-07-18 17:26:31 -040020import com.google.common.collect.ImmutableMap;
Yi Tseng82512da2017-08-16 19:46:36 -070021import com.google.common.collect.Lists;
Carmelo Casconeb045ddc2017-09-01 01:26:35 +020022import com.google.common.collect.Maps;
Yi Tseng82512da2017-08-16 19:46:36 -070023import com.google.common.collect.Multimap;
Carmelo Casconef7aa3f92017-07-06 23:56:50 -040024import com.google.protobuf.ByteString;
Yi Tsenge67e1412018-01-31 17:35:20 -080025import com.google.protobuf.InvalidProtocolBufferException;
Carmelo Cascone59f57de2017-07-11 19:55:09 -040026import io.grpc.Context;
Carmelo Casconef7aa3f92017-07-06 23:56:50 -040027import io.grpc.ManagedChannel;
28import io.grpc.Status;
29import io.grpc.StatusRuntimeException;
30import io.grpc.stub.StreamObserver;
Carmelo Cascone5bc7e102018-02-18 18:27:55 -080031import org.apache.commons.lang3.tuple.ImmutablePair;
Andrea Campanella288b2732017-07-28 14:16:16 +020032import org.onlab.osgi.DefaultServiceDirectory;
Yi Tseng82512da2017-08-16 19:46:36 -070033import org.onlab.util.Tools;
Carmelo Casconef7aa3f92017-07-06 23:56:50 -040034import org.onosproject.net.DeviceId;
Yi Tseng3e7f1452017-10-20 10:31:53 -070035import org.onosproject.net.MastershipRole;
Carmelo Cascone87892e22017-11-13 16:01:29 -080036import org.onosproject.net.pi.model.PiActionProfileId;
37import org.onosproject.net.pi.model.PiCounterId;
Carmelo Cascone81929aa2018-04-07 01:38:55 -070038import org.onosproject.net.pi.model.PiMeterId;
Andrea Campanella432f7182017-07-14 18:43:27 +020039import org.onosproject.net.pi.model.PiPipeconf;
Carmelo Cascone87892e22017-11-13 16:01:29 -080040import org.onosproject.net.pi.model.PiTableId;
Carmelo Cascone87b9b392017-10-02 18:33:20 +020041import org.onosproject.net.pi.runtime.PiActionGroup;
42import org.onosproject.net.pi.runtime.PiActionGroupMember;
Carmelo Casconeb045ddc2017-09-01 01:26:35 +020043import org.onosproject.net.pi.runtime.PiCounterCellData;
44import org.onosproject.net.pi.runtime.PiCounterCellId;
Carmelo Cascone5bc7e102018-02-18 18:27:55 -080045import org.onosproject.net.pi.runtime.PiEntity;
Frank Wangd7e3b4b2017-09-24 13:37:54 +090046import org.onosproject.net.pi.runtime.PiMeterCellConfig;
47import org.onosproject.net.pi.runtime.PiMeterCellId;
Andrea Campanella432f7182017-07-14 18:43:27 +020048import org.onosproject.net.pi.runtime.PiPacketOperation;
Carmelo Casconef7aa3f92017-07-06 23:56:50 -040049import org.onosproject.net.pi.runtime.PiTableEntry;
Yi Tsenge67e1412018-01-31 17:35:20 -080050import org.onosproject.net.pi.service.PiPipeconfService;
Carmelo Casconef7aa3f92017-07-06 23:56:50 -040051import org.onosproject.p4runtime.api.P4RuntimeClient;
52import org.onosproject.p4runtime.api.P4RuntimeEvent;
53import org.slf4j.Logger;
54import p4.P4RuntimeGrpc;
Carmelo Cascone5bc7e102018-02-18 18:27:55 -080055import p4.P4RuntimeOuterClass;
Yi Tseng82512da2017-08-16 19:46:36 -070056import p4.P4RuntimeOuterClass.ActionProfileGroup;
57import p4.P4RuntimeOuterClass.ActionProfileMember;
Carmelo Cascone8d99b172017-07-18 17:26:31 -040058import p4.P4RuntimeOuterClass.Entity;
59import p4.P4RuntimeOuterClass.ForwardingPipelineConfig;
60import p4.P4RuntimeOuterClass.MasterArbitrationUpdate;
61import p4.P4RuntimeOuterClass.PacketIn;
62import p4.P4RuntimeOuterClass.ReadRequest;
63import p4.P4RuntimeOuterClass.ReadResponse;
64import p4.P4RuntimeOuterClass.SetForwardingPipelineConfigRequest;
65import p4.P4RuntimeOuterClass.StreamMessageRequest;
66import p4.P4RuntimeOuterClass.StreamMessageResponse;
67import p4.P4RuntimeOuterClass.TableEntry;
Yi Tseng3e7f1452017-10-20 10:31:53 -070068import p4.P4RuntimeOuterClass.Uint128;
Carmelo Cascone8d99b172017-07-18 17:26:31 -040069import p4.P4RuntimeOuterClass.Update;
70import p4.P4RuntimeOuterClass.WriteRequest;
Andrea Campanellafc1d34c2017-07-18 17:01:41 +020071import p4.config.P4InfoOuterClass.P4Info;
Carmelo Casconef7aa3f92017-07-06 23:56:50 -040072import p4.tmp.P4Config;
73
Carmelo Casconed61fdb32017-10-30 10:09:57 -070074import java.nio.ByteBuffer;
Carmelo Casconef7aa3f92017-07-06 23:56:50 -040075import java.util.Collection;
Carmelo Cascone8d99b172017-07-18 17:26:31 -040076import java.util.Collections;
77import java.util.Iterator;
78import java.util.List;
79import java.util.Map;
Carmelo Cascone87b9b392017-10-02 18:33:20 +020080import java.util.Objects;
Carmelo Casconeb045ddc2017-09-01 01:26:35 +020081import java.util.Set;
Carmelo Casconef7aa3f92017-07-06 23:56:50 -040082import java.util.concurrent.CompletableFuture;
Yi Tseng3e7f1452017-10-20 10:31:53 -070083import java.util.concurrent.ExecutionException;
Carmelo Cascone8d99b172017-07-18 17:26:31 -040084import java.util.concurrent.Executor;
Carmelo Casconef7aa3f92017-07-06 23:56:50 -040085import java.util.concurrent.ExecutorService;
Carmelo Cascone8d99b172017-07-18 17:26:31 -040086import java.util.concurrent.Executors;
Carmelo Casconef7aa3f92017-07-06 23:56:50 -040087import java.util.concurrent.TimeUnit;
Carmelo Cascone8d99b172017-07-18 17:26:31 -040088import java.util.concurrent.locks.Lock;
89import java.util.concurrent.locks.ReentrantLock;
90import java.util.function.Supplier;
91import java.util.stream.Collectors;
92import java.util.stream.StreamSupport;
Carmelo Casconef7aa3f92017-07-06 23:56:50 -040093
Carmelo Casconed61fdb32017-10-30 10:09:57 -070094import static com.google.common.base.Preconditions.checkNotNull;
Carmelo Cascone5bc7e102018-02-18 18:27:55 -080095import static java.lang.String.format;
Carmelo Cascone8d99b172017-07-18 17:26:31 -040096import static org.onlab.util.Tools.groupedThreads;
Carmelo Casconef7aa3f92017-07-06 23:56:50 -040097import static org.slf4j.LoggerFactory.getLogger;
Carmelo Casconed61fdb32017-10-30 10:09:57 -070098import static p4.P4RuntimeOuterClass.Entity.EntityCase.ACTION_PROFILE_GROUP;
99import static p4.P4RuntimeOuterClass.Entity.EntityCase.ACTION_PROFILE_MEMBER;
100import static p4.P4RuntimeOuterClass.Entity.EntityCase.TABLE_ENTRY;
Andrea Campanellafc1d34c2017-07-18 17:01:41 +0200101import static p4.P4RuntimeOuterClass.PacketOut;
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400102import static p4.P4RuntimeOuterClass.SetForwardingPipelineConfigRequest.Action.VERIFY_AND_COMMIT;
103
104/**
105 * Implementation of a P4Runtime client.
106 */
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400107public final class P4RuntimeClientImpl implements P4RuntimeClient {
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400108
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400109 private static final Map<WriteOperationType, Update.Type> UPDATE_TYPES = ImmutableMap.of(
110 WriteOperationType.UNSPECIFIED, Update.Type.UNSPECIFIED,
111 WriteOperationType.INSERT, Update.Type.INSERT,
112 WriteOperationType.MODIFY, Update.Type.MODIFY,
113 WriteOperationType.DELETE, Update.Type.DELETE
114 );
115
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400116 private final Logger log = getLogger(getClass());
117
118 private final DeviceId deviceId;
Carmelo Casconef423bec2017-08-30 01:56:25 +0200119 private final long p4DeviceId;
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400120 private final P4RuntimeControllerImpl controller;
121 private final P4RuntimeGrpc.P4RuntimeBlockingStub blockingStub;
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400122 private final Context.CancellableContext cancellableContext;
123 private final ExecutorService executorService;
124 private final Executor contextExecutor;
125 private final Lock writeLock = new ReentrantLock();
126 private final StreamObserver<StreamMessageRequest> streamRequestObserver;
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400127
Yi Tseng3e7f1452017-10-20 10:31:53 -0700128 private Map<Uint128, CompletableFuture<Boolean>> arbitrationUpdateMap = Maps.newConcurrentMap();
129 protected Uint128 p4RuntimeElectionId;
130
Yi Tseng82512da2017-08-16 19:46:36 -0700131 /**
132 * Default constructor.
133 *
Carmelo Cascone87b9b392017-10-02 18:33:20 +0200134 * @param deviceId the ONOS device id
Yi Tseng82512da2017-08-16 19:46:36 -0700135 * @param p4DeviceId the P4 device id
Carmelo Cascone87b9b392017-10-02 18:33:20 +0200136 * @param channel gRPC channel
Yi Tseng82512da2017-08-16 19:46:36 -0700137 * @param controller runtime client controller
138 */
Carmelo Casconef423bec2017-08-30 01:56:25 +0200139 P4RuntimeClientImpl(DeviceId deviceId, long p4DeviceId, ManagedChannel channel,
140 P4RuntimeControllerImpl controller) {
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400141 this.deviceId = deviceId;
142 this.p4DeviceId = p4DeviceId;
143 this.controller = controller;
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400144 this.cancellableContext = Context.current().withCancellation();
Carmelo Casconea966c342017-07-30 01:56:30 -0400145 this.executorService = Executors.newFixedThreadPool(15, groupedThreads(
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400146 "onos/p4runtime-client-" + deviceId.toString(),
147 deviceId.toString() + "-%d"));
148 this.contextExecutor = this.cancellableContext.fixedContextExecutor(executorService);
Carmelo Cascone2cad9ef2017-08-01 21:52:07 +0200149 //TODO Investigate deadline or timeout in supplyInContext Method
150 this.blockingStub = P4RuntimeGrpc.newBlockingStub(channel);
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400151 P4RuntimeGrpc.P4RuntimeStub asyncStub = P4RuntimeGrpc.newStub(channel);
152 this.streamRequestObserver = asyncStub.streamChannel(new StreamChannelResponseObserver());
153 }
154
155 /**
156 * Executes the given task (supplier) in the gRPC context executor of this client, such that if the context is
157 * cancelled (e.g. client shutdown) the RPC is automatically cancelled.
158 * <p>
159 * Important: Tasks submitted in parallel by different threads are forced executed sequentially.
160 * <p>
161 */
Carmelo Cascone2cad9ef2017-08-01 21:52:07 +0200162 private <U> CompletableFuture<U> supplyInContext(Supplier<U> supplier, String opDescription) {
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400163 return CompletableFuture.supplyAsync(() -> {
164 // TODO: explore a more relaxed locking strategy.
165 writeLock.lock();
166 try {
167 return supplier.get();
Yi Tsenge67e1412018-01-31 17:35:20 -0800168 } catch (StatusRuntimeException ex) {
Carmelo Cascone5bc7e102018-02-18 18:27:55 -0800169 log.warn("Unable to execute {} on {}: {}", opDescription, deviceId, ex.toString());
Yi Tsenge67e1412018-01-31 17:35:20 -0800170 throw ex;
Carmelo Casconea966c342017-07-30 01:56:30 -0400171 } catch (Throwable ex) {
Yi Tsenge67e1412018-01-31 17:35:20 -0800172 log.error("Exception in client of {}, executing {}", deviceId, opDescription, ex);
Carmelo Casconea966c342017-07-30 01:56:30 -0400173 throw ex;
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400174 } finally {
175 writeLock.unlock();
176 }
177 }, contextExecutor);
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400178 }
179
180 @Override
181 public CompletableFuture<Boolean> initStreamChannel() {
Carmelo Cascone2cad9ef2017-08-01 21:52:07 +0200182 return supplyInContext(this::doInitStreamChannel, "initStreamChannel");
Carmelo Cascone59f57de2017-07-11 19:55:09 -0400183 }
184
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400185 @Override
Carmelo Casconed61fdb32017-10-30 10:09:57 -0700186 public CompletableFuture<Boolean> setPipelineConfig(PiPipeconf pipeconf, ByteBuffer deviceData) {
187 return supplyInContext(() -> doSetPipelineConfig(pipeconf, deviceData), "setPipelineConfig");
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400188 }
189
190 @Override
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400191 public CompletableFuture<Boolean> writeTableEntries(Collection<PiTableEntry> piTableEntries,
192 WriteOperationType opType, PiPipeconf pipeconf) {
Carmelo Cascone2cad9ef2017-08-01 21:52:07 +0200193 return supplyInContext(() -> doWriteTableEntries(piTableEntries, opType, pipeconf),
194 "writeTableEntries-" + opType.name());
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400195 }
196
197 @Override
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400198 public CompletableFuture<Collection<PiTableEntry>> dumpTable(PiTableId piTableId, PiPipeconf pipeconf) {
Carmelo Cascone2cad9ef2017-08-01 21:52:07 +0200199 return supplyInContext(() -> doDumpTable(piTableId, pipeconf), "dumpTable-" + piTableId);
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400200 }
201
202 @Override
Andrea Campanella432f7182017-07-14 18:43:27 +0200203 public CompletableFuture<Boolean> packetOut(PiPacketOperation packet, PiPipeconf pipeconf) {
Carmelo Cascone2cad9ef2017-08-01 21:52:07 +0200204 return supplyInContext(() -> doPacketOut(packet, pipeconf), "packetOut");
Andrea Campanella432f7182017-07-14 18:43:27 +0200205 }
206
Carmelo Casconeb045ddc2017-09-01 01:26:35 +0200207 @Override
208 public CompletableFuture<Collection<PiCounterCellData>> readCounterCells(Set<PiCounterCellId> cellIds,
209 PiPipeconf pipeconf) {
210 return supplyInContext(() -> doReadCounterCells(cellIds, pipeconf),
211 "readCounterCells-" + cellIds.hashCode());
212 }
213
214 @Override
215 public CompletableFuture<Collection<PiCounterCellData>> readAllCounterCells(Set<PiCounterId> counterIds,
216 PiPipeconf pipeconf) {
Carmelo Cascone81929aa2018-04-07 01:38:55 -0700217 return supplyInContext(() -> doReadAllCounterCells(counterIds, pipeconf),
218 "readAllCounterCells-" + counterIds.hashCode());
Carmelo Casconeb045ddc2017-09-01 01:26:35 +0200219 }
220
Yi Tseng82512da2017-08-16 19:46:36 -0700221 @Override
222 public CompletableFuture<Boolean> writeActionGroupMembers(PiActionGroup group,
Yi Tseng82512da2017-08-16 19:46:36 -0700223 WriteOperationType opType,
224 PiPipeconf pipeconf) {
Carmelo Cascone87b9b392017-10-02 18:33:20 +0200225 return supplyInContext(() -> doWriteActionGroupMembers(group, opType, pipeconf),
Yi Tseng82512da2017-08-16 19:46:36 -0700226 "writeActionGroupMembers-" + opType.name());
227 }
228
229 @Override
230 public CompletableFuture<Boolean> writeActionGroup(PiActionGroup group,
231 WriteOperationType opType,
232 PiPipeconf pipeconf) {
233 return supplyInContext(() -> doWriteActionGroup(group, opType, pipeconf),
234 "writeActionGroup-" + opType.name());
235 }
236
237 @Override
238 public CompletableFuture<Collection<PiActionGroup>> dumpGroups(PiActionProfileId actionProfileId,
239 PiPipeconf pipeconf) {
240 return supplyInContext(() -> doDumpGroups(actionProfileId, pipeconf),
241 "dumpGroups-" + actionProfileId.id());
242 }
243
Yi Tseng3e7f1452017-10-20 10:31:53 -0700244 @Override
245 public CompletableFuture<Boolean> sendMasterArbitrationUpdate() {
246 return supplyInContext(this::doArbitrationUpdate, "arbitrationUpdate");
247 }
Frank Wangd7e3b4b2017-09-24 13:37:54 +0900248 public CompletableFuture<Boolean> writeMeterCells(Collection<PiMeterCellConfig> cellIds, PiPipeconf pipeconf) {
249
250 return supplyInContext(() -> doWriteMeterCells(cellIds, pipeconf),
251 "writeMeterCells");
252 }
253
254 @Override
255 public CompletableFuture<Collection<PiMeterCellConfig>> readMeterCells(Set<PiMeterCellId> cellIds,
256 PiPipeconf pipeconf) {
257 return supplyInContext(() -> doReadMeterCells(cellIds, pipeconf),
258 "readMeterCells-" + cellIds.hashCode());
259 }
260
261 @Override
262 public CompletableFuture<Collection<PiMeterCellConfig>> readAllMeterCells(Set<PiMeterId> meterIds,
263 PiPipeconf pipeconf) {
Carmelo Cascone81929aa2018-04-07 01:38:55 -0700264 return supplyInContext(() -> doReadAllMeterCells(meterIds, pipeconf),
265 "readAllMeterCells-" + meterIds.hashCode());
Frank Wangd7e3b4b2017-09-24 13:37:54 +0900266 }
Yi Tseng3e7f1452017-10-20 10:31:53 -0700267
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400268 /* Blocking method implementations below */
269
Yi Tseng3e7f1452017-10-20 10:31:53 -0700270 private boolean doArbitrationUpdate() {
271 CompletableFuture<Boolean> result = new CompletableFuture<>();
272 // TODO: currently we use 64-bit Long type for election id, should
273 // we use 128-bit ?
274 long nextElectId = controller.getNewMasterElectionId();
275 Uint128 newElectionId = Uint128.newBuilder()
276 .setLow(nextElectId)
277 .build();
278 MasterArbitrationUpdate arbitrationUpdate = MasterArbitrationUpdate.newBuilder()
279 .setDeviceId(p4DeviceId)
280 .setElectionId(newElectionId)
281 .build();
282 StreamMessageRequest requestMsg = StreamMessageRequest.newBuilder()
283 .setArbitration(arbitrationUpdate)
284 .build();
285 log.debug("Sending arbitration update to {} with election id {}...",
286 deviceId, newElectionId);
287 arbitrationUpdateMap.put(newElectionId, result);
288 try {
289 streamRequestObserver.onNext(requestMsg);
290 return result.get();
Yi Tsenge67e1412018-01-31 17:35:20 -0800291 } catch (StatusRuntimeException e) {
Carmelo Cascone5bc7e102018-02-18 18:27:55 -0800292 log.error("Unable to perform arbitration update on {}: {}", deviceId, e.getMessage());
Yi Tsenge67e1412018-01-31 17:35:20 -0800293 arbitrationUpdateMap.remove(newElectionId);
294 return false;
295 } catch (InterruptedException | ExecutionException e) {
Yi Tseng3e7f1452017-10-20 10:31:53 -0700296 log.warn("Arbitration update failed for {} due to {}", deviceId, e);
297 arbitrationUpdateMap.remove(newElectionId);
298 return false;
299 }
300 }
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400301 private boolean doInitStreamChannel() {
302 // To listen for packets and other events, we need to start the RPC.
303 // Here we do it by sending a master arbitration update.
Yi Tseng3e7f1452017-10-20 10:31:53 -0700304 return doArbitrationUpdate();
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400305 }
306
Carmelo Casconed61fdb32017-10-30 10:09:57 -0700307 private boolean doSetPipelineConfig(PiPipeconf pipeconf, ByteBuffer deviceData) {
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400308
Carmelo Casconed61fdb32017-10-30 10:09:57 -0700309 log.info("Setting pipeline config for {} to {}...", deviceId, pipeconf.id());
310
311 checkNotNull(deviceData, "deviceData cannot be null");
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400312
313 P4Info p4Info = PipeconfHelper.getP4Info(pipeconf);
314 if (p4Info == null) {
315 // Problem logged by PipeconfHelper.
316 return false;
317 }
318
Carmelo Casconed61fdb32017-10-30 10:09:57 -0700319 P4Config.P4DeviceConfig p4DeviceConfigMsg = P4Config.P4DeviceConfig
320 .newBuilder()
321 .setExtras(P4Config.P4DeviceConfig.Extras.getDefaultInstance())
322 .setReassign(true)
323 .setDeviceData(ByteString.copyFrom(deviceData))
324 .build();
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400325
Carmelo Casconed61fdb32017-10-30 10:09:57 -0700326 ForwardingPipelineConfig pipelineConfig = ForwardingPipelineConfig
Andrea Campanella0288c872017-08-07 18:32:51 +0200327 .newBuilder()
Carmelo Casconed61fdb32017-10-30 10:09:57 -0700328 .setP4Info(p4Info)
329 .setP4DeviceConfig(p4DeviceConfigMsg.toByteString())
330 .build();
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400331
332 SetForwardingPipelineConfigRequest request = SetForwardingPipelineConfigRequest
333 .newBuilder()
Andrea Campanella8bcd5862017-12-11 11:34:45 +0100334 .setDeviceId(p4DeviceId)
Yi Tseng3e7f1452017-10-20 10:31:53 -0700335 .setElectionId(p4RuntimeElectionId)
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400336 .setAction(VERIFY_AND_COMMIT)
Andrea Campanella8bcd5862017-12-11 11:34:45 +0100337 .setConfig(pipelineConfig)
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400338 .build();
339
340 try {
341 this.blockingStub.setForwardingPipelineConfig(request);
Carmelo Casconed61fdb32017-10-30 10:09:57 -0700342 return true;
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400343 } catch (StatusRuntimeException ex) {
Carmelo Cascone5bc7e102018-02-18 18:27:55 -0800344 log.warn("Unable to set pipeline config on {}: {}", deviceId, ex.getMessage());
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400345 return false;
346 }
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400347 }
348
349 private boolean doWriteTableEntries(Collection<PiTableEntry> piTableEntries, WriteOperationType opType,
350 PiPipeconf pipeconf) {
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400351 WriteRequest.Builder writeRequestBuilder = WriteRequest.newBuilder();
352
Carmelo Cascone5bc7e102018-02-18 18:27:55 -0800353 if (piTableEntries.size() == 0) {
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400354 return true;
355 }
356
Carmelo Cascone81929aa2018-04-07 01:38:55 -0700357 Collection<Update> updateMsgs;
Carmelo Cascone5bc7e102018-02-18 18:27:55 -0800358 try {
359 updateMsgs = TableEntryEncoder.encode(piTableEntries, pipeconf)
360 .stream()
361 .map(tableEntryMsg ->
362 Update.newBuilder()
363 .setEntity(Entity.newBuilder()
364 .setTableEntry(tableEntryMsg)
365 .build())
366 .setType(UPDATE_TYPES.get(opType))
367 .build())
368 .collect(Collectors.toList());
369 } catch (EncodeException e) {
370 log.error("Unable to encode table entries, aborting {} operation: {}",
371 opType.name(), e.getMessage());
372 return false;
373 }
374
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400375 writeRequestBuilder
376 .setDeviceId(p4DeviceId)
Yi Tseng3e7f1452017-10-20 10:31:53 -0700377 .setElectionId(p4RuntimeElectionId)
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400378 .addAllUpdates(updateMsgs)
379 .build();
380
381 try {
382 blockingStub.write(writeRequestBuilder.build());
383 return true;
384 } catch (StatusRuntimeException e) {
Carmelo Cascone5bc7e102018-02-18 18:27:55 -0800385 logWriteErrors(piTableEntries, e, opType, "table entry");
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400386 return false;
387 }
388 }
389
390 private Collection<PiTableEntry> doDumpTable(PiTableId piTableId, PiPipeconf pipeconf) {
391
Carmelo Cascone9f007702017-08-24 13:30:51 +0200392 log.debug("Dumping table {} from {} (pipeconf {})...", piTableId, deviceId, pipeconf.id());
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400393
394 P4InfoBrowser browser = PipeconfHelper.getP4InfoBrowser(pipeconf);
395 int tableId;
396 try {
Carmelo Casconecb0a49c2017-10-03 14:32:23 +0200397 tableId = browser.tables().getByName(piTableId.id()).getPreamble().getId();
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400398 } catch (P4InfoBrowser.NotFoundException e) {
399 log.warn("Unable to dump table: {}", e.getMessage());
400 return Collections.emptyList();
401 }
402
403 ReadRequest requestMsg = ReadRequest.newBuilder()
404 .setDeviceId(p4DeviceId)
405 .addEntities(Entity.newBuilder()
406 .setTableEntry(TableEntry.newBuilder()
407 .setTableId(tableId)
408 .build())
409 .build())
410 .build();
411
412 Iterator<ReadResponse> responses;
413 try {
414 responses = blockingStub.read(requestMsg);
415 } catch (StatusRuntimeException e) {
Carmelo Cascone5bc7e102018-02-18 18:27:55 -0800416 log.warn("Unable to dump table {} from {}: {}", piTableId, deviceId, e.getMessage());
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400417 return Collections.emptyList();
418 }
419
420 Iterable<ReadResponse> responseIterable = () -> responses;
421 List<TableEntry> tableEntryMsgs = StreamSupport
422 .stream(responseIterable.spliterator(), false)
423 .map(ReadResponse::getEntitiesList)
424 .flatMap(List::stream)
425 .filter(entity -> entity.getEntityCase() == TABLE_ENTRY)
426 .map(Entity::getTableEntry)
427 .collect(Collectors.toList());
428
Carmelo Cascone9f007702017-08-24 13:30:51 +0200429 log.debug("Retrieved {} entries from table {} on {}...", tableEntryMsgs.size(), piTableId, deviceId);
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400430
431 return TableEntryEncoder.decode(tableEntryMsgs, pipeconf);
432 }
433
Andrea Campanellafc1d34c2017-07-18 17:01:41 +0200434 private boolean doPacketOut(PiPacketOperation packet, PiPipeconf pipeconf) {
435 try {
436 //encode the PiPacketOperation into a PacketOut
437 PacketOut packetOut = PacketIOCodec.encodePacketOut(packet, pipeconf);
438
439 //Build the request
440 StreamMessageRequest packetOutRequest = StreamMessageRequest
441 .newBuilder().setPacket(packetOut).build();
442
443 //Send the request
444 streamRequestObserver.onNext(packetOutRequest);
445
446 } catch (P4InfoBrowser.NotFoundException e) {
447 log.error("Cant find expected metadata in p4Info file. {}", e.getMessage());
448 log.debug("Exception", e);
449 return false;
450 }
451 return true;
452 }
453
Carmelo Casconea966c342017-07-30 01:56:30 -0400454 private void doPacketIn(PacketIn packetInMsg) {
455
456 // Retrieve the pipeconf for this client's device.
457 PiPipeconfService pipeconfService = DefaultServiceDirectory.getService(PiPipeconfService.class);
458 if (pipeconfService == null) {
459 throw new IllegalStateException("PiPipeconfService is null. Can't handle packet in.");
460 }
461 final PiPipeconf pipeconf;
462 if (pipeconfService.ofDevice(deviceId).isPresent() &&
463 pipeconfService.getPipeconf(pipeconfService.ofDevice(deviceId).get()).isPresent()) {
464 pipeconf = pipeconfService.getPipeconf(pipeconfService.ofDevice(deviceId).get()).get();
465 } else {
466 log.warn("Unable to get pipeconf of {}. Can't handle packet in", deviceId);
467 return;
468 }
469 // Decode packet message and post event.
Carmelo Cascone87892e22017-11-13 16:01:29 -0800470 PiPacketOperation packetOperation = PacketIOCodec.decodePacketIn(packetInMsg, pipeconf, deviceId);
Carmelo Cascone2cad9ef2017-08-01 21:52:07 +0200471 DefaultPacketIn packetInEventSubject = new DefaultPacketIn(deviceId, packetOperation);
472 P4RuntimeEvent event = new P4RuntimeEvent(P4RuntimeEvent.Type.PACKET_IN, packetInEventSubject);
Carmelo Casconea966c342017-07-30 01:56:30 -0400473 log.debug("Received packet in: {}", event);
474 controller.postEvent(event);
475 }
476
477 private void doArbitrationUpdateFromDevice(MasterArbitrationUpdate arbitrationMsg) {
Yi Tseng3e7f1452017-10-20 10:31:53 -0700478 log.debug("Received arbitration update from {}: {}", deviceId, arbitrationMsg);
Carmelo Casconea966c342017-07-30 01:56:30 -0400479
Yi Tseng3e7f1452017-10-20 10:31:53 -0700480 Uint128 electionId = arbitrationMsg.getElectionId();
481 CompletableFuture<Boolean> mastershipFeature = arbitrationUpdateMap.remove(electionId);
482
483 if (mastershipFeature == null) {
484 log.warn("Can't find completable future of election id {}", electionId);
485 return;
486 }
487
488 this.p4RuntimeElectionId = electionId;
489 int statusCode = arbitrationMsg.getStatus().getCode();
490 MastershipRole arbitrationRole;
491 // arbitration update success
492
493 if (statusCode == Status.OK.getCode().value()) {
494 mastershipFeature.complete(true);
495 arbitrationRole = MastershipRole.MASTER;
496 } else {
497 mastershipFeature.complete(false);
498 arbitrationRole = MastershipRole.STANDBY;
499 }
500
501 DefaultArbitration arbitrationEventSubject = new DefaultArbitration(arbitrationRole, electionId);
502 P4RuntimeEvent event = new P4RuntimeEvent(P4RuntimeEvent.Type.ARBITRATION,
503 arbitrationEventSubject);
504 controller.postEvent(event);
Carmelo Casconea966c342017-07-30 01:56:30 -0400505 }
506
Carmelo Cascone81929aa2018-04-07 01:38:55 -0700507 private Collection<PiCounterCellData> doReadAllCounterCells(
508 Collection<PiCounterId> counterIds, PiPipeconf pipeconf) {
509 return doReadCounterEntities(
510 CounterEntryCodec.readAllCellsEntities(counterIds, pipeconf),
511 pipeconf);
512 }
Carmelo Casconeb045ddc2017-09-01 01:26:35 +0200513
Carmelo Cascone81929aa2018-04-07 01:38:55 -0700514 private Collection<PiCounterCellData> doReadCounterCells(
515 Collection<PiCounterCellId> cellIds, PiPipeconf pipeconf) {
516 return doReadCounterEntities(
517 CounterEntryCodec.encodePiCounterCellIds(cellIds, pipeconf),
518 pipeconf);
519 }
520
521 private Collection<PiCounterCellData> doReadCounterEntities(
522 Collection<Entity> counterEntities, PiPipeconf pipeconf) {
523
524 if (counterEntities.size() == 0) {
525 return Collections.emptyList();
526 }
Carmelo Casconeb045ddc2017-09-01 01:26:35 +0200527
Carmelo Cascone7f75be42017-09-07 14:37:02 +0200528 final ReadRequest request = ReadRequest.newBuilder()
529 .setDeviceId(p4DeviceId)
Carmelo Cascone81929aa2018-04-07 01:38:55 -0700530 .addAllEntities(counterEntities)
Carmelo Cascone7f75be42017-09-07 14:37:02 +0200531 .build();
532
Carmelo Cascone7f75be42017-09-07 14:37:02 +0200533 final Iterable<ReadResponse> responses;
Carmelo Casconeb045ddc2017-09-01 01:26:35 +0200534 try {
Carmelo Cascone7f75be42017-09-07 14:37:02 +0200535 responses = () -> blockingStub.read(request);
Carmelo Casconeb045ddc2017-09-01 01:26:35 +0200536 } catch (StatusRuntimeException e) {
Carmelo Cascone5bc7e102018-02-18 18:27:55 -0800537 log.warn("Unable to read counter cells from {}: {}", deviceId, e.getMessage());
Carmelo Casconeb045ddc2017-09-01 01:26:35 +0200538 return Collections.emptyList();
539 }
540
Carmelo Cascone7f75be42017-09-07 14:37:02 +0200541 List<Entity> entities = StreamSupport.stream(responses.spliterator(), false)
Carmelo Casconeb045ddc2017-09-01 01:26:35 +0200542 .map(ReadResponse::getEntitiesList)
543 .flatMap(List::stream)
Carmelo Cascone7f75be42017-09-07 14:37:02 +0200544 .collect(Collectors.toList());
Carmelo Casconeb045ddc2017-09-01 01:26:35 +0200545
Carmelo Cascone81929aa2018-04-07 01:38:55 -0700546 return CounterEntryCodec.decodeCounterEntities(entities, pipeconf);
Carmelo Casconeb045ddc2017-09-01 01:26:35 +0200547 }
548
Carmelo Cascone87b9b392017-10-02 18:33:20 +0200549 private boolean doWriteActionGroupMembers(PiActionGroup group, WriteOperationType opType, PiPipeconf pipeconf) {
Carmelo Cascone87b9b392017-10-02 18:33:20 +0200550 final Collection<ActionProfileMember> actionProfileMembers = Lists.newArrayList();
Carmelo Cascone5bc7e102018-02-18 18:27:55 -0800551
552 for (PiActionGroupMember member : group.members()) {
553 try {
Carmelo Cascone87b9b392017-10-02 18:33:20 +0200554 actionProfileMembers.add(ActionProfileMemberEncoder.encode(group, member, pipeconf));
Carmelo Cascone5bc7e102018-02-18 18:27:55 -0800555 } catch (EncodeException | P4InfoBrowser.NotFoundException e) {
556 log.warn("Unable to encode group member, aborting {} operation: {} [{}]",
557 opType.name(), e.getMessage(), member.toString());
558 return false;
Yi Tseng82512da2017-08-16 19:46:36 -0700559 }
Yi Tseng82512da2017-08-16 19:46:36 -0700560 }
561
Carmelo Cascone87b9b392017-10-02 18:33:20 +0200562 final Collection<Update> updateMsgs = actionProfileMembers.stream()
Yi Tseng82512da2017-08-16 19:46:36 -0700563 .map(actionProfileMember ->
564 Update.newBuilder()
565 .setEntity(Entity.newBuilder()
566 .setActionProfileMember(actionProfileMember)
567 .build())
568 .setType(UPDATE_TYPES.get(opType))
569 .build())
570 .collect(Collectors.toList());
571
572 if (updateMsgs.size() == 0) {
Carmelo Cascone87b9b392017-10-02 18:33:20 +0200573 // Nothing to update.
Yi Tseng82512da2017-08-16 19:46:36 -0700574 return true;
575 }
576
Carmelo Cascone87b9b392017-10-02 18:33:20 +0200577 WriteRequest writeRequestMsg = WriteRequest.newBuilder()
Yi Tseng82512da2017-08-16 19:46:36 -0700578 .setDeviceId(p4DeviceId)
Yi Tseng3e7f1452017-10-20 10:31:53 -0700579 .setElectionId(p4RuntimeElectionId)
Carmelo Cascone87b9b392017-10-02 18:33:20 +0200580 .addAllUpdates(updateMsgs)
581 .build();
Yi Tseng82512da2017-08-16 19:46:36 -0700582 try {
Carmelo Cascone87b9b392017-10-02 18:33:20 +0200583 blockingStub.write(writeRequestMsg);
Yi Tseng82512da2017-08-16 19:46:36 -0700584 return true;
585 } catch (StatusRuntimeException e) {
Carmelo Cascone5bc7e102018-02-18 18:27:55 -0800586 logWriteErrors(group.members(), e, opType, "group member");
Yi Tseng82512da2017-08-16 19:46:36 -0700587 return false;
588 }
589 }
590
591 private Collection<PiActionGroup> doDumpGroups(PiActionProfileId piActionProfileId, PiPipeconf pipeconf) {
592 log.debug("Dumping groups from action profile {} from {} (pipeconf {})...",
593 piActionProfileId.id(), deviceId, pipeconf.id());
Carmelo Cascone87b9b392017-10-02 18:33:20 +0200594
595 final P4InfoBrowser browser = PipeconfHelper.getP4InfoBrowser(pipeconf);
Yi Tseng82512da2017-08-16 19:46:36 -0700596 if (browser == null) {
Carmelo Cascone87b9b392017-10-02 18:33:20 +0200597 log.warn("Unable to get a P4Info browser for pipeconf {}, aborting dump action profile", pipeconf);
Yi Tseng82512da2017-08-16 19:46:36 -0700598 return Collections.emptySet();
599 }
600
Carmelo Cascone87b9b392017-10-02 18:33:20 +0200601 final int actionProfileId;
Yi Tseng82512da2017-08-16 19:46:36 -0700602 try {
Carmelo Cascone87b9b392017-10-02 18:33:20 +0200603 actionProfileId = browser
604 .actionProfiles()
Carmelo Casconecb0a49c2017-10-03 14:32:23 +0200605 .getByName(piActionProfileId.id())
Carmelo Cascone87b9b392017-10-02 18:33:20 +0200606 .getPreamble()
607 .getId();
Yi Tseng82512da2017-08-16 19:46:36 -0700608 } catch (P4InfoBrowser.NotFoundException e) {
Carmelo Cascone87b9b392017-10-02 18:33:20 +0200609 log.warn("Unable to dump groups: {}", e.getMessage());
Yi Tseng82512da2017-08-16 19:46:36 -0700610 return Collections.emptySet();
611 }
612
Carmelo Cascone87b9b392017-10-02 18:33:20 +0200613 // Prepare read request to read all groups from the given action profile.
614 final ReadRequest groupRequestMsg = ReadRequest.newBuilder()
Yi Tseng82512da2017-08-16 19:46:36 -0700615 .setDeviceId(p4DeviceId)
616 .addEntities(Entity.newBuilder()
Carmelo Cascone87b9b392017-10-02 18:33:20 +0200617 .setActionProfileGroup(
618 ActionProfileGroup.newBuilder()
619 .setActionProfileId(actionProfileId)
620 .build())
Yi Tseng82512da2017-08-16 19:46:36 -0700621 .build())
622 .build();
623
Carmelo Cascone87b9b392017-10-02 18:33:20 +0200624 // Read groups.
625 final Iterator<ReadResponse> groupResponses;
Yi Tseng82512da2017-08-16 19:46:36 -0700626 try {
Carmelo Cascone87b9b392017-10-02 18:33:20 +0200627 groupResponses = blockingStub.read(groupRequestMsg);
Yi Tseng82512da2017-08-16 19:46:36 -0700628 } catch (StatusRuntimeException e) {
Carmelo Cascone5bc7e102018-02-18 18:27:55 -0800629 log.warn("Unable to dump action profile {} from {}: {}", piActionProfileId, deviceId, e.getMessage());
Yi Tseng82512da2017-08-16 19:46:36 -0700630 return Collections.emptySet();
631 }
632
Carmelo Cascone87b9b392017-10-02 18:33:20 +0200633 final List<ActionProfileGroup> groupMsgs = Tools.stream(() -> groupResponses)
634 .map(ReadResponse::getEntitiesList)
635 .flatMap(List::stream)
636 .filter(entity -> entity.getEntityCase() == ACTION_PROFILE_GROUP)
637 .map(Entity::getActionProfileGroup)
638 .collect(Collectors.toList());
Yi Tseng82512da2017-08-16 19:46:36 -0700639
640 log.debug("Retrieved {} groups from action profile {} on {}...",
Carmelo Cascone87b9b392017-10-02 18:33:20 +0200641 groupMsgs.size(), piActionProfileId.id(), deviceId);
Yi Tseng82512da2017-08-16 19:46:36 -0700642
Carmelo Cascone87b9b392017-10-02 18:33:20 +0200643 // Returned groups contain only a minimal description of their members.
644 // We need to issue a new request to get the full description of each member.
Yi Tseng82512da2017-08-16 19:46:36 -0700645
Carmelo Cascone87b9b392017-10-02 18:33:20 +0200646 // Keep a map of all member IDs for each group ID, will need it later.
647 final Multimap<Integer, Integer> groupIdToMemberIdsMap = HashMultimap.create();
648 groupMsgs.forEach(g -> groupIdToMemberIdsMap.putAll(
649 g.getGroupId(),
650 g.getMembersList().stream()
651 .map(ActionProfileGroup.Member::getMemberId)
652 .collect(Collectors.toList())));
Yi Tseng82512da2017-08-16 19:46:36 -0700653
Carmelo Cascone87b9b392017-10-02 18:33:20 +0200654 // Prepare one big read request to read all members in one shot.
655 final Set<Entity> entityMsgs = groupMsgs.stream()
656 .flatMap(g -> g.getMembersList().stream())
657 .map(ActionProfileGroup.Member::getMemberId)
658 // Prevent issuing many read requests for the same member.
659 .distinct()
660 .map(id -> ActionProfileMember.newBuilder()
661 .setActionProfileId(actionProfileId)
662 .setMemberId(id)
663 .build())
664 .map(m -> Entity.newBuilder()
665 .setActionProfileMember(m)
666 .build())
667 .collect(Collectors.toSet());
668 final ReadRequest memberRequestMsg = ReadRequest.newBuilder().setDeviceId(p4DeviceId)
669 .addAllEntities(entityMsgs)
670 .build();
Yi Tseng82512da2017-08-16 19:46:36 -0700671
Carmelo Cascone87b9b392017-10-02 18:33:20 +0200672 // Read members.
673 final Iterator<ReadResponse> memberResponses;
674 try {
675 memberResponses = blockingStub.read(memberRequestMsg);
676 } catch (StatusRuntimeException e) {
Carmelo Cascone5bc7e102018-02-18 18:27:55 -0800677 log.warn("Unable to read members of action profile {} from {}: {}",
678 piActionProfileId, deviceId, e.getMessage());
Carmelo Cascone87b9b392017-10-02 18:33:20 +0200679 return Collections.emptyList();
Yi Tseng82512da2017-08-16 19:46:36 -0700680 }
681
Carmelo Cascone87b9b392017-10-02 18:33:20 +0200682 final Multimap<Integer, ActionProfileMember> groupIdToMembersMap = HashMultimap.create();
683 Tools.stream(() -> memberResponses)
684 .map(ReadResponse::getEntitiesList)
685 .flatMap(List::stream)
686 .filter(e -> e.getEntityCase() == ACTION_PROFILE_MEMBER)
687 .map(Entity::getActionProfileMember)
688 .forEach(member -> groupIdToMemberIdsMap.asMap()
689 // Get all group IDs that contain this member.
690 .entrySet()
691 .stream()
692 .filter(entry -> entry.getValue().contains(member.getMemberId()))
693 .map(Map.Entry::getKey)
694 .forEach(gid -> groupIdToMembersMap.put(gid, member)));
695
696 log.debug("Retrieved {} group members from action profile {} on {}...",
697 groupIdToMembersMap.size(), piActionProfileId.id(), deviceId);
698
699 return groupMsgs.stream()
700 .map(groupMsg -> {
701 try {
702 return ActionProfileGroupEncoder.decode(groupMsg,
703 groupIdToMembersMap.get(groupMsg.getGroupId()),
704 pipeconf);
705 } catch (P4InfoBrowser.NotFoundException | EncodeException e) {
706 log.warn("Unable to decode group: {}\n {}", e.getMessage(), groupMsg);
707 return null;
708 }
709 })
710 .filter(Objects::nonNull)
711 .collect(Collectors.toList());
Yi Tseng82512da2017-08-16 19:46:36 -0700712 }
713
714 private boolean doWriteActionGroup(PiActionGroup group, WriteOperationType opType, PiPipeconf pipeconf) {
Carmelo Cascone87b9b392017-10-02 18:33:20 +0200715 final ActionProfileGroup actionProfileGroup;
Yi Tseng82512da2017-08-16 19:46:36 -0700716 try {
717 actionProfileGroup = ActionProfileGroupEncoder.encode(group, pipeconf);
718 } catch (EncodeException | P4InfoBrowser.NotFoundException e) {
Carmelo Cascone5bc7e102018-02-18 18:27:55 -0800719 log.warn("Unable to encode group, aborting {} operation: {}", e.getMessage(), opType.name());
Yi Tseng82512da2017-08-16 19:46:36 -0700720 return false;
721 }
Carmelo Cascone87b9b392017-10-02 18:33:20 +0200722
723 final WriteRequest writeRequestMsg = WriteRequest.newBuilder()
Yi Tseng82512da2017-08-16 19:46:36 -0700724 .setDeviceId(p4DeviceId)
Yi Tseng3e7f1452017-10-20 10:31:53 -0700725 .setElectionId(p4RuntimeElectionId)
Carmelo Cascone87b9b392017-10-02 18:33:20 +0200726 .addUpdates(Update.newBuilder()
727 .setEntity(Entity.newBuilder()
728 .setActionProfileGroup(actionProfileGroup)
729 .build())
730 .setType(UPDATE_TYPES.get(opType))
731 .build())
732 .build();
Yi Tseng82512da2017-08-16 19:46:36 -0700733 try {
Carmelo Cascone87b9b392017-10-02 18:33:20 +0200734 blockingStub.write(writeRequestMsg);
Yi Tseng82512da2017-08-16 19:46:36 -0700735 return true;
736 } catch (StatusRuntimeException e) {
Carmelo Cascone5bc7e102018-02-18 18:27:55 -0800737 logWriteErrors(Collections.singleton(group), e, opType, "group");
Yi Tseng82512da2017-08-16 19:46:36 -0700738 return false;
739 }
740 }
741
Carmelo Cascone81929aa2018-04-07 01:38:55 -0700742 private Collection<PiMeterCellConfig> doReadAllMeterCells(
743 Collection<PiMeterId> meterIds, PiPipeconf pipeconf) {
744 return doReadMeterEntities(MeterEntryCodec.readAllCellsEntities(
745 meterIds, pipeconf), pipeconf);
746 }
Frank Wangd7e3b4b2017-09-24 13:37:54 +0900747
Carmelo Cascone81929aa2018-04-07 01:38:55 -0700748 private Collection<PiMeterCellConfig> doReadMeterCells(
749 Collection<PiMeterCellId> cellIds, PiPipeconf pipeconf) {
750
751 final Collection<PiMeterCellConfig> piMeterCellConfigs = cellIds.stream()
Frank Wangd7e3b4b2017-09-24 13:37:54 +0900752 .map(cellId -> PiMeterCellConfig.builder()
Carmelo Cascone81929aa2018-04-07 01:38:55 -0700753 .withMeterCellId(cellId)
754 .build())
Frank Wangd7e3b4b2017-09-24 13:37:54 +0900755 .collect(Collectors.toList());
756
Carmelo Cascone81929aa2018-04-07 01:38:55 -0700757 return doReadMeterEntities(MeterEntryCodec.encodePiMeterCellConfigs(
758 piMeterCellConfigs, pipeconf), pipeconf);
759 }
760
761 private Collection<PiMeterCellConfig> doReadMeterEntities(
762 Collection<Entity> entitiesToRead, PiPipeconf pipeconf) {
763
764 if (entitiesToRead.size() == 0) {
765 return Collections.emptyList();
766 }
767
Frank Wangd7e3b4b2017-09-24 13:37:54 +0900768 final ReadRequest request = ReadRequest.newBuilder()
769 .setDeviceId(p4DeviceId)
Carmelo Cascone81929aa2018-04-07 01:38:55 -0700770 .addAllEntities(entitiesToRead)
Frank Wangd7e3b4b2017-09-24 13:37:54 +0900771 .build();
772
Frank Wangd7e3b4b2017-09-24 13:37:54 +0900773 final Iterable<ReadResponse> responses;
774 try {
775 responses = () -> blockingStub.read(request);
776 } catch (StatusRuntimeException e) {
Carmelo Cascone81929aa2018-04-07 01:38:55 -0700777 log.warn("Unable to read meter cells: {}", e.getMessage());
Frank Wangd7e3b4b2017-09-24 13:37:54 +0900778 log.debug("exception", e);
779 return Collections.emptyList();
780 }
781
Carmelo Cascone81929aa2018-04-07 01:38:55 -0700782 List<Entity> responseEntities = StreamSupport
783 .stream(responses.spliterator(), false)
Frank Wangd7e3b4b2017-09-24 13:37:54 +0900784 .map(ReadResponse::getEntitiesList)
785 .flatMap(List::stream)
786 .collect(Collectors.toList());
787
Carmelo Cascone81929aa2018-04-07 01:38:55 -0700788 return MeterEntryCodec.decodeMeterEntities(responseEntities, pipeconf);
Frank Wangd7e3b4b2017-09-24 13:37:54 +0900789 }
790
791 private boolean doWriteMeterCells(Collection<PiMeterCellConfig> cellIds, PiPipeconf pipeconf) {
792
Frank Wangd7e3b4b2017-09-24 13:37:54 +0900793 WriteRequest.Builder writeRequestBuilder = WriteRequest.newBuilder();
794
Carmelo Cascone81929aa2018-04-07 01:38:55 -0700795 Collection<Update> updateMsgs = MeterEntryCodec.encodePiMeterCellConfigs(cellIds, pipeconf)
Frank Wangd7e3b4b2017-09-24 13:37:54 +0900796 .stream()
797 .map(meterEntryMsg ->
798 Update.newBuilder()
799 .setEntity(meterEntryMsg)
800 .setType(UPDATE_TYPES.get(WriteOperationType.MODIFY))
801 .build())
802 .collect(Collectors.toList());
803
804 if (updateMsgs.size() == 0) {
805 return true;
806 }
807
808 writeRequestBuilder
809 .setDeviceId(p4DeviceId)
810 .setElectionId(p4RuntimeElectionId)
811 .addAllUpdates(updateMsgs)
812 .build();
813 try {
814 blockingStub.write(writeRequestBuilder.build());
815 return true;
816 } catch (StatusRuntimeException e) {
817 log.warn("Unable to write meter entries : {}", e.getMessage());
818 log.debug("exception", e);
819 return false;
820 }
821 }
822
Carmelo Casconeb2e3dba2017-07-27 12:07:09 -0400823 /**
824 * Returns the internal P4 device ID associated with this client.
825 *
826 * @return P4 device ID
827 */
Carmelo Casconef423bec2017-08-30 01:56:25 +0200828 public long p4DeviceId() {
Carmelo Casconeb2e3dba2017-07-27 12:07:09 -0400829 return p4DeviceId;
830 }
831
832 /**
833 * For testing purpose only. TODO: remove before release.
834 *
835 * @return blocking stub
836 */
837 public P4RuntimeGrpc.P4RuntimeBlockingStub blockingStub() {
838 return this.blockingStub;
839 }
840
Andrea Campanellafc1d34c2017-07-18 17:01:41 +0200841
Andrea Campanella432f7182017-07-14 18:43:27 +0200842 @Override
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400843 public void shutdown() {
844
Carmelo Cascone59f57de2017-07-11 19:55:09 -0400845 log.info("Shutting down client for {}...", deviceId);
846
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400847 writeLock.lock();
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400848 try {
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400849 if (streamRequestObserver != null) {
850 streamRequestObserver.onCompleted();
851 cancellableContext.cancel(new InterruptedException("Requested client shutdown"));
852 }
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400853
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400854 this.executorService.shutdown();
855 try {
856 executorService.awaitTermination(5, TimeUnit.SECONDS);
857 } catch (InterruptedException e) {
858 log.warn("Executor service didn't shutdown in time.");
Ray Milkey5c7d4882018-02-05 14:50:39 -0800859 Thread.currentThread().interrupt();
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400860 }
861 } finally {
862 writeLock.unlock();
863 }
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400864 }
865
Carmelo Cascone5bc7e102018-02-18 18:27:55 -0800866 private <E extends PiEntity> void logWriteErrors(Collection<E> writeEntities,
867 StatusRuntimeException ex,
868 WriteOperationType opType,
869 String entryType) {
870 List<P4RuntimeOuterClass.Error> errors = null;
871 String description = null;
872 try {
873 errors = extractWriteErrorDetails(ex);
874 } catch (InvalidProtocolBufferException e) {
875 description = ex.getStatus().getDescription();
876 }
877
878 log.warn("Unable to {} {} {}(s) on {}: {}{} (detailed errors might be logged below)",
879 opType.name(), writeEntities.size(), entryType, deviceId,
880 ex.getStatus().getCode().name(),
881 description == null ? "" : " - " + description);
882
883 if (errors == null || errors.isEmpty()) {
884 return;
885 }
886
887 // FIXME: we are assuming entities is an ordered collection, e.g. a list,
888 // and that errors are reported in the same order as the corresponding
889 // written entity. Write RPC methods should be refactored to accept an
890 // order list of entities, instead of a collection.
891 if (errors.size() == writeEntities.size()) {
892 Iterator<E> entityIterator = writeEntities.iterator();
893 errors.stream()
894 .map(e -> ImmutablePair.of(e, entityIterator.next()))
895 .filter(p -> p.left.getCanonicalCode() != Status.OK.getCode().value())
896 .forEach(p -> log.warn("Unable to {} {}: {} [{}]",
897 opType.name(), entryType, parseP4Error(p.getLeft()),
898 p.getRight().toString()));
899 } else {
900 log.error("Unable to reconcile error details to updates " +
901 "(sent {} updates, but device returned {} errors)",
902 entryType, writeEntities.size(), errors.size());
903 errors.stream()
904 .filter(err -> err.getCanonicalCode() != Status.OK.getCode().value())
905 .forEach(err -> log.warn("Unable to {} {} (unknown): {}",
906 opType.name(), entryType, parseP4Error(err)));
907 }
908 }
909
910 private List<P4RuntimeOuterClass.Error> extractWriteErrorDetails(
911 StatusRuntimeException ex) throws InvalidProtocolBufferException {
912 String statusString = ex.getStatus().getDescription();
913 if (statusString == null) {
914 return Collections.emptyList();
915 }
916 com.google.rpc.Status status = com.google.rpc.Status
917 .parseFrom(statusString.getBytes());
918 return status.getDetailsList().stream()
919 .map(any -> {
920 try {
921 return any.unpack(P4RuntimeOuterClass.Error.class);
922 } catch (InvalidProtocolBufferException e) {
923 log.warn("Unable to unpack P4Runtime Error: {}",
924 any.toString());
925 return null;
926 }
927 })
928 .filter(Objects::nonNull)
929 .collect(Collectors.toList());
930
931 }
932
933 private String parseP4Error(P4RuntimeOuterClass.Error err) {
934 return format("%s %s (%s code %d)%s",
935 Status.fromCodeValue(err.getCanonicalCode()),
936 err.getMessage(),
937 err.getSpace(),
938 err.getCode(),
939 err.hasDetails() ? "\n" + err.getDetails().toString() : "");
940 }
941
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400942 /**
943 * Handles messages received from the device on the stream channel.
944 */
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400945 private class StreamChannelResponseObserver implements StreamObserver<StreamMessageResponse> {
946
947 @Override
948 public void onNext(StreamMessageResponse message) {
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400949 executorService.submit(() -> doNext(message));
950 }
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400951
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400952 private void doNext(StreamMessageResponse message) {
Carmelo Casconea966c342017-07-30 01:56:30 -0400953 try {
Andrea Campanella0288c872017-08-07 18:32:51 +0200954 log.debug("Received message on stream channel from {}: {}", deviceId, message.getUpdateCase());
Carmelo Casconea966c342017-07-30 01:56:30 -0400955 switch (message.getUpdateCase()) {
956 case PACKET:
957 // Packet-in
958 doPacketIn(message.getPacket());
Andrea Campanella288b2732017-07-28 14:16:16 +0200959 return;
Carmelo Casconea966c342017-07-30 01:56:30 -0400960 case ARBITRATION:
961 doArbitrationUpdateFromDevice(message.getArbitration());
962 return;
963 default:
964 log.warn("Unrecognized stream message from {}: {}", deviceId, message.getUpdateCase());
965 }
966 } catch (Throwable ex) {
967 log.error("Exception while processing stream channel message from {}", deviceId, ex);
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400968 }
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400969 }
970
971 @Override
972 public void onError(Throwable throwable) {
Carmelo Cascone59f57de2017-07-11 19:55:09 -0400973 log.warn("Error on stream channel for {}: {}", deviceId, Status.fromThrowable(throwable));
974 // FIXME: we might want to recreate the channel.
975 // In general, we want to be robust against any transient error and, if the channel is open, make sure the
976 // stream channel is always on.
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400977 }
978
979 @Override
980 public void onCompleted() {
Carmelo Cascone59f57de2017-07-11 19:55:09 -0400981 log.warn("Stream channel for {} has completed", deviceId);
982 // FIXME: same concern as before.
Carmelo Casconef7aa3f92017-07-06 23:56:50 -0400983 }
984 }
Carmelo Cascone87892e22017-11-13 16:01:29 -0800985}