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.eclipse.jdt.annotation.NonNull;
55 import org.opendaylight.mdsal.common.api.CommitInfo;
56 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
57 import org.opendaylight.mdsal.common.api.OptimisticLockFailedException;
58 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
59 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
60 import org.opendaylight.mdsal.dom.api.DOMRpcImplementationNotAvailableException;
61 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
62 import org.opendaylight.mdsal.dom.api.DOMRpcService;
63 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
64 import org.opendaylight.netconf.sal.rest.api.Draft02;
65 import org.opendaylight.netconf.sal.rest.api.RestconfService;
66 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
67 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
68 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
69 import org.opendaylight.netconf.sal.streams.websockets.WebSocketServer;
70 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
71 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
72 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
73 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
74 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
75 import org.opendaylight.restconf.common.patch.PatchContext;
76 import org.opendaylight.restconf.common.patch.PatchStatusContext;
77 import org.opendaylight.restconf.common.util.DataChangeScope;
78 import org.opendaylight.restconf.common.util.OperationsResourceUtils;
79 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
80 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
81 import org.opendaylight.yangtools.yang.common.Empty;
82 import org.opendaylight.yangtools.yang.common.QName;
83 import org.opendaylight.yangtools.yang.common.QNameModule;
84 import org.opendaylight.yangtools.yang.common.Revision;
85 import org.opendaylight.yangtools.yang.common.YangConstants;
86 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
87 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
88 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
89 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
90 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
91 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
92 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
93 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
94 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
95 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
96 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
97 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
98 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
99 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
100 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
101 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
102 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
103 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
104 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
105 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
106 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeBuilder;
107 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
108 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
109 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
110 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
111 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
112 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
113 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
114 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
115 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
116 import org.opendaylight.yangtools.yang.model.api.Module;
117 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
118 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
119 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
120 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
121 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
122 import org.slf4j.Logger;
123 import org.slf4j.LoggerFactory;
126 public final class RestconfImpl implements RestconfService {
128 * Notifications are served on port 8181.
130 private static final int NOTIFICATION_PORT = 8181;
132 private static final int CHAR_NOT_FOUND = -1;
134 private static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
136 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
138 private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
140 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
142 private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
144 private static final String DATASTORE_PARAM_NAME = "datastore";
146 private static final String SCOPE_PARAM_NAME = "scope";
148 private static final String OUTPUT_TYPE_PARAM_NAME = "notification-output-type";
150 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
152 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
154 private static final QName NETCONF_BASE_QNAME = QName.create(QNameModule.create(URI.create(NETCONF_BASE)),
155 NETCONF_BASE_PAYLOAD_NAME).intern();
157 private static final QNameModule SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
158 Revision.of("2014-07-08"));
160 private static final AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER =
161 new AugmentationIdentifier(ImmutableSet.of(
162 QName.create(SAL_REMOTE_AUGMENT, "scope"), QName.create(SAL_REMOTE_AUGMENT, "datastore"),
163 QName.create(SAL_REMOTE_AUGMENT, "notification-output-type")));
165 public static final CharSequence DATA_SUBSCR = "data-change-event-subscription";
166 private static final CharSequence CREATE_DATA_SUBSCR = "create-" + DATA_SUBSCR;
168 public static final CharSequence NOTIFICATION_STREAM = "notification-stream";
169 private static final CharSequence CREATE_NOTIFICATION_STREAM = "create-" + NOTIFICATION_STREAM;
171 private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
172 .appendValue(ChronoField.YEAR, 4).appendLiteral('-')
173 .appendValue(ChronoField.MONTH_OF_YEAR, 2).appendLiteral('-')
174 .appendValue(ChronoField.DAY_OF_MONTH, 2).appendLiteral('T')
175 .appendValue(ChronoField.HOUR_OF_DAY, 2).appendLiteral(':')
176 .appendValue(ChronoField.MINUTE_OF_HOUR, 2).appendLiteral(':')
177 .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
178 .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
179 .appendOffset("+HH:MM", "Z").toFormatter();
181 private final BrokerFacade broker;
183 private final ControllerContext controllerContext;
186 public RestconfImpl(final BrokerFacade broker, final ControllerContext controllerContext) {
187 this.broker = broker;
188 this.controllerContext = controllerContext;
194 * @deprecated Just use {@link #RestconfImpl(BrokerFacade, ControllerContext)} constructor instead.
197 public static RestconfImpl newInstance(final BrokerFacade broker, final ControllerContext controllerContext) {
198 return new RestconfImpl(broker, controllerContext);
202 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
203 final MapNode allModuleMap = makeModuleMapNode(controllerContext.getAllModules());
205 final EffectiveModelContext schemaContext = this.controllerContext.getGlobalSchema();
207 final Module restconfModule = getRestconfModule();
208 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
209 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
210 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
212 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
213 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
214 moduleContainerBuilder.withChild(allModuleMap);
216 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode, null, schemaContext),
217 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
221 * Valid only for mount point.
224 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
225 Preconditions.checkNotNull(identifier);
226 if (!identifier.contains(ControllerContext.MOUNT)) {
227 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
228 + " URI has to end with " + ControllerContext.MOUNT;
229 LOG.debug("{} for {}", errMsg, identifier);
230 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
233 final InstanceIdentifierContext<?> mountPointIdentifier =
234 this.controllerContext.toMountPointIdentifier(identifier);
235 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
236 final MapNode mountPointModulesMap = makeModuleMapNode(controllerContext.getAllModules(mountPoint));
238 final Module restconfModule = getRestconfModule();
239 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
240 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
241 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
243 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
244 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
245 moduleContainerBuilder.withChild(mountPointModulesMap);
247 return new NormalizedNodeContext(
248 new InstanceIdentifierContext<>(null, modulesSchemaNode, mountPoint,
249 this.controllerContext.getGlobalSchema()),
250 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
254 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
255 Preconditions.checkNotNull(identifier);
256 final Entry<String, Revision> nameRev = getModuleNameAndRevision(identifier);
257 Module module = null;
258 DOMMountPoint mountPoint = null;
259 final EffectiveModelContext schemaContext;
260 if (identifier.contains(ControllerContext.MOUNT)) {
261 final InstanceIdentifierContext<?> mountPointIdentifier =
262 this.controllerContext.toMountPointIdentifier(identifier);
263 mountPoint = mountPointIdentifier.getMountPoint();
264 module = this.controllerContext.findModuleByNameAndRevision(mountPoint, nameRev.getKey(),
266 schemaContext = mountPoint.getEffectiveModelContext();
268 module = this.controllerContext.findModuleByNameAndRevision(nameRev.getKey(), nameRev.getValue());
269 schemaContext = this.controllerContext.getGlobalSchema();
272 if (module == null) {
273 LOG.debug("Module with name '{}' and revision '{}' was not found.", nameRev.getKey(), nameRev.getValue());
274 throw new RestconfDocumentedException("Module with name '" + nameRev.getKey() + "' and revision '"
275 + nameRev.getValue() + "' was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
278 final Module restconfModule = getRestconfModule();
279 final Set<Module> modules = Collections.singleton(module);
280 final MapNode moduleMap = makeModuleMapNode(modules);
282 final DataSchemaNode moduleSchemaNode = this.controllerContext
283 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
284 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
286 return new NormalizedNodeContext(
287 new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint, schemaContext), moduleMap,
288 QueryParametersParser.parseWriterParameters(uriInfo));
292 public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
293 final EffectiveModelContext schemaContext = this.controllerContext.getGlobalSchema();
294 final Set<String> availableStreams = Notificator.getStreamNames();
295 final Module restconfModule = getRestconfModule();
296 final DataSchemaNode streamSchemaNode = this.controllerContext
297 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
298 Preconditions.checkState(streamSchemaNode instanceof ListSchemaNode);
300 final CollectionNodeBuilder<MapEntryNode, MapNode> listStreamsBuilder =
301 Builders.mapBuilder((ListSchemaNode) streamSchemaNode);
303 for (final String streamName : availableStreams) {
304 listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
307 final DataSchemaNode streamsContainerSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
308 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
309 Preconditions.checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
311 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
312 Builders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
313 streamsContainerBuilder.withChild(listStreamsBuilder.build());
315 return new NormalizedNodeContext(
316 new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null, schemaContext),
317 streamsContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
321 public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
322 return OperationsResourceUtils.contextForModelContext(controllerContext.getGlobalSchema(), null);
326 public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
327 if (!identifier.contains(ControllerContext.MOUNT)) {
328 final String errMsg = "URI has bad format. If operations behind mount point should be showed, URI has to "
329 + " end with " + ControllerContext.MOUNT;
330 LOG.debug("{} for {}", errMsg, identifier);
331 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
334 final InstanceIdentifierContext<?> mountPointIdentifier =
335 this.controllerContext.toMountPointIdentifier(identifier);
336 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
337 return OperationsResourceUtils.contextForModelContext(mountPoint.getSchemaContext(), mountPoint);
340 private Module getRestconfModule() {
341 final Module restconfModule = this.controllerContext.getRestconfModule();
342 if (restconfModule == null) {
343 LOG.debug("ietf-restconf module was not found.");
344 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
345 ErrorTag.OPERATION_NOT_SUPPORTED);
348 return restconfModule;
351 private static Entry<String, Revision> getModuleNameAndRevision(final String identifier) {
352 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
353 String moduleNameAndRevision = "";
354 if (mountIndex >= 0) {
355 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
357 moduleNameAndRevision = identifier;
360 final Splitter splitter = Splitter.on('/').omitEmptyStrings();
361 final List<String> pathArgs = splitter.splitToList(moduleNameAndRevision);
362 if (pathArgs.size() < 2) {
363 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' {}", identifier);
364 throw new RestconfDocumentedException(
365 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
366 ErrorTag.INVALID_VALUE);
370 return new SimpleImmutableEntry<>(pathArgs.get(0), Revision.of(pathArgs.get(1)));
371 } catch (final DateTimeParseException e) {
372 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' {}", identifier);
373 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
374 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
379 public Object getRoot() {
384 public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload,
385 final UriInfo uriInfo) {
386 if (payload == null) {
387 // no payload specified, reroute this to no payload invokeRpc implementation
388 return invokeRpc(identifier, uriInfo);
391 final SchemaNode schema = payload.getInstanceIdentifierContext().getSchemaNode();
392 final ListenableFuture<? extends DOMRpcResult> response;
393 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
394 final NormalizedNode<?, ?> input = nonnullInput(schema, payload.getData());
395 final EffectiveModelContext schemaContext;
397 if (mountPoint != null) {
398 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
399 if (!mountRpcServices.isPresent()) {
400 LOG.debug("Error: Rpc service is missing.");
401 throw new RestconfDocumentedException("Rpc service is missing.");
403 schemaContext = mountPoint.getEffectiveModelContext();
404 response = mountRpcServices.get().invokeRpc(schema.getPath(), input);
406 final URI namespace = schema.getQName().getNamespace();
407 if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
408 if (identifier.contains(CREATE_DATA_SUBSCR)) {
409 response = invokeSalRemoteRpcSubscribeRPC(payload);
410 } else if (identifier.contains(CREATE_NOTIFICATION_STREAM)) {
411 response = invokeSalRemoteRpcNotifiStrRPC(payload);
413 final String msg = "Not supported operation";
415 throw new RestconfDocumentedException(msg, ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED);
418 response = this.broker.invokeRpc(schema.getPath(), input);
420 schemaContext = this.controllerContext.getGlobalSchema();
423 final DOMRpcResult result = checkRpcResponse(response);
425 RpcDefinition resultNodeSchema = null;
426 final NormalizedNode<?, ?> resultData;
427 if (result != null && result.getResult() != null) {
428 resultData = result.getResult();
429 resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
434 if (resultData != null && ((ContainerNode) resultData).getValue().isEmpty()) {
435 throw new WebApplicationException(Response.Status.NO_CONTENT);
437 return new NormalizedNodeContext(
438 new InstanceIdentifierContext<>(null, resultNodeSchema, mountPoint, schemaContext),
439 resultData, QueryParametersParser.parseWriterParameters(uriInfo));
443 @SuppressFBWarnings(value = "NP_LOAD_OF_KNOWN_NULL_VALUE",
444 justification = "Looks like a false positive, see below FIXME")
445 private NormalizedNodeContext invokeRpc(final String identifier, final UriInfo uriInfo) {
446 final DOMMountPoint mountPoint;
447 final String identifierEncoded;
448 final EffectiveModelContext schemaContext;
449 if (identifier.contains(ControllerContext.MOUNT)) {
450 // mounted RPC call - look up mount instance.
451 final InstanceIdentifierContext<?> mountPointId = this.controllerContext.toMountPointIdentifier(identifier);
452 mountPoint = mountPointId.getMountPoint();
453 schemaContext = mountPoint.getEffectiveModelContext();
454 final int startOfRemoteRpcName =
455 identifier.lastIndexOf(ControllerContext.MOUNT) + ControllerContext.MOUNT.length() + 1;
456 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
457 identifierEncoded = remoteRpcName;
459 } else if (identifier.indexOf('/') == CHAR_NOT_FOUND) {
460 identifierEncoded = identifier;
462 schemaContext = this.controllerContext.getGlobalSchema();
464 LOG.debug("Identifier {} cannot contain slash character (/).", identifier);
465 throw new RestconfDocumentedException(String.format("Identifier %n%s%ncan\'t contain slash character (/).%n"
466 + "If slash is part of identifier name then use %%2F placeholder.", identifier), ErrorType.PROTOCOL,
467 ErrorTag.INVALID_VALUE);
470 final String identifierDecoded = ControllerContext.urlPathArgDecode(identifierEncoded);
471 final RpcDefinition rpc;
472 if (mountPoint == null) {
473 rpc = this.controllerContext.getRpcDefinition(identifierDecoded);
475 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
479 LOG.debug("RPC {} does not exist.", identifierDecoded);
480 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
483 if (!rpc.getInput().getChildNodes().isEmpty()) {
484 LOG.debug("No input specified for RPC {} with an input section", rpc);
485 throw new RestconfDocumentedException("No input specified for RPC " + rpc
486 + " with an input section defined", ErrorType.RPC, ErrorTag.MISSING_ELEMENT);
489 final ContainerNode input = defaultInput(rpc.getQName());
490 final ListenableFuture<? extends DOMRpcResult> response;
491 if (mountPoint != null) {
492 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
493 if (!mountRpcServices.isPresent()) {
494 throw new RestconfDocumentedException("Rpc service is missing.");
496 response = mountRpcServices.get().invokeRpc(rpc.getPath(), input);
498 response = this.broker.invokeRpc(rpc.getPath(), input);
501 final NormalizedNode<?, ?> result = checkRpcResponse(response).getResult();
502 if (result != null && ((ContainerNode) result).getValue().isEmpty()) {
503 throw new WebApplicationException(Response.Status.NO_CONTENT);
506 // FIXME: in reference to the above @SupressFBWarnings: "mountPoint" reference here trips up SpotBugs, as it
507 // thinks it can only ever be null. Except it can very much be non-null. The core problem is the horrible
508 // structure of this code where we have a sh*tload of checks for mountpoint above and all over the
509 // codebase where all that difference should have been properly encapsulated.
511 // This is legacy code, so if anybody cares to do that refactor, feel free to contribute, but I am not
513 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpc, mountPoint, schemaContext), result,
514 QueryParametersParser.parseWriterParameters(uriInfo));
517 private static @NonNull NormalizedNode<?, ?> nonnullInput(final SchemaNode rpc, final NormalizedNode<?, ?> input) {
518 return input != null ? input : defaultInput(rpc.getQName());
521 private static @NonNull ContainerNode defaultInput(final QName rpcName) {
522 return ImmutableNodes.containerNode(YangConstants.operationInputQName(rpcName.getModule()));
525 @SuppressWarnings("checkstyle:avoidHidingCauseException")
526 private static DOMRpcResult checkRpcResponse(final ListenableFuture<? extends DOMRpcResult> response) {
527 if (response == null) {
531 final DOMRpcResult retValue = response.get();
532 if (retValue.getErrors().isEmpty()) {
535 LOG.debug("RpcError message {}", retValue.getErrors());
536 throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
537 } catch (final InterruptedException e) {
538 final String errMsg = "The operation was interrupted while executing and did not complete.";
539 LOG.debug("Rpc Interrupt - {}", errMsg, e);
540 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION, e);
541 } catch (final ExecutionException e) {
542 LOG.debug("Execution RpcError: ", e);
543 Throwable cause = e.getCause();
545 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
548 while (cause.getCause() != null) {
549 cause = cause.getCause();
552 if (cause instanceof IllegalArgumentException) {
553 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
554 } else if (cause instanceof DOMRpcImplementationNotAvailableException) {
555 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.APPLICATION,
556 ErrorTag.OPERATION_NOT_SUPPORTED);
558 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
560 } catch (final CancellationException e) {
561 final String errMsg = "The operation was cancelled while executing.";
562 LOG.debug("Cancel RpcExecution: {}", errMsg, e);
563 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
567 private static void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
568 if (inputSchema != null && payload.getData() == null) {
569 // expected a non null payload
570 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
571 } else if (inputSchema == null && payload.getData() != null) {
572 // did not expect any input
573 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
577 private ListenableFuture<DOMRpcResult> invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
578 final ContainerNode value = (ContainerNode) payload.getData();
579 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
580 final Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(
581 new NodeIdentifier(QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(),
583 final Object pathValue = path.isPresent() ? path.get().getValue() : null;
585 if (!(pathValue instanceof YangInstanceIdentifier)) {
586 LOG.debug("Instance identifier {} was not normalized correctly", rpcQName);
587 throw new RestconfDocumentedException("Instance identifier was not normalized correctly",
588 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
591 final YangInstanceIdentifier pathIdentifier = (YangInstanceIdentifier) pathValue;
592 String streamName = (String) CREATE_DATA_SUBSCR;
593 NotificationOutputType outputType = null;
594 if (!pathIdentifier.isEmpty()) {
595 final String fullRestconfIdentifier =
596 DATA_SUBSCR + this.controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
598 LogicalDatastoreType datastore =
599 parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
600 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
602 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
603 scope = scope == null ? DEFAULT_SCOPE : scope;
605 outputType = parseEnumTypeParameter(value, NotificationOutputType.class, OUTPUT_TYPE_PARAM_NAME);
606 outputType = outputType == null ? NotificationOutputType.XML : outputType;
608 streamName = Notificator
609 .createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore + "/scope=" + scope);
612 if (Strings.isNullOrEmpty(streamName)) {
613 LOG.debug("Path is empty or contains value node which is not Container or List built-in type at {}",
615 throw new RestconfDocumentedException("Path is empty or contains value node which is not Container or List "
616 + "built-in type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
619 final QName outputQname = QName.create(rpcQName, "output");
620 final QName streamNameQname = QName.create(rpcQName, "stream-name");
622 final ContainerNode output =
623 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
624 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
626 if (!Notificator.existListenerFor(streamName)) {
627 Notificator.createListener(pathIdentifier, streamName, outputType, controllerContext);
630 return Futures.immediateFuture(new DefaultDOMRpcResult(output));
633 private static RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
634 final String[] splittedIdentifier = identifierDecoded.split(":");
635 if (splittedIdentifier.length != 2) {
636 LOG.debug("{} could not be split to 2 parts (module:rpc name)", identifierDecoded);
637 throw new RestconfDocumentedException(identifierDecoded + " could not be split to 2 parts "
638 + "(module:rpc name)", ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
640 for (final Module module : schemaContext.getModules()) {
641 if (module.getName().equals(splittedIdentifier[0])) {
642 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
643 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
644 return rpcDefinition;
653 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
654 boolean withDefaUsed = false;
655 String withDefa = null;
657 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
658 switch (entry.getKey()) {
659 case "with-defaults":
662 withDefa = entry.getValue().iterator().next();
664 throw new RestconfDocumentedException("With-defaults parameter can be used only once.");
668 LOG.info("Unknown key : {}.", entry.getKey());
672 boolean tagged = false;
674 if ("report-all-tagged".equals(withDefa)) {
678 if ("report-all".equals(withDefa)) {
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.readConfigurationData(mountPoint, normalizedII, withDefa);
690 data = this.broker.readConfigurationData(normalizedII, withDefa);
693 throw dataMissing(identifier);
695 return new NormalizedNodeContext(iiWithData, data,
696 QueryParametersParser.parseWriterParameters(uriInfo, tagged));
700 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
701 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
702 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
703 NormalizedNode<?, ?> data = null;
704 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
705 if (mountPoint != null) {
706 data = this.broker.readOperationalData(mountPoint, normalizedII);
708 data = this.broker.readOperationalData(normalizedII);
711 throw dataMissing(identifier);
713 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
716 private static RestconfDocumentedException dataMissing(final String identifier) {
717 LOG.debug("Request could not be completed because the relevant data model content does not exist {}",
719 return new RestconfDocumentedException("Request could not be completed because the relevant data model content "
720 + "does not exist", ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
724 public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload,
725 final UriInfo uriInfo) {
726 boolean insertUsed = false;
727 boolean pointUsed = false;
728 String insert = null;
731 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
732 switch (entry.getKey()) {
736 insert = entry.getValue().iterator().next();
738 throw new RestconfDocumentedException("Insert parameter can be used only once.");
744 point = entry.getValue().iterator().next();
746 throw new RestconfDocumentedException("Point parameter can be used only once.");
750 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
754 if (pointUsed && !insertUsed) {
755 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
757 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
758 throw new RestconfDocumentedException(
759 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
762 Preconditions.checkNotNull(identifier);
764 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
766 validateInput(iiWithData.getSchemaNode(), payload);
767 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
768 validateListKeysEqualityInPayloadAndUri(payload);
770 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
771 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
774 * There is a small window where another write transaction could be
775 * updating the same data simultaneously and we get an
776 * OptimisticLockFailedException. This error is likely transient and The
777 * WriteTransaction#submit API docs state that a retry will likely
778 * succeed. So we'll try again if that scenario occurs. If it fails a
779 * third time then it probably will never succeed so we'll fail in that
782 * By retrying we're attempting to hide the internal implementation of
783 * the data store and how it handles concurrent updates from the
784 * restconf client. The client has instructed us to put the data and we
785 * should make every effort to do so without pushing optimistic lock
786 * failures back to the client and forcing them to handle it via retry
787 * (and having to document the behavior).
789 PutResult result = null;
792 if (mountPoint != null) {
794 result = this.broker.commitMountPointDataPut(mountPoint, normalizedII, payload.getData(), insert,
797 result = this.broker.commitConfigurationDataPut(this.controllerContext.getGlobalSchema(), normalizedII,
798 payload.getData(), insert, point);
802 result.getFutureOfPutData().get();
803 } catch (final InterruptedException e) {
804 LOG.debug("Update failed for {}", identifier, e);
805 throw new RestconfDocumentedException(e.getMessage(), e);
806 } catch (final ExecutionException e) {
807 final TransactionCommitFailedException failure = Throwables.getCauseAs(e,
808 TransactionCommitFailedException.class);
809 if (failure instanceof OptimisticLockFailedException) {
811 LOG.debug("Got OptimisticLockFailedException on last try - failing {}", identifier);
812 throw new RestconfDocumentedException(e.getMessage(), e, failure.getErrorList());
815 LOG.debug("Got OptimisticLockFailedException - trying again {}", identifier);
819 LOG.debug("Update failed for {}", identifier, e);
820 throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), failure);
823 return Response.status(result.getStatus()).build();
827 private static void validateTopLevelNodeName(final NormalizedNodeContext node,
828 final YangInstanceIdentifier identifier) {
830 final String payloadName = node.getData().getNodeType().getLocalName();
833 if (identifier.isEmpty()) {
835 if (!node.getData().getNodeType().equals(NETCONF_BASE_QNAME)) {
836 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
837 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
841 final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
842 if (!payloadName.equals(identifierName)) {
843 throw new RestconfDocumentedException(
844 "Payload name (" + payloadName + ") is different from identifier name (" + identifierName + ")",
845 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
851 * Validates whether keys in {@code payload} are equal to values of keys in
852 * {@code iiWithData} for list schema node.
854 * @throws RestconfDocumentedException
855 * if key values or key count in payload and URI isn't equal
858 private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
859 Preconditions.checkArgument(payload != null);
860 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
861 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
862 final SchemaNode schemaNode = iiWithData.getSchemaNode();
863 final NormalizedNode<?, ?> data = payload.getData();
864 if (schemaNode instanceof ListSchemaNode) {
865 final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
866 if (lastPathArgument instanceof NodeIdentifierWithPredicates && data instanceof MapEntryNode) {
867 final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument).asMap();
868 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
874 public static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final MapEntryNode payload,
875 final List<QName> keyDefinitions) {
877 final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
878 for (final QName keyDefinition : keyDefinitions) {
879 final Object uriKeyValue = RestconfDocumentedException.throwIfNull(
880 // should be caught during parsing URI to InstanceIdentifier
881 mutableCopyUriKeyValues.remove(keyDefinition), ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
882 "Missing key %s in URI.", keyDefinition);
884 final Object dataKeyValue = payload.getIdentifier().getValue(keyDefinition);
886 if (!Objects.deepEquals(uriKeyValue, dataKeyValue)) {
887 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName()
888 + "' specified in the URI doesn't match the value '" + dataKeyValue
889 + "' specified in the message body. ";
890 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
896 public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload,
897 final UriInfo uriInfo) {
898 return createConfigurationData(payload, uriInfo);
902 public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
903 if (payload == null) {
904 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
906 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
907 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
908 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
910 boolean insertUsed = false;
911 boolean pointUsed = false;
912 String insert = null;
915 if (uriInfo != null) {
916 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
917 switch (entry.getKey()) {
921 insert = entry.getValue().iterator().next();
923 throw new RestconfDocumentedException("Insert parameter can be used only once.");
929 point = entry.getValue().iterator().next();
931 throw new RestconfDocumentedException("Point parameter can be used only once.");
935 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
940 if (pointUsed && !insertUsed) {
941 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
943 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
944 throw new RestconfDocumentedException(
945 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
948 FluentFuture<? extends CommitInfo> future;
949 if (mountPoint != null) {
950 future = this.broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData(), insert,
953 future = this.broker.commitConfigurationDataPost(this.controllerContext.getGlobalSchema(), normalizedII,
954 payload.getData(), insert, point);
959 } catch (final InterruptedException e) {
960 LOG.info("Error creating data {}", uriInfo != null ? uriInfo.getPath() : "", e);
961 throw new RestconfDocumentedException(e.getMessage(), e);
962 } catch (final ExecutionException e) {
963 LOG.info("Error creating data {}", uriInfo != null ? uriInfo.getPath() : "", e);
964 throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), Throwables.getCauseAs(e,
965 TransactionCommitFailedException.class));
968 LOG.trace("Successfuly created data.");
970 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
971 // FIXME: Provide path to result.
972 final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
973 if (location != null) {
974 responseBuilder.location(location);
976 return responseBuilder.build();
979 @SuppressWarnings("checkstyle:IllegalCatch")
980 private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint,
981 final YangInstanceIdentifier normalizedII) {
982 if (uriInfo == null) {
983 // This is null if invoked internally
987 final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
988 uriBuilder.path("config");
990 uriBuilder.path(this.controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
991 } catch (final Exception e) {
992 LOG.info("Location for instance identifier {} was not created", normalizedII, e);
995 return uriBuilder.build();
999 public Response deleteConfigurationData(final String identifier) {
1000 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
1001 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
1002 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
1004 final FluentFuture<? extends CommitInfo> future;
1005 if (mountPoint != null) {
1006 future = this.broker.commitConfigurationDataDelete(mountPoint, normalizedII);
1008 future = this.broker.commitConfigurationDataDelete(normalizedII);
1013 } catch (final InterruptedException e) {
1014 throw new RestconfDocumentedException(e.getMessage(), e);
1015 } catch (final ExecutionException e) {
1016 final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
1017 Predicates.instanceOf(ModifiedNodeDoesNotExistException.class)).toJavaUtil();
1018 if (searchedException.isPresent()) {
1019 throw new RestconfDocumentedException("Data specified for delete doesn't exist.", ErrorType.APPLICATION,
1020 ErrorTag.DATA_MISSING, e);
1023 throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), Throwables.getCauseAs(e,
1024 TransactionCommitFailedException.class));
1027 return Response.status(Status.OK).build();
1031 * Subscribes to some path in schema context (stream) to listen on changes
1035 * Additional parameters for subscribing to stream are loaded via rpc input
1038 * <li>datastore - default CONFIGURATION (other values of
1039 * {@link LogicalDatastoreType} enum type)</li>
1040 * <li>scope - default BASE (other values of {@link DataChangeScope})</li>
1044 public NormalizedNodeContext subscribeToStream(final String identifier, final UriInfo uriInfo) {
1045 boolean startTimeUsed = false;
1046 boolean stopTimeUsed = false;
1047 Instant start = Instant.now();
1048 Instant stop = null;
1049 boolean filterUsed = false;
1050 String filter = null;
1051 boolean leafNodesOnlyUsed = false;
1052 boolean leafNodesOnly = false;
1053 boolean skipNotificationDataUsed = false;
1054 boolean skipNotificationData = false;
1056 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
1057 switch (entry.getKey()) {
1059 if (!startTimeUsed) {
1060 startTimeUsed = true;
1061 start = parseDateFromQueryParam(entry);
1063 throw new RestconfDocumentedException("Start-time parameter can be used only once.");
1067 if (!stopTimeUsed) {
1068 stopTimeUsed = true;
1069 stop = parseDateFromQueryParam(entry);
1071 throw new RestconfDocumentedException("Stop-time parameter can be used only once.");
1077 filter = entry.getValue().iterator().next();
1079 throw new RestconfDocumentedException("Filter parameter can be used only once.");
1082 case "odl-leaf-nodes-only":
1083 if (!leafNodesOnlyUsed) {
1084 leafNodesOnlyUsed = true;
1085 leafNodesOnly = Boolean.parseBoolean(entry.getValue().iterator().next());
1087 throw new RestconfDocumentedException("Odl-leaf-nodes-only parameter can be used only once.");
1090 case "odl-skip-notification-data":
1091 if (!skipNotificationDataUsed) {
1092 skipNotificationDataUsed = true;
1093 skipNotificationData = Boolean.parseBoolean(entry.getValue().iterator().next());
1095 throw new RestconfDocumentedException(
1096 "Odl-skip-notification-data parameter can be used only once.");
1100 throw new RestconfDocumentedException("Bad parameter used with notifications: " + entry.getKey());
1103 if (!startTimeUsed && stopTimeUsed) {
1104 throw new RestconfDocumentedException("Stop-time parameter has to be used with start-time parameter.");
1106 URI response = null;
1107 if (identifier.contains(DATA_SUBSCR)) {
1108 response = dataSubs(identifier, uriInfo, start, stop, filter, leafNodesOnly, skipNotificationData);
1109 } else if (identifier.contains(NOTIFICATION_STREAM)) {
1110 response = notifStream(identifier, uriInfo, start, stop, filter);
1113 if (response != null) {
1114 // prepare node with value of location
1115 final InstanceIdentifierContext<?> iid = prepareIIDSubsStreamOutput();
1116 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> builder =
1117 ImmutableLeafNodeBuilder.create().withValue(response.toString());
1118 builder.withNodeIdentifier(
1119 NodeIdentifier.create(QName.create("subscribe:to:notification", "2016-10-28", "location")));
1121 // prepare new header with location
1122 final Map<String, Object> headers = new HashMap<>();
1123 headers.put("Location", response);
1125 return new NormalizedNodeContext(iid, builder.build(), headers);
1128 final String msg = "Bad type of notification of sal-remote";
1130 throw new RestconfDocumentedException(msg);
1133 private static Instant parseDateFromQueryParam(final Entry<String, List<String>> entry) {
1134 final DateAndTime event = new DateAndTime(entry.getValue().iterator().next());
1135 final String value = event.getValue();
1136 final TemporalAccessor p;
1138 p = FORMATTER.parse(value);
1139 } catch (final DateTimeParseException e) {
1140 throw new RestconfDocumentedException("Cannot parse of value in date: " + value, e);
1142 return Instant.from(p);
1146 * Prepare instance identifier.
1148 * @return {@link InstanceIdentifierContext} of location leaf for
1151 private InstanceIdentifierContext<?> prepareIIDSubsStreamOutput() {
1152 final QName qnameBase = QName.create("subscribe:to:notification", "2016-10-28", "notifi");
1153 final EffectiveModelContext schemaCtx = controllerContext.getGlobalSchema();
1154 final DataSchemaNode location = ((ContainerSchemaNode) schemaCtx
1155 .findModule(qnameBase.getModule()).orElse(null)
1156 .getDataChildByName(qnameBase)).getDataChildByName(QName.create(qnameBase, "location"));
1157 final List<PathArgument> path = new ArrayList<>();
1158 path.add(NodeIdentifier.create(qnameBase));
1159 path.add(NodeIdentifier.create(QName.create(qnameBase, "location")));
1161 return new InstanceIdentifierContext<SchemaNode>(YangInstanceIdentifier.create(path), location, null,
1166 * Register notification listener by stream name.
1173 * stop-time of getting notification
1175 * start-time of getting notification
1177 * indicate which subset of all possible events are of interest
1178 * @return {@link URI} of location
1180 private URI notifStream(final String identifier, final UriInfo uriInfo, final Instant start,
1181 final Instant stop, final String filter) {
1182 final String streamName = Notificator.createStreamNameFromUri(identifier);
1183 if (Strings.isNullOrEmpty(streamName)) {
1184 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1186 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
1187 if (listeners == null || listeners.isEmpty()) {
1188 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1189 ErrorTag.UNKNOWN_ELEMENT);
1192 for (final NotificationListenerAdapter listener : listeners) {
1193 this.broker.registerToListenNotification(listener);
1194 listener.setQueryParams(start, Optional.ofNullable(stop), Optional.ofNullable(filter), false, false);
1197 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1199 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance(NOTIFICATION_PORT);
1200 final int notificationPort = webSocketServerInstance.getPort();
1203 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme(getWsScheme(uriInfo));
1205 return uriToWebsocketServerBuilder.replacePath(streamName).build();
1208 private static String getWsScheme(final UriInfo uriInfo) {
1209 URI uri = uriInfo.getAbsolutePath();
1213 String subscriptionScheme = uri.getScheme().toLowerCase(Locale.ROOT);
1214 return subscriptionScheme.equals("https") ? "wss" : "ws";
1218 * Register data change listener by stream name.
1225 * start-time of getting notification
1227 * stop-time of getting notification
1229 * indicate which subset of all possible events are of interest
1230 * @return {@link URI} of location
1232 private URI dataSubs(final String identifier, final UriInfo uriInfo, final Instant start, final Instant stop,
1233 final String filter, final boolean leafNodesOnly, final boolean skipNotificationData) {
1234 final String streamName = Notificator.createStreamNameFromUri(identifier);
1235 if (Strings.isNullOrEmpty(streamName)) {
1236 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1239 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1240 if (listener == null) {
1241 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1242 ErrorTag.UNKNOWN_ELEMENT);
1244 listener.setQueryParams(start, Optional.ofNullable(stop), Optional.ofNullable(filter), leafNodesOnly,
1245 skipNotificationData);
1247 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1248 final LogicalDatastoreType datastore =
1249 parserURIEnumParameter(LogicalDatastoreType.class, paramToValues.get(DATASTORE_PARAM_NAME));
1250 if (datastore == null) {
1251 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1252 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1254 final DataChangeScope scope =
1255 parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
1256 if (scope == null) {
1257 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1258 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1261 this.broker.registerToListenDataChanges(datastore, scope, listener);
1263 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1265 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance(NOTIFICATION_PORT);
1266 final int notificationPort = webSocketServerInstance.getPort();
1268 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme(getWsScheme(uriInfo));
1270 return uriToWebsocketServerBuilder.replacePath(streamName).build();
1273 @SuppressWarnings("checkstyle:IllegalCatch")
1275 public PatchStatusContext patchConfigurationData(final String identifier, final PatchContext context,
1276 final UriInfo uriInfo) {
1277 if (context == null) {
1278 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1282 return this.broker.patchConfigurationDataWithinTransaction(context);
1283 } catch (final Exception e) {
1284 LOG.debug("Patch transaction failed", e);
1285 throw new RestconfDocumentedException(e.getMessage(), e);
1289 @SuppressWarnings("checkstyle:IllegalCatch")
1291 public PatchStatusContext patchConfigurationData(final PatchContext context, @Context final UriInfo uriInfo) {
1292 if (context == null) {
1293 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1297 return this.broker.patchConfigurationDataWithinTransaction(context);
1298 } catch (final Exception e) {
1299 LOG.debug("Patch transaction failed", e);
1300 throw new RestconfDocumentedException(e.getMessage(), e);
1305 * Load parameter for subscribing to stream from input composite node.
1309 * @return enum object if its string value is equal to {@code paramName}. In
1312 private static <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1313 final String paramName) {
1314 final Optional<DataContainerChild<? extends PathArgument, ?>> optAugNode = value.getChild(
1315 SAL_REMOTE_AUG_IDENTIFIER);
1316 if (!optAugNode.isPresent()) {
1319 final DataContainerChild<? extends PathArgument, ?> augNode = optAugNode.get();
1320 if (!(augNode instanceof AugmentationNode)) {
1323 final Optional<DataContainerChild<? extends PathArgument, ?>> enumNode = ((AugmentationNode) augNode).getChild(
1324 new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1325 if (!enumNode.isPresent()) {
1328 final Object rawValue = enumNode.get().getValue();
1329 if (!(rawValue instanceof String)) {
1333 return resolveAsEnum(classDescriptor, (String) rawValue);
1337 * Checks whether {@code value} is one of the string representation of
1338 * enumeration {@code classDescriptor}.
1340 * @return enum object if string value of {@code classDescriptor}
1341 * enumeration is equal to {@code value}. Other cases null.
1343 private static <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1344 if (Strings.isNullOrEmpty(value)) {
1347 return resolveAsEnum(classDescriptor, value);
1350 private static <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1351 final T[] enumConstants = classDescriptor.getEnumConstants();
1352 if (enumConstants != null) {
1353 for (final T enm : classDescriptor.getEnumConstants()) {
1354 if (((Enum<?>) enm).name().equals(value)) {
1362 private static Map<String, String> resolveValuesFromUri(final String uri) {
1363 final Map<String, String> result = new HashMap<>();
1364 final String[] tokens = uri.split("/");
1365 for (int i = 1; i < tokens.length; i++) {
1366 final String[] parameterTokens = tokens[i].split("=");
1367 if (parameterTokens.length == 2) {
1368 result.put(parameterTokens[0], parameterTokens[1]);
1374 private MapNode makeModuleMapNode(final Collection<? extends Module> modules) {
1375 Preconditions.checkNotNull(modules);
1376 final Module restconfModule = getRestconfModule();
1377 final DataSchemaNode moduleSchemaNode = this.controllerContext
1378 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1379 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1381 final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder =
1382 Builders.mapBuilder((ListSchemaNode) moduleSchemaNode);
1384 for (final Module module : modules) {
1385 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1387 return listModuleBuilder.build();
1390 private MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1391 Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1392 "moduleSchemaNode has to be of type ListSchemaNode");
1393 final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1394 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues =
1395 Builders.mapEntryBuilder(listModuleSchemaNode);
1397 List<DataSchemaNode> instanceDataChildrenByName =
1398 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "name");
1399 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1400 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1402 .withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName()).build());
1404 final QNameModule qNameModule = module.getQNameModule();
1406 instanceDataChildrenByName =
1407 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "revision");
1408 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1409 Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1410 final Optional<Revision> revision = qNameModule.getRevision();
1411 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode)
1412 .withValue(revision.map(Revision::toString).orElse("")).build());
1414 instanceDataChildrenByName =
1415 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "namespace");
1416 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1417 Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1418 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1419 .withValue(qNameModule.getNamespace().toString()).build());
1421 instanceDataChildrenByName =
1422 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "feature");
1423 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1424 Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1425 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder =
1426 Builders.leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1427 for (final FeatureDefinition feature : module.getFeatures()) {
1428 featuresBuilder.withChild(Builders.leafSetEntryBuilder((LeafListSchemaNode) featureSchemaNode)
1429 .withValue(feature.getQName().getLocalName()).build());
1431 moduleNodeValues.withChild(featuresBuilder.build());
1433 return moduleNodeValues.build();
1436 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1437 Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1438 "streamSchemaNode has to be of type ListSchemaNode");
1439 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1440 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues =
1441 Builders.mapEntryBuilder(listStreamSchemaNode);
1443 List<DataSchemaNode> instanceDataChildrenByName =
1444 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "name");
1445 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1446 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1447 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName).build());
1449 instanceDataChildrenByName =
1450 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "description");
1451 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1452 Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1453 streamNodeValues.withChild(
1454 Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue("DESCRIPTION_PLACEHOLDER").build());
1456 instanceDataChildrenByName =
1457 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-support");
1458 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1459 Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1460 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1461 .withValue(Boolean.TRUE).build());
1463 instanceDataChildrenByName =
1464 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-log-creation-time");
1465 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1466 Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1467 streamNodeValues.withChild(
1468 Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode).withValue("").build());
1470 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "events");
1471 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1472 Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1473 streamNodeValues.withChild(
1474 Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode).withValue(Empty.getInstance()).build());
1476 return streamNodeValues.build();
1480 * Prepare stream for notification.
1483 * contains list of qnames of notifications
1484 * @return - checked future object
1486 private ListenableFuture<DOMRpcResult> invokeSalRemoteRpcNotifiStrRPC(final NormalizedNodeContext payload) {
1487 final ContainerNode data = (ContainerNode) payload.getData();
1488 LeafSetNode leafSet = null;
1489 String outputType = "XML";
1490 for (final DataContainerChild<? extends PathArgument, ?> dataChild : data.getValue()) {
1491 if (dataChild instanceof LeafSetNode) {
1492 leafSet = (LeafSetNode) dataChild;
1493 } else if (dataChild instanceof AugmentationNode) {
1494 outputType = (String) ((AugmentationNode) dataChild).getValue().iterator().next().getValue();
1498 final Collection<LeafSetEntryNode> entryNodes = leafSet.getValue();
1499 final List<SchemaPath> paths = new ArrayList<>();
1500 String streamName = CREATE_NOTIFICATION_STREAM + "/";
1502 StringBuilder streamNameBuilder = new StringBuilder(streamName);
1503 final Iterator<LeafSetEntryNode> iterator = entryNodes.iterator();
1504 while (iterator.hasNext()) {
1505 final QName valueQName = QName.create((String) iterator.next().getValue());
1506 final Module module = controllerContext.findModuleByNamespace(valueQName.getModule().getNamespace());
1507 Preconditions.checkNotNull(module,
1508 "Module for namespace " + valueQName.getModule().getNamespace() + " does not exist");
1509 NotificationDefinition notifiDef = null;
1510 for (final NotificationDefinition notification : module.getNotifications()) {
1511 if (notification.getQName().equals(valueQName)) {
1512 notifiDef = notification;
1516 final String moduleName = module.getName();
1517 Preconditions.checkNotNull(notifiDef,
1518 "Notification " + valueQName + "doesn't exist in module " + moduleName);
1519 paths.add(notifiDef.getPath());
1520 streamNameBuilder.append(moduleName).append(':').append(valueQName.getLocalName());
1521 if (iterator.hasNext()) {
1522 streamNameBuilder.append(',');
1526 streamName = streamNameBuilder.toString();
1528 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
1529 final QName outputQname = QName.create(rpcQName, "output");
1530 final QName streamNameQname = QName.create(rpcQName, "notification-stream-identifier");
1532 final ContainerNode output =
1533 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
1534 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
1536 if (!Notificator.existNotificationListenerFor(streamName)) {
1537 Notificator.createNotificationListener(paths, streamName, outputType, controllerContext);
1540 return Futures.immediateFuture(new DefaultDOMRpcResult(output));