2 * Copyright (c) 2014 - 2016 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
8 package org.opendaylight.netconf.sal.restconf.impl;
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Predicates;
13 import com.google.common.base.Splitter;
14 import com.google.common.base.Strings;
15 import com.google.common.base.Throwables;
16 import com.google.common.collect.ImmutableSet;
17 import com.google.common.collect.Iterables;
18 import com.google.common.collect.Maps;
19 import com.google.common.util.concurrent.FluentFuture;
20 import com.google.common.util.concurrent.Futures;
21 import com.google.common.util.concurrent.ListenableFuture;
23 import java.time.Instant;
24 import java.time.format.DateTimeFormatter;
25 import java.time.format.DateTimeFormatterBuilder;
26 import java.time.format.DateTimeParseException;
27 import java.time.temporal.ChronoField;
28 import java.time.temporal.TemporalAccessor;
29 import java.util.AbstractMap.SimpleImmutableEntry;
30 import java.util.ArrayList;
31 import java.util.Collection;
32 import java.util.Collections;
33 import java.util.HashMap;
34 import java.util.Iterator;
35 import java.util.List;
36 import java.util.Locale;
38 import java.util.Map.Entry;
39 import java.util.Objects;
40 import java.util.Optional;
42 import java.util.concurrent.CancellationException;
43 import java.util.concurrent.ExecutionException;
44 import javax.inject.Inject;
45 import javax.inject.Singleton;
46 import javax.ws.rs.WebApplicationException;
47 import javax.ws.rs.core.Context;
48 import javax.ws.rs.core.Response;
49 import javax.ws.rs.core.Response.ResponseBuilder;
50 import javax.ws.rs.core.Response.Status;
51 import javax.ws.rs.core.UriBuilder;
52 import javax.ws.rs.core.UriInfo;
53 import org.opendaylight.mdsal.common.api.CommitInfo;
54 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
55 import org.opendaylight.mdsal.common.api.OptimisticLockFailedException;
56 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
57 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
58 import org.opendaylight.mdsal.dom.api.DOMRpcImplementationNotAvailableException;
59 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
60 import org.opendaylight.mdsal.dom.api.DOMRpcService;
61 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
62 import org.opendaylight.netconf.sal.rest.api.Draft02;
63 import org.opendaylight.netconf.sal.rest.api.RestconfService;
64 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
65 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
66 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
67 import org.opendaylight.netconf.sal.streams.websockets.WebSocketServer;
68 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
69 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
70 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
71 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
72 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
73 import org.opendaylight.restconf.common.patch.PatchContext;
74 import org.opendaylight.restconf.common.patch.PatchStatusContext;
75 import org.opendaylight.restconf.common.util.DataChangeScope;
76 import org.opendaylight.restconf.common.util.OperationsResourceUtils;
77 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
78 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
79 import org.opendaylight.yangtools.yang.common.QName;
80 import org.opendaylight.yangtools.yang.common.QNameModule;
81 import org.opendaylight.yangtools.yang.common.Revision;
82 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
83 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
84 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
85 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
86 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
87 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
88 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
89 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
90 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
91 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
92 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
93 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
94 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
95 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
96 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
97 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
98 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
99 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
100 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
101 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
102 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeBuilder;
103 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
104 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
105 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
106 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
107 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
108 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
109 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
110 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
111 import org.opendaylight.yangtools.yang.model.api.Module;
112 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
113 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
114 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
115 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
116 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
117 import org.slf4j.Logger;
118 import org.slf4j.LoggerFactory;
121 public final class RestconfImpl implements RestconfService {
123 * Notifications are served on port 8181.
125 private static final int NOTIFICATION_PORT = 8181;
127 private static final int CHAR_NOT_FOUND = -1;
129 private static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
131 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
133 private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
135 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
137 private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
139 private static final String DATASTORE_PARAM_NAME = "datastore";
141 private static final String SCOPE_PARAM_NAME = "scope";
143 private static final String OUTPUT_TYPE_PARAM_NAME = "notification-output-type";
145 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
147 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
149 private static final QName NETCONF_BASE_QNAME = QName.create(QNameModule.create(URI.create(NETCONF_BASE)),
150 NETCONF_BASE_PAYLOAD_NAME).intern();
152 private static final QNameModule SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
153 Revision.of("2014-07-08"));
155 private static final AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER =
156 new AugmentationIdentifier(ImmutableSet.of(
157 QName.create(SAL_REMOTE_AUGMENT, "scope"), QName.create(SAL_REMOTE_AUGMENT, "datastore"),
158 QName.create(SAL_REMOTE_AUGMENT, "notification-output-type")));
160 public static final CharSequence DATA_SUBSCR = "data-change-event-subscription";
161 private static final CharSequence CREATE_DATA_SUBSCR = "create-" + DATA_SUBSCR;
163 public static final CharSequence NOTIFICATION_STREAM = "notification-stream";
164 private static final CharSequence CREATE_NOTIFICATION_STREAM = "create-" + NOTIFICATION_STREAM;
166 private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
167 .appendValue(ChronoField.YEAR, 4).appendLiteral('-')
168 .appendValue(ChronoField.MONTH_OF_YEAR, 2).appendLiteral('-')
169 .appendValue(ChronoField.DAY_OF_MONTH, 2).appendLiteral('T')
170 .appendValue(ChronoField.HOUR_OF_DAY, 2).appendLiteral(':')
171 .appendValue(ChronoField.MINUTE_OF_HOUR, 2).appendLiteral(':')
172 .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
173 .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
174 .appendOffset("+HH:MM", "Z").toFormatter();
176 private final BrokerFacade broker;
178 private final ControllerContext controllerContext;
181 public RestconfImpl(final BrokerFacade broker, final ControllerContext controllerContext) {
182 this.broker = broker;
183 this.controllerContext = controllerContext;
189 * @deprecated Just use {@link #RestconfImpl(BrokerFacade, ControllerContext)} constructor instead.
192 public static RestconfImpl newInstance(final BrokerFacade broker, final ControllerContext controllerContext) {
193 return new RestconfImpl(broker, controllerContext);
197 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
198 final Set<Module> allModules = this.controllerContext.getAllModules();
199 final MapNode allModuleMap = makeModuleMapNode(allModules);
201 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
203 final Module restconfModule = getRestconfModule();
204 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
205 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
206 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
208 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
209 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
210 moduleContainerBuilder.withChild(allModuleMap);
212 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode, null, schemaContext),
213 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
217 * Valid only for mount point.
220 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
221 Preconditions.checkNotNull(identifier);
222 if (!identifier.contains(ControllerContext.MOUNT)) {
223 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
224 + " URI has to end with " + ControllerContext.MOUNT;
225 LOG.debug("{} for {}", errMsg, identifier);
226 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
229 final InstanceIdentifierContext<?> mountPointIdentifier =
230 this.controllerContext.toMountPointIdentifier(identifier);
231 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
232 final Set<Module> modules = this.controllerContext.getAllModules(mountPoint);
233 final MapNode mountPointModulesMap = makeModuleMapNode(modules);
235 final Module restconfModule = getRestconfModule();
236 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
237 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
238 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
240 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
241 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
242 moduleContainerBuilder.withChild(mountPointModulesMap);
244 return new NormalizedNodeContext(
245 new InstanceIdentifierContext<>(null, modulesSchemaNode, mountPoint,
246 this.controllerContext.getGlobalSchema()),
247 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
251 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
252 Preconditions.checkNotNull(identifier);
253 final Entry<String, Revision> nameRev = getModuleNameAndRevision(identifier);
254 Module module = null;
255 DOMMountPoint mountPoint = null;
256 final SchemaContext schemaContext;
257 if (identifier.contains(ControllerContext.MOUNT)) {
258 final InstanceIdentifierContext<?> mountPointIdentifier =
259 this.controllerContext.toMountPointIdentifier(identifier);
260 mountPoint = mountPointIdentifier.getMountPoint();
261 module = this.controllerContext.findModuleByNameAndRevision(mountPoint, nameRev.getKey(),
263 schemaContext = mountPoint.getSchemaContext();
265 module = this.controllerContext.findModuleByNameAndRevision(nameRev.getKey(), nameRev.getValue());
266 schemaContext = this.controllerContext.getGlobalSchema();
269 if (module == null) {
270 LOG.debug("Module with name '{}' and revision '{}' was not found.", nameRev.getKey(), nameRev.getValue());
271 throw new RestconfDocumentedException("Module with name '" + nameRev.getKey() + "' and revision '"
272 + nameRev.getValue() + "' was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
275 final Module restconfModule = getRestconfModule();
276 final Set<Module> modules = Collections.singleton(module);
277 final MapNode moduleMap = makeModuleMapNode(modules);
279 final DataSchemaNode moduleSchemaNode = this.controllerContext
280 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
281 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
283 return new NormalizedNodeContext(
284 new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint, schemaContext), moduleMap,
285 QueryParametersParser.parseWriterParameters(uriInfo));
289 public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
290 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
291 final Set<String> availableStreams = Notificator.getStreamNames();
292 final Module restconfModule = getRestconfModule();
293 final DataSchemaNode streamSchemaNode = this.controllerContext
294 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
295 Preconditions.checkState(streamSchemaNode instanceof ListSchemaNode);
297 final CollectionNodeBuilder<MapEntryNode, MapNode> listStreamsBuilder =
298 Builders.mapBuilder((ListSchemaNode) streamSchemaNode);
300 for (final String streamName : availableStreams) {
301 listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
304 final DataSchemaNode streamsContainerSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
305 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
306 Preconditions.checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
308 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
309 Builders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
310 streamsContainerBuilder.withChild(listStreamsBuilder.build());
312 return new NormalizedNodeContext(
313 new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null, schemaContext),
314 streamsContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
318 public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
319 return OperationsResourceUtils.contextForModelContext(controllerContext.getGlobalSchema(), null);
323 public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
324 if (!identifier.contains(ControllerContext.MOUNT)) {
325 final String errMsg = "URI has bad format. If operations behind mount point should be showed, URI has to "
326 + " end with " + ControllerContext.MOUNT;
327 LOG.debug("{} for {}", errMsg, identifier);
328 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
331 final InstanceIdentifierContext<?> mountPointIdentifier =
332 this.controllerContext.toMountPointIdentifier(identifier);
333 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
334 return OperationsResourceUtils.contextForModelContext(mountPoint.getSchemaContext(), mountPoint);
337 private Module getRestconfModule() {
338 final Module restconfModule = this.controllerContext.getRestconfModule();
339 if (restconfModule == null) {
340 LOG.debug("ietf-restconf module was not found.");
341 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
342 ErrorTag.OPERATION_NOT_SUPPORTED);
345 return restconfModule;
348 private static Entry<String, Revision> getModuleNameAndRevision(final String identifier) {
349 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
350 String moduleNameAndRevision = "";
351 if (mountIndex >= 0) {
352 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
354 moduleNameAndRevision = identifier;
357 final Splitter splitter = Splitter.on('/').omitEmptyStrings();
358 final List<String> pathArgs = splitter.splitToList(moduleNameAndRevision);
359 if (pathArgs.size() < 2) {
360 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' {}", identifier);
361 throw new RestconfDocumentedException(
362 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
363 ErrorTag.INVALID_VALUE);
367 return new SimpleImmutableEntry<>(pathArgs.get(0), Revision.of(pathArgs.get(1)));
368 } catch (final DateTimeParseException e) {
369 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' {}", identifier);
370 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
371 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
376 public Object getRoot() {
381 public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload,
382 final UriInfo uriInfo) {
383 if (payload == null) {
384 // no payload specified, reroute this to no payload invokeRpc implementation
385 return invokeRpc(identifier, uriInfo);
388 final SchemaPath type = payload.getInstanceIdentifierContext().getSchemaNode().getPath();
389 final URI namespace = payload.getInstanceIdentifierContext().getSchemaNode().getQName().getNamespace();
390 final ListenableFuture<DOMRpcResult> response;
391 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
392 final SchemaContext schemaContext;
394 if (mountPoint != null) {
395 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
396 if (!mountRpcServices.isPresent()) {
397 LOG.debug("Error: Rpc service is missing.");
398 throw new RestconfDocumentedException("Rpc service is missing.");
400 schemaContext = mountPoint.getSchemaContext();
401 response = mountRpcServices.get().invokeRpc(type, payload.getData());
403 if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
404 if (identifier.contains(CREATE_DATA_SUBSCR)) {
405 response = invokeSalRemoteRpcSubscribeRPC(payload);
406 } else if (identifier.contains(CREATE_NOTIFICATION_STREAM)) {
407 response = invokeSalRemoteRpcNotifiStrRPC(payload);
409 final String msg = "Not supported operation";
411 throw new RestconfDocumentedException(msg, ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED);
414 response = this.broker.invokeRpc(type, payload.getData());
416 schemaContext = this.controllerContext.getGlobalSchema();
419 final DOMRpcResult result = checkRpcResponse(response);
421 RpcDefinition resultNodeSchema = null;
422 final NormalizedNode<?, ?> resultData;
423 if (result != null && result.getResult() != null) {
424 resultData = result.getResult();
425 resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
430 if (resultData != null && ((ContainerNode) resultData).getValue().isEmpty()) {
431 throw new WebApplicationException(Response.Status.NO_CONTENT);
433 return new NormalizedNodeContext(
434 new InstanceIdentifierContext<>(null, resultNodeSchema, mountPoint, schemaContext),
435 resultData, QueryParametersParser.parseWriterParameters(uriInfo));
439 private NormalizedNodeContext invokeRpc(final String identifier, final UriInfo uriInfo) {
441 DOMMountPoint mountPoint = null;
442 final String identifierEncoded;
443 final SchemaContext schemaContext;
444 if (identifier.contains(ControllerContext.MOUNT)) {
445 // mounted RPC call - look up mount instance.
446 final InstanceIdentifierContext<?> mountPointId = this.controllerContext.toMountPointIdentifier(identifier);
447 mountPoint = mountPointId.getMountPoint();
448 schemaContext = mountPoint.getSchemaContext();
449 final int startOfRemoteRpcName =
450 identifier.lastIndexOf(ControllerContext.MOUNT) + ControllerContext.MOUNT.length() + 1;
451 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
452 identifierEncoded = remoteRpcName;
454 } else if (identifier.indexOf('/') != CHAR_NOT_FOUND) {
455 LOG.debug("Identifier {} cannot contain slash character (/).", identifier);
456 throw new RestconfDocumentedException(String.format("Identifier %n%s%ncan\'t contain slash character (/).%n"
457 + "If slash is part of identifier name then use %%2F placeholder.", identifier), ErrorType.PROTOCOL,
458 ErrorTag.INVALID_VALUE);
460 identifierEncoded = identifier;
461 schemaContext = this.controllerContext.getGlobalSchema();
464 final String identifierDecoded = ControllerContext.urlPathArgDecode(identifierEncoded);
467 if (mountPoint == null) {
468 rpc = this.controllerContext.getRpcDefinition(identifierDecoded);
470 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
474 LOG.debug("RPC {} does not exist.", identifierDecoded);
475 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
478 if (!rpc.getInput().getChildNodes().isEmpty()) {
479 LOG.debug("No input specified for RPC {} with an input section", rpc);
480 throw new RestconfDocumentedException("No input specified for RPC " + rpc
481 + " with an input section defined", ErrorType.RPC, ErrorTag.MISSING_ELEMENT);
484 final ListenableFuture<DOMRpcResult> response;
485 if (mountPoint != null) {
486 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
487 if (!mountRpcServices.isPresent()) {
488 throw new RestconfDocumentedException("Rpc service is missing.");
490 response = mountRpcServices.get().invokeRpc(rpc.getPath(), null);
492 response = this.broker.invokeRpc(rpc.getPath(), null);
495 final DOMRpcResult result = checkRpcResponse(response);
497 if (result.getResult() != null && ((ContainerNode) result.getResult()).getValue().isEmpty()) {
498 throw new WebApplicationException(Response.Status.NO_CONTENT);
500 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpc, mountPoint, schemaContext),
501 result.getResult(), QueryParametersParser.parseWriterParameters(uriInfo));
505 @SuppressWarnings("checkstyle:avoidHidingCauseException")
506 private static DOMRpcResult checkRpcResponse(final ListenableFuture<DOMRpcResult> response) {
507 if (response == null) {
511 final DOMRpcResult retValue = response.get();
512 if (retValue.getErrors().isEmpty()) {
515 LOG.debug("RpcError message {}", retValue.getErrors());
516 throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
517 } catch (final InterruptedException e) {
518 final String errMsg = "The operation was interrupted while executing and did not complete.";
519 LOG.debug("Rpc Interrupt - {}", errMsg, e);
520 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION, e);
521 } catch (final ExecutionException e) {
522 LOG.debug("Execution RpcError: ", e);
523 Throwable cause = e.getCause();
525 while (cause.getCause() != null) {
526 cause = cause.getCause();
529 if (cause instanceof IllegalArgumentException) {
530 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL,
531 ErrorTag.INVALID_VALUE);
532 } else if (cause instanceof DOMRpcImplementationNotAvailableException) {
533 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.APPLICATION,
534 ErrorTag.OPERATION_NOT_SUPPORTED);
536 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
539 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
542 } catch (final CancellationException e) {
543 final String errMsg = "The operation was cancelled while executing.";
544 LOG.debug("Cancel RpcExecution: {}", errMsg, e);
545 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
549 private static void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
550 if (inputSchema != null && payload.getData() == null) {
551 // expected a non null payload
552 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
553 } else if (inputSchema == null && payload.getData() != null) {
554 // did not expect any input
555 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
559 private ListenableFuture<DOMRpcResult> invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
560 final ContainerNode value = (ContainerNode) payload.getData();
561 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
562 final Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(
563 new NodeIdentifier(QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(),
565 final Object pathValue = path.isPresent() ? path.get().getValue() : null;
567 if (!(pathValue instanceof YangInstanceIdentifier)) {
568 LOG.debug("Instance identifier {} was not normalized correctly", rpcQName);
569 throw new RestconfDocumentedException("Instance identifier was not normalized correctly",
570 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
573 final YangInstanceIdentifier pathIdentifier = (YangInstanceIdentifier) pathValue;
574 String streamName = (String) CREATE_DATA_SUBSCR;
575 NotificationOutputType outputType = null;
576 if (!pathIdentifier.isEmpty()) {
577 final String fullRestconfIdentifier =
578 DATA_SUBSCR + this.controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
580 LogicalDatastoreType datastore =
581 parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
582 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
584 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
585 scope = scope == null ? DEFAULT_SCOPE : scope;
587 outputType = parseEnumTypeParameter(value, NotificationOutputType.class, OUTPUT_TYPE_PARAM_NAME);
588 outputType = outputType == null ? NotificationOutputType.XML : outputType;
590 streamName = Notificator
591 .createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore + "/scope=" + scope);
594 if (Strings.isNullOrEmpty(streamName)) {
595 LOG.debug("Path is empty or contains value node which is not Container or List built-in type at {}",
597 throw new RestconfDocumentedException("Path is empty or contains value node which is not Container or List "
598 + "built-in type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
601 final QName outputQname = QName.create(rpcQName, "output");
602 final QName streamNameQname = QName.create(rpcQName, "stream-name");
604 final ContainerNode output =
605 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
606 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
608 if (!Notificator.existListenerFor(streamName)) {
609 Notificator.createListener(pathIdentifier, streamName, outputType, controllerContext);
612 return Futures.immediateFuture(new DefaultDOMRpcResult(output));
615 private static RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
616 final String[] splittedIdentifier = identifierDecoded.split(":");
617 if (splittedIdentifier.length != 2) {
618 LOG.debug("{} could not be split to 2 parts (module:rpc name)", identifierDecoded);
619 throw new RestconfDocumentedException(identifierDecoded + " could not be split to 2 parts "
620 + "(module:rpc name)", ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
622 for (final Module module : schemaContext.getModules()) {
623 if (module.getName().equals(splittedIdentifier[0])) {
624 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
625 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
626 return rpcDefinition;
635 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
636 boolean withDefaUsed = false;
637 String withDefa = null;
639 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
640 switch (entry.getKey()) {
641 case "with-defaults":
644 withDefa = entry.getValue().iterator().next();
646 throw new RestconfDocumentedException("With-defaults parameter can be used only once.");
650 LOG.info("Unknown key : {}.", entry.getKey());
654 boolean tagged = false;
656 if ("report-all-tagged".equals(withDefa)) {
660 if ("report-all".equals(withDefa)) {
665 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
666 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
667 NormalizedNode<?, ?> data = null;
668 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
669 if (mountPoint != null) {
670 data = this.broker.readConfigurationData(mountPoint, normalizedII, withDefa);
672 data = this.broker.readConfigurationData(normalizedII, withDefa);
675 throw dataMissing(identifier);
677 return new NormalizedNodeContext(iiWithData, data,
678 QueryParametersParser.parseWriterParameters(uriInfo, tagged));
682 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
683 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
684 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
685 NormalizedNode<?, ?> data = null;
686 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
687 if (mountPoint != null) {
688 data = this.broker.readOperationalData(mountPoint, normalizedII);
690 data = this.broker.readOperationalData(normalizedII);
693 throw dataMissing(identifier);
695 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
698 private static RestconfDocumentedException dataMissing(final String identifier) {
699 LOG.debug("Request could not be completed because the relevant data model content does not exist {}",
701 return new RestconfDocumentedException("Request could not be completed because the relevant data model content "
702 + "does not exist", ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
706 public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload,
707 final UriInfo uriInfo) {
708 boolean insertUsed = false;
709 boolean pointUsed = false;
710 String insert = null;
713 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
714 switch (entry.getKey()) {
718 insert = entry.getValue().iterator().next();
720 throw new RestconfDocumentedException("Insert parameter can be used only once.");
726 point = entry.getValue().iterator().next();
728 throw new RestconfDocumentedException("Point parameter can be used only once.");
732 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
736 if (pointUsed && !insertUsed) {
737 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
739 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
740 throw new RestconfDocumentedException(
741 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
744 Preconditions.checkNotNull(identifier);
746 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
748 validateInput(iiWithData.getSchemaNode(), payload);
749 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
750 validateListKeysEqualityInPayloadAndUri(payload);
752 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
753 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
756 * There is a small window where another write transaction could be
757 * updating the same data simultaneously and we get an
758 * OptimisticLockFailedException. This error is likely transient and The
759 * WriteTransaction#submit API docs state that a retry will likely
760 * succeed. So we'll try again if that scenario occurs. If it fails a
761 * third time then it probably will never succeed so we'll fail in that
764 * By retrying we're attempting to hide the internal implementation of
765 * the data store and how it handles concurrent updates from the
766 * restconf client. The client has instructed us to put the data and we
767 * should make every effort to do so without pushing optimistic lock
768 * failures back to the client and forcing them to handle it via retry
769 * (and having to document the behavior).
771 PutResult result = null;
774 if (mountPoint != null) {
776 result = this.broker.commitMountPointDataPut(mountPoint, normalizedII, payload.getData(), insert,
779 result = this.broker.commitConfigurationDataPut(this.controllerContext.getGlobalSchema(), normalizedII,
780 payload.getData(), insert, point);
784 result.getFutureOfPutData().get();
785 } catch (final InterruptedException e) {
786 LOG.debug("Update failed for {}", identifier, e);
787 throw new RestconfDocumentedException(e.getMessage(), e);
788 } catch (final ExecutionException e) {
789 final TransactionCommitFailedException failure = Throwables.getCauseAs(e,
790 TransactionCommitFailedException.class);
791 if (failure instanceof OptimisticLockFailedException) {
793 LOG.debug("Got OptimisticLockFailedException on last try - failing {}", identifier);
794 throw new RestconfDocumentedException(e.getMessage(), e, failure.getErrorList());
797 LOG.debug("Got OptimisticLockFailedException - trying again {}", identifier);
801 LOG.debug("Update failed for {}", identifier, e);
802 throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), failure);
805 return Response.status(result.getStatus()).build();
809 private static void validateTopLevelNodeName(final NormalizedNodeContext node,
810 final YangInstanceIdentifier identifier) {
812 final String payloadName = node.getData().getNodeType().getLocalName();
815 if (identifier.isEmpty()) {
817 if (!node.getData().getNodeType().equals(NETCONF_BASE_QNAME)) {
818 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
819 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
823 final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
824 if (!payloadName.equals(identifierName)) {
825 throw new RestconfDocumentedException(
826 "Payload name (" + payloadName + ") is different from identifier name (" + identifierName + ")",
827 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
833 * Validates whether keys in {@code payload} are equal to values of keys in
834 * {@code iiWithData} for list schema node.
836 * @throws RestconfDocumentedException
837 * if key values or key count in payload and URI isn't equal
840 private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
841 Preconditions.checkArgument(payload != null);
842 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
843 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
844 final SchemaNode schemaNode = iiWithData.getSchemaNode();
845 final NormalizedNode<?, ?> data = payload.getData();
846 if (schemaNode instanceof ListSchemaNode) {
847 final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
848 if (lastPathArgument instanceof NodeIdentifierWithPredicates && data instanceof MapEntryNode) {
849 final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument).asMap();
850 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
856 public static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final MapEntryNode payload,
857 final List<QName> keyDefinitions) {
859 final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
860 for (final QName keyDefinition : keyDefinitions) {
861 final Object uriKeyValue = RestconfDocumentedException.throwIfNull(
862 // should be caught during parsing URI to InstanceIdentifier
863 mutableCopyUriKeyValues.remove(keyDefinition), ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
864 "Missing key %s in URI.", keyDefinition);
866 final Object dataKeyValue = payload.getIdentifier().getValue(keyDefinition);
868 if (!Objects.deepEquals(uriKeyValue, dataKeyValue)) {
869 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName()
870 + "' specified in the URI doesn't match the value '" + dataKeyValue
871 + "' specified in the message body. ";
872 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
878 public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload,
879 final UriInfo uriInfo) {
880 return createConfigurationData(payload, uriInfo);
884 public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
885 if (payload == null) {
886 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
888 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
889 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
890 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
892 boolean insertUsed = false;
893 boolean pointUsed = false;
894 String insert = null;
897 if (uriInfo != null) {
898 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
899 switch (entry.getKey()) {
903 insert = entry.getValue().iterator().next();
905 throw new RestconfDocumentedException("Insert parameter can be used only once.");
911 point = entry.getValue().iterator().next();
913 throw new RestconfDocumentedException("Point parameter can be used only once.");
917 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
922 if (pointUsed && !insertUsed) {
923 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
925 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
926 throw new RestconfDocumentedException(
927 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
930 FluentFuture<? extends CommitInfo> future;
931 if (mountPoint != null) {
932 future = this.broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData(), insert,
935 future = this.broker.commitConfigurationDataPost(this.controllerContext.getGlobalSchema(), normalizedII,
936 payload.getData(), insert, point);
941 } catch (final InterruptedException e) {
942 LOG.info("Error creating data {}", uriInfo != null ? uriInfo.getPath() : "", e);
943 throw new RestconfDocumentedException(e.getMessage(), e);
944 } catch (final ExecutionException e) {
945 LOG.info("Error creating data {}", uriInfo != null ? uriInfo.getPath() : "", e);
946 throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), Throwables.getCauseAs(e,
947 TransactionCommitFailedException.class));
950 LOG.trace("Successfuly created data.");
952 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
953 // FIXME: Provide path to result.
954 final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
955 if (location != null) {
956 responseBuilder.location(location);
958 return responseBuilder.build();
961 @SuppressWarnings("checkstyle:IllegalCatch")
962 private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint,
963 final YangInstanceIdentifier normalizedII) {
964 if (uriInfo == null) {
965 // This is null if invoked internally
969 final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
970 uriBuilder.path("config");
972 uriBuilder.path(this.controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
973 } catch (final Exception e) {
974 LOG.info("Location for instance identifier {} was not created", normalizedII, e);
977 return uriBuilder.build();
981 public Response deleteConfigurationData(final String identifier) {
982 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
983 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
984 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
986 final FluentFuture<? extends CommitInfo> future;
987 if (mountPoint != null) {
988 future = this.broker.commitConfigurationDataDelete(mountPoint, normalizedII);
990 future = this.broker.commitConfigurationDataDelete(normalizedII);
995 } catch (final InterruptedException e) {
996 throw new RestconfDocumentedException(e.getMessage(), e);
997 } catch (final ExecutionException e) {
998 final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
999 Predicates.instanceOf(ModifiedNodeDoesNotExistException.class)).toJavaUtil();
1000 if (searchedException.isPresent()) {
1001 throw new RestconfDocumentedException("Data specified for delete doesn't exist.", ErrorType.APPLICATION,
1002 ErrorTag.DATA_MISSING, e);
1005 throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), Throwables.getCauseAs(e,
1006 TransactionCommitFailedException.class));
1009 return Response.status(Status.OK).build();
1013 * Subscribes to some path in schema context (stream) to listen on changes
1017 * Additional parameters for subscribing to stream are loaded via rpc input
1020 * <li>datastore - default CONFIGURATION (other values of
1021 * {@link LogicalDatastoreType} enum type)</li>
1022 * <li>scope - default BASE (other values of {@link DataChangeScope})</li>
1026 public NormalizedNodeContext subscribeToStream(final String identifier, final UriInfo uriInfo) {
1027 boolean startTimeUsed = false;
1028 boolean stopTimeUsed = false;
1029 Instant start = Instant.now();
1030 Instant stop = null;
1031 boolean filterUsed = false;
1032 String filter = null;
1033 boolean leafNodesOnlyUsed = false;
1034 boolean leafNodesOnly = false;
1036 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
1037 switch (entry.getKey()) {
1039 if (!startTimeUsed) {
1040 startTimeUsed = true;
1041 start = parseDateFromQueryParam(entry);
1043 throw new RestconfDocumentedException("Start-time parameter can be used only once.");
1047 if (!stopTimeUsed) {
1048 stopTimeUsed = true;
1049 stop = parseDateFromQueryParam(entry);
1051 throw new RestconfDocumentedException("Stop-time parameter can be used only once.");
1057 filter = entry.getValue().iterator().next();
1059 throw new RestconfDocumentedException("Filter parameter can be used only once.");
1062 case "odl-leaf-nodes-only":
1063 if (!leafNodesOnlyUsed) {
1064 leafNodesOnlyUsed = true;
1065 leafNodesOnly = Boolean.parseBoolean(entry.getValue().iterator().next());
1067 throw new RestconfDocumentedException("Odl-leaf-nodes-only parameter can be used only once.");
1071 throw new RestconfDocumentedException("Bad parameter used with notifications: " + entry.getKey());
1074 if (!startTimeUsed && stopTimeUsed) {
1075 throw new RestconfDocumentedException("Stop-time parameter has to be used with start-time parameter.");
1077 URI response = null;
1078 if (identifier.contains(DATA_SUBSCR)) {
1079 response = dataSubs(identifier, uriInfo, start, stop, filter, leafNodesOnly);
1080 } else if (identifier.contains(NOTIFICATION_STREAM)) {
1081 response = notifStream(identifier, uriInfo, start, stop, filter);
1084 if (response != null) {
1085 // prepare node with value of location
1086 final InstanceIdentifierContext<?> iid = prepareIIDSubsStreamOutput();
1087 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> builder =
1088 ImmutableLeafNodeBuilder.create().withValue(response.toString());
1089 builder.withNodeIdentifier(
1090 NodeIdentifier.create(QName.create("subscribe:to:notification", "2016-10-28", "location")));
1092 // prepare new header with location
1093 final Map<String, Object> headers = new HashMap<>();
1094 headers.put("Location", response);
1096 return new NormalizedNodeContext(iid, builder.build(), headers);
1099 final String msg = "Bad type of notification of sal-remote";
1101 throw new RestconfDocumentedException(msg);
1104 private static Instant parseDateFromQueryParam(final Entry<String, List<String>> entry) {
1105 final DateAndTime event = new DateAndTime(entry.getValue().iterator().next());
1106 final String value = event.getValue();
1107 final TemporalAccessor p;
1109 p = FORMATTER.parse(value);
1110 } catch (final DateTimeParseException e) {
1111 throw new RestconfDocumentedException("Cannot parse of value in date: " + value, e);
1113 return Instant.from(p);
1117 * Prepare instance identifier.
1119 * @return {@link InstanceIdentifierContext} of location leaf for
1122 private InstanceIdentifierContext<?> prepareIIDSubsStreamOutput() {
1123 final QName qnameBase = QName.create("subscribe:to:notification", "2016-10-28", "notifi");
1124 final SchemaContext schemaCtx = controllerContext.getGlobalSchema();
1125 final DataSchemaNode location = ((ContainerSchemaNode) schemaCtx
1126 .findModule(qnameBase.getModule()).orElse(null)
1127 .getDataChildByName(qnameBase)).getDataChildByName(QName.create(qnameBase, "location"));
1128 final List<PathArgument> path = new ArrayList<>();
1129 path.add(NodeIdentifier.create(qnameBase));
1130 path.add(NodeIdentifier.create(QName.create(qnameBase, "location")));
1132 return new InstanceIdentifierContext<SchemaNode>(YangInstanceIdentifier.create(path), location, null,
1137 * Register notification listener by stream name.
1144 * stop-time of getting notification
1146 * start-time of getting notification
1148 * indicate which subset of all possible events are of interest
1149 * @return {@link URI} of location
1151 private URI notifStream(final String identifier, final UriInfo uriInfo, final Instant start,
1152 final Instant stop, final String filter) {
1153 final String streamName = Notificator.createStreamNameFromUri(identifier);
1154 if (Strings.isNullOrEmpty(streamName)) {
1155 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1157 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
1158 if (listeners == null || listeners.isEmpty()) {
1159 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1160 ErrorTag.UNKNOWN_ELEMENT);
1163 for (final NotificationListenerAdapter listener : listeners) {
1164 this.broker.registerToListenNotification(listener);
1165 listener.setQueryParams(start, Optional.ofNullable(stop), Optional.ofNullable(filter), false);
1168 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1170 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance(NOTIFICATION_PORT);
1171 final int notificationPort = webSocketServerInstance.getPort();
1174 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme(getWsScheme(uriInfo));
1176 return uriToWebsocketServerBuilder.replacePath(streamName).build();
1179 private static String getWsScheme(final UriInfo uriInfo) {
1180 URI uri = uriInfo.getAbsolutePath();
1184 String subscriptionScheme = uri.getScheme().toLowerCase(Locale.ROOT);
1185 return subscriptionScheme.equals("https") ? "wss" : "ws";
1189 * Register data change listener by stream name.
1196 * start-time of getting notification
1198 * stop-time of getting notification
1200 * indicate which subset of all possible events are of interest
1201 * @return {@link URI} of location
1203 private URI dataSubs(final String identifier, final UriInfo uriInfo, final Instant start, final Instant stop,
1204 final String filter, final boolean leafNodesOnly) {
1205 final String streamName = Notificator.createStreamNameFromUri(identifier);
1206 if (Strings.isNullOrEmpty(streamName)) {
1207 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1210 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1211 if (listener == null) {
1212 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1213 ErrorTag.UNKNOWN_ELEMENT);
1215 listener.setQueryParams(start, Optional.ofNullable(stop), Optional.ofNullable(filter), leafNodesOnly);
1217 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1218 final LogicalDatastoreType datastore =
1219 parserURIEnumParameter(LogicalDatastoreType.class, paramToValues.get(DATASTORE_PARAM_NAME));
1220 if (datastore == null) {
1221 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1222 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1224 final DataChangeScope scope =
1225 parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
1226 if (scope == null) {
1227 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1228 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1231 this.broker.registerToListenDataChanges(datastore, scope, listener);
1233 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1235 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance(NOTIFICATION_PORT);
1236 final int notificationPort = webSocketServerInstance.getPort();
1238 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme(getWsScheme(uriInfo));
1240 return uriToWebsocketServerBuilder.replacePath(streamName).build();
1243 @SuppressWarnings("checkstyle:IllegalCatch")
1245 public PatchStatusContext patchConfigurationData(final String identifier, final PatchContext context,
1246 final UriInfo uriInfo) {
1247 if (context == null) {
1248 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1252 return this.broker.patchConfigurationDataWithinTransaction(context);
1253 } catch (final Exception e) {
1254 LOG.debug("Patch transaction failed", e);
1255 throw new RestconfDocumentedException(e.getMessage(), e);
1259 @SuppressWarnings("checkstyle:IllegalCatch")
1261 public PatchStatusContext patchConfigurationData(final PatchContext context, @Context final UriInfo uriInfo) {
1262 if (context == null) {
1263 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1267 return this.broker.patchConfigurationDataWithinTransaction(context);
1268 } catch (final Exception e) {
1269 LOG.debug("Patch transaction failed", e);
1270 throw new RestconfDocumentedException(e.getMessage(), e);
1275 * Load parameter for subscribing to stream from input composite node.
1279 * @return enum object if its string value is equal to {@code paramName}. In
1282 private static <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1283 final String paramName) {
1284 final Optional<DataContainerChild<? extends PathArgument, ?>> optAugNode = value.getChild(
1285 SAL_REMOTE_AUG_IDENTIFIER);
1286 if (!optAugNode.isPresent()) {
1289 final DataContainerChild<? extends PathArgument, ?> augNode = optAugNode.get();
1290 if (!(augNode instanceof AugmentationNode)) {
1293 final Optional<DataContainerChild<? extends PathArgument, ?>> enumNode = ((AugmentationNode) augNode).getChild(
1294 new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1295 if (!enumNode.isPresent()) {
1298 final Object rawValue = enumNode.get().getValue();
1299 if (!(rawValue instanceof String)) {
1303 return resolveAsEnum(classDescriptor, (String) rawValue);
1307 * Checks whether {@code value} is one of the string representation of
1308 * enumeration {@code classDescriptor}.
1310 * @return enum object if string value of {@code classDescriptor}
1311 * enumeration is equal to {@code value}. Other cases null.
1313 private static <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1314 if (Strings.isNullOrEmpty(value)) {
1317 return resolveAsEnum(classDescriptor, value);
1320 private static <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1321 final T[] enumConstants = classDescriptor.getEnumConstants();
1322 if (enumConstants != null) {
1323 for (final T enm : classDescriptor.getEnumConstants()) {
1324 if (((Enum<?>) enm).name().equals(value)) {
1332 private static Map<String, String> resolveValuesFromUri(final String uri) {
1333 final Map<String, String> result = new HashMap<>();
1334 final String[] tokens = uri.split("/");
1335 for (int i = 1; i < tokens.length; i++) {
1336 final String[] parameterTokens = tokens[i].split("=");
1337 if (parameterTokens.length == 2) {
1338 result.put(parameterTokens[0], parameterTokens[1]);
1344 private MapNode makeModuleMapNode(final Set<Module> modules) {
1345 Preconditions.checkNotNull(modules);
1346 final Module restconfModule = getRestconfModule();
1347 final DataSchemaNode moduleSchemaNode = this.controllerContext
1348 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1349 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1351 final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder =
1352 Builders.mapBuilder((ListSchemaNode) moduleSchemaNode);
1354 for (final Module module : modules) {
1355 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1357 return listModuleBuilder.build();
1360 private MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1361 Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1362 "moduleSchemaNode has to be of type ListSchemaNode");
1363 final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1364 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues =
1365 Builders.mapEntryBuilder(listModuleSchemaNode);
1367 List<DataSchemaNode> instanceDataChildrenByName =
1368 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "name");
1369 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1370 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1372 .withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName()).build());
1374 final QNameModule qNameModule = module.getQNameModule();
1376 instanceDataChildrenByName =
1377 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "revision");
1378 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1379 Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1380 final Optional<Revision> revision = qNameModule.getRevision();
1381 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode)
1382 .withValue(revision.map(Revision::toString).orElse("")).build());
1384 instanceDataChildrenByName =
1385 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "namespace");
1386 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1387 Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1388 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1389 .withValue(qNameModule.getNamespace().toString()).build());
1391 instanceDataChildrenByName =
1392 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "feature");
1393 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1394 Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1395 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder =
1396 Builders.leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1397 for (final FeatureDefinition feature : module.getFeatures()) {
1398 featuresBuilder.withChild(Builders.leafSetEntryBuilder((LeafListSchemaNode) featureSchemaNode)
1399 .withValue(feature.getQName().getLocalName()).build());
1401 moduleNodeValues.withChild(featuresBuilder.build());
1403 return moduleNodeValues.build();
1406 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1407 Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1408 "streamSchemaNode has to be of type ListSchemaNode");
1409 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1410 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues =
1411 Builders.mapEntryBuilder(listStreamSchemaNode);
1413 List<DataSchemaNode> instanceDataChildrenByName =
1414 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "name");
1415 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1416 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1417 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName).build());
1419 instanceDataChildrenByName =
1420 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "description");
1421 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1422 Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1423 streamNodeValues.withChild(
1424 Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue("DESCRIPTION_PLACEHOLDER").build());
1426 instanceDataChildrenByName =
1427 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-support");
1428 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1429 Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1430 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1431 .withValue(Boolean.TRUE).build());
1433 instanceDataChildrenByName =
1434 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-log-creation-time");
1435 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1436 Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1437 streamNodeValues.withChild(
1438 Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode).withValue("").build());
1440 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "events");
1441 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1442 Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1443 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode).build());
1445 return streamNodeValues.build();
1449 * Prepare stream for notification.
1452 * contains list of qnames of notifications
1453 * @return - checked future object
1455 private ListenableFuture<DOMRpcResult> invokeSalRemoteRpcNotifiStrRPC(final NormalizedNodeContext payload) {
1456 final ContainerNode data = (ContainerNode) payload.getData();
1457 LeafSetNode leafSet = null;
1458 String outputType = "XML";
1459 for (final DataContainerChild<? extends PathArgument, ?> dataChild : data.getValue()) {
1460 if (dataChild instanceof LeafSetNode) {
1461 leafSet = (LeafSetNode) dataChild;
1462 } else if (dataChild instanceof AugmentationNode) {
1463 outputType = (String) ((AugmentationNode) dataChild).getValue().iterator().next().getValue();
1467 final Collection<LeafSetEntryNode> entryNodes = leafSet.getValue();
1468 final List<SchemaPath> paths = new ArrayList<>();
1469 String streamName = CREATE_NOTIFICATION_STREAM + "/";
1471 StringBuilder streamNameBuilder = new StringBuilder(streamName);
1472 final Iterator<LeafSetEntryNode> iterator = entryNodes.iterator();
1473 while (iterator.hasNext()) {
1474 final QName valueQName = QName.create((String) iterator.next().getValue());
1475 final Module module = controllerContext.findModuleByNamespace(valueQName.getModule().getNamespace());
1476 Preconditions.checkNotNull(module,
1477 "Module for namespace " + valueQName.getModule().getNamespace() + " does not exist");
1478 NotificationDefinition notifiDef = null;
1479 for (final NotificationDefinition notification : module.getNotifications()) {
1480 if (notification.getQName().equals(valueQName)) {
1481 notifiDef = notification;
1485 final String moduleName = module.getName();
1486 Preconditions.checkNotNull(notifiDef,
1487 "Notification " + valueQName + "doesn't exist in module " + moduleName);
1488 paths.add(notifiDef.getPath());
1489 streamNameBuilder.append(moduleName).append(':').append(valueQName.getLocalName());
1490 if (iterator.hasNext()) {
1491 streamNameBuilder.append(',');
1495 streamName = streamNameBuilder.toString();
1497 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
1498 final QName outputQname = QName.create(rpcQName, "output");
1499 final QName streamNameQname = QName.create(rpcQName, "notification-stream-identifier");
1501 final ContainerNode output =
1502 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
1503 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
1505 if (!Notificator.existNotificationListenerFor(streamName)) {
1506 Notificator.createNotificationListener(paths, streamName, outputType, controllerContext);
1509 return Futures.immediateFuture(new DefaultDOMRpcResult(output));