Jin Gan | 79f7537 | 2017-01-05 15:08:11 -0800 | [diff] [blame] | 1 | /* |
jingan | 7c5bf1f | 2017-02-09 02:58:09 -0800 | [diff] [blame] | 2 | * Copyright 2017-present Open Networking Laboratory |
Jin Gan | 79f7537 | 2017-01-05 15:08:11 -0800 | [diff] [blame] | 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 | */ |
jingan | 7c5bf1f | 2017-02-09 02:58:09 -0800 | [diff] [blame] | 16 | |
Jin Gan | 79f7537 | 2017-01-05 15:08:11 -0800 | [diff] [blame] | 17 | package org.onosproject.restconf.restconfmanager; |
| 18 | |
| 19 | import com.fasterxml.jackson.databind.node.ObjectNode; |
| 20 | import com.google.common.util.concurrent.ThreadFactoryBuilder; |
| 21 | import org.apache.felix.scr.annotations.Activate; |
| 22 | import org.apache.felix.scr.annotations.Component; |
| 23 | import org.apache.felix.scr.annotations.Deactivate; |
jingan | 7c5bf1f | 2017-02-09 02:58:09 -0800 | [diff] [blame] | 24 | import org.apache.felix.scr.annotations.Reference; |
| 25 | import org.apache.felix.scr.annotations.ReferenceCardinality; |
Jin Gan | 79f7537 | 2017-01-05 15:08:11 -0800 | [diff] [blame] | 26 | import org.apache.felix.scr.annotations.Service; |
| 27 | import org.glassfish.jersey.server.ChunkedOutput; |
Henry Yu | 14af778 | 2017-03-09 19:33:36 -0500 | [diff] [blame] | 28 | import org.onosproject.config.DynamicConfigService; |
| 29 | import org.onosproject.config.FailedException; |
| 30 | import org.onosproject.config.Filter; |
| 31 | import org.onosproject.restconf.api.RestconfException; |
| 32 | import org.onosproject.restconf.api.RestconfService; |
| 33 | import org.onosproject.yang.model.DataNode; |
sonugupta-huawei | f0af7aa | 2017-03-17 00:54:52 +0530 | [diff] [blame^] | 34 | import org.onosproject.yang.model.InnerNode; |
| 35 | import org.onosproject.yang.model.KeyLeaf; |
| 36 | import org.onosproject.yang.model.ListKey; |
| 37 | import org.onosproject.yang.model.NodeKey; |
Henry Yu | 14af778 | 2017-03-09 19:33:36 -0500 | [diff] [blame] | 38 | import org.onosproject.yang.model.ResourceData; |
| 39 | import org.onosproject.yang.model.ResourceId; |
sonugupta-huawei | f0af7aa | 2017-03-17 00:54:52 +0530 | [diff] [blame^] | 40 | import org.onosproject.yang.model.SchemaId; |
| 41 | import org.onosproject.yang.runtime.DefaultResourceData; |
Jin Gan | 79f7537 | 2017-01-05 15:08:11 -0800 | [diff] [blame] | 42 | import org.slf4j.Logger; |
| 43 | import org.slf4j.LoggerFactory; |
| 44 | |
| 45 | import java.io.IOException; |
jingan | 7c5bf1f | 2017-02-09 02:58:09 -0800 | [diff] [blame] | 46 | import java.util.List; |
Jin Gan | 79f7537 | 2017-01-05 15:08:11 -0800 | [diff] [blame] | 47 | import java.util.concurrent.BlockingQueue; |
| 48 | import java.util.concurrent.ConcurrentHashMap; |
| 49 | import java.util.concurrent.ConcurrentMap; |
| 50 | import java.util.concurrent.ExecutorService; |
| 51 | import java.util.concurrent.Executors; |
| 52 | import java.util.concurrent.LinkedBlockingQueue; |
| 53 | import java.util.concurrent.ThreadPoolExecutor; |
Henry Yu | 14af778 | 2017-03-09 19:33:36 -0500 | [diff] [blame] | 54 | |
Jin Gan | 79f7537 | 2017-01-05 15:08:11 -0800 | [diff] [blame] | 55 | import static java.util.concurrent.TimeUnit.SECONDS; |
| 56 | import static javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR; |
jingan | 7c5bf1f | 2017-02-09 02:58:09 -0800 | [diff] [blame] | 57 | import static org.onosproject.restconf.utils.RestconfUtils.convertDataNodeToJson; |
Henry Yu | 14af778 | 2017-03-09 19:33:36 -0500 | [diff] [blame] | 58 | import static org.onosproject.restconf.utils.RestconfUtils.convertJsonToDataNode; |
| 59 | import static org.onosproject.restconf.utils.RestconfUtils.convertUriToRid; |
sonugupta-huawei | f0af7aa | 2017-03-17 00:54:52 +0530 | [diff] [blame^] | 60 | import static org.onosproject.yang.model.DataNode.Type.MULTI_INSTANCE_NODE; |
| 61 | import static org.onosproject.yang.model.DataNode.Type.SINGLE_INSTANCE_LEAF_VALUE_NODE; |
| 62 | import static org.onosproject.yang.model.DataNode.Type.SINGLE_INSTANCE_NODE; |
jingan | 7c5bf1f | 2017-02-09 02:58:09 -0800 | [diff] [blame] | 63 | |
Jin Gan | 79f7537 | 2017-01-05 15:08:11 -0800 | [diff] [blame] | 64 | /* |
jingan | 7c5bf1f | 2017-02-09 02:58:09 -0800 | [diff] [blame] | 65 | * ONOS RESTCONF application. The RESTCONF Manager |
| 66 | * implements the main logic of the RESTCONF application. |
Jin Gan | 79f7537 | 2017-01-05 15:08:11 -0800 | [diff] [blame] | 67 | * |
| 68 | * The design of the RESTCONF subsystem contains 2 major bundles: |
jingan | 7c5bf1f | 2017-02-09 02:58:09 -0800 | [diff] [blame] | 69 | * This bundle module is the back-end of the server. |
Jin Gan | 79f7537 | 2017-01-05 15:08:11 -0800 | [diff] [blame] | 70 | * It provides the main logic of the RESTCONF server. It interacts with |
jingan | 7c5bf1f | 2017-02-09 02:58:09 -0800 | [diff] [blame] | 71 | * the Dynamic Config Service and yang runtime service to run operations |
| 72 | * on the YANG data objects (i.e., resource id, yang data node). |
Jin Gan | 79f7537 | 2017-01-05 15:08:11 -0800 | [diff] [blame] | 73 | */ |
| 74 | |
| 75 | /** |
| 76 | * Implementation of the RestconfService interface. The class is designed |
| 77 | * as a Apache Flex component. Note that to avoid unnecessary |
| 78 | * activation, the @Component annotation's immediate parameter is set to false. |
| 79 | * So the component is not activated until a RESTCONF request is received by |
| 80 | * the RESTCONF Protocol Proxy (RPP) module, which consumes the service. |
| 81 | */ |
| 82 | @Component(immediate = false) |
| 83 | @Service |
| 84 | public class RestconfManager implements RestconfService { |
| 85 | |
| 86 | private static final String RESTCONF_ROOT = "/onos/restconf"; |
| 87 | private static final int THREAD_TERMINATION_TIMEOUT = 10; |
| 88 | |
| 89 | // Jersey's default chunk parser uses "\r\n" as the chunk separator. |
| 90 | private static final String EOL = "\r\n"; |
| 91 | |
| 92 | private final int maxNumOfWorkerThreads = 5; |
| 93 | |
| 94 | private final Logger log = LoggerFactory.getLogger(getClass()); |
| 95 | |
jingan | 7c5bf1f | 2017-02-09 02:58:09 -0800 | [diff] [blame] | 96 | @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) |
Henry Yu | 14af778 | 2017-03-09 19:33:36 -0500 | [diff] [blame] | 97 | protected DynamicConfigService dynamicConfigService; |
Jin Gan | 79f7537 | 2017-01-05 15:08:11 -0800 | [diff] [blame] | 98 | |
| 99 | private ConcurrentMap<String, BlockingQueue<ObjectNode>> eventQueueList = |
| 100 | new ConcurrentHashMap<>(); |
| 101 | |
| 102 | private ExecutorService workerThreadPool; |
| 103 | |
| 104 | @Activate |
| 105 | protected void activate() { |
| 106 | workerThreadPool = Executors |
| 107 | .newFixedThreadPool(maxNumOfWorkerThreads, |
| 108 | new ThreadFactoryBuilder() |
| 109 | .setNameFormat("restconf-worker") |
| 110 | .build()); |
| 111 | log.info("Started"); |
| 112 | } |
| 113 | |
| 114 | @Deactivate |
| 115 | protected void deactivate() { |
| 116 | shutdownAndAwaitTermination(workerThreadPool); |
| 117 | log.info("Stopped"); |
| 118 | } |
| 119 | |
| 120 | @Override |
| 121 | public ObjectNode runGetOperationOnDataResource(String uri) |
| 122 | throws RestconfException { |
jingan | 7c5bf1f | 2017-02-09 02:58:09 -0800 | [diff] [blame] | 123 | ResourceId rid = convertUriToRid(uri); |
| 124 | // TODO: define Filter (if there is any requirement). |
| 125 | Filter filter = new Filter(); |
| 126 | DataNode dataNode; |
| 127 | try { |
Henry Yu | 14af778 | 2017-03-09 19:33:36 -0500 | [diff] [blame] | 128 | dataNode = dynamicConfigService.readNode(rid, filter); |
jingan | 7c5bf1f | 2017-02-09 02:58:09 -0800 | [diff] [blame] | 129 | } catch (FailedException e) { |
| 130 | log.error("ERROR: DynamicConfigService: ", e); |
| 131 | throw new RestconfException("ERROR: DynamicConfigService", |
| 132 | INTERNAL_SERVER_ERROR); |
| 133 | } |
| 134 | ObjectNode rootNode = convertDataNodeToJson(rid, dataNode); |
| 135 | return rootNode; |
Jin Gan | 79f7537 | 2017-01-05 15:08:11 -0800 | [diff] [blame] | 136 | } |
| 137 | |
| 138 | @Override |
| 139 | public void runPostOperationOnDataResource(String uri, ObjectNode rootNode) |
| 140 | throws RestconfException { |
sonugupta-huawei | f0af7aa | 2017-03-17 00:54:52 +0530 | [diff] [blame^] | 141 | ResourceData receivedData = convertJsonToDataNode(uri, rootNode); |
| 142 | ResourceData resourceData = getDataForStore(receivedData); |
jingan | 7c5bf1f | 2017-02-09 02:58:09 -0800 | [diff] [blame] | 143 | ResourceId rid = resourceData.resourceId(); |
| 144 | List<DataNode> dataNodeList = resourceData.dataNodes(); |
| 145 | // TODO: Error message needs to be fixed |
| 146 | if (dataNodeList.size() > 1) { |
| 147 | log.warn("ERROR: There are more than one Data Node can be proceed"); |
| 148 | } |
| 149 | DataNode dataNode = dataNodeList.get(0); |
| 150 | try { |
jingan | 364cec3 | 2017-03-10 12:29:11 -0800 | [diff] [blame] | 151 | dynamicConfigService.createNodeRecursive(rid, dataNode); |
jingan | 7c5bf1f | 2017-02-09 02:58:09 -0800 | [diff] [blame] | 152 | } catch (FailedException e) { |
| 153 | log.error("ERROR: DynamicConfigService: ", e); |
| 154 | throw new RestconfException("ERROR: DynamicConfigService", |
| 155 | INTERNAL_SERVER_ERROR); |
| 156 | } |
Jin Gan | 79f7537 | 2017-01-05 15:08:11 -0800 | [diff] [blame] | 157 | } |
| 158 | |
| 159 | @Override |
| 160 | public void runPutOperationOnDataResource(String uri, ObjectNode rootNode) |
| 161 | throws RestconfException { |
jingan | 7c5bf1f | 2017-02-09 02:58:09 -0800 | [diff] [blame] | 162 | runPostOperationOnDataResource(uri, rootNode); |
Jin Gan | 79f7537 | 2017-01-05 15:08:11 -0800 | [diff] [blame] | 163 | } |
| 164 | |
| 165 | @Override |
| 166 | public void runDeleteOperationOnDataResource(String uri) |
| 167 | throws RestconfException { |
jingan | 7c5bf1f | 2017-02-09 02:58:09 -0800 | [diff] [blame] | 168 | ResourceId rid = convertUriToRid(uri); |
| 169 | try { |
jingan | 364cec3 | 2017-03-10 12:29:11 -0800 | [diff] [blame] | 170 | dynamicConfigService.deleteNodeRecursive(rid); |
jingan | 7c5bf1f | 2017-02-09 02:58:09 -0800 | [diff] [blame] | 171 | } catch (FailedException e) { |
| 172 | log.error("ERROR: DynamicConfigService: ", e); |
| 173 | throw new RestconfException("ERROR: DynamicConfigService", |
| 174 | INTERNAL_SERVER_ERROR); |
| 175 | } |
Jin Gan | 79f7537 | 2017-01-05 15:08:11 -0800 | [diff] [blame] | 176 | } |
| 177 | |
| 178 | @Override |
| 179 | public void runPatchOperationOnDataResource(String uri, ObjectNode rootNode) |
| 180 | throws RestconfException { |
| 181 | } |
| 182 | |
| 183 | @Override |
| 184 | public String getRestconfRootPath() { |
| 185 | return RESTCONF_ROOT; |
| 186 | } |
| 187 | |
| 188 | /** |
| 189 | * Creates a worker thread to listen to events and write to chunkedOutput. |
| 190 | * The worker thread blocks if no events arrive. |
| 191 | * |
| 192 | * @param streamId the RESTCONF stream id to which the client subscribes |
| 193 | * @param output the string data stream |
| 194 | * @throws RestconfException if the worker thread fails to create |
| 195 | */ |
| 196 | @Override |
| 197 | public void subscribeEventStream(String streamId, |
| 198 | ChunkedOutput<String> output) |
| 199 | throws RestconfException { |
| 200 | if (workerThreadPool instanceof ThreadPoolExecutor) { |
| 201 | if (((ThreadPoolExecutor) workerThreadPool).getActiveCount() >= |
| 202 | maxNumOfWorkerThreads) { |
| 203 | throw new RestconfException("no more work threads left to " + |
| 204 | "handle event subscription", |
| 205 | INTERNAL_SERVER_ERROR); |
| 206 | } |
| 207 | } else { |
| 208 | throw new RestconfException("Server ERROR: workerThreadPool NOT " + |
| 209 | "instanceof ThreadPoolExecutor", |
| 210 | INTERNAL_SERVER_ERROR); |
Jin Gan | 79f7537 | 2017-01-05 15:08:11 -0800 | [diff] [blame] | 211 | } |
| 212 | |
| 213 | BlockingQueue<ObjectNode> eventQueue = new LinkedBlockingQueue<>(); |
| 214 | workerThreadPool.submit(new EventConsumer(output, eventQueue)); |
| 215 | } |
| 216 | |
sonugupta-huawei | f0af7aa | 2017-03-17 00:54:52 +0530 | [diff] [blame^] | 217 | private ResourceData getDataForStore(ResourceData resourceData) { |
| 218 | List<DataNode> nodes = resourceData.dataNodes(); |
| 219 | ResourceId rid = resourceData.resourceId(); |
| 220 | DataNode.Builder dbr = null; |
| 221 | ResourceId parentId = null; |
| 222 | try { |
| 223 | NodeKey lastKey = rid.nodeKeys().get(rid.nodeKeys().size() - 1); |
| 224 | SchemaId sid = lastKey.schemaId(); |
| 225 | if (lastKey instanceof ListKey) { |
| 226 | dbr = InnerNode.builder( |
| 227 | sid.name(), sid.namespace()).type(MULTI_INSTANCE_NODE); |
| 228 | for (KeyLeaf keyLeaf : ((ListKey) lastKey).keyLeafs()) { |
| 229 | Object val = keyLeaf.leafValue(); |
| 230 | dbr = dbr.addKeyLeaf(keyLeaf.leafSchema().name(), |
| 231 | sid.namespace(), val); |
| 232 | dbr = dbr.createChildBuilder(keyLeaf.leafSchema().name(), |
| 233 | sid.namespace(), val) |
| 234 | .type(SINGLE_INSTANCE_LEAF_VALUE_NODE); |
| 235 | } |
| 236 | } else { |
| 237 | dbr = InnerNode.builder( |
| 238 | sid.name(), sid.namespace()).type(SINGLE_INSTANCE_NODE); |
| 239 | } |
| 240 | if (nodes != null && !nodes.isEmpty()) { |
| 241 | // adding the parent node for given list of nodes |
| 242 | for (DataNode node : nodes) { |
| 243 | dbr = ((InnerNode.Builder) dbr).addNode(node); |
| 244 | } |
| 245 | } |
| 246 | parentId = rid.copyBuilder().removeLastKey().build(); |
| 247 | } catch (CloneNotSupportedException e) { |
| 248 | e.printStackTrace(); |
| 249 | } |
| 250 | ResourceData.Builder resData = DefaultResourceData.builder(); |
| 251 | resData.addDataNode(dbr.build()); |
| 252 | resData.resourceId(parentId); |
| 253 | return resData.build(); |
| 254 | } |
| 255 | |
Jin Gan | 79f7537 | 2017-01-05 15:08:11 -0800 | [diff] [blame] | 256 | /** |
| 257 | * Shutdown a pool cleanly if possible. |
| 258 | * |
| 259 | * @param pool an executorService |
| 260 | */ |
| 261 | private void shutdownAndAwaitTermination(ExecutorService pool) { |
| 262 | pool.shutdown(); // Disable new tasks from being submitted |
| 263 | try { |
| 264 | // Wait a while for existing tasks to terminate |
| 265 | if (!pool.awaitTermination(THREAD_TERMINATION_TIMEOUT, SECONDS)) { |
| 266 | pool.shutdownNow(); // Cancel currently executing tasks |
| 267 | // Wait a while for tasks to respond to being cancelled |
| 268 | if (!pool.awaitTermination(THREAD_TERMINATION_TIMEOUT, |
| 269 | SECONDS)) { |
| 270 | log.error("Pool did not terminate"); |
| 271 | } |
| 272 | } |
| 273 | } catch (Exception ie) { |
| 274 | // (Re-)Cancel if current thread also interrupted |
| 275 | pool.shutdownNow(); |
| 276 | // Preserve interrupt status |
| 277 | Thread.currentThread().interrupt(); |
| 278 | } |
| 279 | } |
| 280 | |
| 281 | /** |
| 282 | * Implementation of a worker thread which reads data from a |
| 283 | * blocking queue and writes the data to a given chunk output stream. |
| 284 | * The thread is blocked when no data arrive to the queue and is |
| 285 | * terminated when the chunk output stream is closed (i.e., the |
| 286 | * HTTP-keep-alive session is closed). |
| 287 | */ |
| 288 | private class EventConsumer implements Runnable { |
| 289 | |
| 290 | private String queueId; |
| 291 | private final ChunkedOutput<String> output; |
| 292 | private final BlockingQueue<ObjectNode> bqueue; |
| 293 | |
| 294 | public EventConsumer(ChunkedOutput<String> output, |
| 295 | BlockingQueue<ObjectNode> q) { |
| 296 | this.output = output; |
| 297 | this.bqueue = q; |
| 298 | } |
| 299 | |
| 300 | @Override |
| 301 | public void run() { |
| 302 | try { |
| 303 | queueId = String.valueOf(Thread.currentThread().getId()); |
| 304 | eventQueueList.put(queueId, bqueue); |
| 305 | log.debug("EventConsumer thread created: {}", queueId); |
| 306 | |
| 307 | ObjectNode chunk; |
| 308 | while ((chunk = bqueue.take()) != null) { |
| 309 | output.write(chunk.toString().concat(EOL)); |
| 310 | } |
| 311 | } catch (IOException e) { |
| 312 | log.debug("chunkedOuput is closed: {}", this.bqueue.toString()); |
| 313 | /* |
| 314 | * Remove queue from the queue list, so that the event producer |
| 315 | * (i.e., listener) would stop working. |
| 316 | */ |
| 317 | eventQueueList.remove(this.queueId); |
| 318 | } catch (InterruptedException e) { |
| 319 | log.error("ERROR: EventConsumer: bqueue.take() " + |
| 320 | "has been interrupted."); |
| 321 | log.debug("EventConsumer Exception:", e); |
| 322 | } finally { |
| 323 | try { |
| 324 | output.close(); |
| 325 | log.debug("EventConsumer thread terminated: {}", queueId); |
| 326 | } catch (IOException e) { |
| 327 | log.error("ERROR: EventConsumer: ", e); |
| 328 | } |
| 329 | } |
| 330 | } |
| 331 | } |
| 332 | } |