2 * Copyright (c) 2014, 2015 Brocade Communication Systems, Inc., Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.netconf.sal.restconf.impl;
11 import com.google.common.base.CharMatcher;
12 import com.google.common.base.Optional;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Splitter;
15 import com.google.common.base.Strings;
16 import com.google.common.collect.Iterables;
17 import com.google.common.collect.Lists;
18 import com.google.common.collect.Maps;
19 import com.google.common.collect.Sets;
20 import com.google.common.util.concurrent.CheckedFuture;
21 import com.google.common.util.concurrent.FutureCallback;
22 import com.google.common.util.concurrent.Futures;
24 import java.net.URISyntaxException;
25 import java.text.ParseException;
26 import java.text.SimpleDateFormat;
27 import java.util.ArrayList;
28 import java.util.Collection;
29 import java.util.Collections;
30 import java.util.Date;
31 import java.util.HashMap;
32 import java.util.HashSet;
33 import java.util.Iterator;
34 import java.util.List;
37 import java.util.concurrent.CancellationException;
38 import java.util.concurrent.CountDownLatch;
39 import java.util.concurrent.ExecutionException;
40 import javax.ws.rs.core.Context;
41 import javax.ws.rs.core.Response;
42 import javax.ws.rs.core.Response.ResponseBuilder;
43 import javax.ws.rs.core.Response.Status;
44 import javax.ws.rs.core.UriBuilder;
45 import javax.ws.rs.core.UriInfo;
46 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
47 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
48 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
49 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
50 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
51 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
52 import org.opendaylight.controller.md.sal.dom.api.DOMRpcImplementationNotAvailableException;
53 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
54 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
55 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
56 import org.opendaylight.netconf.md.sal.rest.common.RestconfValidationUtils;
57 import org.opendaylight.netconf.sal.rest.api.Draft02;
58 import org.opendaylight.netconf.sal.rest.api.RestconfService;
59 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
60 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
61 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
62 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
63 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
64 import org.opendaylight.netconf.sal.streams.websockets.WebSocketServer;
65 import org.opendaylight.yangtools.yang.common.QName;
66 import org.opendaylight.yangtools.yang.common.QNameModule;
67 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
68 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
69 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
70 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
71 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
72 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
73 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
74 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
75 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
76 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
77 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
78 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
79 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
80 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
81 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
82 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
83 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
84 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
85 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
86 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
87 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
88 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
90 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
91 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
92 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
93 import org.opendaylight.yangtools.yang.model.api.Module;
94 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
95 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
96 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
97 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
98 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
99 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.EffectiveSchemaContext;
100 import org.slf4j.Logger;
101 import org.slf4j.LoggerFactory;
103 public class RestconfImpl implements RestconfService {
105 private static final RestconfImpl INSTANCE = new RestconfImpl();
108 * Notifications are served on port 8181.
110 private static final int NOTIFICATION_PORT = 8181;
112 private static final int CHAR_NOT_FOUND = -1;
114 private static final SimpleDateFormat REVISION_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
116 private static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
118 private BrokerFacade broker;
120 private ControllerContext controllerContext;
122 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
124 private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
126 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
128 private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
130 private static final String DATASTORE_PARAM_NAME = "datastore";
132 private static final String SCOPE_PARAM_NAME = "scope";
134 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
136 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
138 private static final QName NETCONF_BASE_QNAME;
140 private static final QNameModule SAL_REMOTE_AUGMENT;
142 private static final YangInstanceIdentifier.AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER;
144 public static final CharSequence DATA_SUBSCR = "data-change-event-subscription";
145 private static final CharSequence CREATE_DATA_SUBSCR = "create-" + DATA_SUBSCR;
147 public static final CharSequence NOTIFICATION_STREAM = "notification-stream";
148 private static final CharSequence CREATE_NOTIFICATION_STREAM = "create-" + NOTIFICATION_STREAM;
152 final Date eventSubscriptionAugRevision = new SimpleDateFormat("yyyy-MM-dd").parse("2014-07-08");
153 NETCONF_BASE_QNAME = QName.create(QNameModule.create(new URI(NETCONF_BASE), null), NETCONF_BASE_PAYLOAD_NAME );
154 SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
155 eventSubscriptionAugRevision);
156 SAL_REMOTE_AUG_IDENTIFIER = new YangInstanceIdentifier.AugmentationIdentifier(Sets.newHashSet(QName.create(SAL_REMOTE_AUGMENT, "scope"),
157 QName.create(SAL_REMOTE_AUGMENT, "datastore")));
158 } catch (final ParseException e) {
159 final String errMsg = "It wasn't possible to convert revision date of sal-remote-augment to date";
161 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
162 } catch (final URISyntaxException e) {
163 final String errMsg = "It wasn't possible to create instance of URI class with "+NETCONF_BASE+" URI";
164 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
168 public void setBroker(final BrokerFacade broker) {
169 this.broker = broker;
172 public void setControllerContext(final ControllerContext controllerContext) {
173 this.controllerContext = controllerContext;
176 private RestconfImpl() {
179 public static RestconfImpl getInstance() {
184 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
185 final Set<Module> allModules = this.controllerContext.getAllModules();
186 final MapNode allModuleMap = makeModuleMapNode(allModules);
188 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
190 final Module restconfModule = getRestconfModule();
191 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
192 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
193 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
195 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
196 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
197 moduleContainerBuilder.withChild(allModuleMap);
199 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode,
200 null, schemaContext), moduleContainerBuilder.build(),
201 QueryParametersParser.parseWriterParameters(uriInfo));
205 * Valid only for mount point
208 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
209 Preconditions.checkNotNull(identifier);
210 if ( ! identifier.contains(ControllerContext.MOUNT)) {
211 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
212 + " URI has to end with " + ControllerContext.MOUNT;
213 LOG.debug(errMsg + " for " + identifier);
214 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
217 final InstanceIdentifierContext<?> mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier);
218 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
219 final Set<Module> modules = this.controllerContext.getAllModules(mountPoint);
220 final MapNode mountPointModulesMap = makeModuleMapNode(modules);
222 final Module restconfModule = getRestconfModule();
223 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
224 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
225 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
227 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
228 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
229 moduleContainerBuilder.withChild(mountPointModulesMap);
231 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode,
232 mountPoint, this.controllerContext.getGlobalSchema()), moduleContainerBuilder.build(),
233 QueryParametersParser.parseWriterParameters(uriInfo));
237 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
238 Preconditions.checkNotNull(identifier);
239 final QName moduleNameAndRevision = getModuleNameAndRevision(identifier);
240 Module module = null;
241 DOMMountPoint mountPoint = null;
242 final SchemaContext schemaContext;
243 if (identifier.contains(ControllerContext.MOUNT)) {
244 final InstanceIdentifierContext<?> mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier);
245 mountPoint = mountPointIdentifier.getMountPoint();
246 module = this.controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision);
247 schemaContext = mountPoint.getSchemaContext();
249 module = this.controllerContext.findModuleByNameAndRevision(moduleNameAndRevision);
250 schemaContext = this.controllerContext.getGlobalSchema();
253 if (module == null) {
254 final String errMsg = "Module with name '" + moduleNameAndRevision.getLocalName()
255 + "' and revision '" + moduleNameAndRevision.getRevision() + "' was not found.";
257 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
260 final Module restconfModule = getRestconfModule();
261 final Set<Module> modules = Collections.singleton(module);
262 final MapNode moduleMap = makeModuleMapNode(modules);
264 final DataSchemaNode moduleSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
265 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
266 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
268 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint,
269 schemaContext), moduleMap, QueryParametersParser.parseWriterParameters(uriInfo));
273 public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
274 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
275 final Set<String> availableStreams = Notificator.getStreamNames();
276 final Module restconfModule = getRestconfModule();
277 final DataSchemaNode streamSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
278 Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
279 Preconditions.checkState(streamSchemaNode instanceof ListSchemaNode);
281 final CollectionNodeBuilder<MapEntryNode, MapNode> listStreamsBuilder = Builders
282 .mapBuilder((ListSchemaNode) streamSchemaNode);
284 for (final String streamName : availableStreams) {
285 listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
288 final DataSchemaNode streamsContainerSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
289 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
290 Preconditions.checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
292 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
293 Builders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
294 streamsContainerBuilder.withChild(listStreamsBuilder.build());
297 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null,
298 schemaContext), streamsContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
302 public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
303 final Set<Module> allModules = this.controllerContext.getAllModules();
304 return operationsFromModulesToNormalizedContext(allModules, null);
308 public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
309 Set<Module> modules = null;
310 DOMMountPoint mountPoint = null;
311 if (identifier.contains(ControllerContext.MOUNT)) {
312 final InstanceIdentifierContext<?> mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier);
313 mountPoint = mountPointIdentifier.getMountPoint();
314 modules = this.controllerContext.getAllModules(mountPoint);
317 final String errMsg = "URI has bad format. If operations behind mount point should be showed, URI has to end with ";
318 LOG.debug(errMsg + ControllerContext.MOUNT + " for " + identifier);
319 throw new RestconfDocumentedException(errMsg + ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
322 return operationsFromModulesToNormalizedContext(modules, mountPoint);
326 * Special case only for GET restconf/operations use (since moment of pre-Beryllium
327 * Yang parser and Yang model API removal). The method is creating fake
328 * schema context with fake module and fake data by use own implementations
329 * of schema nodes and module.
332 * - set of modules for get RPCs from every module
334 * - mount point, if in use otherwise null
335 * @return {@link NormalizedNodeContext}
337 private NormalizedNodeContext operationsFromModulesToNormalizedContext(final Set<Module> modules,
338 final DOMMountPoint mountPoint) {
340 final ContainerSchemaNodeImpl fakeCont = new ContainerSchemaNodeImpl();
341 final List<LeafNode<Object>> listRpcNodes = new ArrayList<>();
342 for (final Module m : modules) {
343 for (final RpcDefinition rpc : m.getRpcs()) {
345 final LeafSchemaNode fakeLeaf = new LeafSchemaNodeImpl(fakeCont.getPath(),
346 QName.create(ModuleImpl.moduleQName, m.getName() + ":" + rpc.getQName().getLocalName()));
347 fakeCont.addNodeChild(fakeLeaf);
348 listRpcNodes.add(Builders.leafBuilder(fakeLeaf).build());
351 final ContainerSchemaNode fakeContSchNode = fakeCont;
352 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> containerBuilder = Builders
353 .containerBuilder(fakeContSchNode);
355 for (final LeafNode<Object> rpcNode : listRpcNodes) {
356 containerBuilder.withChild(rpcNode);
359 final Module fakeModule = new ModuleImpl(fakeContSchNode);
361 final Set<Module> fakeModules = new HashSet<>();
362 fakeModules.add(fakeModule);
363 final SchemaContext fakeSchemaCtx = EffectiveSchemaContext.resolveSchemaContext(fakeModules);
364 final InstanceIdentifierContext<ContainerSchemaNode> instanceIdentifierContext = new InstanceIdentifierContext<>(
365 null, fakeContSchNode, mountPoint, fakeSchemaCtx);
366 return new NormalizedNodeContext(instanceIdentifierContext, containerBuilder.build());
369 private Module getRestconfModule() {
370 final Module restconfModule = this.controllerContext.getRestconfModule();
371 if (restconfModule == null) {
372 LOG.debug("ietf-restconf module was not found.");
373 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
374 ErrorTag.OPERATION_NOT_SUPPORTED);
377 return restconfModule;
380 private static QName getModuleNameAndRevision(final String identifier) {
381 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
382 String moduleNameAndRevision = "";
383 if (mountIndex >= 0) {
384 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
386 moduleNameAndRevision = identifier;
389 final Splitter splitter = Splitter.on("/").omitEmptyStrings();
390 final Iterable<String> split = splitter.split(moduleNameAndRevision);
391 final List<String> pathArgs = Lists.<String> newArrayList(split);
392 if (pathArgs.size() < 2) {
393 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
394 throw new RestconfDocumentedException(
395 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
396 ErrorTag.INVALID_VALUE);
400 final String moduleName = pathArgs.get(0);
401 final String revision = pathArgs.get(1);
402 final Date moduleRevision = REVISION_FORMAT.parse(revision);
403 return QName.create(null, moduleRevision, moduleName);
404 } catch (final ParseException e) {
405 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
406 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
407 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
412 public Object getRoot() {
417 public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
418 final SchemaPath type = payload.getInstanceIdentifierContext().getSchemaNode().getPath();
419 final URI namespace = payload.getInstanceIdentifierContext().getSchemaNode().getQName().getNamespace();
420 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
421 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
422 final SchemaContext schemaContext;
423 if (mountPoint != null) {
424 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
425 if ( ! mountRpcServices.isPresent()) {
426 LOG.debug("Error: Rpc service is missing.");
427 throw new RestconfDocumentedException("Rpc service is missing.");
429 schemaContext = mountPoint.getSchemaContext();
430 response = mountRpcServices.get().invokeRpc(type, payload.getData());
432 if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
433 if (identifier.contains(CREATE_DATA_SUBSCR)) {
434 response = invokeSalRemoteRpcSubscribeRPC(payload);
435 } else if (identifier.contains(CREATE_NOTIFICATION_STREAM)) {
436 response = invokeSalRemoteRpcNotifiStrRPC(payload);
438 final String msg = "Not supported operation";
440 throw new RestconfDocumentedException(msg, ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED);
443 response = this.broker.invokeRpc(type, payload.getData());
445 schemaContext = this.controllerContext.getGlobalSchema();
448 final DOMRpcResult result = checkRpcResponse(response);
450 RpcDefinition resultNodeSchema = null;
451 final NormalizedNode<?, ?> resultData = result.getResult();
452 if ((result != null) && (result.getResult() != null)) {
453 resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
456 return new NormalizedNodeContext(new InstanceIdentifierContext<RpcDefinition>(null,
457 resultNodeSchema, mountPoint, schemaContext), resultData,
458 QueryParametersParser.parseWriterParameters(uriInfo));
461 private static DOMRpcResult checkRpcResponse(final CheckedFuture<DOMRpcResult, DOMRpcException> response) {
462 if (response == null) {
466 final DOMRpcResult retValue = response.get();
467 if ((retValue.getErrors() == null) || retValue.getErrors().isEmpty()) {
470 LOG.debug("RpcError message", retValue.getErrors());
471 throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
472 } catch (final InterruptedException e) {
473 final String errMsg = "The operation was interrupted while executing and did not complete.";
474 LOG.debug("Rpc Interrupt - " + errMsg, e);
475 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
476 } catch (final ExecutionException e) {
477 LOG.debug("Execution RpcError: ", e);
478 Throwable cause = e.getCause();
480 while (cause.getCause() != null) {
481 cause = cause.getCause();
484 if (cause instanceof IllegalArgumentException) {
485 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL,
486 ErrorTag.INVALID_VALUE);
487 } else if (cause instanceof DOMRpcImplementationNotAvailableException) {
488 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
490 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",cause);
492 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",e);
494 } catch (final CancellationException e) {
495 final String errMsg = "The operation was cancelled while executing.";
496 LOG.debug("Cancel RpcExecution: " + errMsg, e);
497 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
501 private static void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
502 if ((inputSchema != null) && (payload.getData() == null)) {
503 // expected a non null payload
504 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
505 } else if ((inputSchema == null) && (payload.getData() != null)) {
506 // did not expect any input
507 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
511 private CheckedFuture<DOMRpcResult, DOMRpcException> invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
512 final ContainerNode value = (ContainerNode) payload.getData();
513 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
514 final Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(new NodeIdentifier(
515 QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(), "path")));
516 final Object pathValue = path.isPresent() ? path.get().getValue() : null;
518 if (!(pathValue instanceof YangInstanceIdentifier)) {
519 final String errMsg = "Instance identifier was not normalized correctly ";
520 LOG.debug(errMsg + rpcQName);
521 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
524 final YangInstanceIdentifier pathIdentifier = ((YangInstanceIdentifier) pathValue);
525 String streamName = (String) CREATE_DATA_SUBSCR;
526 if (!pathIdentifier.isEmpty()) {
527 final String fullRestconfIdentifier = DATA_SUBSCR
528 + this.controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
530 LogicalDatastoreType datastore = parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
531 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
533 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
534 scope = scope == null ? DEFAULT_SCOPE : scope;
536 streamName = Notificator.createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore
537 + "/scope=" + scope);
540 if (Strings.isNullOrEmpty(streamName)) {
541 final String errMsg = "Path is empty or contains value node which is not Container or List build-in type.";
542 LOG.debug(errMsg + pathIdentifier);
543 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
546 final QName outputQname = QName.create(rpcQName, "output");
547 final QName streamNameQname = QName.create(rpcQName, "stream-name");
549 final ContainerNode output = ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
550 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
552 if (!Notificator.existListenerFor(streamName)) {
553 Notificator.createListener(pathIdentifier, streamName);
556 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
558 return Futures.immediateCheckedFuture(defaultDOMRpcResult);
562 public NormalizedNodeContext invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
563 if ((noPayload != null) && !CharMatcher.WHITESPACE.matchesAllOf(noPayload)) {
564 throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
567 String identifierEncoded = null;
568 DOMMountPoint mountPoint = null;
569 final SchemaContext schemaContext;
570 if (identifier.contains(ControllerContext.MOUNT)) {
571 // mounted RPC call - look up mount instance.
572 final InstanceIdentifierContext<?> mountPointId = this.controllerContext.toMountPointIdentifier(identifier);
573 mountPoint = mountPointId.getMountPoint();
574 schemaContext = mountPoint.getSchemaContext();
575 final int startOfRemoteRpcName = identifier.lastIndexOf(ControllerContext.MOUNT)
576 + ControllerContext.MOUNT.length() + 1;
577 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
578 identifierEncoded = remoteRpcName;
580 } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
581 final String slashErrorMsg = String.format("Identifier %n%s%ncan\'t contain slash "
582 + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.", identifier);
583 LOG.debug(slashErrorMsg);
584 throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
586 identifierEncoded = identifier;
587 schemaContext = this.controllerContext.getGlobalSchema();
590 final String identifierDecoded = this.controllerContext.urlPathArgDecode(identifierEncoded);
592 RpcDefinition rpc = null;
593 if (mountPoint == null) {
594 rpc = this.controllerContext.getRpcDefinition(identifierDecoded, null);
596 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
600 LOG.debug("RPC " + identifierDecoded + " does not exist.");
601 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
604 if (rpc.getInput() != null) {
605 LOG.debug("RPC " + rpc + " does not need input value.");
606 // FIXME : find a correct Error from specification
607 throw new IllegalStateException("RPC " + rpc + " does'n need input value!");
610 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
611 if (mountPoint != null) {
612 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
613 if ( ! mountRpcServices.isPresent()) {
614 throw new RestconfDocumentedException("Rpc service is missing.");
616 response = mountRpcServices.get().invokeRpc(rpc.getPath(), null);
618 response = this.broker.invokeRpc(rpc.getPath(), null);
621 final DOMRpcResult result = checkRpcResponse(response);
623 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpc, mountPoint, schemaContext),
624 result.getResult(), QueryParametersParser.parseWriterParameters(uriInfo));
627 private static RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
628 final String[] splittedIdentifier = identifierDecoded.split(":");
629 if (splittedIdentifier.length != 2) {
630 final String errMsg = identifierDecoded + " couldn't be splitted to 2 parts (module:rpc name)";
632 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
634 for (final Module module : schemaContext.getModules()) {
635 if (module.getName().equals(splittedIdentifier[0])) {
636 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
637 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
638 return rpcDefinition;
647 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
648 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
649 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
650 NormalizedNode<?, ?> data = null;
651 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
652 if (mountPoint != null) {
653 data = this.broker.readConfigurationData(mountPoint, normalizedII);
655 data = this.broker.readConfigurationData(normalizedII);
658 final String errMsg = "Request could not be completed because the relevant data model content does not exist ";
659 LOG.debug(errMsg + identifier);
660 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
662 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
666 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
667 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
668 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
669 NormalizedNode<?, ?> data = null;
670 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
671 if (mountPoint != null) {
672 data = this.broker.readOperationalData(mountPoint, normalizedII);
674 data = this.broker.readOperationalData(normalizedII);
677 final String errMsg = "Request could not be completed because the relevant data model content does not exist ";
678 LOG.debug(errMsg + identifier);
679 throw new RestconfDocumentedException(errMsg , ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
681 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
685 public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload) {
686 Preconditions.checkNotNull(identifier);
687 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
689 validateInput(iiWithData.getSchemaNode(), payload);
690 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
691 validateListKeysEqualityInPayloadAndUri(payload);
693 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
694 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
697 * There is a small window where another write transaction could be updating the same data
698 * simultaneously and we get an OptimisticLockFailedException. This error is likely
699 * transient and The WriteTransaction#submit API docs state that a retry will likely
700 * succeed. So we'll try again if that scenario occurs. If it fails a third time then it
701 * probably will never succeed so we'll fail in that case.
703 * By retrying we're attempting to hide the internal implementation of the data store and
704 * how it handles concurrent updates from the restconf client. The client has instructed us
705 * to put the data and we should make every effort to do so without pushing optimistic lock
706 * failures back to the client and forcing them to handle it via retry (and having to
707 * document the behavior).
709 PutResult result = null;
710 final TryOfPutData tryPutData = new TryOfPutData();
712 if (mountPoint != null) {
714 result = this.broker.commitMountPointDataPut(mountPoint, normalizedII, payload.getData());
716 result = this.broker.commitConfigurationDataPut(this.controllerContext.getGlobalSchema(), normalizedII,
719 final CountDownLatch waiter = new CountDownLatch(1);
720 Futures.addCallback(result.getFutureOfPutData(), new FutureCallback<Void>() {
723 public void onSuccess(final Void result) {
724 handlingLoggerPut(null, tryPutData, identifier);
729 public void onFailure(final Throwable t) {
731 handlingLoggerPut(t, tryPutData, identifier);
737 } catch (final Exception e) {
738 final String msg = "Problem while waiting for response";
740 throw new RestconfDocumentedException(msg, e);
743 if(tryPutData.isDone()){
746 throw new RestconfDocumentedException("Problem while PUT operations");
750 return Response.status(result.getStatus()).build();
753 protected void handlingLoggerPut(final Throwable t, final TryOfPutData tryPutData, final String identifier) {
755 if (t instanceof OptimisticLockFailedException) {
756 if (tryPutData.countGet() <= 0) {
757 LOG.debug("Got OptimisticLockFailedException on last try - failing " + identifier);
758 throw new RestconfDocumentedException(t.getMessage(), t);
760 LOG.debug("Got OptimisticLockFailedException - trying again " + identifier);
761 tryPutData.countDown();
763 LOG.debug("Update ConfigDataStore fail " + identifier, t);
764 throw new RestconfDocumentedException(t.getMessage(), t);
767 LOG.trace("PUT Successful " + identifier);
772 private static void validateTopLevelNodeName(final NormalizedNodeContext node,
773 final YangInstanceIdentifier identifier) {
775 final String payloadName = node.getData().getNodeType().getLocalName();
778 if (identifier.isEmpty()) {
780 if (!node.getData().getNodeType().equals(NETCONF_BASE_QNAME)) {
781 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
782 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
786 final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
787 if (!payloadName.equals(identifierName)) {
788 throw new RestconfDocumentedException("Payload name (" + payloadName
789 + ") is different from identifier name (" + identifierName + ")", ErrorType.PROTOCOL,
790 ErrorTag.MALFORMED_MESSAGE);
796 * Validates whether keys in {@code payload} are equal to values of keys in {@code iiWithData} for list schema node
798 * @throws RestconfDocumentedException
799 * if key values or key count in payload and URI isn't equal
802 private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
803 Preconditions.checkArgument(payload != null);
804 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
805 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
806 final SchemaNode schemaNode = iiWithData.getSchemaNode();
807 final NormalizedNode<?, ?> data = payload.getData();
808 if (schemaNode instanceof ListSchemaNode) {
809 final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
810 if ((lastPathArgument instanceof NodeIdentifierWithPredicates) && (data instanceof MapEntryNode)) {
811 final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument).getKeyValues();
812 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
817 private static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues,
818 final MapEntryNode payload, final List<QName> keyDefinitions) {
820 final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
821 for (final QName keyDefinition : keyDefinitions) {
822 final Object uriKeyValue = mutableCopyUriKeyValues.remove(keyDefinition);
823 // should be caught during parsing URI to InstanceIdentifier
824 RestconfValidationUtils.checkDocumentedError(uriKeyValue != null, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
825 "Missing key " + keyDefinition + " in URI.");
827 final Object dataKeyValue = payload.getIdentifier().getKeyValues().get(keyDefinition);
829 if ( ! uriKeyValue.equals(dataKeyValue)) {
830 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName() +
831 "' specified in the URI doesn't match the value '" + dataKeyValue + "' specified in the message body. ";
832 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
838 public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
839 return createConfigurationData(payload, uriInfo);
842 // FIXME create RestconfIdetifierHelper and move this method there
843 private static YangInstanceIdentifier checkConsistencyOfNormalizedNodeContext(final NormalizedNodeContext payload) {
844 Preconditions.checkArgument(payload != null);
845 Preconditions.checkArgument(payload.getData() != null);
846 Preconditions.checkArgument(payload.getData().getNodeType() != null);
847 Preconditions.checkArgument(payload.getInstanceIdentifierContext() != null);
848 Preconditions.checkArgument(payload.getInstanceIdentifierContext().getInstanceIdentifier() != null);
850 final QName payloadNodeQname = payload.getData().getNodeType();
851 final YangInstanceIdentifier yangIdent = payload.getInstanceIdentifierContext().getInstanceIdentifier();
852 if (payloadNodeQname.compareTo(yangIdent.getLastPathArgument().getNodeType()) > 0) {
855 final InstanceIdentifierContext<?> parentContext = payload.getInstanceIdentifierContext();
856 final SchemaNode parentSchemaNode = parentContext.getSchemaNode();
857 if(parentSchemaNode instanceof DataNodeContainer) {
858 final DataNodeContainer cast = (DataNodeContainer) parentSchemaNode;
859 for (final DataSchemaNode child : cast.getChildNodes()) {
860 if (payloadNodeQname.compareTo(child.getQName()) == 0) {
861 return YangInstanceIdentifier.builder(yangIdent).node(child.getQName()).build();
865 if (parentSchemaNode instanceof RpcDefinition) {
868 final String errMsg = "Error parsing input: DataSchemaNode has not children ";
869 LOG.info(errMsg + yangIdent);
870 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
874 public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
875 if (payload == null) {
876 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
879 // FIXME: move this to parsing stage (we can have augmentation nodes here which do not have namespace)
880 // final URI payloadNS = payload.getData().getNodeType().getNamespace();
881 // if (payloadNS == null) {
882 // throw new RestconfDocumentedException(
883 // "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
884 // ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
887 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
888 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
889 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
891 CheckedFuture<Void, TransactionCommitFailedException> future;
892 if (mountPoint != null) {
893 future = this.broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData());
895 future = this.broker.commitConfigurationDataPost(this.controllerContext.getGlobalSchema(), normalizedII,
899 final CountDownLatch waiter = new CountDownLatch(1);
900 Futures.addCallback(future, new FutureCallback<Void>() {
903 public void onSuccess(final Void result) {
904 handlerLoggerPost(null, uriInfo);
909 public void onFailure(final Throwable t) {
911 handlerLoggerPost(t, uriInfo);
917 } catch (final Exception e) {
918 final String msg = "Problem while waiting for response";
920 throw new RestconfDocumentedException(msg, e);
923 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
924 // FIXME: Provide path to result.
925 final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
926 if (location != null) {
927 responseBuilder.location(location);
929 return responseBuilder.build();
932 protected void handlerLoggerPost(final Throwable t, final UriInfo uriInfo) {
934 final String errMsg = "Error creating data ";
935 LOG.warn(errMsg + (uriInfo != null ? uriInfo.getPath() : ""), t);
936 throw new RestconfDocumentedException(errMsg, t);
938 LOG.trace("Successfuly create data.");
942 private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint, final YangInstanceIdentifier normalizedII) {
943 if(uriInfo == null) {
944 // This is null if invoked internally
948 final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
949 uriBuilder.path("config");
951 uriBuilder.path(this.controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
952 } catch (final Exception e) {
953 LOG.info("Location for instance identifier" + normalizedII + "wasn't created", e);
956 return uriBuilder.build();
960 public Response deleteConfigurationData(final String identifier) {
961 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
962 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
963 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
965 final CheckedFuture<Void, TransactionCommitFailedException> future;
966 if (mountPoint != null) {
967 future = this.broker.commitConfigurationDataDelete(mountPoint, normalizedII);
969 future = this.broker.commitConfigurationDataDelete(normalizedII);
972 final CountDownLatch waiter = new CountDownLatch(1);
973 Futures.addCallback(future, new FutureCallback<Void>() {
976 public void onSuccess(final Void result) {
977 handlerLoggerDelete(null);
982 public void onFailure(final Throwable t) {
984 handlerLoggerDelete(t);
991 } catch (final Exception e) {
992 final String msg = "Problem while waiting for response";
994 throw new RestconfDocumentedException(msg, e);
997 return Response.status(Status.OK).build();
1000 protected void handlerLoggerDelete(final Throwable t) {
1002 final String errMsg = "Error while deleting data";
1003 LOG.info(errMsg, t);
1004 throw new RestconfDocumentedException(errMsg, t);
1006 LOG.trace("Successfuly delete data.");
1011 * Subscribes to some path in schema context (stream) to listen on changes on this stream.
1013 * Additional parameters for subscribing to stream are loaded via rpc input parameters:
1015 * <li>datastore - default CONFIGURATION (other values of {@link LogicalDatastoreType} enum type)</li>
1016 * <li>scope - default BASE (other values of {@link DataChangeScope})</li>
1020 public Response subscribeToStream(final String identifier, final UriInfo uriInfo) {
1021 if (identifier.contains(DATA_SUBSCR)) {
1022 return dataSubs(identifier, uriInfo);
1023 } else if (identifier.contains(NOTIFICATION_STREAM)) {
1024 return notifStream(identifier, uriInfo);
1026 final String msg = "Bad type of notification of sal-remote";
1028 throw new RestconfDocumentedException(msg);
1032 * Register notification listener by stream name
1038 * @return {@link Response}
1040 private Response notifStream(final String identifier, final UriInfo uriInfo) {
1041 final String streamName = Notificator.createStreamNameFromUri(identifier);
1042 if (Strings.isNullOrEmpty(streamName)) {
1043 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1045 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
1046 if ((listeners == null) || listeners.isEmpty()) {
1047 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1048 ErrorTag.UNKNOWN_ELEMENT);
1051 for (final NotificationListenerAdapter listener : listeners) {
1052 this.broker.registerToListenNotification(listener);
1055 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1056 int notificationPort = NOTIFICATION_PORT;
1058 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
1059 notificationPort = webSocketServerInstance.getPort();
1060 } catch (final NullPointerException e) {
1061 WebSocketServer.createInstance(NOTIFICATION_PORT);
1063 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1064 final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
1066 return Response.status(Status.OK).location(uriToWebsocketServer).build();
1070 * Register data change listener by stream name
1076 * @return {@link Response}
1078 private Response dataSubs(final String identifier, final UriInfo uriInfo) {
1079 final String streamName = Notificator.createStreamNameFromUri(identifier);
1080 if (Strings.isNullOrEmpty(streamName)) {
1081 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1084 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1085 if (listener == null) {
1086 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
1089 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1090 final LogicalDatastoreType datastore = parserURIEnumParameter(LogicalDatastoreType.class,
1091 paramToValues.get(DATASTORE_PARAM_NAME));
1092 if (datastore == null) {
1093 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1094 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1096 final DataChangeScope scope = parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
1097 if (scope == null) {
1098 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1099 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1102 this.broker.registerToListenDataChanges(datastore, scope, listener);
1104 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1105 int notificationPort = NOTIFICATION_PORT;
1107 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
1108 notificationPort = webSocketServerInstance.getPort();
1109 } catch (final NullPointerException e) {
1110 WebSocketServer.createInstance(NOTIFICATION_PORT);
1112 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1113 final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
1115 return Response.status(Status.OK).location(uriToWebsocketServer).build();
1119 public PATCHStatusContext patchConfigurationData(final String identifier, final PATCHContext context, final UriInfo uriInfo) {
1120 if (context == null) {
1121 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1125 return this.broker.patchConfigurationDataWithinTransaction(context);
1126 } catch (final Exception e) {
1127 LOG.debug("Patch transaction failed", e);
1128 throw new RestconfDocumentedException(e.getMessage());
1133 public PATCHStatusContext patchConfigurationData(final PATCHContext context, @Context final UriInfo uriInfo) {
1134 if (context == null) {
1135 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1139 return this.broker.patchConfigurationDataWithinTransaction(context);
1140 } catch (final Exception e) {
1141 LOG.debug("Patch transaction failed", e);
1142 throw new RestconfDocumentedException(e.getMessage());
1147 * Load parameter for subscribing to stream from input composite node
1151 * @return enum object if its string value is equal to {@code paramName}. In other cases null.
1153 private static <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1154 final String paramName) {
1155 final Optional<DataContainerChild<? extends PathArgument, ?>> augNode = value.getChild(SAL_REMOTE_AUG_IDENTIFIER);
1156 if (!augNode.isPresent() && !(augNode instanceof AugmentationNode)) {
1159 final Optional<DataContainerChild<? extends PathArgument, ?>> enumNode =
1160 ((AugmentationNode) augNode.get()).getChild(new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1161 if (!enumNode.isPresent()) {
1164 final Object rawValue = enumNode.get().getValue();
1165 if (!(rawValue instanceof String)) {
1169 return resolveAsEnum(classDescriptor, (String) rawValue);
1173 * Checks whether {@code value} is one of the string representation of enumeration {@code classDescriptor}
1175 * @return enum object if string value of {@code classDescriptor} enumeration is equal to {@code value}. Other cases
1178 private static <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1179 if (Strings.isNullOrEmpty(value)) {
1182 return resolveAsEnum(classDescriptor, value);
1185 private static <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1186 final T[] enumConstants = classDescriptor.getEnumConstants();
1187 if (enumConstants != null) {
1188 for (final T enm : classDescriptor.getEnumConstants()) {
1189 if (((Enum<?>) enm).name().equals(value)) {
1197 private static Map<String, String> resolveValuesFromUri(final String uri) {
1198 final Map<String, String> result = new HashMap<>();
1199 final String[] tokens = uri.split("/");
1200 for (int i = 1; i < tokens.length; i++) {
1201 final String[] parameterTokens = tokens[i].split("=");
1202 if (parameterTokens.length == 2) {
1203 result.put(parameterTokens[0], parameterTokens[1]);
1209 private MapNode makeModuleMapNode(final Set<Module> modules) {
1210 Preconditions.checkNotNull(modules);
1211 final Module restconfModule = getRestconfModule();
1212 final DataSchemaNode moduleSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
1213 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1214 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1216 final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder = Builders
1217 .mapBuilder((ListSchemaNode) moduleSchemaNode);
1219 for (final Module module : modules) {
1220 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1222 return listModuleBuilder.build();
1225 protected MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1226 Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1227 "moduleSchemaNode has to be of type ListSchemaNode");
1228 final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1229 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues = Builders
1230 .mapEntryBuilder(listModuleSchemaNode);
1232 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1233 (listModuleSchemaNode), "name");
1234 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1235 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1236 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName())
1239 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1240 (listModuleSchemaNode), "revision");
1241 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1242 Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1243 final String revision = REVISION_FORMAT.format(module.getRevision());
1244 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode).withValue(revision)
1247 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1248 (listModuleSchemaNode), "namespace");
1249 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1250 Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1251 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1252 .withValue(module.getNamespace().toString()).build());
1254 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1255 (listModuleSchemaNode), "feature");
1256 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1257 Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1258 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder = Builders
1259 .leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1260 for (final FeatureDefinition feature : module.getFeatures()) {
1261 featuresBuilder.withChild(Builders.leafSetEntryBuilder(((LeafListSchemaNode) featureSchemaNode))
1262 .withValue(feature.getQName().getLocalName()).build());
1264 moduleNodeValues.withChild(featuresBuilder.build());
1266 return moduleNodeValues.build();
1269 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1270 Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1271 "streamSchemaNode has to be of type ListSchemaNode");
1272 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1273 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues = Builders
1274 .mapEntryBuilder(listStreamSchemaNode);
1276 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1277 (listStreamSchemaNode), "name");
1278 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1279 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1280 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName)
1283 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1284 (listStreamSchemaNode), "description");
1285 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1286 Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1287 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode)
1288 .withValue("DESCRIPTION_PLACEHOLDER").build());
1290 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1291 (listStreamSchemaNode), "replay-support");
1292 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1293 Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1294 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1295 .withValue(Boolean.valueOf(true)).build());
1297 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1298 (listStreamSchemaNode), "replay-log-creation-time");
1299 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1300 Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1301 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode)
1302 .withValue("").build());
1304 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1305 (listStreamSchemaNode), "events");
1306 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1307 Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1308 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode)
1309 .withValue("").build());
1311 return streamNodeValues.build();
1315 * Prepare stream for notification
1318 * - contains list of qnames of notifications
1319 * @return - checked future object
1321 private CheckedFuture<DOMRpcResult, DOMRpcException> invokeSalRemoteRpcNotifiStrRPC(
1322 final NormalizedNodeContext payload) {
1323 final ContainerNode data = (ContainerNode) payload.getData();
1324 LeafSetNode leafSet = null;
1325 String outputType = "XML";
1326 for (final DataContainerChild<? extends PathArgument, ?> dataChild : data.getValue()) {
1327 if (dataChild instanceof LeafSetNode) {
1328 leafSet = (LeafSetNode) dataChild;
1329 } else if (dataChild instanceof AugmentationNode) {
1330 outputType = (String) (((AugmentationNode) dataChild).getValue()).iterator().next().getValue();
1334 final Collection<LeafSetEntryNode> entryNodes = leafSet.getValue();
1335 final List<SchemaPath> paths = new ArrayList<>();
1336 String streamName = CREATE_NOTIFICATION_STREAM + "/";
1338 final Iterator<LeafSetEntryNode> iterator = entryNodes.iterator();
1339 while (iterator.hasNext()) {
1340 final QName valueQName = QName.create((String) iterator.next().getValue());
1341 final Module module = ControllerContext.getInstance()
1342 .findModuleByNamespace(valueQName.getModule().getNamespace());
1343 Preconditions.checkNotNull(module, "Module for namespace " + valueQName.getModule().getNamespace()
1344 + " does not exist");
1345 NotificationDefinition notifiDef = null;
1346 for (final NotificationDefinition notification : module.getNotifications()) {
1347 if (notification.getQName().equals(valueQName)) {
1348 notifiDef = notification;
1352 final String moduleName = module.getName();
1353 Preconditions.checkNotNull(notifiDef,
1354 "Notification " + valueQName + "doesn't exist in module " + moduleName);
1355 paths.add(notifiDef.getPath());
1356 streamName = streamName + moduleName + ":" + valueQName.getLocalName();
1357 if (iterator.hasNext()) {
1358 streamName = streamName + ",";
1362 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
1363 final QName outputQname = QName.create(rpcQName, "output");
1364 final QName streamNameQname = QName.create(rpcQName, "notification-stream-identifier");
1366 final ContainerNode output = ImmutableContainerNodeBuilder.create()
1367 .withNodeIdentifier(new NodeIdentifier(outputQname))
1368 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
1370 if (!Notificator.existNotificationListenerFor(streamName)) {
1371 Notificator.createNotificationListener(paths, streamName, outputType);
1374 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
1376 return Futures.immediateCheckedFuture(defaultDOMRpcResult);
1379 private class TryOfPutData {
1381 boolean done = false;