Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2019-present Open Networking Foundation |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | package org.onosproject.p4runtime.ctl.client; |
| 18 | |
| 19 | import com.google.protobuf.TextFormat; |
| 20 | import io.grpc.Status; |
| 21 | import io.grpc.StatusRuntimeException; |
| 22 | import io.grpc.stub.ClientCallStreamObserver; |
| 23 | import io.grpc.stub.StreamObserver; |
Carmelo Cascone | b8a2505 | 2019-04-08 15:22:32 -0700 | [diff] [blame] | 24 | import org.onlab.util.SharedScheduledExecutors; |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 25 | import org.onosproject.net.DeviceId; |
Carmelo Cascone | 3977ea4 | 2019-02-28 13:43:42 -0800 | [diff] [blame] | 26 | import org.onosproject.net.device.DeviceAgentEvent; |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 27 | import org.onosproject.net.pi.model.PiPipeconf; |
| 28 | import org.onosproject.net.pi.runtime.PiPacketOperation; |
| 29 | import org.onosproject.net.pi.service.PiPipeconfService; |
| 30 | import org.onosproject.p4runtime.api.P4RuntimeEvent; |
| 31 | import org.onosproject.p4runtime.api.P4RuntimeStreamClient; |
| 32 | import org.onosproject.p4runtime.ctl.codec.CodecException; |
Carmelo Cascone | 3977ea4 | 2019-02-28 13:43:42 -0800 | [diff] [blame] | 33 | import org.onosproject.p4runtime.ctl.controller.MasterElectionIdStore; |
| 34 | import org.onosproject.p4runtime.ctl.controller.MasterElectionIdStore.MasterElectionIdListener; |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 35 | import org.onosproject.p4runtime.ctl.controller.P4RuntimeControllerImpl; |
| 36 | import org.onosproject.p4runtime.ctl.controller.PacketInEvent; |
| 37 | import org.slf4j.Logger; |
| 38 | import p4.v1.P4RuntimeOuterClass; |
| 39 | import p4.v1.P4RuntimeOuterClass.StreamMessageRequest; |
| 40 | import p4.v1.P4RuntimeOuterClass.StreamMessageResponse; |
| 41 | |
| 42 | import java.math.BigInteger; |
| 43 | import java.net.ConnectException; |
| 44 | import java.nio.ByteBuffer; |
Carmelo Cascone | b8a2505 | 2019-04-08 15:22:32 -0700 | [diff] [blame] | 45 | import java.util.concurrent.ScheduledFuture; |
| 46 | import java.util.concurrent.TimeUnit; |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 47 | import java.util.concurrent.atomic.AtomicBoolean; |
| 48 | |
Carmelo Cascone | 3977ea4 | 2019-02-28 13:43:42 -0800 | [diff] [blame] | 49 | import static com.google.common.base.Preconditions.checkArgument; |
| 50 | import static com.google.common.base.Preconditions.checkNotNull; |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 51 | import static java.lang.String.format; |
Carmelo Cascone | b8a2505 | 2019-04-08 15:22:32 -0700 | [diff] [blame] | 52 | import static java.lang.System.currentTimeMillis; |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 53 | import static org.onosproject.p4runtime.ctl.codec.Codecs.CODECS; |
| 54 | import static org.slf4j.LoggerFactory.getLogger; |
| 55 | |
| 56 | /** |
| 57 | * Implementation of P4RuntimeStreamClient. Handles P4Runtime StreamChannel RPC |
Carmelo Cascone | c2be50a | 2019-04-10 00:15:39 -0700 | [diff] [blame] | 58 | * operations, such as arbitration update and packet-in/out, for a given |
| 59 | * P4Runtime-internal device ID. |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 60 | */ |
| 61 | public final class StreamClientImpl implements P4RuntimeStreamClient { |
| 62 | |
| 63 | private static final Logger log = getLogger(StreamClientImpl.class); |
| 64 | |
Carmelo Cascone | b8a2505 | 2019-04-08 15:22:32 -0700 | [diff] [blame] | 65 | private static final int ARBITRATION_RETRY_SECONDS = 3; |
| 66 | private static final int ARBITRATION_TIMEOUT_SECONDS = 15; |
| 67 | |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 68 | private final P4RuntimeClientImpl client; |
| 69 | private final DeviceId deviceId; |
| 70 | private final long p4DeviceId; |
| 71 | private final PiPipeconfService pipeconfService; |
Carmelo Cascone | 3977ea4 | 2019-02-28 13:43:42 -0800 | [diff] [blame] | 72 | private final MasterElectionIdStore masterElectionIdStore; |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 73 | private final P4RuntimeControllerImpl controller; |
Carmelo Cascone | 3977ea4 | 2019-02-28 13:43:42 -0800 | [diff] [blame] | 74 | |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 75 | private final StreamChannelManager streamChannelManager = new StreamChannelManager(); |
Carmelo Cascone | 3977ea4 | 2019-02-28 13:43:42 -0800 | [diff] [blame] | 76 | private final MasterElectionIdListener masterElectionIdListener = new InternalMasterElectionIdListener(); |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 77 | |
Carmelo Cascone | 3977ea4 | 2019-02-28 13:43:42 -0800 | [diff] [blame] | 78 | private final AtomicBoolean isMaster = new AtomicBoolean(false); |
| 79 | private final AtomicBoolean requestedToBeMaster = new AtomicBoolean(false); |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 80 | |
Carmelo Cascone | 3977ea4 | 2019-02-28 13:43:42 -0800 | [diff] [blame] | 81 | private BigInteger pendingElectionId = null; |
| 82 | private BigInteger lastUsedElectionId = null; |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 83 | |
Carmelo Cascone | b8a2505 | 2019-04-08 15:22:32 -0700 | [diff] [blame] | 84 | private ScheduledFuture<?> pendingElectionIdRetryTask = null; |
| 85 | private long pendingElectionIdTimestamp = 0; |
| 86 | |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 87 | StreamClientImpl( |
| 88 | PiPipeconfService pipeconfService, |
Carmelo Cascone | 3977ea4 | 2019-02-28 13:43:42 -0800 | [diff] [blame] | 89 | MasterElectionIdStore masterElectionIdStore, |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 90 | P4RuntimeClientImpl client, |
Carmelo Cascone | c2be50a | 2019-04-10 00:15:39 -0700 | [diff] [blame] | 91 | long p4DeviceId, |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 92 | P4RuntimeControllerImpl controller) { |
| 93 | this.client = client; |
| 94 | this.deviceId = client.deviceId(); |
Carmelo Cascone | c2be50a | 2019-04-10 00:15:39 -0700 | [diff] [blame] | 95 | this.p4DeviceId = p4DeviceId; |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 96 | this.pipeconfService = pipeconfService; |
Carmelo Cascone | 3977ea4 | 2019-02-28 13:43:42 -0800 | [diff] [blame] | 97 | this.masterElectionIdStore = masterElectionIdStore; |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 98 | this.controller = controller; |
| 99 | } |
| 100 | |
| 101 | @Override |
Carmelo Cascone | c2be50a | 2019-04-10 00:15:39 -0700 | [diff] [blame] | 102 | public boolean isSessionOpen(long p4DeviceId) { |
| 103 | checkArgument(this.p4DeviceId == p4DeviceId); |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 104 | return streamChannelManager.isOpen(); |
| 105 | } |
| 106 | |
| 107 | @Override |
Carmelo Cascone | c2be50a | 2019-04-10 00:15:39 -0700 | [diff] [blame] | 108 | public void closeSession(long p4DeviceId) { |
| 109 | checkArgument(this.p4DeviceId == p4DeviceId); |
Carmelo Cascone | 3977ea4 | 2019-02-28 13:43:42 -0800 | [diff] [blame] | 110 | synchronized (requestedToBeMaster) { |
Carmelo Cascone | c2be50a | 2019-04-10 00:15:39 -0700 | [diff] [blame] | 111 | this.masterElectionIdStore.unsetListener(deviceId, p4DeviceId); |
Carmelo Cascone | 3977ea4 | 2019-02-28 13:43:42 -0800 | [diff] [blame] | 112 | streamChannelManager.teardown(); |
| 113 | pendingElectionId = null; |
| 114 | requestedToBeMaster.set(false); |
| 115 | isMaster.set(false); |
| 116 | } |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 117 | } |
| 118 | |
| 119 | @Override |
Carmelo Cascone | c2be50a | 2019-04-10 00:15:39 -0700 | [diff] [blame] | 120 | public void setMastership(long p4DeviceId, boolean master, |
| 121 | BigInteger newElectionId) { |
| 122 | checkArgument(this.p4DeviceId == p4DeviceId); |
Carmelo Cascone | 3977ea4 | 2019-02-28 13:43:42 -0800 | [diff] [blame] | 123 | checkNotNull(newElectionId); |
| 124 | checkArgument(newElectionId.compareTo(BigInteger.ZERO) > 0, |
| 125 | "newElectionId must be a non zero positive number"); |
| 126 | synchronized (requestedToBeMaster) { |
| 127 | requestedToBeMaster.set(master); |
| 128 | pendingElectionId = newElectionId; |
Carmelo Cascone | c2be50a | 2019-04-10 00:15:39 -0700 | [diff] [blame] | 129 | handlePendingElectionId(masterElectionIdStore.get( |
| 130 | deviceId, p4DeviceId)); |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 131 | } |
Carmelo Cascone | 3977ea4 | 2019-02-28 13:43:42 -0800 | [diff] [blame] | 132 | } |
| 133 | |
| 134 | private void handlePendingElectionId(BigInteger masterElectionId) { |
| 135 | synchronized (requestedToBeMaster) { |
| 136 | if (pendingElectionId == null) { |
| 137 | // No pending requests. |
| 138 | return; |
| 139 | } |
Carmelo Cascone | b8a2505 | 2019-04-08 15:22:32 -0700 | [diff] [blame] | 140 | // Cancel any pending task. We'll reschedule if needed. |
| 141 | if (pendingElectionIdRetryTask != null) { |
| 142 | // Do not interrupt if running, as this might be executed by the |
| 143 | // pending task itself. |
| 144 | pendingElectionIdRetryTask.cancel(false); |
| 145 | pendingElectionIdRetryTask = null; |
| 146 | } |
| 147 | // We implement a deferring mechanism to avoid becoming master when |
| 148 | // we shouldn't, i.e. when the requested election ID is bigger than |
| 149 | // the master one on the device, but we don't want to be master. |
| 150 | // However, we make sure not to defer for more than |
| 151 | // ARBITRATION_TIMEOUT_SECONDS. |
| 152 | final boolean timeoutExpired; |
| 153 | if (pendingElectionIdTimestamp == 0) { |
| 154 | pendingElectionIdTimestamp = currentTimeMillis(); |
| 155 | timeoutExpired = false; |
| 156 | } else { |
| 157 | timeoutExpired = (currentTimeMillis() - pendingElectionIdTimestamp) |
| 158 | > ARBITRATION_TIMEOUT_SECONDS * 1000; |
| 159 | } |
| 160 | if (timeoutExpired) { |
Carmelo Cascone | c2be50a | 2019-04-10 00:15:39 -0700 | [diff] [blame] | 161 | log.warn("Arbitration timeout expired for {}! " + |
| 162 | "Will send pending election ID now...", |
Carmelo Cascone | b8a2505 | 2019-04-08 15:22:32 -0700 | [diff] [blame] | 163 | deviceId); |
| 164 | } |
| 165 | if (!timeoutExpired && |
| 166 | !requestedToBeMaster.get() && masterElectionId != null && |
| 167 | pendingElectionId.compareTo(masterElectionId) > 0) { |
| 168 | log.info("Deferring sending master arbitration update for {}, master " + |
| 169 | "election ID of server ({}) is smaller than " + |
| 170 | "requested one ({}), but we do NOT want to be master...", |
| 171 | deviceId, masterElectionId, pendingElectionId); |
| 172 | // Will try again as soon as the master election ID store is |
| 173 | // updated... |
Carmelo Cascone | c2be50a | 2019-04-10 00:15:39 -0700 | [diff] [blame] | 174 | masterElectionIdStore.setListener( |
| 175 | deviceId, p4DeviceId, masterElectionIdListener); |
Carmelo Cascone | b8a2505 | 2019-04-08 15:22:32 -0700 | [diff] [blame] | 176 | // ..or in ARBITRATION_RETRY_SECONDS at the latest (if we missed |
| 177 | // the store event). |
| 178 | pendingElectionIdRetryTask = SharedScheduledExecutors.newTimeout( |
Carmelo Cascone | c2be50a | 2019-04-10 00:15:39 -0700 | [diff] [blame] | 179 | () -> handlePendingElectionId( |
| 180 | masterElectionIdStore.get(deviceId, p4DeviceId)), |
Carmelo Cascone | b8a2505 | 2019-04-08 15:22:32 -0700 | [diff] [blame] | 181 | ARBITRATION_RETRY_SECONDS, TimeUnit.SECONDS); |
Carmelo Cascone | 3977ea4 | 2019-02-28 13:43:42 -0800 | [diff] [blame] | 182 | } else { |
| 183 | // Send now. |
| 184 | log.info("Setting mastership on {}... " + |
Carmelo Cascone | c2be50a | 2019-04-10 00:15:39 -0700 | [diff] [blame] | 185 | "master={}, newElectionId={}, " + |
| 186 | "masterElectionId={}, sessionOpen={}", |
Carmelo Cascone | b8a2505 | 2019-04-08 15:22:32 -0700 | [diff] [blame] | 187 | deviceId, requestedToBeMaster.get(), |
Carmelo Cascone | c2be50a | 2019-04-10 00:15:39 -0700 | [diff] [blame] | 188 | pendingElectionId, masterElectionId, |
| 189 | streamChannelManager.isOpen()); |
Carmelo Cascone | 4b61631 | 2019-04-17 14:15:45 -0700 | [diff] [blame] | 190 | // Optimistically set the reported master status, if wrong, it |
| 191 | // will be updated by the arbitration response. This alleviates |
| 192 | // race conditions when calling isMaster() right after setting |
| 193 | // mastership. |
Carmelo Cascone | 3977ea4 | 2019-02-28 13:43:42 -0800 | [diff] [blame] | 194 | sendMasterArbitrationUpdate(pendingElectionId); |
Carmelo Cascone | 4b61631 | 2019-04-17 14:15:45 -0700 | [diff] [blame] | 195 | isMaster.set(requestedToBeMaster.get()); |
Carmelo Cascone | 3977ea4 | 2019-02-28 13:43:42 -0800 | [diff] [blame] | 196 | pendingElectionId = null; |
Carmelo Cascone | b8a2505 | 2019-04-08 15:22:32 -0700 | [diff] [blame] | 197 | pendingElectionIdTimestamp = 0; |
Carmelo Cascone | 3977ea4 | 2019-02-28 13:43:42 -0800 | [diff] [blame] | 198 | // No need to listen for master election ID changes. |
Carmelo Cascone | c2be50a | 2019-04-10 00:15:39 -0700 | [diff] [blame] | 199 | masterElectionIdStore.unsetListener(deviceId, p4DeviceId); |
Carmelo Cascone | 3977ea4 | 2019-02-28 13:43:42 -0800 | [diff] [blame] | 200 | } |
| 201 | } |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 202 | } |
| 203 | |
| 204 | @Override |
Carmelo Cascone | c2be50a | 2019-04-10 00:15:39 -0700 | [diff] [blame] | 205 | public boolean isMaster(long p4DeviceId) { |
| 206 | checkArgument(this.p4DeviceId == p4DeviceId); |
Carmelo Cascone | 4b61631 | 2019-04-17 14:15:45 -0700 | [diff] [blame] | 207 | synchronized (requestedToBeMaster) { |
| 208 | return isMaster.get(); |
| 209 | } |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 210 | } |
| 211 | |
| 212 | @Override |
Carmelo Cascone | c2be50a | 2019-04-10 00:15:39 -0700 | [diff] [blame] | 213 | public void packetOut(long p4DeviceId, PiPacketOperation packet, PiPipeconf pipeconf) { |
| 214 | checkArgument(this.p4DeviceId == p4DeviceId); |
| 215 | if (!isSessionOpen(p4DeviceId)) { |
Carmelo Cascone | b8a2505 | 2019-04-08 15:22:32 -0700 | [diff] [blame] | 216 | log.warn("Dropping packet-out request for {}, session is closed", |
| 217 | deviceId); |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 218 | return; |
| 219 | } |
| 220 | if (log.isTraceEnabled()) { |
| 221 | log.trace("Sending packet-out to {}: {}", deviceId, packet); |
| 222 | } |
| 223 | try { |
| 224 | // Encode the PiPacketOperation into a PacketOut |
| 225 | final P4RuntimeOuterClass.PacketOut packetOut = |
| 226 | CODECS.packetOut().encode(packet, null, pipeconf); |
| 227 | // Build the request |
| 228 | final StreamMessageRequest packetOutRequest = StreamMessageRequest |
| 229 | .newBuilder().setPacket(packetOut).build(); |
| 230 | // Send. |
Carmelo Cascone | 3977ea4 | 2019-02-28 13:43:42 -0800 | [diff] [blame] | 231 | streamChannelManager.send(packetOutRequest); |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 232 | } catch (CodecException e) { |
| 233 | log.error("Unable to send packet-out: {}", e.getMessage()); |
| 234 | } |
| 235 | } |
| 236 | |
| 237 | private void sendMasterArbitrationUpdate(BigInteger electionId) { |
| 238 | log.debug("Sending arbitration update to {}... electionId={}", |
| 239 | deviceId, electionId); |
| 240 | final P4RuntimeOuterClass.Uint128 idMsg = bigIntegerToUint128(electionId); |
| 241 | streamChannelManager.send( |
| 242 | StreamMessageRequest.newBuilder() |
| 243 | .setArbitration( |
| 244 | P4RuntimeOuterClass.MasterArbitrationUpdate |
| 245 | .newBuilder() |
| 246 | .setDeviceId(p4DeviceId) |
| 247 | .setElectionId(idMsg) |
| 248 | .build()) |
| 249 | .build()); |
Carmelo Cascone | 3977ea4 | 2019-02-28 13:43:42 -0800 | [diff] [blame] | 250 | lastUsedElectionId = electionId; |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 251 | } |
| 252 | |
| 253 | private P4RuntimeOuterClass.Uint128 bigIntegerToUint128(BigInteger value) { |
| 254 | final byte[] arr = value.toByteArray(); |
| 255 | final ByteBuffer bb = ByteBuffer.allocate(Long.BYTES * 2) |
| 256 | .put(new byte[Long.BYTES * 2 - arr.length]) |
| 257 | .put(arr); |
| 258 | bb.rewind(); |
| 259 | return P4RuntimeOuterClass.Uint128.newBuilder() |
| 260 | .setHigh(bb.getLong()) |
| 261 | .setLow(bb.getLong()) |
| 262 | .build(); |
| 263 | } |
| 264 | |
| 265 | private BigInteger uint128ToBigInteger(P4RuntimeOuterClass.Uint128 value) { |
| 266 | return new BigInteger( |
| 267 | ByteBuffer.allocate(Long.BYTES * 2) |
| 268 | .putLong(value.getHigh()) |
| 269 | .putLong(value.getLow()) |
| 270 | .array()); |
| 271 | } |
| 272 | |
| 273 | private void handlePacketIn(P4RuntimeOuterClass.PacketIn packetInMsg) { |
| 274 | if (log.isTraceEnabled()) { |
| 275 | log.trace("Received packet-in from {}: {}", deviceId, packetInMsg); |
| 276 | } |
| 277 | if (!pipeconfService.getPipeconf(deviceId).isPresent()) { |
| 278 | log.warn("Unable to handle packet-in from {}, missing pipeconf: {}", |
| 279 | deviceId, TextFormat.shortDebugString(packetInMsg)); |
| 280 | return; |
| 281 | } |
| 282 | // Decode packet message and post event. |
| 283 | // TODO: consider implementing a cache to speed up |
| 284 | // encoding/deconding of packet-in/out (e.g. LLDP, ARP) |
| 285 | final PiPipeconf pipeconf = pipeconfService.getPipeconf(deviceId).get(); |
| 286 | final PiPacketOperation pktOperation; |
| 287 | try { |
| 288 | pktOperation = CODECS.packetIn().decode( |
| 289 | packetInMsg, null, pipeconf); |
| 290 | } catch (CodecException e) { |
| 291 | log.warn("Unable to process packet-int: {}", e.getMessage()); |
| 292 | return; |
| 293 | } |
| 294 | controller.postEvent(new P4RuntimeEvent( |
| 295 | P4RuntimeEvent.Type.PACKET_IN, |
| 296 | new PacketInEvent(deviceId, pktOperation))); |
| 297 | } |
| 298 | |
| 299 | private void handleArbitrationUpdate(P4RuntimeOuterClass.MasterArbitrationUpdate msg) { |
| 300 | // From the spec... |
| 301 | // - Election_id: The stream RPC with the highest election_id is the |
| 302 | // master. Switch populates with the highest election ID it |
| 303 | // has received from all connected controllers. |
| 304 | // - Status: Switch populates this with OK for the client that is the |
| 305 | // master, and with an error status for all other connected clients (at |
| 306 | // every mastership change). |
| 307 | if (!msg.hasElectionId() || !msg.hasStatus()) { |
| 308 | return; |
| 309 | } |
Carmelo Cascone | 3977ea4 | 2019-02-28 13:43:42 -0800 | [diff] [blame] | 310 | // Is this client master? |
| 311 | isMaster.set(msg.getStatus().getCode() == Status.OK.getCode().value()); |
| 312 | // Notify new master election IDs to all nodes via distributed store. |
| 313 | // This is required for those nodes who do not have a Stream RPC open, |
| 314 | // and that otherwise would not be aware of changes, keeping their |
| 315 | // pending mastership operations forever. |
| 316 | final BigInteger masterElectionId = uint128ToBigInteger(msg.getElectionId()); |
Carmelo Cascone | c2be50a | 2019-04-10 00:15:39 -0700 | [diff] [blame] | 317 | masterElectionIdStore.set(deviceId, p4DeviceId, masterElectionId); |
Carmelo Cascone | 3977ea4 | 2019-02-28 13:43:42 -0800 | [diff] [blame] | 318 | |
| 319 | log.debug("Received arbitration update from {}: isMaster={}, masterElectionId={}", |
| 320 | deviceId, isMaster.get(), masterElectionId); |
| 321 | |
| 322 | // Post mastership event via controller. |
| 323 | controller.postEvent(new DeviceAgentEvent( |
| 324 | isMaster.get() ? DeviceAgentEvent.Type.ROLE_MASTER |
| 325 | : DeviceAgentEvent.Type.ROLE_STANDBY, deviceId)); |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 326 | } |
| 327 | |
| 328 | /** |
| 329 | * Returns the election ID last used in a MasterArbitrationUpdate message |
| 330 | * sent by the client to the server. |
| 331 | * |
| 332 | * @return election ID uint128 protobuf message |
| 333 | */ |
| 334 | P4RuntimeOuterClass.Uint128 lastUsedElectionId() { |
Carmelo Cascone | 3977ea4 | 2019-02-28 13:43:42 -0800 | [diff] [blame] | 335 | return lastUsedElectionId == null |
| 336 | ? P4RuntimeOuterClass.Uint128.getDefaultInstance() |
| 337 | : bigIntegerToUint128(lastUsedElectionId); |
| 338 | } |
| 339 | |
| 340 | /** |
| 341 | * Handles updates of the master election ID by applying any pending |
| 342 | * mastership operation. |
| 343 | */ |
| 344 | private class InternalMasterElectionIdListener |
| 345 | implements MasterElectionIdStore.MasterElectionIdListener { |
| 346 | |
| 347 | @Override |
| 348 | public void updated(BigInteger masterElectionId) { |
Carmelo Cascone | b8a2505 | 2019-04-08 15:22:32 -0700 | [diff] [blame] | 349 | log.debug("UPDATED master election ID of {}: {}", |
| 350 | deviceId, masterElectionId); |
Carmelo Cascone | 3977ea4 | 2019-02-28 13:43:42 -0800 | [diff] [blame] | 351 | handlePendingElectionId(masterElectionId); |
| 352 | } |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 353 | } |
| 354 | |
| 355 | /** |
Carmelo Cascone | c2be50a | 2019-04-10 00:15:39 -0700 | [diff] [blame] | 356 | * A manager for the P4Runtime StreamChannel RPC that opportunistically creates |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 357 | * new stream RCP stubs (e.g. when one fails because of errors) and posts |
| 358 | * channel events via the P4Runtime controller. |
| 359 | */ |
| 360 | private final class StreamChannelManager { |
| 361 | |
| 362 | private final AtomicBoolean open = new AtomicBoolean(false); |
| 363 | private final StreamObserver<StreamMessageResponse> responseObserver = |
| 364 | new InternalStreamResponseObserver(this); |
| 365 | private ClientCallStreamObserver<StreamMessageRequest> requestObserver; |
| 366 | |
| 367 | void send(StreamMessageRequest value) { |
| 368 | synchronized (this) { |
| 369 | initIfRequired(); |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 370 | requestObserver.onNext(value); |
Carmelo Cascone | 3977ea4 | 2019-02-28 13:43:42 -0800 | [diff] [blame] | 371 | // Optimistically set the session as open. In case of errors, it |
| 372 | // will be closed by the response stream observer. |
| 373 | streamChannelManager.signalOpen(); |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 374 | } |
| 375 | } |
| 376 | |
| 377 | private void initIfRequired() { |
| 378 | if (requestObserver == null) { |
Carmelo Cascone | c2be50a | 2019-04-10 00:15:39 -0700 | [diff] [blame] | 379 | log.debug("Starting new StreamChannel RPC for {}...", deviceId); |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 380 | open.set(false); |
| 381 | client.execRpcNoTimeout( |
| 382 | s -> requestObserver = |
| 383 | (ClientCallStreamObserver<StreamMessageRequest>) |
| 384 | s.streamChannel(responseObserver) |
| 385 | ); |
| 386 | } |
| 387 | } |
| 388 | |
Carmelo Cascone | 3977ea4 | 2019-02-28 13:43:42 -0800 | [diff] [blame] | 389 | void teardown() { |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 390 | synchronized (this) { |
| 391 | signalClosed(); |
| 392 | if (requestObserver != null) { |
| 393 | requestObserver.onCompleted(); |
| 394 | requestObserver.cancel("Completed", null); |
| 395 | requestObserver = null; |
| 396 | } |
| 397 | } |
| 398 | } |
| 399 | |
| 400 | void signalOpen() { |
Carmelo Cascone | 3977ea4 | 2019-02-28 13:43:42 -0800 | [diff] [blame] | 401 | open.set(true); |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 402 | } |
| 403 | |
| 404 | void signalClosed() { |
| 405 | synchronized (this) { |
| 406 | final boolean wasOpen = open.getAndSet(false); |
Carmelo Cascone | 4b61631 | 2019-04-17 14:15:45 -0700 | [diff] [blame] | 407 | if (wasOpen) { |
| 408 | // We lost any valid mastership role. |
| 409 | controller.postEvent(new DeviceAgentEvent( |
| 410 | DeviceAgentEvent.Type.ROLE_NONE, deviceId)); |
| 411 | } |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 412 | } |
| 413 | } |
| 414 | |
| 415 | boolean isOpen() { |
| 416 | return open.get(); |
| 417 | } |
| 418 | } |
| 419 | |
| 420 | /** |
Carmelo Cascone | c2be50a | 2019-04-10 00:15:39 -0700 | [diff] [blame] | 421 | * Handles messages received from the device on the StreamChannel RPC. |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 422 | */ |
| 423 | private final class InternalStreamResponseObserver |
| 424 | implements StreamObserver<StreamMessageResponse> { |
| 425 | |
| 426 | private final StreamChannelManager streamChannelManager; |
| 427 | |
| 428 | private InternalStreamResponseObserver( |
| 429 | StreamChannelManager streamChannelManager) { |
| 430 | this.streamChannelManager = streamChannelManager; |
| 431 | } |
| 432 | |
| 433 | @Override |
| 434 | public void onNext(StreamMessageResponse message) { |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 435 | try { |
| 436 | if (log.isTraceEnabled()) { |
Carmelo Cascone | 3977ea4 | 2019-02-28 13:43:42 -0800 | [diff] [blame] | 437 | log.trace("Received {} from {}: {}", |
| 438 | message.getUpdateCase(), deviceId, |
| 439 | TextFormat.shortDebugString(message)); |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 440 | } |
| 441 | switch (message.getUpdateCase()) { |
| 442 | case PACKET: |
| 443 | handlePacketIn(message.getPacket()); |
| 444 | return; |
| 445 | case ARBITRATION: |
| 446 | handleArbitrationUpdate(message.getArbitration()); |
| 447 | return; |
| 448 | default: |
| 449 | log.warn("Unrecognized StreamMessageResponse from {}: {}", |
| 450 | deviceId, message.getUpdateCase()); |
| 451 | } |
| 452 | } catch (Throwable ex) { |
Carmelo Cascone | c2be50a | 2019-04-10 00:15:39 -0700 | [diff] [blame] | 453 | log.error("Exception while processing StreamMessageResponse from {}", |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 454 | deviceId, ex); |
| 455 | } |
| 456 | } |
| 457 | |
| 458 | @Override |
| 459 | public void onError(Throwable throwable) { |
| 460 | if (throwable instanceof StatusRuntimeException) { |
| 461 | final StatusRuntimeException sre = (StatusRuntimeException) throwable; |
| 462 | if (sre.getStatus().getCause() instanceof ConnectException) { |
| 463 | log.warn("{} is unreachable ({})", |
| 464 | deviceId, sre.getCause().getMessage()); |
| 465 | } else { |
Carmelo Cascone | c2be50a | 2019-04-10 00:15:39 -0700 | [diff] [blame] | 466 | log.warn("Error on StreamChannel RPC for {}: {}", |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 467 | deviceId, throwable.getMessage()); |
| 468 | } |
Carmelo Cascone | 3977ea4 | 2019-02-28 13:43:42 -0800 | [diff] [blame] | 469 | log.debug("", throwable); |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 470 | } else { |
Carmelo Cascone | c2be50a | 2019-04-10 00:15:39 -0700 | [diff] [blame] | 471 | log.error(format("Exception on StreamChannel RPC for %s", |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 472 | deviceId), throwable); |
| 473 | } |
Carmelo Cascone | 3977ea4 | 2019-02-28 13:43:42 -0800 | [diff] [blame] | 474 | streamChannelManager.teardown(); |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 475 | } |
| 476 | |
| 477 | @Override |
| 478 | public void onCompleted() { |
Carmelo Cascone | c2be50a | 2019-04-10 00:15:39 -0700 | [diff] [blame] | 479 | log.warn("StreamChannel RPC for {} has completed", deviceId); |
Carmelo Cascone | 3977ea4 | 2019-02-28 13:43:42 -0800 | [diff] [blame] | 480 | streamChannelManager.teardown(); |
Carmelo Cascone | 4c289b7 | 2019-01-22 15:30:45 -0800 | [diff] [blame] | 481 | } |
| 482 | } |
| 483 | } |