blob: 5b5d087d45cdfe69c50fb9e36cc7159b0db136df [file] [log] [blame]
Carmelo Cascone4c289b72019-01-22 15:30:45 -08001/*
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
17package org.onosproject.p4runtime.ctl.client;
18
19import com.google.common.util.concurrent.Futures;
20import com.google.protobuf.TextFormat;
21import io.grpc.stub.StreamObserver;
22import org.onosproject.net.pi.model.PiPipeconf;
23import org.onosproject.net.pi.runtime.PiEntity;
24import org.onosproject.net.pi.runtime.PiHandle;
25import org.onosproject.p4runtime.api.P4RuntimeWriteClient;
26import org.onosproject.p4runtime.ctl.codec.CodecException;
27import org.slf4j.Logger;
28import p4.v1.P4RuntimeOuterClass;
29
30import java.util.concurrent.CompletableFuture;
31
32import static com.google.common.base.Preconditions.checkNotNull;
33import static java.lang.String.format;
34import static java.util.concurrent.CompletableFuture.completedFuture;
35import static org.onosproject.p4runtime.ctl.client.P4RuntimeClientImpl.SHORT_TIMEOUT_SECONDS;
36import static org.onosproject.p4runtime.ctl.codec.Codecs.CODECS;
37import static org.slf4j.LoggerFactory.getLogger;
38
39/**
40 * Handles the creation of P4Runtime WriteRequest and execution of the Write RPC
41 * on the server.
42 */
43final class WriteRequestImpl implements P4RuntimeWriteClient.WriteRequest {
44
45 private static final Logger log = getLogger(WriteRequestImpl.class);
46
47 private static final P4RuntimeOuterClass.WriteResponse P4RT_DEFAULT_WRITE_RESPONSE_MSG =
48 P4RuntimeOuterClass.WriteResponse.getDefaultInstance();
49
50 private final P4RuntimeClientImpl client;
51 private final PiPipeconf pipeconf;
52 // The P4Runtime WriteRequest protobuf message we need to populate.
53 private final P4RuntimeOuterClass.WriteRequest.Builder requestMsg;
54 // WriteResponse instance builder. We populate entity responses as we add new
55 // entities to this request. The status of each entity response will be
56 // set once we receive a response from the device.
57 private final WriteResponseImpl.Builder responseBuilder;
58
59 WriteRequestImpl(P4RuntimeClientImpl client, PiPipeconf pipeconf) {
60 this.client = checkNotNull(client);
61 this.pipeconf = checkNotNull(pipeconf);
62 this.requestMsg = P4RuntimeOuterClass.WriteRequest.newBuilder()
63 .setDeviceId(client.p4DeviceId());
64 this.responseBuilder = WriteResponseImpl.builder(client.deviceId());
65 }
66
67 @Override
68 public P4RuntimeWriteClient.WriteRequest withAtomicity(
69 P4RuntimeWriteClient.Atomicity atomicity) {
70 checkNotNull(atomicity);
71 switch (atomicity) {
72 case CONTINUE_ON_ERROR:
73 requestMsg.setAtomicity(
74 P4RuntimeOuterClass.WriteRequest.Atomicity.CONTINUE_ON_ERROR);
75 break;
76 case ROLLBACK_ON_ERROR:
77 case DATAPLANE_ATOMIC:
78 // Supporting this while allowing codec exceptions to be
79 // reported as write responses can be tricky. Assuming write on
80 // device succeed but we have a codec exception and
81 // atomicity is rollback on error.
82 default:
83 throw new UnsupportedOperationException(format(
84 "Atomicity mode %s not supported", atomicity));
85 }
86 return this;
87 }
88
89 @Override
90 public P4RuntimeWriteClient.WriteRequest insert(PiEntity entity) {
91 return entity(entity, P4RuntimeWriteClient.UpdateType.INSERT);
92 }
93
94 @Override
95 public P4RuntimeWriteClient.WriteRequest insert(
96 Iterable<? extends PiEntity> entities) {
97 return entities(entities, P4RuntimeWriteClient.UpdateType.INSERT);
98 }
99
100 @Override
101 public P4RuntimeWriteClient.WriteRequest modify(PiEntity entity) {
102 return entity(entity, P4RuntimeWriteClient.UpdateType.MODIFY);
103 }
104
105 @Override
106 public P4RuntimeWriteClient.WriteRequest modify(
107 Iterable<? extends PiEntity> entities) {
108 return entities(entities, P4RuntimeWriteClient.UpdateType.MODIFY);
109 }
110
111 @Override
112 public P4RuntimeWriteClient.WriteRequest delete(
113 Iterable<? extends PiHandle> handles) {
114 checkNotNull(handles);
115 handles.forEach(this::delete);
116 return this;
117 }
118
119 @Override
120 public P4RuntimeWriteClient.WriteRequest entities(
121 Iterable<? extends PiEntity> entities,
122 P4RuntimeWriteClient.UpdateType updateType) {
123 checkNotNull(entities);
124 entities.forEach(e -> this.entity(e, updateType));
125 return this;
126 }
127
128 @Override
129 public P4RuntimeWriteClient.WriteRequest entity(
130 PiEntity entity, P4RuntimeWriteClient.UpdateType updateType) {
131 checkNotNull(entity);
132 checkNotNull(updateType);
133 appendToRequestMsg(updateType, entity, entity.handle(client.deviceId()));
134 return this;
135 }
136
137 @Override
138 public P4RuntimeWriteClient.WriteRequest delete(PiHandle handle) {
139 checkNotNull(handle);
140 appendToRequestMsg(P4RuntimeWriteClient.UpdateType.DELETE, null, handle);
141 return this;
142 }
143
144 @Override
145 public P4RuntimeWriteClient.WriteResponse submitSync() {
146 return Futures.getUnchecked(submit());
147 }
148
149 @Override
150 public CompletableFuture<P4RuntimeWriteClient.WriteResponse> submit() {
151 final P4RuntimeOuterClass.WriteRequest writeRequest = requestMsg
152 .setElectionId(client.lastUsedElectionId())
153 .build();
154 log.debug("Sending write request to {} with {} updates...",
155 client.deviceId(), writeRequest.getUpdatesCount());
156 if (writeRequest.getUpdatesCount() == 0) {
157 // No need to ask the server.
158 return completedFuture(WriteResponseImpl.EMPTY);
159 }
160 final CompletableFuture<P4RuntimeWriteClient.WriteResponse> future =
161 new CompletableFuture<>();
162 final StreamObserver<P4RuntimeOuterClass.WriteResponse> observer =
163 new StreamObserver<P4RuntimeOuterClass.WriteResponse>() {
164 @Override
165 public void onNext(P4RuntimeOuterClass.WriteResponse value) {
166 if (!P4RT_DEFAULT_WRITE_RESPONSE_MSG.equals(value)) {
167 log.warn("Received invalid WriteResponse message from {}: {}",
168 client.deviceId(), TextFormat.shortDebugString(value));
169 // Leave all entity responses in pending state.
170 future.complete(responseBuilder.buildAsIs());
171 } else {
172 log.debug("Received write response from {}...",
173 client.deviceId());
174 // All good, all entities written successfully.
175 future.complete(responseBuilder.setSuccessAllAndBuild());
176 }
177 }
178 @Override
179 public void onError(Throwable t) {
180 client.handleRpcError(t, "WRITE");
181 future.complete(responseBuilder.setErrorsAndBuild(t));
182 }
183 @Override
184 public void onCompleted() {
185 // Nothing to do, unary call.
186 }
187 };
188 client.execRpc(s -> s.write(writeRequest, observer), SHORT_TIMEOUT_SECONDS);
189 return future;
190 }
191
192 private void appendToRequestMsg(P4RuntimeWriteClient.UpdateType updateType,
193 PiEntity piEntity, PiHandle handle) {
194 final P4RuntimeOuterClass.Update.Type p4UpdateType;
195 final P4RuntimeOuterClass.Entity entityMsg;
196 try {
197 if (updateType.equals(P4RuntimeWriteClient.UpdateType.DELETE)) {
198 p4UpdateType = P4RuntimeOuterClass.Update.Type.DELETE;
199 entityMsg = CODECS.handle().encode(handle, null, pipeconf);
200 } else {
201 p4UpdateType = updateType == P4RuntimeWriteClient.UpdateType.INSERT
202 ? P4RuntimeOuterClass.Update.Type.INSERT
203 : P4RuntimeOuterClass.Update.Type.MODIFY;
204 entityMsg = CODECS.entity().encode(piEntity, null, pipeconf);
205 }
206 final P4RuntimeOuterClass.Update updateMsg = P4RuntimeOuterClass.Update
207 .newBuilder()
208 .setEntity(entityMsg)
209 .setType(p4UpdateType)
210 .build();
211 requestMsg.addUpdates(updateMsg);
212 responseBuilder.addPendingResponse(handle, piEntity, updateType);
213 } catch (CodecException e) {
214 responseBuilder.addFailedResponse(
215 handle, piEntity, updateType, e.getMessage(),
216 P4RuntimeWriteClient.WriteResponseStatus.CODEC_ERROR);
217 }
218 }
219}