blob: 45c1a4c8ebc5140310a8c1fb492daaebe2df10d7 [file] [log] [blame]
Jin Gan79f75372017-01-05 15:08:11 -08001/*
2 * Copyright 2016-present Open Networking Laboratory
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 */
16package org.onosproject.restconf.restconfmanager;
17
18import com.fasterxml.jackson.databind.node.ObjectNode;
19import com.google.common.util.concurrent.ThreadFactoryBuilder;
20import org.apache.felix.scr.annotations.Activate;
21import org.apache.felix.scr.annotations.Component;
22import org.apache.felix.scr.annotations.Deactivate;
23import org.apache.felix.scr.annotations.Service;
24import org.glassfish.jersey.server.ChunkedOutput;
25import org.onosproject.event.ListenerTracker;
26import org.onosproject.restconf.api.RestconfException;
27import org.onosproject.restconf.api.RestconfService;
28import org.slf4j.Logger;
29import org.slf4j.LoggerFactory;
30
31import java.io.IOException;
32import java.util.concurrent.BlockingQueue;
33import java.util.concurrent.ConcurrentHashMap;
34import java.util.concurrent.ConcurrentMap;
35import java.util.concurrent.ExecutorService;
36import java.util.concurrent.Executors;
37import java.util.concurrent.LinkedBlockingQueue;
38import java.util.concurrent.ThreadPoolExecutor;
39
40import static java.util.concurrent.TimeUnit.SECONDS;
41import static javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR;
42
43/*
44 * Skeletal ONOS RESTCONF Server application. The RESTCONF Manager
45 * implements the main logic of the RESTCONF Server.
46 *
47 * The design of the RESTCONF subsystem contains 2 major bundles:
48 *
49 * 1. RESTCONF Protocol Proxy (RPP). This bundle is implemented as a
50 * JAX-RS application. It acts as the frond-end of the RESTCONF server.
51 * It intercepts/handles HTTP requests that are sent to the RESTCONF
52 * Root Path. It then calls the RESTCONF Manager to process the requests.
53 *
54 * 2. RESTCONF Manager. This bundle module is the back-end of the server.
55 * It provides the main logic of the RESTCONF server. It interacts with
56 * the YMS (YANG Management System) to run operations on the YANG data
57 * objects (i.e., data resources).
58 */
59
60/**
61 * Implementation of the RestconfService interface. The class is designed
62 * as a Apache Flex component. Note that to avoid unnecessary
63 * activation, the @Component annotation's immediate parameter is set to false.
64 * So the component is not activated until a RESTCONF request is received by
65 * the RESTCONF Protocol Proxy (RPP) module, which consumes the service.
66 */
67@Component(immediate = false)
68@Service
69public class RestconfManager implements RestconfService {
70
71 private static final String RESTCONF_ROOT = "/onos/restconf";
72 private static final int THREAD_TERMINATION_TIMEOUT = 10;
73
74 // Jersey's default chunk parser uses "\r\n" as the chunk separator.
75 private static final String EOL = "\r\n";
76
77 private final int maxNumOfWorkerThreads = 5;
78
79 private final Logger log = LoggerFactory.getLogger(getClass());
80
81 private ListenerTracker listeners;
82
83 private ConcurrentMap<String, BlockingQueue<ObjectNode>> eventQueueList =
84 new ConcurrentHashMap<>();
85
86 private ExecutorService workerThreadPool;
87
88 @Activate
89 protected void activate() {
90 workerThreadPool = Executors
91 .newFixedThreadPool(maxNumOfWorkerThreads,
92 new ThreadFactoryBuilder()
93 .setNameFormat("restconf-worker")
94 .build());
95 log.info("Started");
96 }
97
98 @Deactivate
99 protected void deactivate() {
100 shutdownAndAwaitTermination(workerThreadPool);
101 log.info("Stopped");
102 }
103
104 @Override
105 public ObjectNode runGetOperationOnDataResource(String uri)
106 throws RestconfException {
107
108 return null;
109 }
110
111 @Override
112 public void runPostOperationOnDataResource(String uri, ObjectNode rootNode)
113 throws RestconfException {
114 }
115
116 @Override
117 public void runPutOperationOnDataResource(String uri, ObjectNode rootNode)
118 throws RestconfException {
119 }
120
121 @Override
122 public void runDeleteOperationOnDataResource(String uri)
123 throws RestconfException {
124 }
125
126 @Override
127 public void runPatchOperationOnDataResource(String uri, ObjectNode rootNode)
128 throws RestconfException {
129 }
130
131 @Override
132 public String getRestconfRootPath() {
133 return RESTCONF_ROOT;
134 }
135
136 /**
137 * Creates a worker thread to listen to events and write to chunkedOutput.
138 * The worker thread blocks if no events arrive.
139 *
140 * @param streamId the RESTCONF stream id to which the client subscribes
141 * @param output the string data stream
142 * @throws RestconfException if the worker thread fails to create
143 */
144 @Override
145 public void subscribeEventStream(String streamId,
146 ChunkedOutput<String> output)
147 throws RestconfException {
148 if (workerThreadPool instanceof ThreadPoolExecutor) {
149 if (((ThreadPoolExecutor) workerThreadPool).getActiveCount() >=
150 maxNumOfWorkerThreads) {
151 throw new RestconfException("no more work threads left to " +
152 "handle event subscription",
153 INTERNAL_SERVER_ERROR);
154 }
155 } else {
156 throw new RestconfException("Server ERROR: workerThreadPool NOT " +
157 "instanceof ThreadPoolExecutor",
158 INTERNAL_SERVER_ERROR);
159
160 }
161
162 BlockingQueue<ObjectNode> eventQueue = new LinkedBlockingQueue<>();
163 workerThreadPool.submit(new EventConsumer(output, eventQueue));
164 }
165
166 /**
167 * Shutdown a pool cleanly if possible.
168 *
169 * @param pool an executorService
170 */
171 private void shutdownAndAwaitTermination(ExecutorService pool) {
172 pool.shutdown(); // Disable new tasks from being submitted
173 try {
174 // Wait a while for existing tasks to terminate
175 if (!pool.awaitTermination(THREAD_TERMINATION_TIMEOUT, SECONDS)) {
176 pool.shutdownNow(); // Cancel currently executing tasks
177 // Wait a while for tasks to respond to being cancelled
178 if (!pool.awaitTermination(THREAD_TERMINATION_TIMEOUT,
179 SECONDS)) {
180 log.error("Pool did not terminate");
181 }
182 }
183 } catch (Exception ie) {
184 // (Re-)Cancel if current thread also interrupted
185 pool.shutdownNow();
186 // Preserve interrupt status
187 Thread.currentThread().interrupt();
188 }
189 }
190
191 /**
192 * Implementation of a worker thread which reads data from a
193 * blocking queue and writes the data to a given chunk output stream.
194 * The thread is blocked when no data arrive to the queue and is
195 * terminated when the chunk output stream is closed (i.e., the
196 * HTTP-keep-alive session is closed).
197 */
198 private class EventConsumer implements Runnable {
199
200 private String queueId;
201 private final ChunkedOutput<String> output;
202 private final BlockingQueue<ObjectNode> bqueue;
203
204 public EventConsumer(ChunkedOutput<String> output,
205 BlockingQueue<ObjectNode> q) {
206 this.output = output;
207 this.bqueue = q;
208 }
209
210 @Override
211 public void run() {
212 try {
213 queueId = String.valueOf(Thread.currentThread().getId());
214 eventQueueList.put(queueId, bqueue);
215 log.debug("EventConsumer thread created: {}", queueId);
216
217 ObjectNode chunk;
218 while ((chunk = bqueue.take()) != null) {
219 output.write(chunk.toString().concat(EOL));
220 }
221 } catch (IOException e) {
222 log.debug("chunkedOuput is closed: {}", this.bqueue.toString());
223 /*
224 * Remove queue from the queue list, so that the event producer
225 * (i.e., listener) would stop working.
226 */
227 eventQueueList.remove(this.queueId);
228 } catch (InterruptedException e) {
229 log.error("ERROR: EventConsumer: bqueue.take() " +
230 "has been interrupted.");
231 log.debug("EventConsumer Exception:", e);
232 } finally {
233 try {
234 output.close();
235 log.debug("EventConsumer thread terminated: {}", queueId);
236 } catch (IOException e) {
237 log.error("ERROR: EventConsumer: ", e);
238 }
239 }
240 }
241 }
242}