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.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
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 OUTPUT_TYPE_PARAM_NAME = "notification-output-type";
137 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
139 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
141 private static final QName NETCONF_BASE_QNAME;
143 private static final QNameModule SAL_REMOTE_AUGMENT;
145 private static final YangInstanceIdentifier.AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER;
147 public static final CharSequence DATA_SUBSCR = "data-change-event-subscription";
148 private static final CharSequence CREATE_DATA_SUBSCR = "create-" + DATA_SUBSCR;
150 public static final CharSequence NOTIFICATION_STREAM = "notification-stream";
151 private static final CharSequence CREATE_NOTIFICATION_STREAM = "create-" + NOTIFICATION_STREAM;
155 final Date eventSubscriptionAugRevision = new SimpleDateFormat("yyyy-MM-dd").parse("2014-07-08");
156 NETCONF_BASE_QNAME = QName.create(QNameModule.create(new URI(NETCONF_BASE), null),
157 NETCONF_BASE_PAYLOAD_NAME);
158 SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
159 eventSubscriptionAugRevision);
160 SAL_REMOTE_AUG_IDENTIFIER = new YangInstanceIdentifier.AugmentationIdentifier(Sets.newHashSet(
161 QName.create(SAL_REMOTE_AUGMENT, "scope"),
162 QName.create(SAL_REMOTE_AUGMENT, "datastore"),
163 QName.create(SAL_REMOTE_AUGMENT, "notification-output-type")));
164 } catch (final ParseException e) {
165 final String errMsg = "It wasn't possible to convert revision date of sal-remote-augment to date";
167 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
168 } catch (final URISyntaxException e) {
169 final String errMsg = "It wasn't possible to create instance of URI class with "+NETCONF_BASE+" URI";
170 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
174 public void setBroker(final BrokerFacade broker) {
175 this.broker = broker;
178 public void setControllerContext(final ControllerContext controllerContext) {
179 this.controllerContext = controllerContext;
182 private RestconfImpl() {
185 public static RestconfImpl getInstance() {
190 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
191 final Set<Module> allModules = this.controllerContext.getAllModules();
192 final MapNode allModuleMap = makeModuleMapNode(allModules);
194 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
196 final Module restconfModule = getRestconfModule();
197 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
198 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
199 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
201 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
202 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
203 moduleContainerBuilder.withChild(allModuleMap);
205 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode,
206 null, schemaContext), moduleContainerBuilder.build(),
207 QueryParametersParser.parseWriterParameters(uriInfo));
211 * Valid only for mount point
214 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
215 Preconditions.checkNotNull(identifier);
216 if ( ! identifier.contains(ControllerContext.MOUNT)) {
217 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
218 + " URI has to end with " + ControllerContext.MOUNT;
219 LOG.debug(errMsg + " for " + identifier);
220 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
223 final InstanceIdentifierContext<?> mountPointIdentifier = this.controllerContext
224 .toMountPointIdentifier(identifier);
225 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
226 final Set<Module> modules = this.controllerContext.getAllModules(mountPoint);
227 final MapNode mountPointModulesMap = makeModuleMapNode(modules);
229 final Module restconfModule = getRestconfModule();
230 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
231 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
232 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
234 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
235 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
236 moduleContainerBuilder.withChild(mountPointModulesMap);
238 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode,
239 mountPoint, this.controllerContext.getGlobalSchema()), moduleContainerBuilder.build(),
240 QueryParametersParser.parseWriterParameters(uriInfo));
244 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
245 Preconditions.checkNotNull(identifier);
246 final QName moduleNameAndRevision = getModuleNameAndRevision(identifier);
247 Module module = null;
248 DOMMountPoint mountPoint = null;
249 final SchemaContext schemaContext;
250 if (identifier.contains(ControllerContext.MOUNT)) {
251 final InstanceIdentifierContext<?> mountPointIdentifier = this.controllerContext
252 .toMountPointIdentifier(identifier);
253 mountPoint = mountPointIdentifier.getMountPoint();
254 module = this.controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision);
255 schemaContext = mountPoint.getSchemaContext();
257 module = this.controllerContext.findModuleByNameAndRevision(moduleNameAndRevision);
258 schemaContext = this.controllerContext.getGlobalSchema();
261 if (module == null) {
262 final String errMsg = "Module with name '" + moduleNameAndRevision.getLocalName()
263 + "' and revision '" + moduleNameAndRevision.getRevision() + "' was not found.";
265 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
268 final Module restconfModule = getRestconfModule();
269 final Set<Module> modules = Collections.singleton(module);
270 final MapNode moduleMap = makeModuleMapNode(modules);
272 final DataSchemaNode moduleSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
273 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
274 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
276 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint,
277 schemaContext), moduleMap, QueryParametersParser.parseWriterParameters(uriInfo));
281 public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
282 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
283 final Set<String> availableStreams = Notificator.getStreamNames();
284 final Module restconfModule = getRestconfModule();
285 final DataSchemaNode streamSchemaNode = this.controllerContext
286 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
287 Preconditions.checkState(streamSchemaNode instanceof ListSchemaNode);
289 final CollectionNodeBuilder<MapEntryNode, MapNode> listStreamsBuilder = Builders
290 .mapBuilder((ListSchemaNode) streamSchemaNode);
292 for (final String streamName : availableStreams) {
293 listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
296 final DataSchemaNode streamsContainerSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
297 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
298 Preconditions.checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
300 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
301 Builders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
302 streamsContainerBuilder.withChild(listStreamsBuilder.build());
305 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null,
306 schemaContext), streamsContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
310 public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
311 final Set<Module> allModules = this.controllerContext.getAllModules();
312 return operationsFromModulesToNormalizedContext(allModules, null);
316 public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
317 Set<Module> modules = null;
318 DOMMountPoint mountPoint = null;
319 if (identifier.contains(ControllerContext.MOUNT)) {
320 final InstanceIdentifierContext<?> mountPointIdentifier = this.controllerContext
321 .toMountPointIdentifier(identifier);
322 mountPoint = mountPointIdentifier.getMountPoint();
323 modules = this.controllerContext.getAllModules(mountPoint);
326 final String errMsg = "URI has bad format. If operations behind mount point should be showed, URI has to "
328 LOG.debug(errMsg + ControllerContext.MOUNT + " for " + identifier);
329 throw new RestconfDocumentedException(errMsg + ControllerContext.MOUNT, ErrorType.PROTOCOL,
330 ErrorTag.INVALID_VALUE);
333 return operationsFromModulesToNormalizedContext(modules, mountPoint);
337 * Special case only for GET restconf/operations use (since moment of pre-Beryllium
338 * Yang parser and Yang model API removal). The method is creating fake
339 * schema context with fake module and fake data by use own implementations
340 * of schema nodes and module.
343 * - set of modules for get RPCs from every module
345 * - mount point, if in use otherwise null
346 * @return {@link NormalizedNodeContext}
348 private NormalizedNodeContext operationsFromModulesToNormalizedContext(final Set<Module> modules,
349 final DOMMountPoint mountPoint) {
351 final ContainerSchemaNodeImpl fakeCont = new ContainerSchemaNodeImpl();
352 final List<LeafNode<Object>> listRpcNodes = new ArrayList<>();
353 for (final Module m : modules) {
354 for (final RpcDefinition rpc : m.getRpcs()) {
356 final LeafSchemaNode fakeLeaf = new LeafSchemaNodeImpl(fakeCont.getPath(),
357 QName.create(ModuleImpl.moduleQName, m.getName() + ":" + rpc.getQName().getLocalName()));
358 fakeCont.addNodeChild(fakeLeaf);
359 listRpcNodes.add(Builders.leafBuilder(fakeLeaf).build());
362 final ContainerSchemaNode fakeContSchNode = fakeCont;
363 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> containerBuilder = Builders
364 .containerBuilder(fakeContSchNode);
366 for (final LeafNode<Object> rpcNode : listRpcNodes) {
367 containerBuilder.withChild(rpcNode);
370 final Module fakeModule = new ModuleImpl(fakeContSchNode);
372 final Set<Module> fakeModules = new HashSet<>();
373 fakeModules.add(fakeModule);
374 final SchemaContext fakeSchemaCtx = EffectiveSchemaContext.resolveSchemaContext(fakeModules);
375 final InstanceIdentifierContext<ContainerSchemaNode> instanceIdentifierContext =
376 new InstanceIdentifierContext<>(null, fakeContSchNode, mountPoint, fakeSchemaCtx);
377 return new NormalizedNodeContext(instanceIdentifierContext, containerBuilder.build());
380 private Module getRestconfModule() {
381 final Module restconfModule = this.controllerContext.getRestconfModule();
382 if (restconfModule == null) {
383 LOG.debug("ietf-restconf module was not found.");
384 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
385 ErrorTag.OPERATION_NOT_SUPPORTED);
388 return restconfModule;
391 private static QName getModuleNameAndRevision(final String identifier) {
392 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
393 String moduleNameAndRevision = "";
394 if (mountIndex >= 0) {
395 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
397 moduleNameAndRevision = identifier;
400 final Splitter splitter = Splitter.on("/").omitEmptyStrings();
401 final Iterable<String> split = splitter.split(moduleNameAndRevision);
402 final List<String> pathArgs = Lists.<String> newArrayList(split);
403 if (pathArgs.size() < 2) {
404 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
405 throw new RestconfDocumentedException(
406 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
407 ErrorTag.INVALID_VALUE);
411 final String moduleName = pathArgs.get(0);
412 final String revision = pathArgs.get(1);
413 final Date moduleRevision = REVISION_FORMAT.parse(revision);
414 return QName.create(null, moduleRevision, moduleName);
415 } catch (final ParseException e) {
416 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
417 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
418 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
423 public Object getRoot() {
428 public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload,
429 final UriInfo uriInfo) {
430 final SchemaPath type = payload.getInstanceIdentifierContext().getSchemaNode().getPath();
431 final URI namespace = payload.getInstanceIdentifierContext().getSchemaNode().getQName().getNamespace();
432 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
433 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
434 final SchemaContext schemaContext;
435 if (mountPoint != null) {
436 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
437 if ( ! mountRpcServices.isPresent()) {
438 LOG.debug("Error: Rpc service is missing.");
439 throw new RestconfDocumentedException("Rpc service is missing.");
441 schemaContext = mountPoint.getSchemaContext();
442 response = mountRpcServices.get().invokeRpc(type, payload.getData());
444 if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
445 if (identifier.contains(CREATE_DATA_SUBSCR)) {
446 response = invokeSalRemoteRpcSubscribeRPC(payload);
447 } else if (identifier.contains(CREATE_NOTIFICATION_STREAM)) {
448 response = invokeSalRemoteRpcNotifiStrRPC(payload);
450 final String msg = "Not supported operation";
452 throw new RestconfDocumentedException(msg, ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED);
455 response = this.broker.invokeRpc(type, payload.getData());
457 schemaContext = this.controllerContext.getGlobalSchema();
460 final DOMRpcResult result = checkRpcResponse(response);
462 RpcDefinition resultNodeSchema = null;
463 final NormalizedNode<?, ?> resultData = result.getResult();
464 if ((result != null) && (result.getResult() != null)) {
465 resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
468 return new NormalizedNodeContext(new InstanceIdentifierContext<RpcDefinition>(null,
469 resultNodeSchema, mountPoint, schemaContext), resultData,
470 QueryParametersParser.parseWriterParameters(uriInfo));
473 private static DOMRpcResult checkRpcResponse(final CheckedFuture<DOMRpcResult, DOMRpcException> response) {
474 if (response == null) {
478 final DOMRpcResult retValue = response.get();
479 if ((retValue.getErrors() == null) || retValue.getErrors().isEmpty()) {
482 LOG.debug("RpcError message", retValue.getErrors());
483 throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
484 } catch (final InterruptedException e) {
485 final String errMsg = "The operation was interrupted while executing and did not complete.";
486 LOG.debug("Rpc Interrupt - " + errMsg, e);
487 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
488 } catch (final ExecutionException e) {
489 LOG.debug("Execution RpcError: ", e);
490 Throwable cause = e.getCause();
492 while (cause.getCause() != null) {
493 cause = cause.getCause();
496 if (cause instanceof IllegalArgumentException) {
497 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL,
498 ErrorTag.INVALID_VALUE);
499 } else if (cause instanceof DOMRpcImplementationNotAvailableException) {
500 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.APPLICATION,
501 ErrorTag.OPERATION_NOT_SUPPORTED);
503 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
506 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
509 } catch (final CancellationException e) {
510 final String errMsg = "The operation was cancelled while executing.";
511 LOG.debug("Cancel RpcExecution: " + errMsg, e);
512 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
516 private static void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
517 if ((inputSchema != null) && (payload.getData() == null)) {
518 // expected a non null payload
519 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
520 } else if ((inputSchema == null) && (payload.getData() != null)) {
521 // did not expect any input
522 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
526 private CheckedFuture<DOMRpcResult, DOMRpcException>
527 invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
528 final ContainerNode value = (ContainerNode) payload.getData();
529 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
530 final Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(new NodeIdentifier(
531 QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(), "path")));
532 final Object pathValue = path.isPresent() ? path.get().getValue() : null;
534 if (!(pathValue instanceof YangInstanceIdentifier)) {
535 final String errMsg = "Instance identifier was not normalized correctly ";
536 LOG.debug(errMsg + rpcQName);
537 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
540 final YangInstanceIdentifier pathIdentifier = ((YangInstanceIdentifier) pathValue);
541 String streamName = (String) CREATE_DATA_SUBSCR;
542 NotificationOutputType outputType = null;
543 if (!pathIdentifier.isEmpty()) {
544 final String fullRestconfIdentifier = DATA_SUBSCR
545 + this.controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
547 LogicalDatastoreType datastore =
548 parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
549 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
551 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
552 scope = scope == null ? DEFAULT_SCOPE : scope;
554 outputType = parseEnumTypeParameter(value, NotificationOutputType.class,
555 OUTPUT_TYPE_PARAM_NAME);
556 outputType = outputType == null ? NotificationOutputType.XML : outputType;
558 streamName = Notificator.createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore
559 + "/scope=" + scope);
562 if (Strings.isNullOrEmpty(streamName)) {
563 final String errMsg = "Path is empty or contains value node which is not Container or List build-in type.";
564 LOG.debug(errMsg + pathIdentifier);
565 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
568 final QName outputQname = QName.create(rpcQName, "output");
569 final QName streamNameQname = QName.create(rpcQName, "stream-name");
571 final ContainerNode output =
572 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
573 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
575 if (!Notificator.existListenerFor(streamName)) {
576 Notificator.createListener(pathIdentifier, streamName, outputType);
579 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
581 return Futures.immediateCheckedFuture(defaultDOMRpcResult);
585 public NormalizedNodeContext invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
586 if ((noPayload != null) && !CharMatcher.WHITESPACE.matchesAllOf(noPayload)) {
587 throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
590 String identifierEncoded = null;
591 DOMMountPoint mountPoint = null;
592 final SchemaContext schemaContext;
593 if (identifier.contains(ControllerContext.MOUNT)) {
594 // mounted RPC call - look up mount instance.
595 final InstanceIdentifierContext<?> mountPointId = this.controllerContext.toMountPointIdentifier(identifier);
596 mountPoint = mountPointId.getMountPoint();
597 schemaContext = mountPoint.getSchemaContext();
598 final int startOfRemoteRpcName = identifier.lastIndexOf(ControllerContext.MOUNT)
599 + ControllerContext.MOUNT.length() + 1;
600 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
601 identifierEncoded = remoteRpcName;
603 } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
604 final String slashErrorMsg = String.format("Identifier %n%s%ncan\'t contain slash "
605 + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.", identifier);
606 LOG.debug(slashErrorMsg);
607 throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
609 identifierEncoded = identifier;
610 schemaContext = this.controllerContext.getGlobalSchema();
613 final String identifierDecoded = this.controllerContext.urlPathArgDecode(identifierEncoded);
615 RpcDefinition rpc = null;
616 if (mountPoint == null) {
617 rpc = this.controllerContext.getRpcDefinition(identifierDecoded, null);
619 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
623 LOG.debug("RPC " + identifierDecoded + " does not exist.");
624 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
627 if (rpc.getInput() != null) {
628 LOG.debug("RPC " + rpc + " does not need input value.");
629 // FIXME : find a correct Error from specification
630 throw new IllegalStateException("RPC " + rpc + " does'n need input value!");
633 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
634 if (mountPoint != null) {
635 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
636 if ( ! mountRpcServices.isPresent()) {
637 throw new RestconfDocumentedException("Rpc service is missing.");
639 response = mountRpcServices.get().invokeRpc(rpc.getPath(), null);
641 response = this.broker.invokeRpc(rpc.getPath(), null);
644 final DOMRpcResult result = checkRpcResponse(response);
646 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpc, mountPoint, schemaContext),
647 result.getResult(), QueryParametersParser.parseWriterParameters(uriInfo));
650 private static RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
651 final String[] splittedIdentifier = identifierDecoded.split(":");
652 if (splittedIdentifier.length != 2) {
653 final String errMsg = identifierDecoded + " couldn't be splitted to 2 parts (module:rpc name)";
655 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
657 for (final Module module : schemaContext.getModules()) {
658 if (module.getName().equals(splittedIdentifier[0])) {
659 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
660 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
661 return rpcDefinition;
670 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
671 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
672 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
673 NormalizedNode<?, ?> data = null;
674 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
675 if (mountPoint != null) {
676 data = this.broker.readConfigurationData(mountPoint, normalizedII);
678 data = this.broker.readConfigurationData(normalizedII);
681 final String errMsg = "Request could not be completed because the relevant data model content does not exist ";
682 LOG.debug(errMsg + identifier);
683 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
685 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
689 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
690 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
691 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
692 NormalizedNode<?, ?> data = null;
693 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
694 if (mountPoint != null) {
695 data = this.broker.readOperationalData(mountPoint, normalizedII);
697 data = this.broker.readOperationalData(normalizedII);
700 final String errMsg = "Request could not be completed because the relevant data model content does not exist ";
701 LOG.debug(errMsg + identifier);
702 throw new RestconfDocumentedException(errMsg , ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
704 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
708 public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload) {
709 Preconditions.checkNotNull(identifier);
710 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
712 validateInput(iiWithData.getSchemaNode(), payload);
713 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
714 validateListKeysEqualityInPayloadAndUri(payload);
716 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
717 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
720 * There is a small window where another write transaction could be updating the same data
721 * simultaneously and we get an OptimisticLockFailedException. This error is likely
722 * transient and The WriteTransaction#submit API docs state that a retry will likely
723 * succeed. So we'll try again if that scenario occurs. If it fails a third time then it
724 * probably will never succeed so we'll fail in that case.
726 * By retrying we're attempting to hide the internal implementation of the data store and
727 * how it handles concurrent updates from the restconf client. The client has instructed us
728 * to put the data and we should make every effort to do so without pushing optimistic lock
729 * failures back to the client and forcing them to handle it via retry (and having to
730 * document the behavior).
732 PutResult result = null;
733 final TryOfPutData tryPutData = new TryOfPutData();
735 if (mountPoint != null) {
737 result = this.broker.commitMountPointDataPut(mountPoint, normalizedII, payload.getData());
739 result = this.broker.commitConfigurationDataPut(this.controllerContext.getGlobalSchema(), normalizedII,
742 final CountDownLatch waiter = new CountDownLatch(1);
743 Futures.addCallback(result.getFutureOfPutData(), new FutureCallback<Void>() {
746 public void onSuccess(final Void result) {
747 handlingLoggerPut(null, tryPutData, identifier);
752 public void onFailure(final Throwable t) {
754 handlingLoggerPut(t, tryPutData, identifier);
760 } catch (final Exception e) {
761 final String msg = "Problem while waiting for response";
763 throw new RestconfDocumentedException(msg, e);
766 if(tryPutData.isDone()){
769 throw new RestconfDocumentedException("Problem while PUT operations");
773 return Response.status(result.getStatus()).build();
776 protected void handlingLoggerPut(final Throwable t, final TryOfPutData tryPutData, final String identifier) {
778 if (t instanceof OptimisticLockFailedException) {
779 if (tryPutData.countGet() <= 0) {
780 LOG.debug("Got OptimisticLockFailedException on last try - failing " + identifier);
781 throw new RestconfDocumentedException(t.getMessage(), t);
783 LOG.debug("Got OptimisticLockFailedException - trying again " + identifier);
784 tryPutData.countDown();
786 LOG.debug("Update ConfigDataStore fail " + identifier, t);
787 throw new RestconfDocumentedException(t.getMessage(), t);
790 LOG.trace("PUT Successful " + identifier);
795 private static void validateTopLevelNodeName(final NormalizedNodeContext node,
796 final YangInstanceIdentifier identifier) {
798 final String payloadName = node.getData().getNodeType().getLocalName();
801 if (identifier.isEmpty()) {
803 if (!node.getData().getNodeType().equals(NETCONF_BASE_QNAME)) {
804 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
805 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
809 final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
810 if (!payloadName.equals(identifierName)) {
811 throw new RestconfDocumentedException("Payload name (" + payloadName
812 + ") is different from identifier name (" + identifierName + ")", ErrorType.PROTOCOL,
813 ErrorTag.MALFORMED_MESSAGE);
819 * Validates whether keys in {@code payload} are equal to values of keys in {@code iiWithData} for list schema node
821 * @throws RestconfDocumentedException
822 * if key values or key count in payload and URI isn't equal
825 private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
826 Preconditions.checkArgument(payload != null);
827 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
828 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
829 final SchemaNode schemaNode = iiWithData.getSchemaNode();
830 final NormalizedNode<?, ?> data = payload.getData();
831 if (schemaNode instanceof ListSchemaNode) {
832 final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
833 if ((lastPathArgument instanceof NodeIdentifierWithPredicates) && (data instanceof MapEntryNode)) {
834 final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument).getKeyValues();
835 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
840 private static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues,
841 final MapEntryNode payload, final List<QName> keyDefinitions) {
843 final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
844 for (final QName keyDefinition : keyDefinitions) {
845 final Object uriKeyValue = mutableCopyUriKeyValues.remove(keyDefinition);
846 // should be caught during parsing URI to InstanceIdentifier
847 RestconfValidationUtils.checkDocumentedError(uriKeyValue != null, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
848 "Missing key " + keyDefinition + " in URI.");
850 final Object dataKeyValue = payload.getIdentifier().getKeyValues().get(keyDefinition);
852 if ( ! uriKeyValue.equals(dataKeyValue)) {
853 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName() +
854 "' specified in the URI doesn't match the value '" + dataKeyValue
855 + "' specified in the message body. ";
856 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
862 public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload,
863 final UriInfo uriInfo) {
864 return createConfigurationData(payload, uriInfo);
867 // FIXME create RestconfIdetifierHelper and move this method there
868 private static YangInstanceIdentifier checkConsistencyOfNormalizedNodeContext(final NormalizedNodeContext payload) {
869 Preconditions.checkArgument(payload != null);
870 Preconditions.checkArgument(payload.getData() != null);
871 Preconditions.checkArgument(payload.getData().getNodeType() != null);
872 Preconditions.checkArgument(payload.getInstanceIdentifierContext() != null);
873 Preconditions.checkArgument(payload.getInstanceIdentifierContext().getInstanceIdentifier() != null);
875 final QName payloadNodeQname = payload.getData().getNodeType();
876 final YangInstanceIdentifier yangIdent = payload.getInstanceIdentifierContext().getInstanceIdentifier();
877 if (payloadNodeQname.compareTo(yangIdent.getLastPathArgument().getNodeType()) > 0) {
880 final InstanceIdentifierContext<?> parentContext = payload.getInstanceIdentifierContext();
881 final SchemaNode parentSchemaNode = parentContext.getSchemaNode();
882 if(parentSchemaNode instanceof DataNodeContainer) {
883 final DataNodeContainer cast = (DataNodeContainer) parentSchemaNode;
884 for (final DataSchemaNode child : cast.getChildNodes()) {
885 if (payloadNodeQname.compareTo(child.getQName()) == 0) {
886 return YangInstanceIdentifier.builder(yangIdent).node(child.getQName()).build();
890 if (parentSchemaNode instanceof RpcDefinition) {
893 final String errMsg = "Error parsing input: DataSchemaNode has not children ";
894 LOG.info(errMsg + yangIdent);
895 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
899 public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
900 if (payload == null) {
901 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
904 // FIXME: move this to parsing stage (we can have augmentation nodes here which do not have namespace)
905 // final URI payloadNS = payload.getData().getNodeType().getNamespace();
906 // if (payloadNS == null) {
907 // throw new RestconfDocumentedException(
908 // "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
909 // ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
912 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
913 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
914 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
916 CheckedFuture<Void, TransactionCommitFailedException> future;
917 if (mountPoint != null) {
918 future = this.broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData());
920 future = this.broker.commitConfigurationDataPost(this.controllerContext.getGlobalSchema(), normalizedII,
924 final CountDownLatch waiter = new CountDownLatch(1);
925 Futures.addCallback(future, new FutureCallback<Void>() {
928 public void onSuccess(final Void result) {
929 handlerLoggerPost(null, uriInfo);
934 public void onFailure(final Throwable t) {
936 handlerLoggerPost(t, uriInfo);
942 } catch (final Exception e) {
943 final String msg = "Problem while waiting for response";
945 throw new RestconfDocumentedException(msg, e);
948 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
949 // FIXME: Provide path to result.
950 final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
951 if (location != null) {
952 responseBuilder.location(location);
954 return responseBuilder.build();
957 protected void handlerLoggerPost(final Throwable t, final UriInfo uriInfo) {
959 final String errMsg = "Error creating data ";
960 LOG.warn(errMsg + (uriInfo != null ? uriInfo.getPath() : ""), t);
961 throw new RestconfDocumentedException(errMsg, t);
963 LOG.trace("Successfuly create data.");
967 private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint,
968 final YangInstanceIdentifier normalizedII) {
969 if(uriInfo == null) {
970 // This is null if invoked internally
974 final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
975 uriBuilder.path("config");
977 uriBuilder.path(this.controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
978 } catch (final Exception e) {
979 LOG.info("Location for instance identifier" + normalizedII + "wasn't created", e);
982 return uriBuilder.build();
986 public Response deleteConfigurationData(final String identifier) {
987 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
988 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
989 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
991 final CheckedFuture<Void, TransactionCommitFailedException> future;
992 if (mountPoint != null) {
993 future = this.broker.commitConfigurationDataDelete(mountPoint, normalizedII);
995 future = this.broker.commitConfigurationDataDelete(normalizedII);
998 final CountDownLatch waiter = new CountDownLatch(1);
999 Futures.addCallback(future, new FutureCallback<Void>() {
1002 public void onSuccess(final Void result) {
1003 handlerLoggerDelete(null);
1008 public void onFailure(final Throwable t) {
1010 handlerLoggerDelete(t);
1017 } catch (final Exception e) {
1018 final String msg = "Problem while waiting for response";
1020 throw new RestconfDocumentedException(msg, e);
1023 return Response.status(Status.OK).build();
1026 protected void handlerLoggerDelete(final Throwable t) {
1028 final String errMsg = "Error while deleting data";
1029 LOG.info(errMsg, t);
1030 throw new RestconfDocumentedException(errMsg, t);
1032 LOG.trace("Successfuly delete data.");
1037 * Subscribes to some path in schema context (stream) to listen on changes on this stream.
1039 * Additional parameters for subscribing to stream are loaded via rpc input parameters:
1041 * <li>datastore - default CONFIGURATION (other values of {@link LogicalDatastoreType} enum type)</li>
1042 * <li>scope - default BASE (other values of {@link DataChangeScope})</li>
1046 public Response subscribeToStream(final String identifier, final UriInfo uriInfo) {
1047 if (identifier.contains(DATA_SUBSCR)) {
1048 return dataSubs(identifier, uriInfo);
1049 } else if (identifier.contains(NOTIFICATION_STREAM)) {
1050 return notifStream(identifier, uriInfo);
1052 final String msg = "Bad type of notification of sal-remote";
1054 throw new RestconfDocumentedException(msg);
1058 * Register notification listener by stream name
1064 * @return {@link Response}
1066 private Response notifStream(final String identifier, final UriInfo uriInfo) {
1067 final String streamName = Notificator.createStreamNameFromUri(identifier);
1068 if (Strings.isNullOrEmpty(streamName)) {
1069 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1071 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
1072 if ((listeners == null) || listeners.isEmpty()) {
1073 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1074 ErrorTag.UNKNOWN_ELEMENT);
1077 for (final NotificationListenerAdapter listener : listeners) {
1078 this.broker.registerToListenNotification(listener);
1081 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1082 int notificationPort = NOTIFICATION_PORT;
1084 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
1085 notificationPort = webSocketServerInstance.getPort();
1086 } catch (final NullPointerException e) {
1087 WebSocketServer.createInstance(NOTIFICATION_PORT);
1089 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1090 final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
1092 return Response.status(Status.OK).location(uriToWebsocketServer).build();
1096 * Register data change listener by stream name
1102 * @return {@link Response}
1104 private Response dataSubs(final String identifier, final UriInfo uriInfo) {
1105 final String streamName = Notificator.createStreamNameFromUri(identifier);
1106 if (Strings.isNullOrEmpty(streamName)) {
1107 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1110 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1111 if (listener == null) {
1112 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
1115 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1116 final LogicalDatastoreType datastore = parserURIEnumParameter(LogicalDatastoreType.class,
1117 paramToValues.get(DATASTORE_PARAM_NAME));
1118 if (datastore == null) {
1119 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1120 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1122 final DataChangeScope scope = parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
1123 if (scope == null) {
1124 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1125 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1128 this.broker.registerToListenDataChanges(datastore, scope, listener);
1130 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1131 int notificationPort = NOTIFICATION_PORT;
1133 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
1134 notificationPort = webSocketServerInstance.getPort();
1135 } catch (final NullPointerException e) {
1136 WebSocketServer.createInstance(NOTIFICATION_PORT);
1138 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1139 final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
1141 return Response.status(Status.OK).location(uriToWebsocketServer).build();
1145 public PATCHStatusContext patchConfigurationData(final String identifier, final PATCHContext context,
1146 final UriInfo uriInfo) {
1147 if (context == null) {
1148 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1152 return this.broker.patchConfigurationDataWithinTransaction(context);
1153 } catch (final Exception e) {
1154 LOG.debug("Patch transaction failed", e);
1155 throw new RestconfDocumentedException(e.getMessage());
1160 public PATCHStatusContext patchConfigurationData(final PATCHContext context, @Context final UriInfo uriInfo) {
1161 if (context == null) {
1162 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1166 return this.broker.patchConfigurationDataWithinTransaction(context);
1167 } catch (final Exception e) {
1168 LOG.debug("Patch transaction failed", e);
1169 throw new RestconfDocumentedException(e.getMessage());
1174 * Load parameter for subscribing to stream from input composite node
1178 * @return enum object if its string value is equal to {@code paramName}. In other cases null.
1180 private static <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1181 final String paramName) {
1182 final Optional<DataContainerChild<? extends PathArgument, ?>> augNode = value.getChild(SAL_REMOTE_AUG_IDENTIFIER);
1183 if (!augNode.isPresent() && !(augNode instanceof AugmentationNode)) {
1186 final Optional<DataContainerChild<? extends PathArgument, ?>> enumNode =
1187 ((AugmentationNode) augNode.get())
1188 .getChild(new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1189 if (!enumNode.isPresent()) {
1192 final Object rawValue = enumNode.get().getValue();
1193 if (!(rawValue instanceof String)) {
1197 return resolveAsEnum(classDescriptor, (String) rawValue);
1201 * Checks whether {@code value} is one of the string representation of enumeration {@code classDescriptor}
1203 * @return enum object if string value of {@code classDescriptor} enumeration is equal to {@code value}. Other cases
1206 private static <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1207 if (Strings.isNullOrEmpty(value)) {
1210 return resolveAsEnum(classDescriptor, value);
1213 private static <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1214 final T[] enumConstants = classDescriptor.getEnumConstants();
1215 if (enumConstants != null) {
1216 for (final T enm : classDescriptor.getEnumConstants()) {
1217 if (((Enum<?>) enm).name().equals(value)) {
1225 private static Map<String, String> resolveValuesFromUri(final String uri) {
1226 final Map<String, String> result = new HashMap<>();
1227 final String[] tokens = uri.split("/");
1228 for (int i = 1; i < tokens.length; i++) {
1229 final String[] parameterTokens = tokens[i].split("=");
1230 if (parameterTokens.length == 2) {
1231 result.put(parameterTokens[0], parameterTokens[1]);
1237 private MapNode makeModuleMapNode(final Set<Module> modules) {
1238 Preconditions.checkNotNull(modules);
1239 final Module restconfModule = getRestconfModule();
1240 final DataSchemaNode moduleSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
1241 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1242 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1244 final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder = Builders
1245 .mapBuilder((ListSchemaNode) moduleSchemaNode);
1247 for (final Module module : modules) {
1248 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1250 return listModuleBuilder.build();
1253 protected MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1254 Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1255 "moduleSchemaNode has to be of type ListSchemaNode");
1256 final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1257 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues = Builders
1258 .mapEntryBuilder(listModuleSchemaNode);
1260 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1261 (listModuleSchemaNode), "name");
1262 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1263 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1264 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName())
1267 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1268 (listModuleSchemaNode), "revision");
1269 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1270 Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1271 final String revision = REVISION_FORMAT.format(module.getRevision());
1272 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode).withValue(revision)
1275 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1276 (listModuleSchemaNode), "namespace");
1277 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1278 Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1279 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1280 .withValue(module.getNamespace().toString()).build());
1282 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1283 (listModuleSchemaNode), "feature");
1284 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1285 Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1286 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder = Builders
1287 .leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1288 for (final FeatureDefinition feature : module.getFeatures()) {
1289 featuresBuilder.withChild(Builders.leafSetEntryBuilder(((LeafListSchemaNode) featureSchemaNode))
1290 .withValue(feature.getQName().getLocalName()).build());
1292 moduleNodeValues.withChild(featuresBuilder.build());
1294 return moduleNodeValues.build();
1297 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1298 Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1299 "streamSchemaNode has to be of type ListSchemaNode");
1300 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1301 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues = Builders
1302 .mapEntryBuilder(listStreamSchemaNode);
1304 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1305 (listStreamSchemaNode), "name");
1306 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1307 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1308 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName)
1311 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1312 (listStreamSchemaNode), "description");
1313 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1314 Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1315 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode)
1316 .withValue("DESCRIPTION_PLACEHOLDER").build());
1318 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1319 (listStreamSchemaNode), "replay-support");
1320 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1321 Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1322 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1323 .withValue(Boolean.valueOf(true)).build());
1325 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1326 (listStreamSchemaNode), "replay-log-creation-time");
1327 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1328 Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1329 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode)
1330 .withValue("").build());
1332 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1333 (listStreamSchemaNode), "events");
1334 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1335 Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1336 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode)
1337 .withValue("").build());
1339 return streamNodeValues.build();
1343 * Prepare stream for notification
1346 * - contains list of qnames of notifications
1347 * @return - checked future object
1349 private CheckedFuture<DOMRpcResult, DOMRpcException> invokeSalRemoteRpcNotifiStrRPC(
1350 final NormalizedNodeContext payload) {
1351 final ContainerNode data = (ContainerNode) payload.getData();
1352 LeafSetNode leafSet = null;
1353 String outputType = "XML";
1354 for (final DataContainerChild<? extends PathArgument, ?> dataChild : data.getValue()) {
1355 if (dataChild instanceof LeafSetNode) {
1356 leafSet = (LeafSetNode) dataChild;
1357 } else if (dataChild instanceof AugmentationNode) {
1358 outputType = (String) (((AugmentationNode) dataChild).getValue()).iterator().next().getValue();
1362 final Collection<LeafSetEntryNode> entryNodes = leafSet.getValue();
1363 final List<SchemaPath> paths = new ArrayList<>();
1364 String streamName = CREATE_NOTIFICATION_STREAM + "/";
1366 final Iterator<LeafSetEntryNode> iterator = entryNodes.iterator();
1367 while (iterator.hasNext()) {
1368 final QName valueQName = QName.create((String) iterator.next().getValue());
1369 final Module module = ControllerContext.getInstance()
1370 .findModuleByNamespace(valueQName.getModule().getNamespace());
1371 Preconditions.checkNotNull(module, "Module for namespace " + valueQName.getModule().getNamespace()
1372 + " does not exist");
1373 NotificationDefinition notifiDef = null;
1374 for (final NotificationDefinition notification : module.getNotifications()) {
1375 if (notification.getQName().equals(valueQName)) {
1376 notifiDef = notification;
1380 final String moduleName = module.getName();
1381 Preconditions.checkNotNull(notifiDef,
1382 "Notification " + valueQName + "doesn't exist in module " + moduleName);
1383 paths.add(notifiDef.getPath());
1384 streamName = streamName + moduleName + ":" + valueQName.getLocalName();
1385 if (iterator.hasNext()) {
1386 streamName = streamName + ",";
1390 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
1391 final QName outputQname = QName.create(rpcQName, "output");
1392 final QName streamNameQname = QName.create(rpcQName, "notification-stream-identifier");
1394 final ContainerNode output = ImmutableContainerNodeBuilder.create()
1395 .withNodeIdentifier(new NodeIdentifier(outputQname))
1396 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
1398 if (!Notificator.existNotificationListenerFor(streamName)) {
1399 Notificator.createNotificationListener(paths, streamName, outputType);
1402 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
1404 return Futures.immediateCheckedFuture(defaultDOMRpcResult);
1407 private class TryOfPutData {
1409 boolean done = false;