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;
23 import java.math.BigInteger;
25 import java.net.URISyntaxException;
26 import java.text.ParseException;
27 import java.text.SimpleDateFormat;
28 import java.util.ArrayList;
29 import java.util.Collection;
30 import java.util.Collections;
31 import java.util.Date;
32 import java.util.HashMap;
33 import java.util.HashSet;
34 import java.util.Iterator;
35 import java.util.List;
38 import java.util.concurrent.CancellationException;
39 import java.util.concurrent.CountDownLatch;
40 import java.util.concurrent.ExecutionException;
41 import javax.ws.rs.core.Context;
42 import javax.ws.rs.core.Response;
43 import javax.ws.rs.core.Response.ResponseBuilder;
44 import javax.ws.rs.core.Response.Status;
45 import javax.ws.rs.core.UriBuilder;
46 import javax.ws.rs.core.UriInfo;
47 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
48 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
49 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
50 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
51 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
52 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
53 import org.opendaylight.controller.md.sal.dom.api.DOMRpcImplementationNotAvailableException;
54 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
55 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
56 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
57 import org.opendaylight.netconf.md.sal.rest.common.RestconfValidationUtils;
58 import org.opendaylight.netconf.sal.rest.api.Draft02;
59 import org.opendaylight.netconf.sal.rest.api.RestconfService;
60 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
61 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
62 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
63 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
64 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
65 import org.opendaylight.netconf.sal.streams.websockets.WebSocketServer;
66 import org.opendaylight.yangtools.yang.common.QName;
67 import org.opendaylight.yangtools.yang.common.QNameModule;
68 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
69 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
70 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
71 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
72 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
73 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
74 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
75 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
76 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
77 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
78 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
79 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
80 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
81 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
82 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
83 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
84 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
85 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
86 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
87 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
88 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
89 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
90 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
91 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
92 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
93 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
94 import org.opendaylight.yangtools.yang.model.api.Module;
95 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
96 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
97 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
98 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
99 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
100 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.EffectiveSchemaContext;
101 import org.slf4j.Logger;
102 import org.slf4j.LoggerFactory;
104 public class RestconfImpl implements RestconfService {
106 private static final RestconfImpl INSTANCE = new RestconfImpl();
109 * Notifications are served on port 8181.
111 private static final int NOTIFICATION_PORT = 8181;
113 private static final int CHAR_NOT_FOUND = -1;
115 private static final SimpleDateFormat REVISION_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
117 private static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
119 private BrokerFacade broker;
121 private ControllerContext controllerContext;
123 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
125 private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
127 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
129 private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
131 private static final String DATASTORE_PARAM_NAME = "datastore";
133 private static final String SCOPE_PARAM_NAME = "scope";
135 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
137 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
139 private static final QName NETCONF_BASE_QNAME;
141 private static final QNameModule SAL_REMOTE_AUGMENT;
143 private static final YangInstanceIdentifier.AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER;
145 public static final CharSequence DATA_SUBSCR = "data-change-event-subscription";
146 private static final CharSequence CREATE_DATA_SUBSCR = "create-" + DATA_SUBSCR;
148 public static final CharSequence NOTIFICATION_STREAM = "notification-stream";
149 private static final CharSequence CREATE_NOTIFICATION_STREAM = "create-" + NOTIFICATION_STREAM;
153 final Date eventSubscriptionAugRevision = new SimpleDateFormat("yyyy-MM-dd").parse("2014-07-08");
154 NETCONF_BASE_QNAME = QName.create(QNameModule.create(new URI(NETCONF_BASE), null), NETCONF_BASE_PAYLOAD_NAME );
155 SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
156 eventSubscriptionAugRevision);
157 SAL_REMOTE_AUG_IDENTIFIER = new YangInstanceIdentifier.AugmentationIdentifier(Sets.newHashSet(QName.create(SAL_REMOTE_AUGMENT, "scope"),
158 QName.create(SAL_REMOTE_AUGMENT, "datastore")));
159 } catch (final ParseException e) {
160 final String errMsg = "It wasn't possible to convert revision date of sal-remote-augment to date";
162 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
163 } catch (final URISyntaxException e) {
164 final String errMsg = "It wasn't possible to create instance of URI class with "+NETCONF_BASE+" URI";
165 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
169 public void setBroker(final BrokerFacade broker) {
170 this.broker = broker;
173 public void setControllerContext(final ControllerContext controllerContext) {
174 this.controllerContext = controllerContext;
177 private RestconfImpl() {
180 public static RestconfImpl getInstance() {
185 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
186 final Set<Module> allModules = this.controllerContext.getAllModules();
187 final MapNode allModuleMap = makeModuleMapNode(allModules);
189 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
191 final Module restconfModule = getRestconfModule();
192 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
193 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
194 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
196 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
197 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
198 moduleContainerBuilder.withChild(allModuleMap);
200 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode,
201 null, schemaContext), moduleContainerBuilder.build(),
202 QueryParametersParser.parseWriterParameters(uriInfo));
206 * Valid only for mount point
209 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
210 Preconditions.checkNotNull(identifier);
211 if ( ! identifier.contains(ControllerContext.MOUNT)) {
212 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
213 + " URI has to end with " + ControllerContext.MOUNT;
214 LOG.debug(errMsg + " for " + identifier);
215 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
218 final InstanceIdentifierContext<?> mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier);
219 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
220 final Set<Module> modules = this.controllerContext.getAllModules(mountPoint);
221 final MapNode mountPointModulesMap = makeModuleMapNode(modules);
223 final Module restconfModule = getRestconfModule();
224 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
225 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
226 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
228 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
229 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
230 moduleContainerBuilder.withChild(mountPointModulesMap);
232 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode,
233 mountPoint, this.controllerContext.getGlobalSchema()), moduleContainerBuilder.build(),
234 QueryParametersParser.parseWriterParameters(uriInfo));
238 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
239 Preconditions.checkNotNull(identifier);
240 final QName moduleNameAndRevision = getModuleNameAndRevision(identifier);
241 Module module = null;
242 DOMMountPoint mountPoint = null;
243 final SchemaContext schemaContext;
244 if (identifier.contains(ControllerContext.MOUNT)) {
245 final InstanceIdentifierContext<?> mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier);
246 mountPoint = mountPointIdentifier.getMountPoint();
247 module = this.controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision);
248 schemaContext = mountPoint.getSchemaContext();
250 module = this.controllerContext.findModuleByNameAndRevision(moduleNameAndRevision);
251 schemaContext = this.controllerContext.getGlobalSchema();
254 if (module == null) {
255 final String errMsg = "Module with name '" + moduleNameAndRevision.getLocalName()
256 + "' and revision '" + moduleNameAndRevision.getRevision() + "' was not found.";
258 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
261 final Module restconfModule = getRestconfModule();
262 final Set<Module> modules = Collections.singleton(module);
263 final MapNode moduleMap = makeModuleMapNode(modules);
265 final DataSchemaNode moduleSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
266 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
267 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
269 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint,
270 schemaContext), moduleMap, QueryParametersParser.parseWriterParameters(uriInfo));
274 public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
275 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
276 final Set<String> availableStreams = Notificator.getStreamNames();
277 final Module restconfModule = getRestconfModule();
278 final DataSchemaNode streamSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
279 Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
280 Preconditions.checkState(streamSchemaNode instanceof ListSchemaNode);
282 final CollectionNodeBuilder<MapEntryNode, MapNode> listStreamsBuilder = Builders
283 .mapBuilder((ListSchemaNode) streamSchemaNode);
285 for (final String streamName : availableStreams) {
286 listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
289 final DataSchemaNode streamsContainerSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
290 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
291 Preconditions.checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
293 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
294 Builders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
295 streamsContainerBuilder.withChild(listStreamsBuilder.build());
298 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null,
299 schemaContext), streamsContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
303 public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
304 final Set<Module> allModules = this.controllerContext.getAllModules();
305 return operationsFromModulesToNormalizedContext(allModules, null);
309 public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
310 Set<Module> modules = null;
311 DOMMountPoint mountPoint = null;
312 if (identifier.contains(ControllerContext.MOUNT)) {
313 final InstanceIdentifierContext<?> mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier);
314 mountPoint = mountPointIdentifier.getMountPoint();
315 modules = this.controllerContext.getAllModules(mountPoint);
318 final String errMsg = "URI has bad format. If operations behind mount point should be showed, URI has to end with ";
319 LOG.debug(errMsg + ControllerContext.MOUNT + " for " + identifier);
320 throw new RestconfDocumentedException(errMsg + ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
323 return operationsFromModulesToNormalizedContext(modules, mountPoint);
327 * Special case only for GET restconf/operations use (since moment of pre-Beryllium
328 * Yang parser and Yang model API removal). The method is creating fake
329 * schema context with fake module and fake data by use own implementations
330 * of schema nodes and module.
333 * - set of modules for get RPCs from every module
335 * - mount point, if in use otherwise null
336 * @return {@link NormalizedNodeContext}
338 private NormalizedNodeContext operationsFromModulesToNormalizedContext(final Set<Module> modules,
339 final DOMMountPoint mountPoint) {
341 final ContainerSchemaNodeImpl fakeCont = new ContainerSchemaNodeImpl();
342 final List<LeafNode<Object>> listRpcNodes = new ArrayList<>();
343 for (final Module m : modules) {
344 for (final RpcDefinition rpc : m.getRpcs()) {
346 final LeafSchemaNode fakeLeaf = new LeafSchemaNodeImpl(fakeCont.getPath(),
347 QName.create(ModuleImpl.moduleQName, m.getName() + ":" + rpc.getQName().getLocalName()));
348 fakeCont.addNodeChild(fakeLeaf);
349 listRpcNodes.add(Builders.leafBuilder(fakeLeaf).build());
352 final ContainerSchemaNode fakeContSchNode = fakeCont;
353 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> containerBuilder = Builders
354 .containerBuilder(fakeContSchNode);
356 for (final LeafNode<Object> rpcNode : listRpcNodes) {
357 containerBuilder.withChild(rpcNode);
360 final Module fakeModule = new ModuleImpl(fakeContSchNode);
362 final Set<Module> fakeModules = new HashSet<>();
363 fakeModules.add(fakeModule);
364 final SchemaContext fakeSchemaCtx = EffectiveSchemaContext.resolveSchemaContext(fakeModules);
365 final InstanceIdentifierContext<ContainerSchemaNode> instanceIdentifierContext = new InstanceIdentifierContext<>(
366 null, fakeContSchNode, mountPoint, fakeSchemaCtx);
367 return new NormalizedNodeContext(instanceIdentifierContext, containerBuilder.build());
370 private Module getRestconfModule() {
371 final Module restconfModule = this.controllerContext.getRestconfModule();
372 if (restconfModule == null) {
373 LOG.debug("ietf-restconf module was not found.");
374 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
375 ErrorTag.OPERATION_NOT_SUPPORTED);
378 return restconfModule;
381 private static QName getModuleNameAndRevision(final String identifier) {
382 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
383 String moduleNameAndRevision = "";
384 if (mountIndex >= 0) {
385 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
387 moduleNameAndRevision = identifier;
390 final Splitter splitter = Splitter.on("/").omitEmptyStrings();
391 final Iterable<String> split = splitter.split(moduleNameAndRevision);
392 final List<String> pathArgs = Lists.<String> newArrayList(split);
393 if (pathArgs.size() < 2) {
394 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
395 throw new RestconfDocumentedException(
396 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
397 ErrorTag.INVALID_VALUE);
401 final String moduleName = pathArgs.get(0);
402 final String revision = pathArgs.get(1);
403 final Date moduleRevision = REVISION_FORMAT.parse(revision);
404 return QName.create(null, moduleRevision, moduleName);
405 } catch (final ParseException e) {
406 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
407 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
408 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
413 public Object getRoot() {
418 public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
419 final SchemaPath type = payload.getInstanceIdentifierContext().getSchemaNode().getPath();
420 final URI namespace = payload.getInstanceIdentifierContext().getSchemaNode().getQName().getNamespace();
421 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
422 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
423 final SchemaContext schemaContext;
424 if (mountPoint != null) {
425 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
426 if ( ! mountRpcServices.isPresent()) {
427 LOG.debug("Error: Rpc service is missing.");
428 throw new RestconfDocumentedException("Rpc service is missing.");
430 schemaContext = mountPoint.getSchemaContext();
431 response = mountRpcServices.get().invokeRpc(type, payload.getData());
433 if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
434 if (identifier.contains(CREATE_DATA_SUBSCR)) {
435 response = invokeSalRemoteRpcSubscribeRPC(payload);
436 } else if (identifier.contains(CREATE_NOTIFICATION_STREAM)) {
437 response = invokeSalRemoteRpcNotifiStrRPC(payload);
439 final String msg = "Not supported operation";
441 throw new RestconfDocumentedException(msg, ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED);
444 response = this.broker.invokeRpc(type, payload.getData());
446 schemaContext = this.controllerContext.getGlobalSchema();
449 final DOMRpcResult result = checkRpcResponse(response);
451 RpcDefinition resultNodeSchema = null;
452 final NormalizedNode<?, ?> resultData = result.getResult();
453 if ((result != null) && (result.getResult() != null)) {
454 resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
457 return new NormalizedNodeContext(new InstanceIdentifierContext<RpcDefinition>(null,
458 resultNodeSchema, mountPoint, schemaContext), resultData,
459 QueryParametersParser.parseWriterParameters(uriInfo));
462 private static DOMRpcResult checkRpcResponse(final CheckedFuture<DOMRpcResult, DOMRpcException> response) {
463 if (response == null) {
467 final DOMRpcResult retValue = response.get();
468 if ((retValue.getErrors() == null) || retValue.getErrors().isEmpty()) {
471 LOG.debug("RpcError message", retValue.getErrors());
472 throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
473 } catch (final InterruptedException e) {
474 final String errMsg = "The operation was interrupted while executing and did not complete.";
475 LOG.debug("Rpc Interrupt - " + errMsg, e);
476 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
477 } catch (final ExecutionException e) {
478 LOG.debug("Execution RpcError: ", e);
479 Throwable cause = e.getCause();
481 while (cause.getCause() != null) {
482 cause = cause.getCause();
485 if (cause instanceof IllegalArgumentException) {
486 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL,
487 ErrorTag.INVALID_VALUE);
488 } else if (cause instanceof DOMRpcImplementationNotAvailableException) {
489 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
491 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",cause);
493 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",e);
495 } catch (final CancellationException e) {
496 final String errMsg = "The operation was cancelled while executing.";
497 LOG.debug("Cancel RpcExecution: " + errMsg, e);
498 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
502 private static void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
503 if ((inputSchema != null) && (payload.getData() == null)) {
504 // expected a non null payload
505 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
506 } else if ((inputSchema == null) && (payload.getData() != null)) {
507 // did not expect any input
508 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
512 private CheckedFuture<DOMRpcResult, DOMRpcException> invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
513 final ContainerNode value = (ContainerNode) payload.getData();
514 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
515 final Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(new NodeIdentifier(
516 QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(), "path")));
517 final Object pathValue = path.isPresent() ? path.get().getValue() : null;
519 if (!(pathValue instanceof YangInstanceIdentifier)) {
520 final String errMsg = "Instance identifier was not normalized correctly ";
521 LOG.debug(errMsg + rpcQName);
522 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
525 final YangInstanceIdentifier pathIdentifier = ((YangInstanceIdentifier) pathValue);
526 String streamName = (String) CREATE_DATA_SUBSCR;
527 if (!pathIdentifier.isEmpty()) {
528 final String fullRestconfIdentifier = DATA_SUBSCR
529 + this.controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
531 LogicalDatastoreType datastore = parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
532 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
534 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
535 scope = scope == null ? DEFAULT_SCOPE : scope;
537 streamName = Notificator.createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore
538 + "/scope=" + scope);
541 if (Strings.isNullOrEmpty(streamName)) {
542 final String errMsg = "Path is empty or contains value node which is not Container or List build-in type.";
543 LOG.debug(errMsg + pathIdentifier);
544 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
547 final QName outputQname = QName.create(rpcQName, "output");
548 final QName streamNameQname = QName.create(rpcQName, "stream-name");
550 final ContainerNode output = ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
551 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
553 if (!Notificator.existListenerFor(streamName)) {
554 Notificator.createListener(pathIdentifier, streamName);
557 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
559 return Futures.immediateCheckedFuture(defaultDOMRpcResult);
563 public NormalizedNodeContext invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
564 if ((noPayload != null) && !CharMatcher.WHITESPACE.matchesAllOf(noPayload)) {
565 throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
568 String identifierEncoded = null;
569 DOMMountPoint mountPoint = null;
570 final SchemaContext schemaContext;
571 if (identifier.contains(ControllerContext.MOUNT)) {
572 // mounted RPC call - look up mount instance.
573 final InstanceIdentifierContext<?> mountPointId = this.controllerContext.toMountPointIdentifier(identifier);
574 mountPoint = mountPointId.getMountPoint();
575 schemaContext = mountPoint.getSchemaContext();
576 final int startOfRemoteRpcName = identifier.lastIndexOf(ControllerContext.MOUNT)
577 + ControllerContext.MOUNT.length() + 1;
578 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
579 identifierEncoded = remoteRpcName;
581 } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
582 final String slashErrorMsg = String.format("Identifier %n%s%ncan\'t contain slash "
583 + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.", identifier);
584 LOG.debug(slashErrorMsg);
585 throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
587 identifierEncoded = identifier;
588 schemaContext = this.controllerContext.getGlobalSchema();
591 final String identifierDecoded = this.controllerContext.urlPathArgDecode(identifierEncoded);
593 RpcDefinition rpc = null;
594 if (mountPoint == null) {
595 rpc = this.controllerContext.getRpcDefinition(identifierDecoded, null);
597 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
601 LOG.debug("RPC " + identifierDecoded + " does not exist.");
602 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
605 if (rpc.getInput() != null) {
606 LOG.debug("RPC " + rpc + " does not need input value.");
607 // FIXME : find a correct Error from specification
608 throw new IllegalStateException("RPC " + rpc + " does'n need input value!");
611 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
612 if (mountPoint != null) {
613 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
614 if ( ! mountRpcServices.isPresent()) {
615 throw new RestconfDocumentedException("Rpc service is missing.");
617 response = mountRpcServices.get().invokeRpc(rpc.getPath(), null);
619 response = this.broker.invokeRpc(rpc.getPath(), null);
622 final DOMRpcResult result = checkRpcResponse(response);
624 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpc, mountPoint, schemaContext),
625 result.getResult(), QueryParametersParser.parseWriterParameters(uriInfo));
628 private static RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
629 final String[] splittedIdentifier = identifierDecoded.split(":");
630 if (splittedIdentifier.length != 2) {
631 final String errMsg = identifierDecoded + " couldn't be splitted to 2 parts (module:rpc name)";
633 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
635 for (final Module module : schemaContext.getModules()) {
636 if (module.getName().equals(splittedIdentifier[0])) {
637 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
638 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
639 return rpcDefinition;
648 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
649 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
650 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
651 NormalizedNode<?, ?> data = null;
652 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
653 if (mountPoint != null) {
654 data = this.broker.readConfigurationData(mountPoint, normalizedII);
656 data = this.broker.readConfigurationData(normalizedII);
659 final String errMsg = "Request could not be completed because the relevant data model content does not exist ";
660 LOG.debug(errMsg + identifier);
661 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
663 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
667 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
668 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
669 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
670 NormalizedNode<?, ?> data = null;
671 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
672 if (mountPoint != null) {
673 data = this.broker.readOperationalData(mountPoint, normalizedII);
675 data = this.broker.readOperationalData(normalizedII);
678 final String errMsg = "Request could not be completed because the relevant data model content does not exist ";
679 LOG.debug(errMsg + identifier);
680 throw new RestconfDocumentedException(errMsg , ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
682 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
686 public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload) {
687 Preconditions.checkNotNull(identifier);
688 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
690 validateInput(iiWithData.getSchemaNode(), payload);
691 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
692 validateListKeysEqualityInPayloadAndUri(payload);
694 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
695 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
698 * There is a small window where another write transaction could be updating the same data
699 * simultaneously and we get an OptimisticLockFailedException. This error is likely
700 * transient and The WriteTransaction#submit API docs state that a retry will likely
701 * succeed. So we'll try again if that scenario occurs. If it fails a third time then it
702 * probably will never succeed so we'll fail in that case.
704 * By retrying we're attempting to hide the internal implementation of the data store and
705 * how it handles concurrent updates from the restconf client. The client has instructed us
706 * to put the data and we should make every effort to do so without pushing optimistic lock
707 * failures back to the client and forcing them to handle it via retry (and having to
708 * document the behavior).
710 PutResult result = null;
711 final TryOfPutData tryPutData = new TryOfPutData();
713 if (mountPoint != null) {
715 result = this.broker.commitMountPointDataPut(mountPoint, normalizedII, payload.getData());
717 result = this.broker.commitConfigurationDataPut(this.controllerContext.getGlobalSchema(), normalizedII,
720 final CountDownLatch waiter = new CountDownLatch(1);
721 Futures.addCallback(result.getFutureOfPutData(), new FutureCallback<Void>() {
724 public void onSuccess(final Void result) {
725 handlingLoggerPut(null, tryPutData, identifier);
730 public void onFailure(final Throwable t) {
732 handlingLoggerPut(t, tryPutData, identifier);
738 } catch (final InterruptedException e) {
739 final String msg = "Problem while waiting for response";
741 throw new RestconfDocumentedException(msg, e);
744 if(tryPutData.isDone()){
747 throw new RestconfDocumentedException("Problem while PUT operations");
751 return Response.status(result.getStatus()).build();
754 protected void handlingLoggerPut(final Throwable t, final TryOfPutData tryPutData, final String identifier) {
756 if (t instanceof OptimisticLockFailedException) {
757 if (tryPutData.countGet() <= 0) {
758 LOG.debug("Got OptimisticLockFailedException on last try - failing " + identifier);
759 throw new RestconfDocumentedException(t.getMessage(), t);
761 LOG.debug("Got OptimisticLockFailedException - trying again " + identifier);
762 tryPutData.countDown();
764 LOG.debug("Update ConfigDataStore fail " + identifier, t);
765 throw new RestconfDocumentedException(t.getMessage(), t);
768 LOG.trace("PUT Successful " + identifier);
773 private static void validateTopLevelNodeName(final NormalizedNodeContext node,
774 final YangInstanceIdentifier identifier) {
776 final String payloadName = node.getData().getNodeType().getLocalName();
779 if (identifier.isEmpty()) {
781 if (!node.getData().getNodeType().equals(NETCONF_BASE_QNAME)) {
782 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
783 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
787 final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
788 if (!payloadName.equals(identifierName)) {
789 throw new RestconfDocumentedException("Payload name (" + payloadName
790 + ") is different from identifier name (" + identifierName + ")", ErrorType.PROTOCOL,
791 ErrorTag.MALFORMED_MESSAGE);
797 * Validates whether keys in {@code payload} are equal to values of keys in {@code iiWithData} for list schema node
799 * @throws RestconfDocumentedException
800 * if key values or key count in payload and URI isn't equal
803 private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
804 Preconditions.checkArgument(payload != null);
805 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
806 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
807 final SchemaNode schemaNode = iiWithData.getSchemaNode();
808 final NormalizedNode<?, ?> data = payload.getData();
809 if (schemaNode instanceof ListSchemaNode) {
810 final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
811 if ((lastPathArgument instanceof NodeIdentifierWithPredicates) && (data instanceof MapEntryNode)) {
812 final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument).getKeyValues();
813 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
818 private static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues,
819 final MapEntryNode payload, final List<QName> keyDefinitions) {
821 final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
822 for (final QName keyDefinition : keyDefinitions) {
823 final Object uriKeyValue = mutableCopyUriKeyValues.remove(keyDefinition);
824 // should be caught during parsing URI to InstanceIdentifier
825 RestconfValidationUtils.checkDocumentedError(uriKeyValue != null, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
826 "Missing key " + keyDefinition + " in URI.");
828 final Object dataKeyValue = payload.getIdentifier().getKeyValues().get(keyDefinition);
830 if ( ! uriKeyValue.equals(dataKeyValue)) {
831 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName() +
832 "' specified in the URI doesn't match the value '" + dataKeyValue + "' specified in the message body. ";
833 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
839 public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
840 return createConfigurationData(payload, uriInfo);
843 // FIXME create RestconfIdetifierHelper and move this method there
844 private static YangInstanceIdentifier checkConsistencyOfNormalizedNodeContext(final NormalizedNodeContext payload) {
845 Preconditions.checkArgument(payload != null);
846 Preconditions.checkArgument(payload.getData() != null);
847 Preconditions.checkArgument(payload.getData().getNodeType() != null);
848 Preconditions.checkArgument(payload.getInstanceIdentifierContext() != null);
849 Preconditions.checkArgument(payload.getInstanceIdentifierContext().getInstanceIdentifier() != null);
851 final QName payloadNodeQname = payload.getData().getNodeType();
852 final YangInstanceIdentifier yangIdent = payload.getInstanceIdentifierContext().getInstanceIdentifier();
853 if (payloadNodeQname.compareTo(yangIdent.getLastPathArgument().getNodeType()) > 0) {
856 final InstanceIdentifierContext<?> parentContext = payload.getInstanceIdentifierContext();
857 final SchemaNode parentSchemaNode = parentContext.getSchemaNode();
858 if(parentSchemaNode instanceof DataNodeContainer) {
859 final DataNodeContainer cast = (DataNodeContainer) parentSchemaNode;
860 for (final DataSchemaNode child : cast.getChildNodes()) {
861 if (payloadNodeQname.compareTo(child.getQName()) == 0) {
862 return YangInstanceIdentifier.builder(yangIdent).node(child.getQName()).build();
866 if (parentSchemaNode instanceof RpcDefinition) {
869 final String errMsg = "Error parsing input: DataSchemaNode has not children ";
870 LOG.info(errMsg + yangIdent);
871 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
875 public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
876 if (payload == null) {
877 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
880 // FIXME: move this to parsing stage (we can have augmentation nodes here which do not have namespace)
881 // final URI payloadNS = payload.getData().getNodeType().getNamespace();
882 // if (payloadNS == null) {
883 // throw new RestconfDocumentedException(
884 // "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
885 // ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
888 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
889 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
890 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
892 CheckedFuture<Void, TransactionCommitFailedException> future;
893 if (mountPoint != null) {
894 future = this.broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData());
896 future = this.broker.commitConfigurationDataPost(this.controllerContext.getGlobalSchema(), normalizedII,
900 final CountDownLatch waiter = new CountDownLatch(1);
901 Futures.addCallback(future, new FutureCallback<Void>() {
904 public void onSuccess(final Void result) {
905 handlerLoggerPost(null, uriInfo);
910 public void onFailure(final Throwable t) {
912 handlerLoggerPost(t, uriInfo);
918 } catch (final InterruptedException e) {
919 final String msg = "Problem while waiting for response";
921 throw new RestconfDocumentedException(msg, e);
924 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
925 // FIXME: Provide path to result.
926 final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
927 if (location != null) {
928 responseBuilder.location(location);
930 return responseBuilder.build();
933 protected void handlerLoggerPost(final Throwable t, final UriInfo uriInfo) {
935 final String errMsg = "Error creating data ";
936 LOG.warn(errMsg + (uriInfo != null ? uriInfo.getPath() : ""), t);
937 throw new RestconfDocumentedException(errMsg, t);
939 LOG.trace("Successfuly create data.");
943 private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint, final YangInstanceIdentifier normalizedII) {
944 if(uriInfo == null) {
945 // This is null if invoked internally
949 final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
950 uriBuilder.path("config");
952 uriBuilder.path(this.controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
953 } catch (final Exception e) {
954 LOG.info("Location for instance identifier" + normalizedII + "wasn't created", e);
957 return uriBuilder.build();
961 public Response deleteConfigurationData(final String identifier) {
962 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
963 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
964 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
966 final CheckedFuture<Void, TransactionCommitFailedException> future;
967 if (mountPoint != null) {
968 future = this.broker.commitConfigurationDataDelete(mountPoint, normalizedII);
970 future = this.broker.commitConfigurationDataDelete(normalizedII);
973 final CountDownLatch waiter = new CountDownLatch(1);
974 Futures.addCallback(future, new FutureCallback<Void>() {
977 public void onSuccess(final Void result) {
978 handlerLoggerDelete(null);
983 public void onFailure(final Throwable t) {
985 handlerLoggerDelete(t);
992 } catch (final InterruptedException e) {
993 final String msg = "Problem while waiting for response";
995 throw new RestconfDocumentedException(msg, e);
998 return Response.status(Status.OK).build();
1001 protected void handlerLoggerDelete(final Throwable t) {
1003 final String errMsg = "Error while deleting data";
1004 LOG.info(errMsg, t);
1005 throw new RestconfDocumentedException(errMsg, t);
1007 LOG.trace("Successfuly delete data.");
1012 * Subscribes to some path in schema context (stream) to listen on changes on this stream.
1014 * Additional parameters for subscribing to stream are loaded via rpc input parameters:
1016 * <li>datastore - default CONFIGURATION (other values of {@link LogicalDatastoreType} enum type)</li>
1017 * <li>scope - default BASE (other values of {@link DataChangeScope})</li>
1021 public Response subscribeToStream(final String identifier, final UriInfo uriInfo) {
1022 if (identifier.contains(DATA_SUBSCR)) {
1023 return dataSubs(identifier, uriInfo);
1024 } else if (identifier.contains(NOTIFICATION_STREAM)) {
1025 return notifStream(identifier, uriInfo);
1027 final String msg = "Bad type of notification of sal-remote";
1029 throw new RestconfDocumentedException(msg);
1033 * Register notification listener by stream name
1039 * @return {@link Response}
1041 private Response notifStream(final String identifier, final UriInfo uriInfo) {
1042 final String streamName = Notificator.createStreamNameFromUri(identifier);
1043 if (Strings.isNullOrEmpty(streamName)) {
1044 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1046 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
1047 if ((listeners == null) || listeners.isEmpty()) {
1048 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1049 ErrorTag.UNKNOWN_ELEMENT);
1052 for (final NotificationListenerAdapter listener : listeners) {
1053 this.broker.registerToListenNotification(listener);
1056 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1057 int notificationPort = NOTIFICATION_PORT;
1059 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
1060 notificationPort = webSocketServerInstance.getPort();
1061 } catch (final NullPointerException e) {
1062 WebSocketServer.createInstance(NOTIFICATION_PORT);
1064 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1065 final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
1067 return Response.status(Status.OK).location(uriToWebsocketServer).build();
1071 * Register data change listener by stream name
1077 * @return {@link Response}
1079 private Response dataSubs(final String identifier, final UriInfo uriInfo) {
1080 final String streamName = Notificator.createStreamNameFromUri(identifier);
1081 if (Strings.isNullOrEmpty(streamName)) {
1082 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1085 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1086 if (listener == null) {
1087 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
1090 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1091 final LogicalDatastoreType datastore = parserURIEnumParameter(LogicalDatastoreType.class,
1092 paramToValues.get(DATASTORE_PARAM_NAME));
1093 if (datastore == null) {
1094 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1095 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1097 final DataChangeScope scope = parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
1098 if (scope == null) {
1099 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1100 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1103 this.broker.registerToListenDataChanges(datastore, scope, listener);
1105 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1106 int notificationPort = NOTIFICATION_PORT;
1108 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
1109 notificationPort = webSocketServerInstance.getPort();
1110 } catch (final NullPointerException e) {
1111 WebSocketServer.createInstance(NOTIFICATION_PORT);
1113 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1114 final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
1116 return Response.status(Status.OK).location(uriToWebsocketServer).build();
1120 public PATCHStatusContext patchConfigurationData(final String identifier, final PATCHContext context, final UriInfo uriInfo) {
1121 if (context == null) {
1122 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1126 return this.broker.patchConfigurationDataWithinTransaction(context,
1127 this.controllerContext.getGlobalSchema());
1128 } catch (final InterruptedException e) {
1129 LOG.debug("Patch transaction failed", e);
1130 throw new RestconfDocumentedException(e.getMessage());
1135 public PATCHStatusContext patchConfigurationData(final PATCHContext context, @Context final UriInfo uriInfo) {
1136 if (context == null) {
1137 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1141 return this.broker.patchConfigurationDataWithinTransaction(context,
1142 this.controllerContext.getGlobalSchema());
1143 } catch (final InterruptedException e) {
1144 LOG.debug("Patch transaction failed", e);
1145 throw new RestconfDocumentedException(e.getMessage());
1150 * Load parameter for subscribing to stream from input composite node
1154 * @return enum object if its string value is equal to {@code paramName}. In other cases null.
1156 private static <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1157 final String paramName) {
1158 final Optional<DataContainerChild<? extends PathArgument, ?>> augNode = value.getChild(SAL_REMOTE_AUG_IDENTIFIER);
1159 if (!augNode.isPresent() && !(augNode instanceof AugmentationNode)) {
1162 final Optional<DataContainerChild<? extends PathArgument, ?>> enumNode =
1163 ((AugmentationNode) augNode.get()).getChild(new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1164 if (!enumNode.isPresent()) {
1167 final Object rawValue = enumNode.get().getValue();
1168 if (!(rawValue instanceof String)) {
1172 return resolveAsEnum(classDescriptor, (String) rawValue);
1176 * Checks whether {@code value} is one of the string representation of enumeration {@code classDescriptor}
1178 * @return enum object if string value of {@code classDescriptor} enumeration is equal to {@code value}. Other cases
1181 private static <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1182 if (Strings.isNullOrEmpty(value)) {
1185 return resolveAsEnum(classDescriptor, value);
1188 private static <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1189 final T[] enumConstants = classDescriptor.getEnumConstants();
1190 if (enumConstants != null) {
1191 for (final T enm : classDescriptor.getEnumConstants()) {
1192 if (((Enum<?>) enm).name().equals(value)) {
1200 private static Map<String, String> resolveValuesFromUri(final String uri) {
1201 final Map<String, String> result = new HashMap<>();
1202 final String[] tokens = uri.split("/");
1203 for (int i = 1; i < tokens.length; i++) {
1204 final String[] parameterTokens = tokens[i].split("=");
1205 if (parameterTokens.length == 2) {
1206 result.put(parameterTokens[0], parameterTokens[1]);
1212 private MapNode makeModuleMapNode(final Set<Module> modules) {
1213 Preconditions.checkNotNull(modules);
1214 final Module restconfModule = getRestconfModule();
1215 final DataSchemaNode moduleSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
1216 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1217 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1219 final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder = Builders
1220 .mapBuilder((ListSchemaNode) moduleSchemaNode);
1222 for (final Module module : modules) {
1223 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1225 return listModuleBuilder.build();
1228 protected MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1229 Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1230 "moduleSchemaNode has to be of type ListSchemaNode");
1231 final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1232 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues = Builders
1233 .mapEntryBuilder(listModuleSchemaNode);
1235 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1236 (listModuleSchemaNode), "name");
1237 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1238 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1239 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName())
1242 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1243 (listModuleSchemaNode), "revision");
1244 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1245 Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1246 final String revision = REVISION_FORMAT.format(module.getRevision());
1247 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode).withValue(revision)
1250 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1251 (listModuleSchemaNode), "namespace");
1252 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1253 Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1254 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1255 .withValue(module.getNamespace().toString()).build());
1257 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1258 (listModuleSchemaNode), "feature");
1259 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1260 Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1261 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder = Builders
1262 .leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1263 for (final FeatureDefinition feature : module.getFeatures()) {
1264 featuresBuilder.withChild(Builders.leafSetEntryBuilder(((LeafListSchemaNode) featureSchemaNode))
1265 .withValue(feature.getQName().getLocalName()).build());
1267 moduleNodeValues.withChild(featuresBuilder.build());
1269 return moduleNodeValues.build();
1272 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1273 Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1274 "streamSchemaNode has to be of type ListSchemaNode");
1275 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1276 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues = Builders
1277 .mapEntryBuilder(listStreamSchemaNode);
1279 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1280 (listStreamSchemaNode), "name");
1281 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1282 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1283 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName)
1286 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1287 (listStreamSchemaNode), "description");
1288 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1289 Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1290 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode)
1291 .withValue("DESCRIPTION_PLACEHOLDER").build());
1293 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1294 (listStreamSchemaNode), "replay-support");
1295 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1296 Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1297 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1298 .withValue(Boolean.valueOf(true)).build());
1300 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1301 (listStreamSchemaNode), "replay-log-creation-time");
1302 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1303 Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1304 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode)
1305 .withValue("").build());
1307 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1308 (listStreamSchemaNode), "events");
1309 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1310 Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1311 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode)
1312 .withValue("").build());
1314 return streamNodeValues.build();
1318 * Prepare stream for notification
1321 * - contains list of qnames of notifications
1322 * @return - checked future object
1324 private CheckedFuture<DOMRpcResult, DOMRpcException> invokeSalRemoteRpcNotifiStrRPC(
1325 final NormalizedNodeContext payload) {
1326 final ContainerNode data = (ContainerNode) payload.getData();
1327 LeafSetNode leafSet = null;
1328 String outputType = "XML";
1329 for (final DataContainerChild<? extends PathArgument, ?> dataChild : data.getValue()) {
1330 if (dataChild instanceof LeafSetNode) {
1331 leafSet = (LeafSetNode) dataChild;
1332 } else if (dataChild instanceof AugmentationNode) {
1333 outputType = (String) (((AugmentationNode) dataChild).getValue()).iterator().next().getValue();
1337 final Collection<LeafSetEntryNode> entryNodes = leafSet.getValue();
1338 final List<SchemaPath> paths = new ArrayList<>();
1339 String streamName = CREATE_NOTIFICATION_STREAM + "/";
1341 final Iterator<LeafSetEntryNode> iterator = entryNodes.iterator();
1342 while (iterator.hasNext()) {
1343 final QName valueQName = QName.create((String) iterator.next().getValue());
1344 final Module module = ControllerContext.getInstance()
1345 .findModuleByNamespace(valueQName.getModule().getNamespace());
1346 Preconditions.checkNotNull(module, "Module for namespace " + valueQName.getModule().getNamespace()
1347 + " does not exist");
1348 NotificationDefinition notifiDef = null;
1349 for (final NotificationDefinition notification : module.getNotifications()) {
1350 if (notification.getQName().equals(valueQName)) {
1351 notifiDef = notification;
1355 final String moduleName = module.getName();
1356 Preconditions.checkNotNull(notifiDef,
1357 "Notification " + valueQName + "doesn't exist in module " + moduleName);
1358 paths.add(notifiDef.getPath());
1359 streamName = streamName + moduleName + ":" + valueQName.getLocalName();
1360 if (iterator.hasNext()) {
1361 streamName = streamName + ",";
1365 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
1366 final QName outputQname = QName.create(rpcQName, "output");
1367 final QName streamNameQname = QName.create(rpcQName, "notification-stream-identifier");
1369 final ContainerNode output = ImmutableContainerNodeBuilder.create()
1370 .withNodeIdentifier(new NodeIdentifier(outputQname))
1371 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
1373 if (!Notificator.existNotificationListenerFor(streamName)) {
1374 Notificator.createNotificationListener(paths, streamName, outputType);
1377 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
1379 return Futures.immediateCheckedFuture(defaultDOMRpcResult);
1382 private class TryOfPutData {
1384 boolean done = false;