blob: 2304f0e5c6cbd715a4a230ded78fd1d0092948de [file] [log] [blame]
Aaron Kruglikovae7e3b82017-05-03 14:13:53 -07001/*
2 * Copyright 2017-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.protobuf.registry;
18
19import com.google.common.collect.Maps;
20import io.grpc.BindableService;
21import io.grpc.Server;
22import io.grpc.ServerBuilder;
23import org.apache.felix.scr.annotations.Activate;
24import org.apache.felix.scr.annotations.Component;
25import org.apache.felix.scr.annotations.Deactivate;
26import org.apache.felix.scr.annotations.Modified;
27import org.apache.felix.scr.annotations.Property;
28import org.apache.felix.scr.annotations.Service;
29import org.onosproject.protobuf.api.GrpcServiceRegistry;
30import org.osgi.service.component.ComponentContext;
31import org.slf4j.Logger;
32import org.slf4j.LoggerFactory;
33
34import java.io.IOException;
35import java.util.Dictionary;
36import java.util.Map;
37import java.util.concurrent.TimeUnit;
38
39import static org.onlab.util.Tools.get;
40
41/**
42 * A basic implementation of {@link GrpcServiceRegistry} designed for use with
43 * built in gRPC services.
44 *
45 * NOTE: this is an early implementation in which the addition of any new
46 * service forces a restart of the server, this is sufficient for testing but
47 * inappropriate for deployment.
48 */
49@Service
50@Component(immediate = false)
51public class GrpcServiceRegistryImpl implements GrpcServiceRegistry {
52
53 private static final int DEFAULT_SERVER_PORT = 64000;
54 private static final int DEFAULT_SHUTDOWN_TIME = 1;
55
56 private static final String PORT_PROPERTY_NAME = "listeningPort";
57
58 private final Map<Class<? extends BindableService>, BindableService> registeredServices =
59 Maps.newHashMap();
60 private final Logger log = LoggerFactory.getLogger(getClass());
61
62 private Server server;
63
64 /* It is currently the responsibility of the administrator to notify
65 clients of nonstandard port usage as there is no mechanism available to
66 discover the port hosting gRPC services.
67 */
68 @Property(name = PORT_PROPERTY_NAME, intValue = DEFAULT_SERVER_PORT,
69 label = "The port number which ONOS will use to host gRPC services.")
70 private int listeningPort = DEFAULT_SERVER_PORT;
71
72 @Activate
73 public void activate() {
74 log.info("Started");
75 }
76
77 @Deactivate
78 public void deactivate() {
79 attemptGracefulShutdownThenForce(DEFAULT_SHUTDOWN_TIME);
80 log.info("Stopped");
81 }
82
83 @Modified
84 public void modified(ComponentContext context) {
85 if (context != null) {
86 setProperties(context);
87 }
88 log.info("Connection was restarted to allow service to be added, " +
89 "this is a temporary workaround");
90 restartServer(listeningPort);
91 }
92
93 @Override
94 public boolean register(BindableService service) {
95 synchronized (registeredServices) {
96 if (!registeredServices.containsKey(service.getClass())) {
97 registeredServices.put(service.getClass(), service);
98 } else {
99 log.warn("The specified class \"{}\" was not added becuase an " +
100 "instance of the class is already registered.",
101 service.getClass().toString());
102 return false;
103 }
104 }
105 return restartServer(listeningPort);
106 }
107
108 @Override
109 public boolean unregister(BindableService service) {
110 synchronized (registeredServices) {
111 if (registeredServices.containsKey(service.getClass())) {
112 registeredServices.remove(service.getClass());
113 } else {
114 log.warn("The specified class \"{}\" was not removed because it " +
115 "was not present.", service.getClass().toString());
116 return false;
117 }
118 }
119 return restartServer(listeningPort);
120 }
121
122 @Override
123 public boolean containsService(Class<BindableService> serviceClass) {
124 return registeredServices.containsKey(serviceClass);
125 }
126
127 private void setProperties(ComponentContext context) {
128 Dictionary<String, Object> properties = context.getProperties();
129 String listeningPort = get(properties, PORT_PROPERTY_NAME);
130 this.listeningPort = listeningPort == null ? DEFAULT_SERVER_PORT :
131 Integer.parseInt(listeningPort.trim());
132 }
133
134 /**
135 * Attempts a graceful shutdown allowing {@code timeLimitSeconds} to elapse
136 * before forcing a shutdown.
137 *
138 * @param timeLimitSeconds time before a shutdown is forced in seconds
139 * @return true if the server is terminated, false otherwise
140 */
141 private boolean attemptGracefulShutdownThenForce(int timeLimitSeconds) {
142 if (!server.isShutdown()) {
143 server.shutdown();
144 }
145 try {
146 /*This is not conditional in case the server is shutdown but
147 handling requests submitted before shutdown was called.*/
148 server.awaitTermination(timeLimitSeconds, TimeUnit.SECONDS);
149 } catch (InterruptedException e) {
150 log.error("Awaiting server termination failed with error {}",
151 e.getMessage());
152 }
153 if (!server.isTerminated()) {
154 server.shutdownNow();
155 try {
156 server.awaitTermination(10, TimeUnit.MILLISECONDS);
157 } catch (InterruptedException e) {
158 log.error("Server failed to terminate as expected with error" +
159 " {}", e.getMessage());
160 }
161 }
162 return server.isTerminated();
163 }
164
165 private boolean restartServer(int port) {
166 if (!attemptGracefulShutdownThenForce(DEFAULT_SHUTDOWN_TIME)) {
167 log.error("Shutdown failed, the previous server may still be" +
168 " active.");
169 }
170 return createServerAndStart(port);
171 }
172
173 /**
174 * Creates a server with the set of registered services on the specified
175 * port.
176 *
177 * @param port the port on which this server will listen
178 * @return true if the server was started successfully, false otherwise
179 */
180 private boolean createServerAndStart(int port) {
181
182 ServerBuilder serverBuilder =
183 ServerBuilder.forPort(port);
184 synchronized (registeredServices) {
185 registeredServices.values().forEach(
186 service -> serverBuilder.addService(service));
187 }
188 server = serverBuilder.build();
189 try {
190 server.start();
191 } catch (IllegalStateException e) {
192 log.error("The server could not be started because an existing " +
193 "server is already running: {}", e.getMessage());
194 return false;
195 } catch (IOException e) {
196 log.error("The server could not be started due to a failure to " +
197 "bind: {} ", e.getMessage());
198 return false;
199 }
200 return true;
201 }
202}