blob: 73044fb8e863363cc73eb2a5decee15eccfdbc2c [file] [log] [blame]
Jin Gan79f75372017-01-05 15:08:11 -08001/*
jingan7c5bf1f2017-02-09 02:58:09 -08002 * Copyright 2017-present Open Networking Laboratory
Jin Gan79f75372017-01-05 15:08:11 -08003 *
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 */
jingan7c5bf1f2017-02-09 02:58:09 -080016
Jin Gan79f75372017-01-05 15:08:11 -080017package org.onosproject.restconf.restconfmanager;
18
19import com.fasterxml.jackson.databind.node.ObjectNode;
20import com.google.common.util.concurrent.ThreadFactoryBuilder;
21import org.apache.felix.scr.annotations.Activate;
22import org.apache.felix.scr.annotations.Component;
23import org.apache.felix.scr.annotations.Deactivate;
jingan7c5bf1f2017-02-09 02:58:09 -080024import org.apache.felix.scr.annotations.Reference;
25import org.apache.felix.scr.annotations.ReferenceCardinality;
Jin Gan79f75372017-01-05 15:08:11 -080026import org.apache.felix.scr.annotations.Service;
27import org.glassfish.jersey.server.ChunkedOutput;
Henry Yu14af7782017-03-09 19:33:36 -050028import org.onosproject.config.DynamicConfigService;
29import org.onosproject.config.FailedException;
30import org.onosproject.config.Filter;
31import org.onosproject.restconf.api.RestconfException;
32import org.onosproject.restconf.api.RestconfService;
33import org.onosproject.yang.model.DataNode;
34import org.onosproject.yang.model.ResourceData;
35import org.onosproject.yang.model.ResourceId;
Jin Gan79f75372017-01-05 15:08:11 -080036import org.slf4j.Logger;
37import org.slf4j.LoggerFactory;
38
39import java.io.IOException;
jingan7c5bf1f2017-02-09 02:58:09 -080040import java.util.List;
Jin Gan79f75372017-01-05 15:08:11 -080041import java.util.concurrent.BlockingQueue;
42import java.util.concurrent.ConcurrentHashMap;
43import java.util.concurrent.ConcurrentMap;
44import java.util.concurrent.ExecutorService;
45import java.util.concurrent.Executors;
46import java.util.concurrent.LinkedBlockingQueue;
47import java.util.concurrent.ThreadPoolExecutor;
Henry Yu14af7782017-03-09 19:33:36 -050048
Jin Gan79f75372017-01-05 15:08:11 -080049import static java.util.concurrent.TimeUnit.SECONDS;
50import static javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR;
jingan7c5bf1f2017-02-09 02:58:09 -080051import static org.onosproject.restconf.utils.RestconfUtils.convertDataNodeToJson;
Henry Yu14af7782017-03-09 19:33:36 -050052import static org.onosproject.restconf.utils.RestconfUtils.convertJsonToDataNode;
53import static org.onosproject.restconf.utils.RestconfUtils.convertUriToRid;
jingan7c5bf1f2017-02-09 02:58:09 -080054
Jin Gan79f75372017-01-05 15:08:11 -080055/*
jingan7c5bf1f2017-02-09 02:58:09 -080056 * ONOS RESTCONF application. The RESTCONF Manager
57 * implements the main logic of the RESTCONF application.
Jin Gan79f75372017-01-05 15:08:11 -080058 *
59 * The design of the RESTCONF subsystem contains 2 major bundles:
jingan7c5bf1f2017-02-09 02:58:09 -080060 * This bundle module is the back-end of the server.
Jin Gan79f75372017-01-05 15:08:11 -080061 * It provides the main logic of the RESTCONF server. It interacts with
jingan7c5bf1f2017-02-09 02:58:09 -080062 * the Dynamic Config Service and yang runtime service to run operations
63 * on the YANG data objects (i.e., resource id, yang data node).
Jin Gan79f75372017-01-05 15:08:11 -080064 */
65
66/**
67 * Implementation of the RestconfService interface. The class is designed
68 * as a Apache Flex component. Note that to avoid unnecessary
69 * activation, the @Component annotation's immediate parameter is set to false.
70 * So the component is not activated until a RESTCONF request is received by
71 * the RESTCONF Protocol Proxy (RPP) module, which consumes the service.
72 */
73@Component(immediate = false)
74@Service
75public class RestconfManager implements RestconfService {
76
77 private static final String RESTCONF_ROOT = "/onos/restconf";
78 private static final int THREAD_TERMINATION_TIMEOUT = 10;
79
80 // Jersey's default chunk parser uses "\r\n" as the chunk separator.
81 private static final String EOL = "\r\n";
82
83 private final int maxNumOfWorkerThreads = 5;
84
85 private final Logger log = LoggerFactory.getLogger(getClass());
86
jingan7c5bf1f2017-02-09 02:58:09 -080087 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Henry Yu14af7782017-03-09 19:33:36 -050088 protected DynamicConfigService dynamicConfigService;
Jin Gan79f75372017-01-05 15:08:11 -080089
90 private ConcurrentMap<String, BlockingQueue<ObjectNode>> eventQueueList =
91 new ConcurrentHashMap<>();
92
93 private ExecutorService workerThreadPool;
94
95 @Activate
96 protected void activate() {
97 workerThreadPool = Executors
98 .newFixedThreadPool(maxNumOfWorkerThreads,
99 new ThreadFactoryBuilder()
100 .setNameFormat("restconf-worker")
101 .build());
102 log.info("Started");
103 }
104
105 @Deactivate
106 protected void deactivate() {
107 shutdownAndAwaitTermination(workerThreadPool);
108 log.info("Stopped");
109 }
110
111 @Override
112 public ObjectNode runGetOperationOnDataResource(String uri)
113 throws RestconfException {
jingan7c5bf1f2017-02-09 02:58:09 -0800114 ResourceId rid = convertUriToRid(uri);
115 // TODO: define Filter (if there is any requirement).
116 Filter filter = new Filter();
117 DataNode dataNode;
118 try {
Henry Yu14af7782017-03-09 19:33:36 -0500119 dataNode = dynamicConfigService.readNode(rid, filter);
jingan7c5bf1f2017-02-09 02:58:09 -0800120 } catch (FailedException e) {
121 log.error("ERROR: DynamicConfigService: ", e);
122 throw new RestconfException("ERROR: DynamicConfigService",
123 INTERNAL_SERVER_ERROR);
124 }
125 ObjectNode rootNode = convertDataNodeToJson(rid, dataNode);
126 return rootNode;
Jin Gan79f75372017-01-05 15:08:11 -0800127 }
128
129 @Override
130 public void runPostOperationOnDataResource(String uri, ObjectNode rootNode)
131 throws RestconfException {
jingan7c5bf1f2017-02-09 02:58:09 -0800132 ResourceData resourceData = convertJsonToDataNode(uri, rootNode);
133 ResourceId rid = resourceData.resourceId();
134 List<DataNode> dataNodeList = resourceData.dataNodes();
135 // TODO: Error message needs to be fixed
136 if (dataNodeList.size() > 1) {
137 log.warn("ERROR: There are more than one Data Node can be proceed");
138 }
139 DataNode dataNode = dataNodeList.get(0);
140 try {
Henry Yu14af7782017-03-09 19:33:36 -0500141 dynamicConfigService.createNode(rid, dataNode);
jingan7c5bf1f2017-02-09 02:58:09 -0800142 } catch (FailedException e) {
143 log.error("ERROR: DynamicConfigService: ", e);
144 throw new RestconfException("ERROR: DynamicConfigService",
145 INTERNAL_SERVER_ERROR);
146 }
Jin Gan79f75372017-01-05 15:08:11 -0800147 }
148
149 @Override
150 public void runPutOperationOnDataResource(String uri, ObjectNode rootNode)
151 throws RestconfException {
jingan7c5bf1f2017-02-09 02:58:09 -0800152 runPostOperationOnDataResource(uri, rootNode);
Jin Gan79f75372017-01-05 15:08:11 -0800153 }
154
155 @Override
156 public void runDeleteOperationOnDataResource(String uri)
157 throws RestconfException {
jingan7c5bf1f2017-02-09 02:58:09 -0800158 ResourceId rid = convertUriToRid(uri);
159 try {
Henry Yu14af7782017-03-09 19:33:36 -0500160 dynamicConfigService.deleteNode(rid);
jingan7c5bf1f2017-02-09 02:58:09 -0800161 } catch (FailedException e) {
162 log.error("ERROR: DynamicConfigService: ", e);
163 throw new RestconfException("ERROR: DynamicConfigService",
164 INTERNAL_SERVER_ERROR);
165 }
Jin Gan79f75372017-01-05 15:08:11 -0800166 }
167
168 @Override
169 public void runPatchOperationOnDataResource(String uri, ObjectNode rootNode)
170 throws RestconfException {
171 }
172
173 @Override
174 public String getRestconfRootPath() {
175 return RESTCONF_ROOT;
176 }
177
178 /**
179 * Creates a worker thread to listen to events and write to chunkedOutput.
180 * The worker thread blocks if no events arrive.
181 *
182 * @param streamId the RESTCONF stream id to which the client subscribes
183 * @param output the string data stream
184 * @throws RestconfException if the worker thread fails to create
185 */
186 @Override
187 public void subscribeEventStream(String streamId,
188 ChunkedOutput<String> output)
189 throws RestconfException {
190 if (workerThreadPool instanceof ThreadPoolExecutor) {
191 if (((ThreadPoolExecutor) workerThreadPool).getActiveCount() >=
192 maxNumOfWorkerThreads) {
193 throw new RestconfException("no more work threads left to " +
194 "handle event subscription",
195 INTERNAL_SERVER_ERROR);
196 }
197 } else {
198 throw new RestconfException("Server ERROR: workerThreadPool NOT " +
199 "instanceof ThreadPoolExecutor",
200 INTERNAL_SERVER_ERROR);
201
202 }
203
204 BlockingQueue<ObjectNode> eventQueue = new LinkedBlockingQueue<>();
205 workerThreadPool.submit(new EventConsumer(output, eventQueue));
206 }
207
208 /**
209 * Shutdown a pool cleanly if possible.
210 *
211 * @param pool an executorService
212 */
213 private void shutdownAndAwaitTermination(ExecutorService pool) {
214 pool.shutdown(); // Disable new tasks from being submitted
215 try {
216 // Wait a while for existing tasks to terminate
217 if (!pool.awaitTermination(THREAD_TERMINATION_TIMEOUT, SECONDS)) {
218 pool.shutdownNow(); // Cancel currently executing tasks
219 // Wait a while for tasks to respond to being cancelled
220 if (!pool.awaitTermination(THREAD_TERMINATION_TIMEOUT,
221 SECONDS)) {
222 log.error("Pool did not terminate");
223 }
224 }
225 } catch (Exception ie) {
226 // (Re-)Cancel if current thread also interrupted
227 pool.shutdownNow();
228 // Preserve interrupt status
229 Thread.currentThread().interrupt();
230 }
231 }
232
233 /**
234 * Implementation of a worker thread which reads data from a
235 * blocking queue and writes the data to a given chunk output stream.
236 * The thread is blocked when no data arrive to the queue and is
237 * terminated when the chunk output stream is closed (i.e., the
238 * HTTP-keep-alive session is closed).
239 */
240 private class EventConsumer implements Runnable {
241
242 private String queueId;
243 private final ChunkedOutput<String> output;
244 private final BlockingQueue<ObjectNode> bqueue;
245
246 public EventConsumer(ChunkedOutput<String> output,
247 BlockingQueue<ObjectNode> q) {
248 this.output = output;
249 this.bqueue = q;
250 }
251
252 @Override
253 public void run() {
254 try {
255 queueId = String.valueOf(Thread.currentThread().getId());
256 eventQueueList.put(queueId, bqueue);
257 log.debug("EventConsumer thread created: {}", queueId);
258
259 ObjectNode chunk;
260 while ((chunk = bqueue.take()) != null) {
261 output.write(chunk.toString().concat(EOL));
262 }
263 } catch (IOException e) {
264 log.debug("chunkedOuput is closed: {}", this.bqueue.toString());
265 /*
266 * Remove queue from the queue list, so that the event producer
267 * (i.e., listener) would stop working.
268 */
269 eventQueueList.remove(this.queueId);
270 } catch (InterruptedException e) {
271 log.error("ERROR: EventConsumer: bqueue.take() " +
272 "has been interrupted.");
273 log.debug("EventConsumer Exception:", e);
274 } finally {
275 try {
276 output.close();
277 log.debug("EventConsumer thread terminated: {}", queueId);
278 } catch (IOException e) {
279 log.error("ERROR: EventConsumer: ", e);
280 }
281 }
282 }
283 }
284}