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;
22 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
24 import java.time.Instant;
25 import java.time.format.DateTimeFormatter;
26 import java.time.format.DateTimeFormatterBuilder;
27 import java.time.format.DateTimeParseException;
28 import java.time.temporal.ChronoField;
29 import java.time.temporal.TemporalAccessor;
30 import java.util.AbstractMap.SimpleImmutableEntry;
31 import java.util.ArrayList;
32 import java.util.Collection;
33 import java.util.Collections;
34 import java.util.HashMap;
35 import java.util.Iterator;
36 import java.util.List;
37 import java.util.Locale;
39 import java.util.Map.Entry;
40 import java.util.Objects;
41 import java.util.Optional;
43 import java.util.concurrent.CancellationException;
44 import java.util.concurrent.ExecutionException;
45 import javax.inject.Inject;
46 import javax.inject.Singleton;
47 import javax.ws.rs.WebApplicationException;
48 import javax.ws.rs.core.Context;
49 import javax.ws.rs.core.Response;
50 import javax.ws.rs.core.Response.ResponseBuilder;
51 import javax.ws.rs.core.Response.Status;
52 import javax.ws.rs.core.UriBuilder;
53 import javax.ws.rs.core.UriInfo;
54 import org.opendaylight.mdsal.common.api.CommitInfo;
55 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
56 import org.opendaylight.mdsal.common.api.OptimisticLockFailedException;
57 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
58 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
59 import org.opendaylight.mdsal.dom.api.DOMRpcImplementationNotAvailableException;
60 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
61 import org.opendaylight.mdsal.dom.api.DOMRpcService;
62 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
63 import org.opendaylight.netconf.sal.rest.api.Draft02;
64 import org.opendaylight.netconf.sal.rest.api.RestconfService;
65 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
66 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
67 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
68 import org.opendaylight.netconf.sal.streams.websockets.WebSocketServer;
69 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
70 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
71 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
72 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
73 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
74 import org.opendaylight.restconf.common.patch.PatchContext;
75 import org.opendaylight.restconf.common.patch.PatchStatusContext;
76 import org.opendaylight.restconf.common.util.DataChangeScope;
77 import org.opendaylight.restconf.common.util.OperationsResourceUtils;
78 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
79 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
80 import org.opendaylight.yangtools.yang.common.QName;
81 import org.opendaylight.yangtools.yang.common.QNameModule;
82 import org.opendaylight.yangtools.yang.common.Revision;
83 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
84 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
85 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
86 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
87 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
88 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
89 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
90 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
91 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
92 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
93 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
94 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
95 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
96 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
97 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
98 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
99 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
100 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
101 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
102 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
103 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeBuilder;
104 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
105 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
106 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
107 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
108 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
109 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
110 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
111 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
112 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
113 import org.opendaylight.yangtools.yang.model.api.Module;
114 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
115 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
116 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
117 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
118 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
119 import org.slf4j.Logger;
120 import org.slf4j.LoggerFactory;
123 public final class RestconfImpl implements RestconfService {
125 * Notifications are served on port 8181.
127 private static final int NOTIFICATION_PORT = 8181;
129 private static final int CHAR_NOT_FOUND = -1;
131 private static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
133 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
135 private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
137 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
139 private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
141 private static final String DATASTORE_PARAM_NAME = "datastore";
143 private static final String SCOPE_PARAM_NAME = "scope";
145 private static final String OUTPUT_TYPE_PARAM_NAME = "notification-output-type";
147 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
149 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
151 private static final QName NETCONF_BASE_QNAME = QName.create(QNameModule.create(URI.create(NETCONF_BASE)),
152 NETCONF_BASE_PAYLOAD_NAME).intern();
154 private static final QNameModule SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
155 Revision.of("2014-07-08"));
157 private static final AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER =
158 new AugmentationIdentifier(ImmutableSet.of(
159 QName.create(SAL_REMOTE_AUGMENT, "scope"), QName.create(SAL_REMOTE_AUGMENT, "datastore"),
160 QName.create(SAL_REMOTE_AUGMENT, "notification-output-type")));
162 public static final CharSequence DATA_SUBSCR = "data-change-event-subscription";
163 private static final CharSequence CREATE_DATA_SUBSCR = "create-" + DATA_SUBSCR;
165 public static final CharSequence NOTIFICATION_STREAM = "notification-stream";
166 private static final CharSequence CREATE_NOTIFICATION_STREAM = "create-" + NOTIFICATION_STREAM;
168 private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
169 .appendValue(ChronoField.YEAR, 4).appendLiteral('-')
170 .appendValue(ChronoField.MONTH_OF_YEAR, 2).appendLiteral('-')
171 .appendValue(ChronoField.DAY_OF_MONTH, 2).appendLiteral('T')
172 .appendValue(ChronoField.HOUR_OF_DAY, 2).appendLiteral(':')
173 .appendValue(ChronoField.MINUTE_OF_HOUR, 2).appendLiteral(':')
174 .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
175 .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
176 .appendOffset("+HH:MM", "Z").toFormatter();
178 private final BrokerFacade broker;
180 private final ControllerContext controllerContext;
183 public RestconfImpl(final BrokerFacade broker, final ControllerContext controllerContext) {
184 this.broker = broker;
185 this.controllerContext = controllerContext;
191 * @deprecated Just use {@link #RestconfImpl(BrokerFacade, ControllerContext)} constructor instead.
194 public static RestconfImpl newInstance(final BrokerFacade broker, final ControllerContext controllerContext) {
195 return new RestconfImpl(broker, controllerContext);
199 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
200 final MapNode allModuleMap = makeModuleMapNode(controllerContext.getAllModules());
202 final EffectiveModelContext schemaContext = this.controllerContext.getGlobalSchema();
204 final Module restconfModule = getRestconfModule();
205 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
206 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
207 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
209 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
210 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
211 moduleContainerBuilder.withChild(allModuleMap);
213 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode, null, schemaContext),
214 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
218 * Valid only for mount point.
221 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
222 Preconditions.checkNotNull(identifier);
223 if (!identifier.contains(ControllerContext.MOUNT)) {
224 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
225 + " URI has to end with " + ControllerContext.MOUNT;
226 LOG.debug("{} for {}", errMsg, identifier);
227 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
230 final InstanceIdentifierContext<?> mountPointIdentifier =
231 this.controllerContext.toMountPointIdentifier(identifier);
232 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
233 final MapNode mountPointModulesMap = makeModuleMapNode(controllerContext.getAllModules(mountPoint));
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 EffectiveModelContext 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.getEffectiveModelContext();
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 EffectiveModelContext 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<? extends DOMRpcResult> response;
391 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
392 final EffectiveModelContext 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.getEffectiveModelContext();
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 @SuppressFBWarnings(value = "NP_LOAD_OF_KNOWN_NULL_VALUE",
440 justification = "Looks like a false positive, see below FIXME")
441 private NormalizedNodeContext invokeRpc(final String identifier, final UriInfo uriInfo) {
442 final DOMMountPoint mountPoint;
443 final String identifierEncoded;
444 final EffectiveModelContext schemaContext;
445 if (identifier.contains(ControllerContext.MOUNT)) {
446 // mounted RPC call - look up mount instance.
447 final InstanceIdentifierContext<?> mountPointId = this.controllerContext.toMountPointIdentifier(identifier);
448 mountPoint = mountPointId.getMountPoint();
449 schemaContext = mountPoint.getEffectiveModelContext();
450 final int startOfRemoteRpcName =
451 identifier.lastIndexOf(ControllerContext.MOUNT) + ControllerContext.MOUNT.length() + 1;
452 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
453 identifierEncoded = remoteRpcName;
455 } else if (identifier.indexOf('/') == CHAR_NOT_FOUND) {
456 identifierEncoded = identifier;
458 schemaContext = this.controllerContext.getGlobalSchema();
460 LOG.debug("Identifier {} cannot contain slash character (/).", identifier);
461 throw new RestconfDocumentedException(String.format("Identifier %n%s%ncan\'t contain slash character (/).%n"
462 + "If slash is part of identifier name then use %%2F placeholder.", identifier), ErrorType.PROTOCOL,
463 ErrorTag.INVALID_VALUE);
466 final String identifierDecoded = ControllerContext.urlPathArgDecode(identifierEncoded);
467 final RpcDefinition rpc;
468 if (mountPoint == null) {
469 rpc = this.controllerContext.getRpcDefinition(identifierDecoded);
471 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
475 LOG.debug("RPC {} does not exist.", identifierDecoded);
476 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
479 if (!rpc.getInput().getChildNodes().isEmpty()) {
480 LOG.debug("No input specified for RPC {} with an input section", rpc);
481 throw new RestconfDocumentedException("No input specified for RPC " + rpc
482 + " with an input section defined", ErrorType.RPC, ErrorTag.MISSING_ELEMENT);
485 final ListenableFuture<? extends DOMRpcResult> response;
486 if (mountPoint != null) {
487 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
488 if (!mountRpcServices.isPresent()) {
489 throw new RestconfDocumentedException("Rpc service is missing.");
491 response = mountRpcServices.get().invokeRpc(rpc.getPath(), null);
493 response = this.broker.invokeRpc(rpc.getPath(), null);
496 final NormalizedNode<?, ?> result = checkRpcResponse(response).getResult();
497 if (result != null && ((ContainerNode) result).getValue().isEmpty()) {
498 throw new WebApplicationException(Response.Status.NO_CONTENT);
501 // FIXME: in reference to the above @SupressFBWarnings: "mountPoint" reference here trips up SpotBugs, as it
502 // thinks it can only ever be null. Except it can very much be non-null. The core problem is the horrible
503 // structure of this code where we have a sh*tload of checks for mountpoint above and all over the
504 // codebase where all that difference should have been properly encapsulated.
506 // This is legacy code, so if anybody cares to do that refactor, feel free to contribute, but I am not
508 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpc, mountPoint, schemaContext), result,
509 QueryParametersParser.parseWriterParameters(uriInfo));
512 @SuppressWarnings("checkstyle:avoidHidingCauseException")
513 private static DOMRpcResult checkRpcResponse(final ListenableFuture<? extends DOMRpcResult> response) {
514 if (response == null) {
518 final DOMRpcResult retValue = response.get();
519 if (retValue.getErrors().isEmpty()) {
522 LOG.debug("RpcError message {}", retValue.getErrors());
523 throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
524 } catch (final InterruptedException e) {
525 final String errMsg = "The operation was interrupted while executing and did not complete.";
526 LOG.debug("Rpc Interrupt - {}", errMsg, e);
527 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION, e);
528 } catch (final ExecutionException e) {
529 LOG.debug("Execution RpcError: ", e);
530 Throwable cause = e.getCause();
532 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
535 while (cause.getCause() != null) {
536 cause = cause.getCause();
539 if (cause instanceof IllegalArgumentException) {
540 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
541 } else if (cause instanceof DOMRpcImplementationNotAvailableException) {
542 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.APPLICATION,
543 ErrorTag.OPERATION_NOT_SUPPORTED);
545 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
547 } catch (final CancellationException e) {
548 final String errMsg = "The operation was cancelled while executing.";
549 LOG.debug("Cancel RpcExecution: {}", errMsg, e);
550 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
554 private static void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
555 if (inputSchema != null && payload.getData() == null) {
556 // expected a non null payload
557 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
558 } else if (inputSchema == null && payload.getData() != null) {
559 // did not expect any input
560 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
564 private ListenableFuture<DOMRpcResult> invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
565 final ContainerNode value = (ContainerNode) payload.getData();
566 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
567 final Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(
568 new NodeIdentifier(QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(),
570 final Object pathValue = path.isPresent() ? path.get().getValue() : null;
572 if (!(pathValue instanceof YangInstanceIdentifier)) {
573 LOG.debug("Instance identifier {} was not normalized correctly", rpcQName);
574 throw new RestconfDocumentedException("Instance identifier was not normalized correctly",
575 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
578 final YangInstanceIdentifier pathIdentifier = (YangInstanceIdentifier) pathValue;
579 String streamName = (String) CREATE_DATA_SUBSCR;
580 NotificationOutputType outputType = null;
581 if (!pathIdentifier.isEmpty()) {
582 final String fullRestconfIdentifier =
583 DATA_SUBSCR + this.controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
585 LogicalDatastoreType datastore =
586 parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
587 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
589 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
590 scope = scope == null ? DEFAULT_SCOPE : scope;
592 outputType = parseEnumTypeParameter(value, NotificationOutputType.class, OUTPUT_TYPE_PARAM_NAME);
593 outputType = outputType == null ? NotificationOutputType.XML : outputType;
595 streamName = Notificator
596 .createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore + "/scope=" + scope);
599 if (Strings.isNullOrEmpty(streamName)) {
600 LOG.debug("Path is empty or contains value node which is not Container or List built-in type at {}",
602 throw new RestconfDocumentedException("Path is empty or contains value node which is not Container or List "
603 + "built-in type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
606 final QName outputQname = QName.create(rpcQName, "output");
607 final QName streamNameQname = QName.create(rpcQName, "stream-name");
609 final ContainerNode output =
610 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
611 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
613 if (!Notificator.existListenerFor(streamName)) {
614 Notificator.createListener(pathIdentifier, streamName, outputType, controllerContext);
617 return Futures.immediateFuture(new DefaultDOMRpcResult(output));
620 private static RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
621 final String[] splittedIdentifier = identifierDecoded.split(":");
622 if (splittedIdentifier.length != 2) {
623 LOG.debug("{} could not be split to 2 parts (module:rpc name)", identifierDecoded);
624 throw new RestconfDocumentedException(identifierDecoded + " could not be split to 2 parts "
625 + "(module:rpc name)", ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
627 for (final Module module : schemaContext.getModules()) {
628 if (module.getName().equals(splittedIdentifier[0])) {
629 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
630 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
631 return rpcDefinition;
640 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
641 boolean withDefaUsed = false;
642 String withDefa = null;
644 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
645 switch (entry.getKey()) {
646 case "with-defaults":
649 withDefa = entry.getValue().iterator().next();
651 throw new RestconfDocumentedException("With-defaults parameter can be used only once.");
655 LOG.info("Unknown key : {}.", entry.getKey());
659 boolean tagged = false;
661 if ("report-all-tagged".equals(withDefa)) {
665 if ("report-all".equals(withDefa)) {
670 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
671 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
672 NormalizedNode<?, ?> data = null;
673 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
674 if (mountPoint != null) {
675 data = this.broker.readConfigurationData(mountPoint, normalizedII, withDefa);
677 data = this.broker.readConfigurationData(normalizedII, withDefa);
680 throw dataMissing(identifier);
682 return new NormalizedNodeContext(iiWithData, data,
683 QueryParametersParser.parseWriterParameters(uriInfo, tagged));
687 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
688 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
689 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
690 NormalizedNode<?, ?> data = null;
691 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
692 if (mountPoint != null) {
693 data = this.broker.readOperationalData(mountPoint, normalizedII);
695 data = this.broker.readOperationalData(normalizedII);
698 throw dataMissing(identifier);
700 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
703 private static RestconfDocumentedException dataMissing(final String identifier) {
704 LOG.debug("Request could not be completed because the relevant data model content does not exist {}",
706 return new RestconfDocumentedException("Request could not be completed because the relevant data model content "
707 + "does not exist", ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
711 public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload,
712 final UriInfo uriInfo) {
713 boolean insertUsed = false;
714 boolean pointUsed = false;
715 String insert = null;
718 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
719 switch (entry.getKey()) {
723 insert = entry.getValue().iterator().next();
725 throw new RestconfDocumentedException("Insert parameter can be used only once.");
731 point = entry.getValue().iterator().next();
733 throw new RestconfDocumentedException("Point parameter can be used only once.");
737 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
741 if (pointUsed && !insertUsed) {
742 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
744 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
745 throw new RestconfDocumentedException(
746 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
749 Preconditions.checkNotNull(identifier);
751 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
753 validateInput(iiWithData.getSchemaNode(), payload);
754 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
755 validateListKeysEqualityInPayloadAndUri(payload);
757 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
758 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
761 * There is a small window where another write transaction could be
762 * updating the same data simultaneously and we get an
763 * OptimisticLockFailedException. This error is likely transient and The
764 * WriteTransaction#submit API docs state that a retry will likely
765 * succeed. So we'll try again if that scenario occurs. If it fails a
766 * third time then it probably will never succeed so we'll fail in that
769 * By retrying we're attempting to hide the internal implementation of
770 * the data store and how it handles concurrent updates from the
771 * restconf client. The client has instructed us to put the data and we
772 * should make every effort to do so without pushing optimistic lock
773 * failures back to the client and forcing them to handle it via retry
774 * (and having to document the behavior).
776 PutResult result = null;
779 if (mountPoint != null) {
781 result = this.broker.commitMountPointDataPut(mountPoint, normalizedII, payload.getData(), insert,
784 result = this.broker.commitConfigurationDataPut(this.controllerContext.getGlobalSchema(), normalizedII,
785 payload.getData(), insert, point);
789 result.getFutureOfPutData().get();
790 } catch (final InterruptedException e) {
791 LOG.debug("Update failed for {}", identifier, e);
792 throw new RestconfDocumentedException(e.getMessage(), e);
793 } catch (final ExecutionException e) {
794 final TransactionCommitFailedException failure = Throwables.getCauseAs(e,
795 TransactionCommitFailedException.class);
796 if (failure instanceof OptimisticLockFailedException) {
798 LOG.debug("Got OptimisticLockFailedException on last try - failing {}", identifier);
799 throw new RestconfDocumentedException(e.getMessage(), e, failure.getErrorList());
802 LOG.debug("Got OptimisticLockFailedException - trying again {}", identifier);
806 LOG.debug("Update failed for {}", identifier, e);
807 throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), failure);
810 return Response.status(result.getStatus()).build();
814 private static void validateTopLevelNodeName(final NormalizedNodeContext node,
815 final YangInstanceIdentifier identifier) {
817 final String payloadName = node.getData().getNodeType().getLocalName();
820 if (identifier.isEmpty()) {
822 if (!node.getData().getNodeType().equals(NETCONF_BASE_QNAME)) {
823 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
824 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
828 final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
829 if (!payloadName.equals(identifierName)) {
830 throw new RestconfDocumentedException(
831 "Payload name (" + payloadName + ") is different from identifier name (" + identifierName + ")",
832 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
838 * Validates whether keys in {@code payload} are equal to values of keys in
839 * {@code iiWithData} for list schema node.
841 * @throws RestconfDocumentedException
842 * if key values or key count in payload and URI isn't equal
845 private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
846 Preconditions.checkArgument(payload != null);
847 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
848 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
849 final SchemaNode schemaNode = iiWithData.getSchemaNode();
850 final NormalizedNode<?, ?> data = payload.getData();
851 if (schemaNode instanceof ListSchemaNode) {
852 final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
853 if (lastPathArgument instanceof NodeIdentifierWithPredicates && data instanceof MapEntryNode) {
854 final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument).asMap();
855 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
861 public static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final MapEntryNode payload,
862 final List<QName> keyDefinitions) {
864 final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
865 for (final QName keyDefinition : keyDefinitions) {
866 final Object uriKeyValue = RestconfDocumentedException.throwIfNull(
867 // should be caught during parsing URI to InstanceIdentifier
868 mutableCopyUriKeyValues.remove(keyDefinition), ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
869 "Missing key %s in URI.", keyDefinition);
871 final Object dataKeyValue = payload.getIdentifier().getValue(keyDefinition);
873 if (!Objects.deepEquals(uriKeyValue, dataKeyValue)) {
874 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName()
875 + "' specified in the URI doesn't match the value '" + dataKeyValue
876 + "' specified in the message body. ";
877 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
883 public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload,
884 final UriInfo uriInfo) {
885 return createConfigurationData(payload, uriInfo);
889 public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
890 if (payload == null) {
891 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
893 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
894 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
895 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
897 boolean insertUsed = false;
898 boolean pointUsed = false;
899 String insert = null;
902 if (uriInfo != null) {
903 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
904 switch (entry.getKey()) {
908 insert = entry.getValue().iterator().next();
910 throw new RestconfDocumentedException("Insert parameter can be used only once.");
916 point = entry.getValue().iterator().next();
918 throw new RestconfDocumentedException("Point parameter can be used only once.");
922 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
927 if (pointUsed && !insertUsed) {
928 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
930 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
931 throw new RestconfDocumentedException(
932 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
935 FluentFuture<? extends CommitInfo> future;
936 if (mountPoint != null) {
937 future = this.broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData(), insert,
940 future = this.broker.commitConfigurationDataPost(this.controllerContext.getGlobalSchema(), normalizedII,
941 payload.getData(), insert, point);
946 } catch (final InterruptedException e) {
947 LOG.info("Error creating data {}", uriInfo != null ? uriInfo.getPath() : "", e);
948 throw new RestconfDocumentedException(e.getMessage(), e);
949 } catch (final ExecutionException e) {
950 LOG.info("Error creating data {}", uriInfo != null ? uriInfo.getPath() : "", e);
951 throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), Throwables.getCauseAs(e,
952 TransactionCommitFailedException.class));
955 LOG.trace("Successfuly created data.");
957 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
958 // FIXME: Provide path to result.
959 final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
960 if (location != null) {
961 responseBuilder.location(location);
963 return responseBuilder.build();
966 @SuppressWarnings("checkstyle:IllegalCatch")
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 {} was not created", normalizedII, 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 FluentFuture<? extends CommitInfo> future;
992 if (mountPoint != null) {
993 future = this.broker.commitConfigurationDataDelete(mountPoint, normalizedII);
995 future = this.broker.commitConfigurationDataDelete(normalizedII);
1000 } catch (final InterruptedException e) {
1001 throw new RestconfDocumentedException(e.getMessage(), e);
1002 } catch (final ExecutionException e) {
1003 final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
1004 Predicates.instanceOf(ModifiedNodeDoesNotExistException.class)).toJavaUtil();
1005 if (searchedException.isPresent()) {
1006 throw new RestconfDocumentedException("Data specified for delete doesn't exist.", ErrorType.APPLICATION,
1007 ErrorTag.DATA_MISSING, e);
1010 throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), Throwables.getCauseAs(e,
1011 TransactionCommitFailedException.class));
1014 return Response.status(Status.OK).build();
1018 * Subscribes to some path in schema context (stream) to listen on changes
1022 * Additional parameters for subscribing to stream are loaded via rpc input
1025 * <li>datastore - default CONFIGURATION (other values of
1026 * {@link LogicalDatastoreType} enum type)</li>
1027 * <li>scope - default BASE (other values of {@link DataChangeScope})</li>
1031 public NormalizedNodeContext subscribeToStream(final String identifier, final UriInfo uriInfo) {
1032 boolean startTimeUsed = false;
1033 boolean stopTimeUsed = false;
1034 Instant start = Instant.now();
1035 Instant stop = null;
1036 boolean filterUsed = false;
1037 String filter = null;
1038 boolean leafNodesOnlyUsed = false;
1039 boolean leafNodesOnly = false;
1041 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
1042 switch (entry.getKey()) {
1044 if (!startTimeUsed) {
1045 startTimeUsed = true;
1046 start = parseDateFromQueryParam(entry);
1048 throw new RestconfDocumentedException("Start-time parameter can be used only once.");
1052 if (!stopTimeUsed) {
1053 stopTimeUsed = true;
1054 stop = parseDateFromQueryParam(entry);
1056 throw new RestconfDocumentedException("Stop-time parameter can be used only once.");
1062 filter = entry.getValue().iterator().next();
1064 throw new RestconfDocumentedException("Filter parameter can be used only once.");
1067 case "odl-leaf-nodes-only":
1068 if (!leafNodesOnlyUsed) {
1069 leafNodesOnlyUsed = true;
1070 leafNodesOnly = Boolean.parseBoolean(entry.getValue().iterator().next());
1072 throw new RestconfDocumentedException("Odl-leaf-nodes-only parameter can be used only once.");
1076 throw new RestconfDocumentedException("Bad parameter used with notifications: " + entry.getKey());
1079 if (!startTimeUsed && stopTimeUsed) {
1080 throw new RestconfDocumentedException("Stop-time parameter has to be used with start-time parameter.");
1082 URI response = null;
1083 if (identifier.contains(DATA_SUBSCR)) {
1084 response = dataSubs(identifier, uriInfo, start, stop, filter, leafNodesOnly);
1085 } else if (identifier.contains(NOTIFICATION_STREAM)) {
1086 response = notifStream(identifier, uriInfo, start, stop, filter);
1089 if (response != null) {
1090 // prepare node with value of location
1091 final InstanceIdentifierContext<?> iid = prepareIIDSubsStreamOutput();
1092 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> builder =
1093 ImmutableLeafNodeBuilder.create().withValue(response.toString());
1094 builder.withNodeIdentifier(
1095 NodeIdentifier.create(QName.create("subscribe:to:notification", "2016-10-28", "location")));
1097 // prepare new header with location
1098 final Map<String, Object> headers = new HashMap<>();
1099 headers.put("Location", response);
1101 return new NormalizedNodeContext(iid, builder.build(), headers);
1104 final String msg = "Bad type of notification of sal-remote";
1106 throw new RestconfDocumentedException(msg);
1109 private static Instant parseDateFromQueryParam(final Entry<String, List<String>> entry) {
1110 final DateAndTime event = new DateAndTime(entry.getValue().iterator().next());
1111 final String value = event.getValue();
1112 final TemporalAccessor p;
1114 p = FORMATTER.parse(value);
1115 } catch (final DateTimeParseException e) {
1116 throw new RestconfDocumentedException("Cannot parse of value in date: " + value, e);
1118 return Instant.from(p);
1122 * Prepare instance identifier.
1124 * @return {@link InstanceIdentifierContext} of location leaf for
1127 private InstanceIdentifierContext<?> prepareIIDSubsStreamOutput() {
1128 final QName qnameBase = QName.create("subscribe:to:notification", "2016-10-28", "notifi");
1129 final EffectiveModelContext schemaCtx = controllerContext.getGlobalSchema();
1130 final DataSchemaNode location = ((ContainerSchemaNode) schemaCtx
1131 .findModule(qnameBase.getModule()).orElse(null)
1132 .getDataChildByName(qnameBase)).getDataChildByName(QName.create(qnameBase, "location"));
1133 final List<PathArgument> path = new ArrayList<>();
1134 path.add(NodeIdentifier.create(qnameBase));
1135 path.add(NodeIdentifier.create(QName.create(qnameBase, "location")));
1137 return new InstanceIdentifierContext<SchemaNode>(YangInstanceIdentifier.create(path), location, null,
1142 * Register notification listener by stream name.
1149 * stop-time of getting notification
1151 * start-time of getting notification
1153 * indicate which subset of all possible events are of interest
1154 * @return {@link URI} of location
1156 private URI notifStream(final String identifier, final UriInfo uriInfo, final Instant start,
1157 final Instant stop, final String filter) {
1158 final String streamName = Notificator.createStreamNameFromUri(identifier);
1159 if (Strings.isNullOrEmpty(streamName)) {
1160 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1162 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
1163 if (listeners == null || listeners.isEmpty()) {
1164 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1165 ErrorTag.UNKNOWN_ELEMENT);
1168 for (final NotificationListenerAdapter listener : listeners) {
1169 this.broker.registerToListenNotification(listener);
1170 listener.setQueryParams(start, Optional.ofNullable(stop), Optional.ofNullable(filter), false);
1173 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1175 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance(NOTIFICATION_PORT);
1176 final int notificationPort = webSocketServerInstance.getPort();
1179 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme(getWsScheme(uriInfo));
1181 return uriToWebsocketServerBuilder.replacePath(streamName).build();
1184 private static String getWsScheme(final UriInfo uriInfo) {
1185 URI uri = uriInfo.getAbsolutePath();
1189 String subscriptionScheme = uri.getScheme().toLowerCase(Locale.ROOT);
1190 return subscriptionScheme.equals("https") ? "wss" : "ws";
1194 * Register data change listener by stream name.
1201 * start-time of getting notification
1203 * stop-time of getting notification
1205 * indicate which subset of all possible events are of interest
1206 * @return {@link URI} of location
1208 private URI dataSubs(final String identifier, final UriInfo uriInfo, final Instant start, final Instant stop,
1209 final String filter, final boolean leafNodesOnly) {
1210 final String streamName = Notificator.createStreamNameFromUri(identifier);
1211 if (Strings.isNullOrEmpty(streamName)) {
1212 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1215 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1216 if (listener == null) {
1217 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1218 ErrorTag.UNKNOWN_ELEMENT);
1220 listener.setQueryParams(start, Optional.ofNullable(stop), Optional.ofNullable(filter), leafNodesOnly);
1222 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1223 final LogicalDatastoreType datastore =
1224 parserURIEnumParameter(LogicalDatastoreType.class, paramToValues.get(DATASTORE_PARAM_NAME));
1225 if (datastore == null) {
1226 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1227 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1229 final DataChangeScope scope =
1230 parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
1231 if (scope == null) {
1232 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1233 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1236 this.broker.registerToListenDataChanges(datastore, scope, listener);
1238 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1240 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance(NOTIFICATION_PORT);
1241 final int notificationPort = webSocketServerInstance.getPort();
1243 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme(getWsScheme(uriInfo));
1245 return uriToWebsocketServerBuilder.replacePath(streamName).build();
1248 @SuppressWarnings("checkstyle:IllegalCatch")
1250 public PatchStatusContext patchConfigurationData(final String identifier, final PatchContext context,
1251 final UriInfo uriInfo) {
1252 if (context == null) {
1253 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1257 return this.broker.patchConfigurationDataWithinTransaction(context);
1258 } catch (final Exception e) {
1259 LOG.debug("Patch transaction failed", e);
1260 throw new RestconfDocumentedException(e.getMessage(), e);
1264 @SuppressWarnings("checkstyle:IllegalCatch")
1266 public PatchStatusContext patchConfigurationData(final PatchContext context, @Context final UriInfo uriInfo) {
1267 if (context == null) {
1268 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1272 return this.broker.patchConfigurationDataWithinTransaction(context);
1273 } catch (final Exception e) {
1274 LOG.debug("Patch transaction failed", e);
1275 throw new RestconfDocumentedException(e.getMessage(), e);
1280 * Load parameter for subscribing to stream from input composite node.
1284 * @return enum object if its string value is equal to {@code paramName}. In
1287 private static <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1288 final String paramName) {
1289 final Optional<DataContainerChild<? extends PathArgument, ?>> optAugNode = value.getChild(
1290 SAL_REMOTE_AUG_IDENTIFIER);
1291 if (!optAugNode.isPresent()) {
1294 final DataContainerChild<? extends PathArgument, ?> augNode = optAugNode.get();
1295 if (!(augNode instanceof AugmentationNode)) {
1298 final Optional<DataContainerChild<? extends PathArgument, ?>> enumNode = ((AugmentationNode) augNode).getChild(
1299 new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1300 if (!enumNode.isPresent()) {
1303 final Object rawValue = enumNode.get().getValue();
1304 if (!(rawValue instanceof String)) {
1308 return resolveAsEnum(classDescriptor, (String) rawValue);
1312 * Checks whether {@code value} is one of the string representation of
1313 * enumeration {@code classDescriptor}.
1315 * @return enum object if string value of {@code classDescriptor}
1316 * enumeration is equal to {@code value}. Other cases null.
1318 private static <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1319 if (Strings.isNullOrEmpty(value)) {
1322 return resolveAsEnum(classDescriptor, value);
1325 private static <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1326 final T[] enumConstants = classDescriptor.getEnumConstants();
1327 if (enumConstants != null) {
1328 for (final T enm : classDescriptor.getEnumConstants()) {
1329 if (((Enum<?>) enm).name().equals(value)) {
1337 private static Map<String, String> resolveValuesFromUri(final String uri) {
1338 final Map<String, String> result = new HashMap<>();
1339 final String[] tokens = uri.split("/");
1340 for (int i = 1; i < tokens.length; i++) {
1341 final String[] parameterTokens = tokens[i].split("=");
1342 if (parameterTokens.length == 2) {
1343 result.put(parameterTokens[0], parameterTokens[1]);
1349 private MapNode makeModuleMapNode(final Collection<? extends Module> modules) {
1350 Preconditions.checkNotNull(modules);
1351 final Module restconfModule = getRestconfModule();
1352 final DataSchemaNode moduleSchemaNode = this.controllerContext
1353 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1354 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1356 final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder =
1357 Builders.mapBuilder((ListSchemaNode) moduleSchemaNode);
1359 for (final Module module : modules) {
1360 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1362 return listModuleBuilder.build();
1365 private MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1366 Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1367 "moduleSchemaNode has to be of type ListSchemaNode");
1368 final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1369 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues =
1370 Builders.mapEntryBuilder(listModuleSchemaNode);
1372 List<DataSchemaNode> instanceDataChildrenByName =
1373 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "name");
1374 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1375 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1377 .withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName()).build());
1379 final QNameModule qNameModule = module.getQNameModule();
1381 instanceDataChildrenByName =
1382 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "revision");
1383 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1384 Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1385 final Optional<Revision> revision = qNameModule.getRevision();
1386 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode)
1387 .withValue(revision.map(Revision::toString).orElse("")).build());
1389 instanceDataChildrenByName =
1390 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "namespace");
1391 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1392 Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1393 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1394 .withValue(qNameModule.getNamespace().toString()).build());
1396 instanceDataChildrenByName =
1397 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "feature");
1398 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1399 Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1400 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder =
1401 Builders.leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1402 for (final FeatureDefinition feature : module.getFeatures()) {
1403 featuresBuilder.withChild(Builders.leafSetEntryBuilder((LeafListSchemaNode) featureSchemaNode)
1404 .withValue(feature.getQName().getLocalName()).build());
1406 moduleNodeValues.withChild(featuresBuilder.build());
1408 return moduleNodeValues.build();
1411 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1412 Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1413 "streamSchemaNode has to be of type ListSchemaNode");
1414 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1415 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues =
1416 Builders.mapEntryBuilder(listStreamSchemaNode);
1418 List<DataSchemaNode> instanceDataChildrenByName =
1419 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "name");
1420 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1421 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1422 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName).build());
1424 instanceDataChildrenByName =
1425 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "description");
1426 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1427 Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1428 streamNodeValues.withChild(
1429 Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue("DESCRIPTION_PLACEHOLDER").build());
1431 instanceDataChildrenByName =
1432 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-support");
1433 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1434 Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1435 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1436 .withValue(Boolean.TRUE).build());
1438 instanceDataChildrenByName =
1439 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-log-creation-time");
1440 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1441 Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1442 streamNodeValues.withChild(
1443 Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode).withValue("").build());
1445 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "events");
1446 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1447 Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1448 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode).build());
1450 return streamNodeValues.build();
1454 * Prepare stream for notification.
1457 * contains list of qnames of notifications
1458 * @return - checked future object
1460 private ListenableFuture<DOMRpcResult> invokeSalRemoteRpcNotifiStrRPC(final NormalizedNodeContext payload) {
1461 final ContainerNode data = (ContainerNode) payload.getData();
1462 LeafSetNode leafSet = null;
1463 String outputType = "XML";
1464 for (final DataContainerChild<? extends PathArgument, ?> dataChild : data.getValue()) {
1465 if (dataChild instanceof LeafSetNode) {
1466 leafSet = (LeafSetNode) dataChild;
1467 } else if (dataChild instanceof AugmentationNode) {
1468 outputType = (String) ((AugmentationNode) dataChild).getValue().iterator().next().getValue();
1472 final Collection<LeafSetEntryNode> entryNodes = leafSet.getValue();
1473 final List<SchemaPath> paths = new ArrayList<>();
1474 String streamName = CREATE_NOTIFICATION_STREAM + "/";
1476 StringBuilder streamNameBuilder = new StringBuilder(streamName);
1477 final Iterator<LeafSetEntryNode> iterator = entryNodes.iterator();
1478 while (iterator.hasNext()) {
1479 final QName valueQName = QName.create((String) iterator.next().getValue());
1480 final Module module = controllerContext.findModuleByNamespace(valueQName.getModule().getNamespace());
1481 Preconditions.checkNotNull(module,
1482 "Module for namespace " + valueQName.getModule().getNamespace() + " does not exist");
1483 NotificationDefinition notifiDef = null;
1484 for (final NotificationDefinition notification : module.getNotifications()) {
1485 if (notification.getQName().equals(valueQName)) {
1486 notifiDef = notification;
1490 final String moduleName = module.getName();
1491 Preconditions.checkNotNull(notifiDef,
1492 "Notification " + valueQName + "doesn't exist in module " + moduleName);
1493 paths.add(notifiDef.getPath());
1494 streamNameBuilder.append(moduleName).append(':').append(valueQName.getLocalName());
1495 if (iterator.hasNext()) {
1496 streamNameBuilder.append(',');
1500 streamName = streamNameBuilder.toString();
1502 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
1503 final QName outputQname = QName.create(rpcQName, "output");
1504 final QName streamNameQname = QName.create(rpcQName, "notification-stream-identifier");
1506 final ContainerNode output =
1507 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
1508 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
1510 if (!Notificator.existNotificationListenerFor(streamName)) {
1511 Notificator.createNotificationListener(paths, streamName, outputType, controllerContext);
1514 return Futures.immediateFuture(new DefaultDOMRpcResult(output));