blob: 4ad3166e16446f1dde6c97bae665d80f58f3e18b [file] [log] [blame]
Andrea Campanella378e21a2017-06-07 12:09:59 +02001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2017-present Open Networking Foundation
Andrea Campanella378e21a2017-06-07 12:09:59 +02003 *
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.grpc.ctl;
18
Carmelo Casconefb924072017-08-29 20:21:55 +020019import com.google.common.collect.ImmutableMap;
Andrea Campanella378e21a2017-06-07 12:09:59 +020020import com.google.common.collect.ImmutableSet;
Carmelo Cascone158b8c42018-07-04 19:42:37 +020021import com.google.common.util.concurrent.Striped;
Carmelo Cascone8d99b172017-07-18 17:26:31 -040022import io.grpc.CallOptions;
23import io.grpc.Channel;
24import io.grpc.ClientCall;
25import io.grpc.ClientInterceptor;
26import io.grpc.ForwardingClientCall;
27import io.grpc.ForwardingClientCallListener;
Andrea Campanella378e21a2017-06-07 12:09:59 +020028import io.grpc.ManagedChannel;
29import io.grpc.ManagedChannelBuilder;
Carmelo Cascone8d99b172017-07-18 17:26:31 -040030import io.grpc.Metadata;
31import io.grpc.MethodDescriptor;
Carmelo Cascone59f57de2017-07-11 19:55:09 -040032import io.grpc.Status;
33import io.grpc.StatusRuntimeException;
Andrea Campanellaa74bdba2018-05-15 16:45:00 +020034import org.onlab.util.Tools;
35import org.onosproject.cfg.ComponentConfigService;
Yi Tseng2a340f72018-11-02 16:52:47 -070036import org.onosproject.grpc.api.GrpcChannelController;
Andrea Campanella378e21a2017-06-07 12:09:59 +020037import org.onosproject.grpc.api.GrpcChannelId;
Carmelo Cascone6a1ae712018-08-10 12:19:47 -070038import org.onosproject.grpc.proto.dummy.Dummy;
39import org.onosproject.grpc.proto.dummy.DummyServiceGrpc;
Andrea Campanella378e21a2017-06-07 12:09:59 +020040import org.onosproject.net.DeviceId;
Andrea Campanellaa74bdba2018-05-15 16:45:00 +020041import org.osgi.service.component.ComponentContext;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070042import org.osgi.service.component.annotations.Activate;
43import org.osgi.service.component.annotations.Component;
44import org.osgi.service.component.annotations.Deactivate;
45import org.osgi.service.component.annotations.Modified;
46import org.osgi.service.component.annotations.Reference;
47import org.osgi.service.component.annotations.ReferenceCardinality;
Andrea Campanella378e21a2017-06-07 12:09:59 +020048import org.slf4j.Logger;
49import org.slf4j.LoggerFactory;
50
51import java.util.Collection;
Andrea Campanellaa74bdba2018-05-15 16:45:00 +020052import java.util.Dictionary;
Andrea Campanella378e21a2017-06-07 12:09:59 +020053import java.util.HashSet;
54import java.util.Map;
55import java.util.Optional;
56import java.util.Set;
57import java.util.concurrent.ConcurrentHashMap;
Carmelo Cascone59f57de2017-07-11 19:55:09 -040058import java.util.concurrent.TimeUnit;
Carmelo Casconefb924072017-08-29 20:21:55 +020059import java.util.concurrent.locks.Lock;
Carmelo Casconefb924072017-08-29 20:21:55 +020060
61import static com.google.common.base.Preconditions.checkNotNull;
Carmelo Cascone6d57f322018-12-13 23:15:17 -080062import static java.lang.String.format;
Thomas Vachuska00b5d4f2018-10-30 15:13:20 -070063import static org.onosproject.grpc.ctl.OsgiPropertyConstants.ENABLE_MESSAGE_LOG;
64import static org.onosproject.grpc.ctl.OsgiPropertyConstants.ENABLE_MESSAGE_LOG_DEFAULT;
Andrea Campanella378e21a2017-06-07 12:09:59 +020065
66/**
Yi Tseng2a340f72018-11-02 16:52:47 -070067 * Default implementation of the GrpcChannelController.
Andrea Campanella378e21a2017-06-07 12:09:59 +020068 */
Ray Milkey5739b2c2018-11-06 14:04:51 -080069@Component(immediate = true, service = GrpcChannelController.class,
Thomas Vachuska00b5d4f2018-10-30 15:13:20 -070070 property = {
71 ENABLE_MESSAGE_LOG + ":Boolean=" + ENABLE_MESSAGE_LOG_DEFAULT,
72 })
Yi Tseng2a340f72018-11-02 16:52:47 -070073public class GrpcChannelControllerImpl implements GrpcChannelController {
Andrea Campanella378e21a2017-06-07 12:09:59 +020074
Yi Tseng2a340f72018-11-02 16:52:47 -070075 // FIXME: Should use message size to determine whether it needs to log the message or not.
Carmelo Cascone6d57f322018-12-13 23:15:17 -080076 private static final String SET_FORWARDING_PIPELINE_CONFIG_METHOD = "p4.P4Runtime/SetForwardingPipelineConfig";
Andrea Campanellaa74bdba2018-05-15 16:45:00 +020077
Ray Milkeyd84f89b2018-08-17 14:54:17 -070078 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Andrea Campanellaa74bdba2018-05-15 16:45:00 +020079 protected ComponentConfigService componentConfigService;
80
Carmelo Cascone6d57f322018-12-13 23:15:17 -080081 /** Indicates whether to log gRPC messages. */
82 private static boolean enableMessageLog = ENABLE_MESSAGE_LOG_DEFAULT;
Carmelo Cascone8d99b172017-07-18 17:26:31 -040083
Carmelo Cascone47a853b2018-01-05 02:40:58 +010084 private final Logger log = LoggerFactory.getLogger(getClass());
Carmelo Cascone59f57de2017-07-11 19:55:09 -040085
Andrea Campanella378e21a2017-06-07 12:09:59 +020086 private Map<GrpcChannelId, ManagedChannel> channels;
Carmelo Cascone158b8c42018-07-04 19:42:37 +020087 private final Striped<Lock> channelLocks = Striped.lock(30);
Andrea Campanella378e21a2017-06-07 12:09:59 +020088
89 @Activate
90 public void activate() {
Andrea Campanellaa74bdba2018-05-15 16:45:00 +020091 componentConfigService.registerProperties(getClass());
Andrea Campanella378e21a2017-06-07 12:09:59 +020092 channels = new ConcurrentHashMap<>();
Andrea Campanella378e21a2017-06-07 12:09:59 +020093 log.info("Started");
94 }
95
Andrea Campanellaa74bdba2018-05-15 16:45:00 +020096 @Modified
97 public void modified(ComponentContext context) {
98 if (context != null) {
99 Dictionary<?, ?> properties = context.getProperties();
Carmelo Cascone6d57f322018-12-13 23:15:17 -0800100 enableMessageLog = Tools.isPropertyEnabled(
101 properties, ENABLE_MESSAGE_LOG, ENABLE_MESSAGE_LOG_DEFAULT);
102 log.info("Configured. Log of gRPC messages is {} for new channels",
103 enableMessageLog ? "enabled" : "disabled");
Andrea Campanellaa74bdba2018-05-15 16:45:00 +0200104 }
105 }
106
Andrea Campanella378e21a2017-06-07 12:09:59 +0200107 @Deactivate
108 public void deactivate() {
Andrea Campanellaa74bdba2018-05-15 16:45:00 +0200109 componentConfigService.unregisterProperties(getClass(), false);
Carmelo Cascone6d57f322018-12-13 23:15:17 -0800110 channels.values().forEach(ManagedChannel::shutdownNow);
Andrea Campanella378e21a2017-06-07 12:09:59 +0200111 channels.clear();
Andrea Campanella378e21a2017-06-07 12:09:59 +0200112 log.info("Stopped");
113 }
114
115 @Override
Carmelo Cascone47a853b2018-01-05 02:40:58 +0100116 public ManagedChannel connectChannel(GrpcChannelId channelId,
Carmelo Casconea71b8492018-12-17 17:47:50 -0800117 ManagedChannelBuilder<?> channelBuilder) {
Carmelo Casconefb924072017-08-29 20:21:55 +0200118 checkNotNull(channelId);
119 checkNotNull(channelBuilder);
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400120
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200121 Lock lock = channelLocks.get(channelId);
Carmelo Casconefb924072017-08-29 20:21:55 +0200122 lock.lock();
123
124 try {
Carmelo Cascone6d57f322018-12-13 23:15:17 -0800125 if (channels.containsKey(channelId)) {
126 throw new IllegalArgumentException(format(
127 "A channel with ID '%s' already exists", channelId));
128 }
129 if (enableMessageLog) {
130 channelBuilder.intercept(new InternalLogChannelInterceptor(channelId));
131 }
Carmelo Casconefb924072017-08-29 20:21:55 +0200132 ManagedChannel channel = channelBuilder.build();
Carmelo Cascone6d57f322018-12-13 23:15:17 -0800133 // Forced connection API is still experimental. Use workaround...
Carmelo Casconefb924072017-08-29 20:21:55 +0200134 // channel.getState(true);
Carmelo Cascone6d57f322018-12-13 23:15:17 -0800135 try {
136 doDummyMessage(channel);
137 } catch (StatusRuntimeException e) {
Carmelo Casconea71b8492018-12-17 17:47:50 -0800138 shutdownNowAndWait(channel, channelId);
139 throw e;
Carmelo Cascone6d57f322018-12-13 23:15:17 -0800140 }
141 // If here, channel is open.
Carmelo Casconefb924072017-08-29 20:21:55 +0200142 channels.put(channelId, channel);
143 return channel;
144 } finally {
145 lock.unlock();
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400146 }
Andrea Campanella378e21a2017-06-07 12:09:59 +0200147 }
148
Carmelo Cascone6d57f322018-12-13 23:15:17 -0800149 private boolean doDummyMessage(ManagedChannel channel) throws StatusRuntimeException {
Carmelo Cascone47a853b2018-01-05 02:40:58 +0100150 DummyServiceGrpc.DummyServiceBlockingStub dummyStub = DummyServiceGrpc
151 .newBlockingStub(channel)
Carmelo Cascone59f57de2017-07-11 19:55:09 -0400152 .withDeadlineAfter(CONNECTION_TIMEOUT_SECONDS, TimeUnit.SECONDS);
153 try {
Carmelo Cascone6d57f322018-12-13 23:15:17 -0800154 return dummyStub.sayHello(Dummy.DummyMessageThatNoOneWouldReallyUse
155 .getDefaultInstance()) != null;
Carmelo Cascone59f57de2017-07-11 19:55:09 -0400156 } catch (StatusRuntimeException e) {
Carmelo Cascone6d57f322018-12-13 23:15:17 -0800157 if (e.getStatus().equals(Status.UNIMPLEMENTED)) {
Carmelo Cascone47a853b2018-01-05 02:40:58 +0100158 // UNIMPLEMENTED means that the server received our message but
159 // doesn't know how to handle it. Hence, channel is open.
Carmelo Cascone6d57f322018-12-13 23:15:17 -0800160 return true;
161 } else {
162 throw e;
Carmelo Cascone59f57de2017-07-11 19:55:09 -0400163 }
164 }
165 }
166
167 @Override
168 public boolean isChannelOpen(GrpcChannelId channelId) {
Carmelo Casconefb924072017-08-29 20:21:55 +0200169 checkNotNull(channelId);
170
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200171 Lock lock = channelLocks.get(channelId);
Carmelo Casconefb924072017-08-29 20:21:55 +0200172 lock.lock();
Carmelo Cascone59f57de2017-07-11 19:55:09 -0400173
174 try {
Carmelo Casconefb924072017-08-29 20:21:55 +0200175 if (!channels.containsKey(channelId)) {
Carmelo Cascone6d57f322018-12-13 23:15:17 -0800176 log.warn("Unknown channel ID '{}', can't check if channel is open",
Carmelo Cascone47a853b2018-01-05 02:40:58 +0100177 channelId);
Carmelo Casconefb924072017-08-29 20:21:55 +0200178 return false;
179 }
180 try {
Carmelo Cascone6d57f322018-12-13 23:15:17 -0800181 return doDummyMessage(channels.get(channelId));
182 } catch (StatusRuntimeException e) {
Carmelo Cascone47a853b2018-01-05 02:40:58 +0100183 log.debug("Unable to send dummy message to {}: {}",
Carmelo Cascone6d57f322018-12-13 23:15:17 -0800184 channelId, e.toString());
Carmelo Casconefb924072017-08-29 20:21:55 +0200185 return false;
186 }
187 } finally {
188 lock.unlock();
Carmelo Cascone59f57de2017-07-11 19:55:09 -0400189 }
190 }
191
Andrea Campanella378e21a2017-06-07 12:09:59 +0200192 @Override
193 public void disconnectChannel(GrpcChannelId channelId) {
Carmelo Casconefb924072017-08-29 20:21:55 +0200194 checkNotNull(channelId);
195
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200196 Lock lock = channelLocks.get(channelId);
Carmelo Casconefb924072017-08-29 20:21:55 +0200197 lock.lock();
Carmelo Cascone59f57de2017-07-11 19:55:09 -0400198 try {
Carmelo Cascone6d57f322018-12-13 23:15:17 -0800199 final ManagedChannel channel = channels.remove(channelId);
Carmelo Casconea71b8492018-12-17 17:47:50 -0800200 if (channel != null) {
201 shutdownNowAndWait(channel, channelId);
Carmelo Casconefb924072017-08-29 20:21:55 +0200202 }
Carmelo Casconefb924072017-08-29 20:21:55 +0200203 } finally {
204 lock.unlock();
205 }
Andrea Campanella378e21a2017-06-07 12:09:59 +0200206 }
207
Carmelo Casconea71b8492018-12-17 17:47:50 -0800208 private void shutdownNowAndWait(ManagedChannel channel, GrpcChannelId channelId) {
209 try {
210 if (!channel.shutdownNow()
211 .awaitTermination(5, TimeUnit.SECONDS)) {
212 log.error("Channel '{}' didn't terminate, although we " +
213 "triggered a shutdown and waited",
214 channelId);
215 }
216 } catch (InterruptedException e) {
217 log.warn("Channel {} didn't shutdown in time", channelId);
218 Thread.currentThread().interrupt();
219 }
220 }
221
Andrea Campanella378e21a2017-06-07 12:09:59 +0200222 @Override
223 public Map<GrpcChannelId, ManagedChannel> getChannels() {
Carmelo Casconefb924072017-08-29 20:21:55 +0200224 return ImmutableMap.copyOf(channels);
Andrea Campanella378e21a2017-06-07 12:09:59 +0200225 }
226
227 @Override
228 public Collection<ManagedChannel> getChannels(final DeviceId deviceId) {
Carmelo Casconefb924072017-08-29 20:21:55 +0200229 checkNotNull(deviceId);
Andrea Campanella378e21a2017-06-07 12:09:59 +0200230 final Set<ManagedChannel> deviceChannels = new HashSet<>();
231 channels.forEach((k, v) -> {
232 if (k.deviceId().equals(deviceId)) {
233 deviceChannels.add(v);
234 }
235 });
236
237 return ImmutableSet.copyOf(deviceChannels);
238 }
239
240 @Override
241 public Optional<ManagedChannel> getChannel(GrpcChannelId channelId) {
Carmelo Casconefb924072017-08-29 20:21:55 +0200242 checkNotNull(channelId);
243
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200244 Lock lock = channelLocks.get(channelId);
Carmelo Casconefb924072017-08-29 20:21:55 +0200245 lock.lock();
246
247 try {
248 return Optional.ofNullable(channels.get(channelId));
249 } finally {
250 lock.unlock();
251 }
Andrea Campanella378e21a2017-06-07 12:09:59 +0200252 }
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400253
254 /**
255 * gRPC client interceptor that logs all messages sent and received.
256 */
257 private final class InternalLogChannelInterceptor implements ClientInterceptor {
258
259 private final GrpcChannelId channelId;
260
261 private InternalLogChannelInterceptor(GrpcChannelId channelId) {
262 this.channelId = channelId;
263 }
264
265 @Override
Carmelo Cascone47a853b2018-01-05 02:40:58 +0100266 public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
267 MethodDescriptor<ReqT, RespT> methodDescriptor,
268 CallOptions callOptions, Channel channel) {
269 return new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(
270 channel.newCall(methodDescriptor, callOptions.withoutWaitForReady())) {
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400271
272 @Override
273 public void sendMessage(ReqT message) {
Andrea Campanellaa74bdba2018-05-15 16:45:00 +0200274 if (enableMessageLog && !methodDescriptor.getFullMethodName()
275 .startsWith(SET_FORWARDING_PIPELINE_CONFIG_METHOD)) {
276 log.info("*** SENDING GRPC MESSAGE [{}]\n{}:\n{}",
Carmelo Cascone6d57f322018-12-13 23:15:17 -0800277 channelId, methodDescriptor.getFullMethodName(),
278 message.toString());
Andrea Campanellaa74bdba2018-05-15 16:45:00 +0200279 }
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400280 super.sendMessage(message);
281 }
282
283 @Override
284 public void start(Listener<RespT> responseListener, Metadata headers) {
285
286 ClientCall.Listener<RespT> listener = new ForwardingClientCallListener<RespT>() {
287 @Override
288 protected Listener<RespT> delegate() {
289 return responseListener;
290 }
291
292 @Override
293 public void onMessage(RespT message) {
Andrea Campanellaa74bdba2018-05-15 16:45:00 +0200294 if (enableMessageLog) {
295 log.info("*** RECEIVED GRPC MESSAGE [{}]\n{}:\n{}",
Carmelo Cascone6d57f322018-12-13 23:15:17 -0800296 channelId, methodDescriptor.getFullMethodName(),
297 message.toString());
Andrea Campanellaa74bdba2018-05-15 16:45:00 +0200298 }
Carmelo Cascone8d99b172017-07-18 17:26:31 -0400299 super.onMessage(message);
300 }
301 };
302 super.start(listener, headers);
303 }
304 };
305 }
306 }
Andrea Campanella378e21a2017-06-07 12:09:59 +0200307}