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.api.DOMSchemaService;
64 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
65 import org.opendaylight.netconf.sal.rest.api.Draft02;
66 import org.opendaylight.netconf.sal.rest.api.RestconfService;
67 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
68 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
69 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
70 import org.opendaylight.netconf.sal.streams.websockets.WebSocketServer;
71 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
72 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
73 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
74 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
75 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
76 import org.opendaylight.restconf.common.patch.PatchContext;
77 import org.opendaylight.restconf.common.patch.PatchStatusContext;
78 import org.opendaylight.restconf.common.util.DataChangeScope;
79 import org.opendaylight.restconf.common.util.OperationsResourceUtils;
80 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
81 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
82 import org.opendaylight.yangtools.yang.common.Empty;
83 import org.opendaylight.yangtools.yang.common.QName;
84 import org.opendaylight.yangtools.yang.common.QNameModule;
85 import org.opendaylight.yangtools.yang.common.Revision;
86 import org.opendaylight.yangtools.yang.common.YangConstants;
87 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
88 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
89 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
90 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
91 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
92 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
93 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
94 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
95 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
96 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
97 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
98 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
99 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
100 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
101 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
102 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
103 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
104 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
105 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
106 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
107 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeBuilder;
108 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
109 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
110 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
111 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
112 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
113 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
114 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
115 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
116 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
117 import org.opendaylight.yangtools.yang.model.api.Module;
118 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
119 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
120 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
121 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
122 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
123 import org.slf4j.Logger;
124 import org.slf4j.LoggerFactory;
127 public final class RestconfImpl implements RestconfService {
129 * Notifications are served on port 8181.
131 private static final int NOTIFICATION_PORT = 8181;
133 private static final int CHAR_NOT_FOUND = -1;
135 private static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
137 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
139 private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
141 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
143 private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
145 private static final String DATASTORE_PARAM_NAME = "datastore";
147 private static final String SCOPE_PARAM_NAME = "scope";
149 private static final String OUTPUT_TYPE_PARAM_NAME = "notification-output-type";
151 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
153 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
155 private static final QName NETCONF_BASE_QNAME = QName.create(QNameModule.create(URI.create(NETCONF_BASE)),
156 NETCONF_BASE_PAYLOAD_NAME).intern();
158 private static final QNameModule SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
159 Revision.of("2014-07-08"));
161 private static final AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER =
162 new AugmentationIdentifier(ImmutableSet.of(
163 QName.create(SAL_REMOTE_AUGMENT, "scope"), QName.create(SAL_REMOTE_AUGMENT, "datastore"),
164 QName.create(SAL_REMOTE_AUGMENT, "notification-output-type")));
166 public static final CharSequence DATA_SUBSCR = "data-change-event-subscription";
167 private static final CharSequence CREATE_DATA_SUBSCR = "create-" + DATA_SUBSCR;
169 public static final CharSequence NOTIFICATION_STREAM = "notification-stream";
170 private static final CharSequence CREATE_NOTIFICATION_STREAM = "create-" + NOTIFICATION_STREAM;
172 private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
173 .appendValue(ChronoField.YEAR, 4).appendLiteral('-')
174 .appendValue(ChronoField.MONTH_OF_YEAR, 2).appendLiteral('-')
175 .appendValue(ChronoField.DAY_OF_MONTH, 2).appendLiteral('T')
176 .appendValue(ChronoField.HOUR_OF_DAY, 2).appendLiteral(':')
177 .appendValue(ChronoField.MINUTE_OF_HOUR, 2).appendLiteral(':')
178 .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
179 .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
180 .appendOffset("+HH:MM", "Z").toFormatter();
182 private final BrokerFacade broker;
184 private final ControllerContext controllerContext;
187 public RestconfImpl(final BrokerFacade broker, final ControllerContext controllerContext) {
188 this.broker = broker;
189 this.controllerContext = controllerContext;
195 * @deprecated Just use {@link #RestconfImpl(BrokerFacade, ControllerContext)} constructor instead.
198 public static RestconfImpl newInstance(final BrokerFacade broker, final ControllerContext controllerContext) {
199 return new RestconfImpl(broker, controllerContext);
204 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
205 final MapNode allModuleMap = makeModuleMapNode(controllerContext.getAllModules());
207 final EffectiveModelContext schemaContext = this.controllerContext.getGlobalSchema();
209 final Module restconfModule = getRestconfModule();
210 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
211 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
212 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
214 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
215 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
216 moduleContainerBuilder.withChild(allModuleMap);
218 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode, null, schemaContext),
219 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
223 * Valid only for mount point.
227 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
228 Preconditions.checkNotNull(identifier);
229 if (!identifier.contains(ControllerContext.MOUNT)) {
230 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
231 + " URI has to end with " + ControllerContext.MOUNT;
232 LOG.debug("{} for {}", errMsg, identifier);
233 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
236 final InstanceIdentifierContext<?> mountPointIdentifier =
237 this.controllerContext.toMountPointIdentifier(identifier);
238 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
239 final MapNode mountPointModulesMap = makeModuleMapNode(controllerContext.getAllModules(mountPoint));
241 final Module restconfModule = getRestconfModule();
242 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
243 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
244 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
246 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
247 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
248 moduleContainerBuilder.withChild(mountPointModulesMap);
250 return new NormalizedNodeContext(
251 new InstanceIdentifierContext<>(null, modulesSchemaNode, mountPoint,
252 this.controllerContext.getGlobalSchema()),
253 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
258 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
259 Preconditions.checkNotNull(identifier);
260 final Entry<String, Revision> nameRev = getModuleNameAndRevision(identifier);
261 Module module = null;
262 DOMMountPoint mountPoint = null;
263 final EffectiveModelContext schemaContext;
264 if (identifier.contains(ControllerContext.MOUNT)) {
265 final InstanceIdentifierContext<?> mountPointIdentifier =
266 this.controllerContext.toMountPointIdentifier(identifier);
267 mountPoint = mountPointIdentifier.getMountPoint();
268 module = this.controllerContext.findModuleByNameAndRevision(mountPoint, nameRev.getKey(),
270 schemaContext = modelContext(mountPoint);
272 module = this.controllerContext.findModuleByNameAndRevision(nameRev.getKey(), nameRev.getValue());
273 schemaContext = this.controllerContext.getGlobalSchema();
276 if (module == null) {
277 LOG.debug("Module with name '{}' and revision '{}' was not found.", nameRev.getKey(), nameRev.getValue());
278 throw new RestconfDocumentedException("Module with name '" + nameRev.getKey() + "' and revision '"
279 + nameRev.getValue() + "' was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
282 final Module restconfModule = getRestconfModule();
283 final Set<Module> modules = Collections.singleton(module);
284 final MapNode moduleMap = makeModuleMapNode(modules);
286 final DataSchemaNode moduleSchemaNode = this.controllerContext
287 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
288 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
290 return new NormalizedNodeContext(
291 new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint, schemaContext), moduleMap,
292 QueryParametersParser.parseWriterParameters(uriInfo));
297 public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
298 final EffectiveModelContext schemaContext = this.controllerContext.getGlobalSchema();
299 final Set<String> availableStreams = Notificator.getStreamNames();
300 final Module restconfModule = getRestconfModule();
301 final DataSchemaNode streamSchemaNode = this.controllerContext
302 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
303 Preconditions.checkState(streamSchemaNode instanceof ListSchemaNode);
305 final CollectionNodeBuilder<MapEntryNode, MapNode> listStreamsBuilder =
306 Builders.mapBuilder((ListSchemaNode) streamSchemaNode);
308 for (final String streamName : availableStreams) {
309 listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
312 final DataSchemaNode streamsContainerSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
313 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
314 Preconditions.checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
316 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
317 Builders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
318 streamsContainerBuilder.withChild(listStreamsBuilder.build());
320 return new NormalizedNodeContext(
321 new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null, schemaContext),
322 streamsContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
327 public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
328 return OperationsResourceUtils.contextForModelContext(controllerContext.getGlobalSchema(), null);
333 public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
334 if (!identifier.contains(ControllerContext.MOUNT)) {
335 final String errMsg = "URI has bad format. If operations behind mount point should be showed, URI has to "
336 + " end with " + ControllerContext.MOUNT;
337 LOG.debug("{} for {}", errMsg, identifier);
338 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
341 final InstanceIdentifierContext<?> mountPointIdentifier =
342 this.controllerContext.toMountPointIdentifier(identifier);
343 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
344 return OperationsResourceUtils.contextForModelContext(modelContext(mountPoint), mountPoint);
347 private Module getRestconfModule() {
348 final Module restconfModule = this.controllerContext.getRestconfModule();
349 if (restconfModule == null) {
350 LOG.debug("ietf-restconf module was not found.");
351 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
352 ErrorTag.OPERATION_NOT_SUPPORTED);
355 return restconfModule;
358 private static Entry<String, Revision> getModuleNameAndRevision(final String identifier) {
359 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
360 String moduleNameAndRevision = "";
361 if (mountIndex >= 0) {
362 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
364 moduleNameAndRevision = identifier;
367 final Splitter splitter = Splitter.on('/').omitEmptyStrings();
368 final List<String> pathArgs = splitter.splitToList(moduleNameAndRevision);
369 if (pathArgs.size() < 2) {
370 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' {}", identifier);
371 throw new RestconfDocumentedException(
372 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
373 ErrorTag.INVALID_VALUE);
377 return new SimpleImmutableEntry<>(pathArgs.get(0), Revision.of(pathArgs.get(1)));
378 } catch (final DateTimeParseException e) {
379 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' {}", identifier);
380 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
381 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
386 public Object getRoot() {
391 public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload,
392 final UriInfo uriInfo) {
393 if (payload == null) {
394 // no payload specified, reroute this to no payload invokeRpc implementation
395 return invokeRpc(identifier, uriInfo);
398 final SchemaNode schema = payload.getInstanceIdentifierContext().getSchemaNode();
399 final ListenableFuture<? extends DOMRpcResult> response;
400 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
401 final NormalizedNode<?, ?> input = nonnullInput(schema, payload.getData());
402 final EffectiveModelContext schemaContext;
404 if (mountPoint != null) {
405 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
406 if (!mountRpcServices.isPresent()) {
407 LOG.debug("Error: Rpc service is missing.");
408 throw new RestconfDocumentedException("Rpc service is missing.");
410 schemaContext = modelContext(mountPoint);
411 response = mountRpcServices.get().invokeRpc(schema.getQName(), input);
413 final URI namespace = schema.getQName().getNamespace();
414 if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
415 if (identifier.contains(CREATE_DATA_SUBSCR)) {
416 response = invokeSalRemoteRpcSubscribeRPC(payload);
417 } else if (identifier.contains(CREATE_NOTIFICATION_STREAM)) {
418 response = invokeSalRemoteRpcNotifiStrRPC(payload);
420 final String msg = "Not supported operation";
422 throw new RestconfDocumentedException(msg, ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED);
425 response = this.broker.invokeRpc(schema.getQName(), input);
427 schemaContext = this.controllerContext.getGlobalSchema();
430 final DOMRpcResult result = checkRpcResponse(response);
432 RpcDefinition resultNodeSchema = null;
433 final NormalizedNode<?, ?> resultData;
434 if (result != null && result.getResult() != null) {
435 resultData = result.getResult();
436 resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
441 if (resultData != null && ((ContainerNode) resultData).getValue().isEmpty()) {
442 throw new WebApplicationException(Response.Status.NO_CONTENT);
444 return new NormalizedNodeContext(
445 new InstanceIdentifierContext<>(null, resultNodeSchema, mountPoint, schemaContext),
446 resultData, QueryParametersParser.parseWriterParameters(uriInfo));
450 @SuppressFBWarnings(value = "NP_LOAD_OF_KNOWN_NULL_VALUE",
451 justification = "Looks like a false positive, see below FIXME")
452 private NormalizedNodeContext invokeRpc(final String identifier, final UriInfo uriInfo) {
453 final DOMMountPoint mountPoint;
454 final String identifierEncoded;
455 final EffectiveModelContext schemaContext;
456 if (identifier.contains(ControllerContext.MOUNT)) {
457 // mounted RPC call - look up mount instance.
458 final InstanceIdentifierContext<?> mountPointId = this.controllerContext.toMountPointIdentifier(identifier);
459 mountPoint = mountPointId.getMountPoint();
460 schemaContext = modelContext(mountPoint);
461 final int startOfRemoteRpcName =
462 identifier.lastIndexOf(ControllerContext.MOUNT) + ControllerContext.MOUNT.length() + 1;
463 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
464 identifierEncoded = remoteRpcName;
466 } else if (identifier.indexOf('/') == CHAR_NOT_FOUND) {
467 identifierEncoded = identifier;
469 schemaContext = this.controllerContext.getGlobalSchema();
471 LOG.debug("Identifier {} cannot contain slash character (/).", identifier);
472 throw new RestconfDocumentedException(String.format("Identifier %n%s%ncan\'t contain slash character (/).%n"
473 + "If slash is part of identifier name then use %%2F placeholder.", identifier), ErrorType.PROTOCOL,
474 ErrorTag.INVALID_VALUE);
477 final String identifierDecoded = ControllerContext.urlPathArgDecode(identifierEncoded);
478 final RpcDefinition rpc;
479 if (mountPoint == null) {
480 rpc = this.controllerContext.getRpcDefinition(identifierDecoded);
482 rpc = findRpc(modelContext(mountPoint), identifierDecoded);
486 LOG.debug("RPC {} does not exist.", identifierDecoded);
487 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
490 if (!rpc.getInput().getChildNodes().isEmpty()) {
491 LOG.debug("No input specified for RPC {} with an input section", rpc);
492 throw new RestconfDocumentedException("No input specified for RPC " + rpc
493 + " with an input section defined", ErrorType.RPC, ErrorTag.MISSING_ELEMENT);
496 final ContainerNode input = defaultInput(rpc.getQName());
497 final ListenableFuture<? extends DOMRpcResult> response;
498 if (mountPoint != null) {
499 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
500 if (!mountRpcServices.isPresent()) {
501 throw new RestconfDocumentedException("Rpc service is missing.");
503 response = mountRpcServices.get().invokeRpc(rpc.getQName(), input);
505 response = this.broker.invokeRpc(rpc.getQName(), input);
508 final NormalizedNode<?, ?> result = checkRpcResponse(response).getResult();
509 if (result != null && ((ContainerNode) result).getValue().isEmpty()) {
510 throw new WebApplicationException(Response.Status.NO_CONTENT);
513 // FIXME: in reference to the above @SupressFBWarnings: "mountPoint" reference here trips up SpotBugs, as it
514 // thinks it can only ever be null. Except it can very much be non-null. The core problem is the horrible
515 // structure of this code where we have a sh*tload of checks for mountpoint above and all over the
516 // codebase where all that difference should have been properly encapsulated.
518 // This is legacy code, so if anybody cares to do that refactor, feel free to contribute, but I am not
520 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpc, mountPoint, schemaContext), result,
521 QueryParametersParser.parseWriterParameters(uriInfo));
524 private static @NonNull NormalizedNode<?, ?> nonnullInput(final SchemaNode rpc, final NormalizedNode<?, ?> input) {
525 return input != null ? input : defaultInput(rpc.getQName());
528 private static @NonNull ContainerNode defaultInput(final QName rpcName) {
529 return ImmutableNodes.containerNode(YangConstants.operationInputQName(rpcName.getModule()));
532 @SuppressWarnings("checkstyle:avoidHidingCauseException")
533 private static DOMRpcResult checkRpcResponse(final ListenableFuture<? extends DOMRpcResult> response) {
534 if (response == null) {
538 final DOMRpcResult retValue = response.get();
539 if (retValue.getErrors().isEmpty()) {
542 LOG.debug("RpcError message {}", retValue.getErrors());
543 throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
544 } catch (final InterruptedException e) {
545 final String errMsg = "The operation was interrupted while executing and did not complete.";
546 LOG.debug("Rpc Interrupt - {}", errMsg, e);
547 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION, e);
548 } catch (final ExecutionException e) {
549 LOG.debug("Execution RpcError: ", e);
550 Throwable cause = e.getCause();
552 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
555 while (cause.getCause() != null) {
556 cause = cause.getCause();
559 if (cause instanceof IllegalArgumentException) {
560 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
561 } else if (cause instanceof DOMRpcImplementationNotAvailableException) {
562 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.APPLICATION,
563 ErrorTag.OPERATION_NOT_SUPPORTED);
565 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
567 } catch (final CancellationException e) {
568 final String errMsg = "The operation was cancelled while executing.";
569 LOG.debug("Cancel RpcExecution: {}", errMsg, e);
570 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
574 private static void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
575 if (inputSchema != null && payload.getData() == null) {
576 // expected a non null payload
577 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
578 } else if (inputSchema == null && payload.getData() != null) {
579 // did not expect any input
580 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
584 private ListenableFuture<DOMRpcResult> invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
585 final ContainerNode value = (ContainerNode) payload.getData();
586 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
587 final Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(
588 new NodeIdentifier(QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(),
590 final Object pathValue = path.isPresent() ? path.get().getValue() : null;
592 if (!(pathValue instanceof YangInstanceIdentifier)) {
593 LOG.debug("Instance identifier {} was not normalized correctly", rpcQName);
594 throw new RestconfDocumentedException("Instance identifier was not normalized correctly",
595 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
598 final YangInstanceIdentifier pathIdentifier = (YangInstanceIdentifier) pathValue;
599 String streamName = (String) CREATE_DATA_SUBSCR;
600 NotificationOutputType outputType = null;
601 if (!pathIdentifier.isEmpty()) {
602 final String fullRestconfIdentifier =
603 DATA_SUBSCR + this.controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
605 LogicalDatastoreType datastore =
606 parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
607 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
609 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
610 scope = scope == null ? DEFAULT_SCOPE : scope;
612 outputType = parseEnumTypeParameter(value, NotificationOutputType.class, OUTPUT_TYPE_PARAM_NAME);
613 outputType = outputType == null ? NotificationOutputType.XML : outputType;
615 streamName = Notificator
616 .createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore + "/scope=" + scope);
619 if (Strings.isNullOrEmpty(streamName)) {
620 LOG.debug("Path is empty or contains value node which is not Container or List built-in type at {}",
622 throw new RestconfDocumentedException("Path is empty or contains value node which is not Container or List "
623 + "built-in type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
626 final QName outputQname = QName.create(rpcQName, "output");
627 final QName streamNameQname = QName.create(rpcQName, "stream-name");
629 final ContainerNode output =
630 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
631 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
633 if (!Notificator.existListenerFor(streamName)) {
634 Notificator.createListener(pathIdentifier, streamName, outputType, controllerContext);
637 return Futures.immediateFuture(new DefaultDOMRpcResult(output));
640 private static RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
641 final String[] splittedIdentifier = identifierDecoded.split(":");
642 if (splittedIdentifier.length != 2) {
643 LOG.debug("{} could not be split to 2 parts (module:rpc name)", identifierDecoded);
644 throw new RestconfDocumentedException(identifierDecoded + " could not be split to 2 parts "
645 + "(module:rpc name)", ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
647 for (final Module module : schemaContext.getModules()) {
648 if (module.getName().equals(splittedIdentifier[0])) {
649 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
650 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
651 return rpcDefinition;
660 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
661 boolean withDefaUsed = false;
662 String withDefa = null;
664 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
665 switch (entry.getKey()) {
666 case "with-defaults":
669 withDefa = entry.getValue().iterator().next();
671 throw new RestconfDocumentedException("With-defaults parameter can be used only once.");
675 LOG.info("Unknown key : {}.", entry.getKey());
679 boolean tagged = false;
681 if ("report-all-tagged".equals(withDefa)) {
685 if ("report-all".equals(withDefa)) {
690 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
691 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
692 NormalizedNode<?, ?> data = null;
693 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
694 if (mountPoint != null) {
695 data = this.broker.readConfigurationData(mountPoint, normalizedII, withDefa);
697 data = this.broker.readConfigurationData(normalizedII, withDefa);
700 throw dataMissing(identifier);
702 return new NormalizedNodeContext(iiWithData, data,
703 QueryParametersParser.parseWriterParameters(uriInfo, tagged));
707 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
708 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
709 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
710 NormalizedNode<?, ?> data = null;
711 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
712 if (mountPoint != null) {
713 data = this.broker.readOperationalData(mountPoint, normalizedII);
715 data = this.broker.readOperationalData(normalizedII);
718 throw dataMissing(identifier);
720 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
723 private static RestconfDocumentedException dataMissing(final String identifier) {
724 LOG.debug("Request could not be completed because the relevant data model content does not exist {}",
726 return new RestconfDocumentedException("Request could not be completed because the relevant data model content "
727 + "does not exist", ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
731 public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload,
732 final UriInfo uriInfo) {
733 boolean insertUsed = false;
734 boolean pointUsed = false;
735 String insert = null;
738 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
739 switch (entry.getKey()) {
743 insert = entry.getValue().iterator().next();
745 throw new RestconfDocumentedException("Insert parameter can be used only once.");
751 point = entry.getValue().iterator().next();
753 throw new RestconfDocumentedException("Point parameter can be used only once.");
757 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
761 if (pointUsed && !insertUsed) {
762 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
764 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
765 throw new RestconfDocumentedException(
766 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
769 Preconditions.checkNotNull(identifier);
771 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
773 validateInput(iiWithData.getSchemaNode(), payload);
774 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
775 validateListKeysEqualityInPayloadAndUri(payload);
777 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
778 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
781 * There is a small window where another write transaction could be
782 * updating the same data simultaneously and we get an
783 * OptimisticLockFailedException. This error is likely transient and The
784 * WriteTransaction#submit API docs state that a retry will likely
785 * succeed. So we'll try again if that scenario occurs. If it fails a
786 * third time then it probably will never succeed so we'll fail in that
789 * By retrying we're attempting to hide the internal implementation of
790 * the data store and how it handles concurrent updates from the
791 * restconf client. The client has instructed us to put the data and we
792 * should make every effort to do so without pushing optimistic lock
793 * failures back to the client and forcing them to handle it via retry
794 * (and having to document the behavior).
796 PutResult result = null;
799 if (mountPoint != null) {
801 result = this.broker.commitMountPointDataPut(mountPoint, normalizedII, payload.getData(), insert,
804 result = this.broker.commitConfigurationDataPut(this.controllerContext.getGlobalSchema(), normalizedII,
805 payload.getData(), insert, point);
809 result.getFutureOfPutData().get();
810 } catch (final InterruptedException e) {
811 LOG.debug("Update failed for {}", identifier, e);
812 throw new RestconfDocumentedException(e.getMessage(), e);
813 } catch (final ExecutionException e) {
814 final TransactionCommitFailedException failure = Throwables.getCauseAs(e,
815 TransactionCommitFailedException.class);
816 if (failure instanceof OptimisticLockFailedException) {
818 LOG.debug("Got OptimisticLockFailedException on last try - failing {}", identifier);
819 throw new RestconfDocumentedException(e.getMessage(), e, failure.getErrorList());
822 LOG.debug("Got OptimisticLockFailedException - trying again {}", identifier);
826 LOG.debug("Update failed for {}", identifier, e);
827 throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), failure);
830 return Response.status(result.getStatus()).build();
834 private static void validateTopLevelNodeName(final NormalizedNodeContext node,
835 final YangInstanceIdentifier identifier) {
837 final String payloadName = node.getData().getNodeType().getLocalName();
840 if (identifier.isEmpty()) {
842 if (!node.getData().getNodeType().equals(NETCONF_BASE_QNAME)) {
843 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
844 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
848 final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
849 if (!payloadName.equals(identifierName)) {
850 throw new RestconfDocumentedException(
851 "Payload name (" + payloadName + ") is different from identifier name (" + identifierName + ")",
852 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
858 * Validates whether keys in {@code payload} are equal to values of keys in
859 * {@code iiWithData} for list schema node.
861 * @throws RestconfDocumentedException
862 * if key values or key count in payload and URI isn't equal
865 private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
866 Preconditions.checkArgument(payload != null);
867 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
868 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
869 final SchemaNode schemaNode = iiWithData.getSchemaNode();
870 final NormalizedNode<?, ?> data = payload.getData();
871 if (schemaNode instanceof ListSchemaNode) {
872 final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
873 if (lastPathArgument instanceof NodeIdentifierWithPredicates && data instanceof MapEntryNode) {
874 final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument).asMap();
875 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
881 public static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final MapEntryNode payload,
882 final List<QName> keyDefinitions) {
884 final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
885 for (final QName keyDefinition : keyDefinitions) {
886 final Object uriKeyValue = RestconfDocumentedException.throwIfNull(
887 // should be caught during parsing URI to InstanceIdentifier
888 mutableCopyUriKeyValues.remove(keyDefinition), ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
889 "Missing key %s in URI.", keyDefinition);
891 final Object dataKeyValue = payload.getIdentifier().getValue(keyDefinition);
893 if (!Objects.deepEquals(uriKeyValue, dataKeyValue)) {
894 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName()
895 + "' specified in the URI doesn't match the value '" + dataKeyValue
896 + "' specified in the message body. ";
897 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
903 public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload,
904 final UriInfo uriInfo) {
905 return createConfigurationData(payload, uriInfo);
909 public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
910 if (payload == null) {
911 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
913 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
914 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
915 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
917 boolean insertUsed = false;
918 boolean pointUsed = false;
919 String insert = null;
922 if (uriInfo != null) {
923 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
924 switch (entry.getKey()) {
928 insert = entry.getValue().iterator().next();
930 throw new RestconfDocumentedException("Insert parameter can be used only once.");
936 point = entry.getValue().iterator().next();
938 throw new RestconfDocumentedException("Point parameter can be used only once.");
942 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
947 if (pointUsed && !insertUsed) {
948 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
950 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
951 throw new RestconfDocumentedException(
952 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
955 FluentFuture<? extends CommitInfo> future;
956 if (mountPoint != null) {
957 future = this.broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData(), insert,
960 future = this.broker.commitConfigurationDataPost(this.controllerContext.getGlobalSchema(), normalizedII,
961 payload.getData(), insert, point);
966 } catch (final InterruptedException e) {
967 LOG.info("Error creating data {}", uriInfo != null ? uriInfo.getPath() : "", e);
968 throw new RestconfDocumentedException(e.getMessage(), e);
969 } catch (final ExecutionException e) {
970 LOG.info("Error creating data {}", uriInfo != null ? uriInfo.getPath() : "", e);
971 throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), Throwables.getCauseAs(e,
972 TransactionCommitFailedException.class));
975 LOG.trace("Successfuly created data.");
977 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
978 // FIXME: Provide path to result.
979 final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
980 if (location != null) {
981 responseBuilder.location(location);
983 return responseBuilder.build();
986 @SuppressWarnings("checkstyle:IllegalCatch")
987 private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint,
988 final YangInstanceIdentifier normalizedII) {
989 if (uriInfo == null) {
990 // This is null if invoked internally
994 final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
995 uriBuilder.path("config");
997 uriBuilder.path(this.controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
998 } catch (final Exception e) {
999 LOG.info("Location for instance identifier {} was not created", normalizedII, e);
1002 return uriBuilder.build();
1006 public Response deleteConfigurationData(final String identifier) {
1007 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
1008 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
1009 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
1011 final FluentFuture<? extends CommitInfo> future;
1012 if (mountPoint != null) {
1013 future = this.broker.commitConfigurationDataDelete(mountPoint, normalizedII);
1015 future = this.broker.commitConfigurationDataDelete(normalizedII);
1020 } catch (final InterruptedException e) {
1021 throw new RestconfDocumentedException(e.getMessage(), e);
1022 } catch (final ExecutionException e) {
1023 final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
1024 Predicates.instanceOf(ModifiedNodeDoesNotExistException.class)).toJavaUtil();
1025 if (searchedException.isPresent()) {
1026 throw new RestconfDocumentedException("Data specified for delete doesn't exist.", ErrorType.APPLICATION,
1027 ErrorTag.DATA_MISSING, e);
1030 throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), Throwables.getCauseAs(e,
1031 TransactionCommitFailedException.class));
1034 return Response.status(Status.OK).build();
1038 * Subscribes to some path in schema context (stream) to listen on changes
1042 * Additional parameters for subscribing to stream are loaded via rpc input
1045 * <li>datastore - default CONFIGURATION (other values of
1046 * {@link LogicalDatastoreType} enum type)</li>
1047 * <li>scope - default BASE (other values of {@link DataChangeScope})</li>
1051 public NormalizedNodeContext subscribeToStream(final String identifier, final UriInfo uriInfo) {
1052 boolean startTimeUsed = false;
1053 boolean stopTimeUsed = false;
1054 Instant start = Instant.now();
1055 Instant stop = null;
1056 boolean filterUsed = false;
1057 String filter = null;
1058 boolean leafNodesOnlyUsed = false;
1059 boolean leafNodesOnly = false;
1060 boolean skipNotificationDataUsed = false;
1061 boolean skipNotificationData = false;
1063 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
1064 switch (entry.getKey()) {
1066 if (!startTimeUsed) {
1067 startTimeUsed = true;
1068 start = parseDateFromQueryParam(entry);
1070 throw new RestconfDocumentedException("Start-time parameter can be used only once.");
1074 if (!stopTimeUsed) {
1075 stopTimeUsed = true;
1076 stop = parseDateFromQueryParam(entry);
1078 throw new RestconfDocumentedException("Stop-time parameter can be used only once.");
1084 filter = entry.getValue().iterator().next();
1086 throw new RestconfDocumentedException("Filter parameter can be used only once.");
1089 case "odl-leaf-nodes-only":
1090 if (!leafNodesOnlyUsed) {
1091 leafNodesOnlyUsed = true;
1092 leafNodesOnly = Boolean.parseBoolean(entry.getValue().iterator().next());
1094 throw new RestconfDocumentedException("Odl-leaf-nodes-only parameter can be used only once.");
1097 case "odl-skip-notification-data":
1098 if (!skipNotificationDataUsed) {
1099 skipNotificationDataUsed = true;
1100 skipNotificationData = Boolean.parseBoolean(entry.getValue().iterator().next());
1102 throw new RestconfDocumentedException(
1103 "Odl-skip-notification-data parameter can be used only once.");
1107 throw new RestconfDocumentedException("Bad parameter used with notifications: " + entry.getKey());
1110 if (!startTimeUsed && stopTimeUsed) {
1111 throw new RestconfDocumentedException("Stop-time parameter has to be used with start-time parameter.");
1113 URI response = null;
1114 if (identifier.contains(DATA_SUBSCR)) {
1115 response = dataSubs(identifier, uriInfo, start, stop, filter, leafNodesOnly, skipNotificationData);
1116 } else if (identifier.contains(NOTIFICATION_STREAM)) {
1117 response = notifStream(identifier, uriInfo, start, stop, filter);
1120 if (response != null) {
1121 // prepare node with value of location
1122 final InstanceIdentifierContext<?> iid = prepareIIDSubsStreamOutput();
1123 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> builder =
1124 ImmutableLeafNodeBuilder.create().withValue(response.toString());
1125 builder.withNodeIdentifier(
1126 NodeIdentifier.create(QName.create("subscribe:to:notification", "2016-10-28", "location")));
1128 // prepare new header with location
1129 final Map<String, Object> headers = new HashMap<>();
1130 headers.put("Location", response);
1132 return new NormalizedNodeContext(iid, builder.build(), headers);
1135 final String msg = "Bad type of notification of sal-remote";
1137 throw new RestconfDocumentedException(msg);
1140 private static Instant parseDateFromQueryParam(final Entry<String, List<String>> entry) {
1141 final DateAndTime event = new DateAndTime(entry.getValue().iterator().next());
1142 final String value = event.getValue();
1143 final TemporalAccessor p;
1145 p = FORMATTER.parse(value);
1146 } catch (final DateTimeParseException e) {
1147 throw new RestconfDocumentedException("Cannot parse of value in date: " + value, e);
1149 return Instant.from(p);
1153 * Prepare instance identifier.
1155 * @return {@link InstanceIdentifierContext} of location leaf for
1158 private InstanceIdentifierContext<?> prepareIIDSubsStreamOutput() {
1159 final QName qnameBase = QName.create("subscribe:to:notification", "2016-10-28", "notifi");
1160 final EffectiveModelContext schemaCtx = controllerContext.getGlobalSchema();
1161 final DataSchemaNode location = ((ContainerSchemaNode) schemaCtx
1162 .findModule(qnameBase.getModule()).orElse(null)
1163 .getDataChildByName(qnameBase)).getDataChildByName(QName.create(qnameBase, "location"));
1164 final List<PathArgument> path = new ArrayList<>();
1165 path.add(NodeIdentifier.create(qnameBase));
1166 path.add(NodeIdentifier.create(QName.create(qnameBase, "location")));
1168 return new InstanceIdentifierContext<SchemaNode>(YangInstanceIdentifier.create(path), location, null,
1173 * Register notification listener by stream name.
1180 * stop-time of getting notification
1182 * start-time of getting notification
1184 * indicate which subset of all possible events are of interest
1185 * @return {@link URI} of location
1187 private URI notifStream(final String identifier, final UriInfo uriInfo, final Instant start,
1188 final Instant stop, final String filter) {
1189 final String streamName = Notificator.createStreamNameFromUri(identifier);
1190 if (Strings.isNullOrEmpty(streamName)) {
1191 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1193 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
1194 if (listeners == null || listeners.isEmpty()) {
1195 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1196 ErrorTag.UNKNOWN_ELEMENT);
1199 for (final NotificationListenerAdapter listener : listeners) {
1200 this.broker.registerToListenNotification(listener);
1201 listener.setQueryParams(start, Optional.ofNullable(stop), Optional.ofNullable(filter), false, false);
1204 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1206 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance(NOTIFICATION_PORT);
1207 final int notificationPort = webSocketServerInstance.getPort();
1210 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme(getWsScheme(uriInfo));
1212 return uriToWebsocketServerBuilder.replacePath(streamName).build();
1215 private static String getWsScheme(final UriInfo uriInfo) {
1216 URI uri = uriInfo.getAbsolutePath();
1220 String subscriptionScheme = uri.getScheme().toLowerCase(Locale.ROOT);
1221 return subscriptionScheme.equals("https") ? "wss" : "ws";
1225 * Register data change listener by stream name.
1232 * start-time of getting notification
1234 * stop-time of getting notification
1236 * indicate which subset of all possible events are of interest
1237 * @return {@link URI} of location
1239 private URI dataSubs(final String identifier, final UriInfo uriInfo, final Instant start, final Instant stop,
1240 final String filter, final boolean leafNodesOnly, final boolean skipNotificationData) {
1241 final String streamName = Notificator.createStreamNameFromUri(identifier);
1242 if (Strings.isNullOrEmpty(streamName)) {
1243 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1246 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1247 if (listener == null) {
1248 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1249 ErrorTag.UNKNOWN_ELEMENT);
1251 listener.setQueryParams(start, Optional.ofNullable(stop), Optional.ofNullable(filter), leafNodesOnly,
1252 skipNotificationData);
1254 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1255 final LogicalDatastoreType datastore =
1256 parserURIEnumParameter(LogicalDatastoreType.class, paramToValues.get(DATASTORE_PARAM_NAME));
1257 if (datastore == null) {
1258 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1259 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1261 final DataChangeScope scope =
1262 parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
1263 if (scope == null) {
1264 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1265 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1268 this.broker.registerToListenDataChanges(datastore, scope, listener);
1270 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1272 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance(NOTIFICATION_PORT);
1273 final int notificationPort = webSocketServerInstance.getPort();
1275 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme(getWsScheme(uriInfo));
1277 return uriToWebsocketServerBuilder.replacePath(streamName).build();
1280 @SuppressWarnings("checkstyle:IllegalCatch")
1282 public PatchStatusContext patchConfigurationData(final String identifier, final PatchContext context,
1283 final UriInfo uriInfo) {
1284 if (context == null) {
1285 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1289 return this.broker.patchConfigurationDataWithinTransaction(context);
1290 } catch (final Exception e) {
1291 LOG.debug("Patch transaction failed", e);
1292 throw new RestconfDocumentedException(e.getMessage(), e);
1296 @SuppressWarnings("checkstyle:IllegalCatch")
1298 public PatchStatusContext patchConfigurationData(final PatchContext context, @Context final UriInfo uriInfo) {
1299 if (context == null) {
1300 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1304 return this.broker.patchConfigurationDataWithinTransaction(context);
1305 } catch (final Exception e) {
1306 LOG.debug("Patch transaction failed", e);
1307 throw new RestconfDocumentedException(e.getMessage(), e);
1312 * Load parameter for subscribing to stream from input composite node.
1316 * @return enum object if its string value is equal to {@code paramName}. In
1319 private static <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1320 final String paramName) {
1321 final Optional<DataContainerChild<? extends PathArgument, ?>> optAugNode = value.getChild(
1322 SAL_REMOTE_AUG_IDENTIFIER);
1323 if (!optAugNode.isPresent()) {
1326 final DataContainerChild<? extends PathArgument, ?> augNode = optAugNode.get();
1327 if (!(augNode instanceof AugmentationNode)) {
1330 final Optional<DataContainerChild<? extends PathArgument, ?>> enumNode = ((AugmentationNode) augNode).getChild(
1331 new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1332 if (!enumNode.isPresent()) {
1335 final Object rawValue = enumNode.get().getValue();
1336 if (!(rawValue instanceof String)) {
1340 return resolveAsEnum(classDescriptor, (String) rawValue);
1344 * Checks whether {@code value} is one of the string representation of
1345 * enumeration {@code classDescriptor}.
1347 * @return enum object if string value of {@code classDescriptor}
1348 * enumeration is equal to {@code value}. Other cases null.
1350 private static <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1351 if (Strings.isNullOrEmpty(value)) {
1354 return resolveAsEnum(classDescriptor, value);
1357 private static <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1358 final T[] enumConstants = classDescriptor.getEnumConstants();
1359 if (enumConstants != null) {
1360 for (final T enm : classDescriptor.getEnumConstants()) {
1361 if (((Enum<?>) enm).name().equals(value)) {
1369 private static Map<String, String> resolveValuesFromUri(final String uri) {
1370 final Map<String, String> result = new HashMap<>();
1371 final String[] tokens = uri.split("/");
1372 for (int i = 1; i < tokens.length; i++) {
1373 final String[] parameterTokens = tokens[i].split("=");
1374 if (parameterTokens.length == 2) {
1375 result.put(parameterTokens[0], parameterTokens[1]);
1381 private MapNode makeModuleMapNode(final Collection<? extends Module> modules) {
1382 Preconditions.checkNotNull(modules);
1383 final Module restconfModule = getRestconfModule();
1384 final DataSchemaNode moduleSchemaNode = this.controllerContext
1385 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1386 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1388 final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder =
1389 Builders.mapBuilder((ListSchemaNode) moduleSchemaNode);
1391 for (final Module module : modules) {
1392 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1394 return listModuleBuilder.build();
1397 private MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1398 Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1399 "moduleSchemaNode has to be of type ListSchemaNode");
1400 final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1401 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues =
1402 Builders.mapEntryBuilder(listModuleSchemaNode);
1404 List<DataSchemaNode> instanceDataChildrenByName =
1405 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "name");
1406 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1407 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1409 .withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName()).build());
1411 final QNameModule qNameModule = module.getQNameModule();
1413 instanceDataChildrenByName =
1414 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "revision");
1415 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1416 Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1417 final Optional<Revision> revision = qNameModule.getRevision();
1418 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode)
1419 .withValue(revision.map(Revision::toString).orElse("")).build());
1421 instanceDataChildrenByName =
1422 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "namespace");
1423 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1424 Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1425 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1426 .withValue(qNameModule.getNamespace().toString()).build());
1428 instanceDataChildrenByName =
1429 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "feature");
1430 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1431 Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1432 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder =
1433 Builders.leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1434 for (final FeatureDefinition feature : module.getFeatures()) {
1435 featuresBuilder.withChild(Builders.leafSetEntryBuilder((LeafListSchemaNode) featureSchemaNode)
1436 .withValue(feature.getQName().getLocalName()).build());
1438 moduleNodeValues.withChild(featuresBuilder.build());
1440 return moduleNodeValues.build();
1443 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1444 Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1445 "streamSchemaNode has to be of type ListSchemaNode");
1446 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1447 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues =
1448 Builders.mapEntryBuilder(listStreamSchemaNode);
1450 List<DataSchemaNode> instanceDataChildrenByName =
1451 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "name");
1452 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1453 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1454 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName).build());
1456 instanceDataChildrenByName =
1457 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "description");
1458 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1459 Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1460 streamNodeValues.withChild(
1461 Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue("DESCRIPTION_PLACEHOLDER").build());
1463 instanceDataChildrenByName =
1464 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-support");
1465 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1466 Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1467 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1468 .withValue(Boolean.TRUE).build());
1470 instanceDataChildrenByName =
1471 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-log-creation-time");
1472 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1473 Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1474 streamNodeValues.withChild(
1475 Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode).withValue("").build());
1477 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "events");
1478 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1479 Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1480 streamNodeValues.withChild(
1481 Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode).withValue(Empty.getInstance()).build());
1483 return streamNodeValues.build();
1487 * Prepare stream for notification.
1490 * contains list of qnames of notifications
1491 * @return - checked future object
1493 private ListenableFuture<DOMRpcResult> invokeSalRemoteRpcNotifiStrRPC(final NormalizedNodeContext payload) {
1494 final ContainerNode data = (ContainerNode) payload.getData();
1495 LeafSetNode leafSet = null;
1496 String outputType = "XML";
1497 for (final DataContainerChild<? extends PathArgument, ?> dataChild : data.getValue()) {
1498 if (dataChild instanceof LeafSetNode) {
1499 leafSet = (LeafSetNode) dataChild;
1500 } else if (dataChild instanceof AugmentationNode) {
1501 outputType = (String) ((AugmentationNode) dataChild).getValue().iterator().next().getValue();
1505 final Collection<LeafSetEntryNode> entryNodes = leafSet.getValue();
1506 final List<SchemaPath> paths = new ArrayList<>();
1507 String streamName = CREATE_NOTIFICATION_STREAM + "/";
1509 StringBuilder streamNameBuilder = new StringBuilder(streamName);
1510 final Iterator<LeafSetEntryNode> iterator = entryNodes.iterator();
1511 while (iterator.hasNext()) {
1512 final QName valueQName = QName.create((String) iterator.next().getValue());
1513 final Module module = controllerContext.findModuleByNamespace(valueQName.getModule().getNamespace());
1514 Preconditions.checkNotNull(module,
1515 "Module for namespace " + valueQName.getModule().getNamespace() + " does not exist");
1516 NotificationDefinition notifiDef = null;
1517 for (final NotificationDefinition notification : module.getNotifications()) {
1518 if (notification.getQName().equals(valueQName)) {
1519 notifiDef = notification;
1523 final String moduleName = module.getName();
1524 Preconditions.checkNotNull(notifiDef,
1525 "Notification " + valueQName + "doesn't exist in module " + moduleName);
1526 paths.add(notifiDef.getPath());
1527 streamNameBuilder.append(moduleName).append(':').append(valueQName.getLocalName());
1528 if (iterator.hasNext()) {
1529 streamNameBuilder.append(',');
1533 streamName = streamNameBuilder.toString();
1535 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
1536 final QName outputQname = QName.create(rpcQName, "output");
1537 final QName streamNameQname = QName.create(rpcQName, "notification-stream-identifier");
1539 final ContainerNode output =
1540 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
1541 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
1543 if (!Notificator.existNotificationListenerFor(streamName)) {
1544 Notificator.createNotificationListener(paths, streamName, outputType, controllerContext);
1547 return Futures.immediateFuture(new DefaultDOMRpcResult(output));
1550 private static EffectiveModelContext modelContext(final DOMMountPoint mountPoint) {
1551 return mountPoint.getService(DOMSchemaService.class)
1552 .flatMap(svc -> Optional.ofNullable(svc.getGlobalContext()))