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 static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkNotNull;
12 import static com.google.common.base.Preconditions.checkState;
13 import static java.util.Objects.requireNonNull;
15 import com.google.common.annotations.VisibleForTesting;
16 import com.google.common.base.Predicates;
17 import com.google.common.base.Splitter;
18 import com.google.common.base.Strings;
19 import com.google.common.base.Throwables;
20 import com.google.common.collect.ImmutableMap;
21 import com.google.common.collect.ImmutableSet;
22 import com.google.common.collect.Iterables;
23 import com.google.common.util.concurrent.FluentFuture;
24 import com.google.common.util.concurrent.Futures;
25 import com.google.common.util.concurrent.ListenableFuture;
26 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
28 import java.time.Instant;
29 import java.time.format.DateTimeFormatter;
30 import java.time.format.DateTimeFormatterBuilder;
31 import java.time.format.DateTimeParseException;
32 import java.time.temporal.ChronoField;
33 import java.time.temporal.TemporalAccessor;
34 import java.util.AbstractMap.SimpleImmutableEntry;
35 import java.util.ArrayList;
36 import java.util.Collection;
37 import java.util.Collections;
38 import java.util.HashMap;
39 import java.util.Iterator;
40 import java.util.List;
41 import java.util.Locale;
43 import java.util.Map.Entry;
44 import java.util.Objects;
45 import java.util.Optional;
47 import java.util.concurrent.CancellationException;
48 import java.util.concurrent.ExecutionException;
49 import javax.inject.Inject;
50 import javax.inject.Singleton;
51 import javax.ws.rs.WebApplicationException;
52 import javax.ws.rs.core.Context;
53 import javax.ws.rs.core.Response;
54 import javax.ws.rs.core.Response.ResponseBuilder;
55 import javax.ws.rs.core.Response.Status;
56 import javax.ws.rs.core.UriBuilder;
57 import javax.ws.rs.core.UriInfo;
58 import org.eclipse.jdt.annotation.NonNull;
59 import org.opendaylight.mdsal.common.api.CommitInfo;
60 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
61 import org.opendaylight.mdsal.common.api.OptimisticLockFailedException;
62 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
63 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
64 import org.opendaylight.mdsal.dom.api.DOMRpcImplementationNotAvailableException;
65 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
66 import org.opendaylight.mdsal.dom.api.DOMRpcService;
67 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
68 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
69 import org.opendaylight.netconf.sal.rest.api.Draft02;
70 import org.opendaylight.netconf.sal.rest.api.RestconfService;
71 import org.opendaylight.netconf.sal.rest.impl.NormalizedNodeContext;
72 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
73 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
74 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
75 import org.opendaylight.netconf.sal.streams.websockets.WebSocketServer;
76 import org.opendaylight.restconf.common.OperationsContent;
77 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
78 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
79 import org.opendaylight.restconf.common.patch.PatchContext;
80 import org.opendaylight.restconf.common.patch.PatchStatusContext;
81 import org.opendaylight.restconf.common.util.OperationsResourceUtils;
82 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
83 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.CreateDataChangeEventSubscriptionInput1.Scope;
84 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
85 import org.opendaylight.yangtools.yang.common.Empty;
86 import org.opendaylight.yangtools.yang.common.ErrorTag;
87 import org.opendaylight.yangtools.yang.common.ErrorType;
88 import org.opendaylight.yangtools.yang.common.QName;
89 import org.opendaylight.yangtools.yang.common.QNameModule;
90 import org.opendaylight.yangtools.yang.common.Revision;
91 import org.opendaylight.yangtools.yang.common.XMLNamespace;
92 import org.opendaylight.yangtools.yang.common.YangConstants;
93 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
94 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
95 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
96 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
97 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
98 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
99 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
100 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
101 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
102 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
103 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
104 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
105 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
106 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
107 import org.opendaylight.yangtools.yang.data.api.schema.SystemLeafSetNode;
108 import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
109 import org.opendaylight.yangtools.yang.data.api.schema.builder.CollectionNodeBuilder;
110 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
111 import org.opendaylight.yangtools.yang.data.api.schema.builder.ListNodeBuilder;
112 import org.opendaylight.yangtools.yang.data.api.schema.builder.NormalizedNodeBuilder;
113 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
114 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
115 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaAwareBuilders;
116 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
117 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
118 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
119 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
120 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
121 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
122 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
123 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
124 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
125 import org.opendaylight.yangtools.yang.model.api.Module;
126 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
127 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
128 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
129 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
130 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
131 import org.slf4j.Logger;
132 import org.slf4j.LoggerFactory;
135 public final class RestconfImpl implements RestconfService {
137 * Notifications are served on port 8181.
139 private static final int NOTIFICATION_PORT = 8181;
141 private static final int CHAR_NOT_FOUND = -1;
143 private static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
145 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
147 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
149 private static final XMLNamespace NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT =
150 XMLNamespace.of("urn:sal:restconf:event:subscription");
152 private static final String DATASTORE_PARAM_NAME = "datastore";
154 private static final String SCOPE_PARAM_NAME = "scope";
156 private static final String OUTPUT_TYPE_PARAM_NAME = "notification-output-type";
158 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
160 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
162 private static final QName NETCONF_BASE_QNAME = QName.create(QNameModule.create(XMLNamespace.of(NETCONF_BASE)),
163 NETCONF_BASE_PAYLOAD_NAME).intern();
165 private static final QNameModule SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
166 Revision.of("2014-07-08"));
168 private static final AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER =
169 new AugmentationIdentifier(ImmutableSet.of(
170 QName.create(SAL_REMOTE_AUGMENT, "scope"), QName.create(SAL_REMOTE_AUGMENT, "datastore"),
171 QName.create(SAL_REMOTE_AUGMENT, "notification-output-type")));
173 public static final CharSequence DATA_SUBSCR = "data-change-event-subscription";
174 private static final CharSequence CREATE_DATA_SUBSCR = "create-" + DATA_SUBSCR;
176 public static final CharSequence NOTIFICATION_STREAM = "notification-stream";
177 private static final CharSequence CREATE_NOTIFICATION_STREAM = "create-" + NOTIFICATION_STREAM;
179 private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
180 .appendValue(ChronoField.YEAR, 4).appendLiteral('-')
181 .appendValue(ChronoField.MONTH_OF_YEAR, 2).appendLiteral('-')
182 .appendValue(ChronoField.DAY_OF_MONTH, 2).appendLiteral('T')
183 .appendValue(ChronoField.HOUR_OF_DAY, 2).appendLiteral(':')
184 .appendValue(ChronoField.MINUTE_OF_HOUR, 2).appendLiteral(':')
185 .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
186 .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
187 .appendOffset("+HH:MM", "Z").toFormatter();
189 private final BrokerFacade broker;
191 private final ControllerContext controllerContext;
194 public RestconfImpl(final BrokerFacade broker, final ControllerContext controllerContext) {
195 this.broker = broker;
196 this.controllerContext = controllerContext;
202 * @deprecated Just use {@link #RestconfImpl(BrokerFacade, ControllerContext)} constructor instead.
205 public static RestconfImpl newInstance(final BrokerFacade broker, final ControllerContext controllerContext) {
206 return new RestconfImpl(broker, controllerContext);
211 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
212 final MapNode allModuleMap = makeModuleMapNode(controllerContext.getAllModules());
214 final EffectiveModelContext schemaContext = controllerContext.getGlobalSchema();
216 final Module restconfModule = getRestconfModule();
217 final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
218 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
219 checkState(modulesSchemaNode instanceof ContainerSchemaNode);
221 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
222 SchemaAwareBuilders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
223 moduleContainerBuilder.withChild(allModuleMap);
225 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode, null, schemaContext),
226 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
230 * Valid only for mount point.
234 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
235 if (!identifier.contains(ControllerContext.MOUNT)) {
236 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
237 + " URI has to end with " + ControllerContext.MOUNT;
238 LOG.debug("{} for {}", errMsg, identifier);
239 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
242 final InstanceIdentifierContext<?> mountPointIdentifier =
243 controllerContext.toMountPointIdentifier(identifier);
244 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
245 final MapNode mountPointModulesMap = makeModuleMapNode(controllerContext.getAllModules(mountPoint));
247 final Module restconfModule = getRestconfModule();
248 final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
249 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
250 checkState(modulesSchemaNode instanceof ContainerSchemaNode);
252 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
253 SchemaAwareBuilders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
254 moduleContainerBuilder.withChild(mountPointModulesMap);
256 return new NormalizedNodeContext(
257 new InstanceIdentifierContext<>(null, modulesSchemaNode, mountPoint,
258 controllerContext.getGlobalSchema()),
259 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
264 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
265 final Entry<String, Revision> nameRev = getModuleNameAndRevision(requireNonNull(identifier));
266 Module module = null;
267 DOMMountPoint mountPoint = null;
268 final EffectiveModelContext schemaContext;
269 if (identifier.contains(ControllerContext.MOUNT)) {
270 final InstanceIdentifierContext<?> mountPointIdentifier =
271 controllerContext.toMountPointIdentifier(identifier);
272 mountPoint = mountPointIdentifier.getMountPoint();
273 module = controllerContext.findModuleByNameAndRevision(mountPoint, nameRev.getKey(),
275 schemaContext = modelContext(mountPoint);
277 module = controllerContext.findModuleByNameAndRevision(nameRev.getKey(), nameRev.getValue());
278 schemaContext = controllerContext.getGlobalSchema();
281 if (module == null) {
282 LOG.debug("Module with name '{}' and revision '{}' was not found.", nameRev.getKey(), nameRev.getValue());
283 throw new RestconfDocumentedException("Module with name '" + nameRev.getKey() + "' and revision '"
284 + nameRev.getValue() + "' was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
287 final Module restconfModule = getRestconfModule();
288 final Set<Module> modules = Collections.singleton(module);
289 final MapNode moduleMap = makeModuleMapNode(modules);
291 final DataSchemaNode moduleSchemaNode = controllerContext
292 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
293 checkState(moduleSchemaNode instanceof ListSchemaNode);
295 return new NormalizedNodeContext(
296 new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint, schemaContext), moduleMap,
297 QueryParametersParser.parseWriterParameters(uriInfo));
302 public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
303 final EffectiveModelContext schemaContext = controllerContext.getGlobalSchema();
304 final Set<String> availableStreams = Notificator.getStreamNames();
305 final Module restconfModule = getRestconfModule();
306 final DataSchemaNode streamSchemaNode = controllerContext
307 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
308 checkState(streamSchemaNode instanceof ListSchemaNode);
310 final CollectionNodeBuilder<MapEntryNode, SystemMapNode> listStreamsBuilder =
311 SchemaAwareBuilders.mapBuilder((ListSchemaNode) streamSchemaNode);
313 for (final String streamName : availableStreams) {
314 listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
317 final DataSchemaNode streamsContainerSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
318 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
319 checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
321 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
322 SchemaAwareBuilders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
323 streamsContainerBuilder.withChild(listStreamsBuilder.build());
325 return new NormalizedNodeContext(
326 new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null, schemaContext),
327 streamsContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
332 public String getOperationsJSON() {
333 return OperationsContent.JSON.bodyFor(controllerContext.getGlobalSchema());
338 public String getOperationsXML() {
339 return OperationsContent.XML.bodyFor(controllerContext.getGlobalSchema());
344 public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
345 if (!identifier.contains(ControllerContext.MOUNT)) {
346 final String errMsg = "URI has bad format. If operations behind mount point should be showed, URI has to "
347 + " end with " + ControllerContext.MOUNT;
348 LOG.debug("{} for {}", errMsg, identifier);
349 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
352 final InstanceIdentifierContext<?> mountPointIdentifier =
353 controllerContext.toMountPointIdentifier(identifier);
354 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
355 final var entry = OperationsResourceUtils.contextForModelContext(modelContext(mountPoint), mountPoint);
356 return new NormalizedNodeContext(entry.getKey(), entry.getValue());
359 private Module getRestconfModule() {
360 final Module restconfModule = controllerContext.getRestconfModule();
361 if (restconfModule == null) {
362 LOG.debug("ietf-restconf module was not found.");
363 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
364 ErrorTag.OPERATION_NOT_SUPPORTED);
367 return restconfModule;
370 private static Entry<String, Revision> getModuleNameAndRevision(final String identifier) {
371 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
372 String moduleNameAndRevision = "";
373 if (mountIndex >= 0) {
374 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
376 moduleNameAndRevision = identifier;
379 final Splitter splitter = Splitter.on('/').omitEmptyStrings();
380 final List<String> pathArgs = splitter.splitToList(moduleNameAndRevision);
381 if (pathArgs.size() < 2) {
382 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' {}", identifier);
383 throw new RestconfDocumentedException(
384 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
385 ErrorTag.INVALID_VALUE);
389 return new SimpleImmutableEntry<>(pathArgs.get(0), Revision.of(pathArgs.get(1)));
390 } catch (final DateTimeParseException e) {
391 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' {}", identifier);
392 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
393 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
398 public Object getRoot() {
403 public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload,
404 final UriInfo uriInfo) {
405 if (payload == null) {
406 // no payload specified, reroute this to no payload invokeRpc implementation
407 return invokeRpc(identifier, uriInfo);
410 final SchemaNode schema = payload.getInstanceIdentifierContext().getSchemaNode();
411 final ListenableFuture<? extends DOMRpcResult> response;
412 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
413 final NormalizedNode input = nonnullInput(schema, payload.getData());
414 final EffectiveModelContext schemaContext;
416 if (mountPoint != null) {
417 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
418 if (mountRpcServices.isEmpty()) {
419 LOG.debug("Error: Rpc service is missing.");
420 throw new RestconfDocumentedException("Rpc service is missing.");
422 schemaContext = modelContext(mountPoint);
423 response = mountRpcServices.get().invokeRpc(schema.getQName(), input);
425 final XMLNamespace namespace = schema.getQName().getNamespace();
426 if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
427 if (identifier.contains(CREATE_DATA_SUBSCR)) {
428 response = invokeSalRemoteRpcSubscribeRPC(payload);
429 } else if (identifier.contains(CREATE_NOTIFICATION_STREAM)) {
430 response = invokeSalRemoteRpcNotifiStrRPC(payload);
432 final String msg = "Not supported operation";
434 throw new RestconfDocumentedException(msg, ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED);
437 response = broker.invokeRpc(schema.getQName(), input);
439 schemaContext = controllerContext.getGlobalSchema();
442 final DOMRpcResult result = checkRpcResponse(response);
444 RpcDefinition resultNodeSchema = null;
445 final NormalizedNode resultData;
446 if (result != null && result.getResult() != null) {
447 resultData = result.getResult();
448 resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
453 if (resultData != null && ((ContainerNode) resultData).isEmpty()) {
454 throw new WebApplicationException(Response.Status.NO_CONTENT);
456 return new NormalizedNodeContext(
457 new InstanceIdentifierContext<>(null, resultNodeSchema, mountPoint, schemaContext),
458 resultData, QueryParametersParser.parseWriterParameters(uriInfo));
462 @SuppressFBWarnings(value = "NP_LOAD_OF_KNOWN_NULL_VALUE",
463 justification = "Looks like a false positive, see below FIXME")
464 private NormalizedNodeContext invokeRpc(final String identifier, final UriInfo uriInfo) {
465 final DOMMountPoint mountPoint;
466 final String identifierEncoded;
467 final EffectiveModelContext schemaContext;
468 if (identifier.contains(ControllerContext.MOUNT)) {
469 // mounted RPC call - look up mount instance.
470 final InstanceIdentifierContext<?> mountPointId = controllerContext.toMountPointIdentifier(identifier);
471 mountPoint = mountPointId.getMountPoint();
472 schemaContext = modelContext(mountPoint);
473 final int startOfRemoteRpcName =
474 identifier.lastIndexOf(ControllerContext.MOUNT) + ControllerContext.MOUNT.length() + 1;
475 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
476 identifierEncoded = remoteRpcName;
478 } else if (identifier.indexOf('/') == CHAR_NOT_FOUND) {
479 identifierEncoded = identifier;
481 schemaContext = controllerContext.getGlobalSchema();
483 LOG.debug("Identifier {} cannot contain slash character (/).", identifier);
484 throw new RestconfDocumentedException(String.format("Identifier %n%s%ncan\'t contain slash character (/).%n"
485 + "If slash is part of identifier name then use %%2F placeholder.", identifier), ErrorType.PROTOCOL,
486 ErrorTag.INVALID_VALUE);
489 final String identifierDecoded = ControllerContext.urlPathArgDecode(identifierEncoded);
490 final RpcDefinition rpc;
491 if (mountPoint == null) {
492 rpc = controllerContext.getRpcDefinition(identifierDecoded);
494 rpc = findRpc(modelContext(mountPoint), identifierDecoded);
498 LOG.debug("RPC {} does not exist.", identifierDecoded);
499 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
502 if (!rpc.getInput().getChildNodes().isEmpty()) {
503 LOG.debug("No input specified for RPC {} with an input section", rpc);
504 throw new RestconfDocumentedException("No input specified for RPC " + rpc
505 + " with an input section defined", ErrorType.RPC, ErrorTag.MISSING_ELEMENT);
508 final ContainerNode input = defaultInput(rpc.getQName());
509 final ListenableFuture<? extends DOMRpcResult> response;
510 if (mountPoint != null) {
511 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
512 if (mountRpcServices.isEmpty()) {
513 throw new RestconfDocumentedException("Rpc service is missing.");
515 response = mountRpcServices.get().invokeRpc(rpc.getQName(), input);
517 response = broker.invokeRpc(rpc.getQName(), input);
520 final NormalizedNode result = checkRpcResponse(response).getResult();
521 if (result != null && ((ContainerNode) result).isEmpty()) {
522 throw new WebApplicationException(Response.Status.NO_CONTENT);
525 // FIXME: in reference to the above @SupressFBWarnings: "mountPoint" reference here trips up SpotBugs, as it
526 // thinks it can only ever be null. Except it can very much be non-null. The core problem is the horrible
527 // structure of this code where we have a sh*tload of checks for mountpoint above and all over the
528 // codebase where all that difference should have been properly encapsulated.
530 // This is legacy code, so if anybody cares to do that refactor, feel free to contribute, but I am not
532 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpc, mountPoint, schemaContext), result,
533 QueryParametersParser.parseWriterParameters(uriInfo));
536 private static @NonNull NormalizedNode nonnullInput(final SchemaNode rpc, final NormalizedNode input) {
537 return input != null ? input : defaultInput(rpc.getQName());
540 private static @NonNull ContainerNode defaultInput(final QName rpcName) {
541 return ImmutableNodes.containerNode(YangConstants.operationInputQName(rpcName.getModule()));
544 @SuppressWarnings("checkstyle:avoidHidingCauseException")
545 private static DOMRpcResult checkRpcResponse(final ListenableFuture<? extends DOMRpcResult> response) {
546 if (response == null) {
550 final DOMRpcResult retValue = response.get();
551 if (retValue.getErrors().isEmpty()) {
554 LOG.debug("RpcError message {}", retValue.getErrors());
555 throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
556 } catch (final InterruptedException e) {
557 final String errMsg = "The operation was interrupted while executing and did not complete.";
558 LOG.debug("Rpc Interrupt - {}", errMsg, e);
559 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION, e);
560 } catch (final ExecutionException e) {
561 LOG.debug("Execution RpcError: ", e);
562 Throwable cause = e.getCause();
564 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
567 while (cause.getCause() != null) {
568 cause = cause.getCause();
571 if (cause instanceof IllegalArgumentException) {
572 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
573 } else if (cause instanceof DOMRpcImplementationNotAvailableException) {
574 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.APPLICATION,
575 ErrorTag.OPERATION_NOT_SUPPORTED);
577 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
579 } catch (final CancellationException e) {
580 final String errMsg = "The operation was cancelled while executing.";
581 LOG.debug("Cancel RpcExecution: {}", errMsg, e);
582 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
586 private static void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
587 if (inputSchema != null && payload.getData() == null) {
588 // expected a non null payload
589 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
590 } else if (inputSchema == null && payload.getData() != null) {
591 // did not expect any input
592 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
596 private ListenableFuture<DOMRpcResult> invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
597 final ContainerNode value = (ContainerNode) payload.getData();
598 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
599 final Optional<DataContainerChild> path =
600 value.findChildByArg(new NodeIdentifier(QName.create(rpcQName, "path")));
601 final Object pathValue = path.isPresent() ? path.get().body() : null;
603 if (!(pathValue instanceof YangInstanceIdentifier)) {
604 LOG.debug("Instance identifier {} was not normalized correctly", rpcQName);
605 throw new RestconfDocumentedException("Instance identifier was not normalized correctly",
606 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
609 final YangInstanceIdentifier pathIdentifier = (YangInstanceIdentifier) pathValue;
610 String streamName = (String) CREATE_DATA_SUBSCR;
611 NotificationOutputType outputType = null;
612 if (!pathIdentifier.isEmpty()) {
613 final String fullRestconfIdentifier =
614 DATA_SUBSCR + controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
616 LogicalDatastoreType datastore =
617 parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
618 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
620 Scope scope = parseEnumTypeParameter(value, Scope.class, SCOPE_PARAM_NAME);
621 scope = scope == null ? Scope.BASE : scope;
623 outputType = parseEnumTypeParameter(value, NotificationOutputType.class, OUTPUT_TYPE_PARAM_NAME);
624 outputType = outputType == null ? NotificationOutputType.XML : outputType;
626 streamName = Notificator
627 .createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore + "/scope=" + scope);
630 if (Strings.isNullOrEmpty(streamName)) {
631 LOG.debug("Path is empty or contains value node which is not Container or List built-in type at {}",
633 throw new RestconfDocumentedException("Path is empty or contains value node which is not Container or List "
634 + "built-in type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
637 final QName outputQname = QName.create(rpcQName, "output");
638 final QName streamNameQname = QName.create(rpcQName, "stream-name");
640 final ContainerNode output =
641 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
642 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
644 if (!Notificator.existListenerFor(streamName)) {
645 Notificator.createListener(pathIdentifier, streamName, outputType, controllerContext);
648 return Futures.immediateFuture(new DefaultDOMRpcResult(output));
651 private static RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
652 final String[] splittedIdentifier = identifierDecoded.split(":");
653 if (splittedIdentifier.length != 2) {
654 LOG.debug("{} could not be split to 2 parts (module:rpc name)", identifierDecoded);
655 throw new RestconfDocumentedException(identifierDecoded + " could not be split to 2 parts "
656 + "(module:rpc name)", ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
658 for (final Module module : schemaContext.getModules()) {
659 if (module.getName().equals(splittedIdentifier[0])) {
660 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
661 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
662 return rpcDefinition;
671 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
672 boolean withDefaUsed = false;
673 String withDefa = null;
675 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
676 switch (entry.getKey()) {
677 case "with-defaults":
680 withDefa = entry.getValue().iterator().next();
682 throw new RestconfDocumentedException("With-defaults parameter can be used only once.");
686 LOG.info("Unknown key : {}.", entry.getKey());
691 // TODO: this flag is always ignored
692 boolean tagged = false;
694 if ("report-all-tagged".equals(withDefa)) {
698 if ("report-all".equals(withDefa)) {
703 final InstanceIdentifierContext<?> iiWithData = controllerContext.toInstanceIdentifier(identifier);
704 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
705 NormalizedNode data = null;
706 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
707 if (mountPoint != null) {
708 data = broker.readConfigurationData(mountPoint, normalizedII, withDefa);
710 data = broker.readConfigurationData(normalizedII, withDefa);
713 throw dataMissing(identifier);
715 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
719 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
720 final InstanceIdentifierContext<?> iiWithData = controllerContext.toInstanceIdentifier(identifier);
721 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
722 NormalizedNode data = null;
723 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
724 if (mountPoint != null) {
725 data = broker.readOperationalData(mountPoint, normalizedII);
727 data = broker.readOperationalData(normalizedII);
730 throw dataMissing(identifier);
732 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
735 private static RestconfDocumentedException dataMissing(final String identifier) {
736 LOG.debug("Request could not be completed because the relevant data model content does not exist {}",
738 return new RestconfDocumentedException("Request could not be completed because the relevant data model content "
739 + "does not exist", ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
743 public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload,
744 final UriInfo uriInfo) {
745 boolean insertUsed = false;
746 boolean pointUsed = false;
747 String insert = null;
750 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
751 switch (entry.getKey()) {
755 insert = entry.getValue().iterator().next();
757 throw new RestconfDocumentedException("Insert parameter can be used only once.");
763 point = entry.getValue().iterator().next();
765 throw new RestconfDocumentedException("Point parameter can be used only once.");
769 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
773 if (pointUsed && !insertUsed) {
774 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
776 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
777 throw new RestconfDocumentedException(
778 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
781 requireNonNull(identifier);
783 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
785 validateInput(iiWithData.getSchemaNode(), payload);
786 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
787 validateListKeysEqualityInPayloadAndUri(payload);
789 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
790 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
793 * There is a small window where another write transaction could be
794 * updating the same data simultaneously and we get an
795 * OptimisticLockFailedException. This error is likely transient and The
796 * WriteTransaction#submit API docs state that a retry will likely
797 * succeed. So we'll try again if that scenario occurs. If it fails a
798 * third time then it probably will never succeed so we'll fail in that
801 * By retrying we're attempting to hide the internal implementation of
802 * the data store and how it handles concurrent updates from the
803 * restconf client. The client has instructed us to put the data and we
804 * should make every effort to do so without pushing optimistic lock
805 * failures back to the client and forcing them to handle it via retry
806 * (and having to document the behavior).
808 PutResult result = null;
811 if (mountPoint != null) {
813 result = broker.commitMountPointDataPut(mountPoint, normalizedII, payload.getData(), insert,
816 result = broker.commitConfigurationDataPut(controllerContext.getGlobalSchema(), normalizedII,
817 payload.getData(), insert, point);
821 result.getFutureOfPutData().get();
822 } catch (final InterruptedException e) {
823 LOG.debug("Update failed for {}", identifier, e);
824 throw new RestconfDocumentedException(e.getMessage(), e);
825 } catch (final ExecutionException e) {
826 final TransactionCommitFailedException failure = Throwables.getCauseAs(e,
827 TransactionCommitFailedException.class);
828 if (failure instanceof OptimisticLockFailedException) {
830 LOG.debug("Got OptimisticLockFailedException on last try - failing {}", identifier);
831 throw new RestconfDocumentedException(e.getMessage(), e, failure.getErrorList());
834 LOG.debug("Got OptimisticLockFailedException - trying again {}", identifier);
838 LOG.debug("Update failed for {}", identifier, e);
839 throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), failure);
842 return Response.status(result.getStatus()).build();
846 private static void validateTopLevelNodeName(final NormalizedNodeContext node,
847 final YangInstanceIdentifier identifier) {
849 final String payloadName = node.getData().getIdentifier().getNodeType().getLocalName();
852 if (identifier.isEmpty()) {
854 if (!node.getData().getIdentifier().getNodeType().equals(NETCONF_BASE_QNAME)) {
855 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
856 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
860 final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
861 if (!payloadName.equals(identifierName)) {
862 throw new RestconfDocumentedException(
863 "Payload name (" + payloadName + ") is different from identifier name (" + identifierName + ")",
864 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
870 * Validates whether keys in {@code payload} are equal to values of keys in
871 * {@code iiWithData} for list schema node.
873 * @throws RestconfDocumentedException
874 * if key values or key count in payload and URI isn't equal
877 private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
878 checkArgument(payload != null);
879 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
880 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
881 final SchemaNode schemaNode = iiWithData.getSchemaNode();
882 final NormalizedNode data = payload.getData();
883 if (schemaNode instanceof ListSchemaNode) {
884 final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
885 if (lastPathArgument instanceof NodeIdentifierWithPredicates && data instanceof MapEntryNode) {
886 final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument).asMap();
887 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
893 public static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final MapEntryNode payload,
894 final List<QName> keyDefinitions) {
896 final Map<QName, Object> mutableCopyUriKeyValues = new HashMap<>(uriKeyValues);
897 for (final QName keyDefinition : keyDefinitions) {
898 final Object uriKeyValue = RestconfDocumentedException.throwIfNull(
899 // should be caught during parsing URI to InstanceIdentifier
900 mutableCopyUriKeyValues.remove(keyDefinition), ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
901 "Missing key %s in URI.", keyDefinition);
903 final Object dataKeyValue = payload.getIdentifier().getValue(keyDefinition);
905 if (!Objects.deepEquals(uriKeyValue, dataKeyValue)) {
906 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName()
907 + "' specified in the URI doesn't match the value '" + dataKeyValue
908 + "' specified in the message body. ";
909 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
915 public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload,
916 final UriInfo uriInfo) {
917 return createConfigurationData(payload, uriInfo);
921 public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
922 if (payload == null) {
923 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
925 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
926 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
927 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
929 boolean insertUsed = false;
930 boolean pointUsed = false;
931 String insert = null;
934 if (uriInfo != null) {
935 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
936 switch (entry.getKey()) {
940 insert = entry.getValue().iterator().next();
942 throw new RestconfDocumentedException("Insert parameter can be used only once.");
948 point = entry.getValue().iterator().next();
950 throw new RestconfDocumentedException("Point parameter can be used only once.");
954 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
959 if (pointUsed && !insertUsed) {
960 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
962 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
963 throw new RestconfDocumentedException(
964 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
967 FluentFuture<? extends CommitInfo> future;
968 if (mountPoint != null) {
969 future = broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData(), insert,
972 future = broker.commitConfigurationDataPost(controllerContext.getGlobalSchema(), normalizedII,
973 payload.getData(), insert, point);
978 } catch (final InterruptedException e) {
979 LOG.info("Error creating data {}", uriInfo != null ? uriInfo.getPath() : "", e);
980 throw new RestconfDocumentedException(e.getMessage(), e);
981 } catch (final ExecutionException e) {
982 LOG.info("Error creating data {}", uriInfo != null ? uriInfo.getPath() : "", e);
983 throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), Throwables.getCauseAs(e,
984 TransactionCommitFailedException.class));
987 LOG.trace("Successfuly created data.");
989 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
990 // FIXME: Provide path to result.
991 final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
992 if (location != null) {
993 responseBuilder.location(location);
995 return responseBuilder.build();
998 @SuppressWarnings("checkstyle:IllegalCatch")
999 private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint,
1000 final YangInstanceIdentifier normalizedII) {
1001 if (uriInfo == null) {
1002 // This is null if invoked internally
1006 final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
1007 uriBuilder.path("config");
1009 uriBuilder.path(controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
1010 } catch (final Exception e) {
1011 LOG.info("Location for instance identifier {} was not created", normalizedII, e);
1014 return uriBuilder.build();
1018 public Response deleteConfigurationData(final String identifier) {
1019 final InstanceIdentifierContext<?> iiWithData = controllerContext.toInstanceIdentifier(identifier);
1020 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
1021 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
1023 final FluentFuture<? extends CommitInfo> future;
1024 if (mountPoint != null) {
1025 future = broker.commitConfigurationDataDelete(mountPoint, normalizedII);
1027 future = broker.commitConfigurationDataDelete(normalizedII);
1032 } catch (final InterruptedException e) {
1033 throw new RestconfDocumentedException(e.getMessage(), e);
1034 } catch (final ExecutionException e) {
1035 final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
1036 Predicates.instanceOf(ModifiedNodeDoesNotExistException.class)).toJavaUtil();
1037 if (searchedException.isPresent()) {
1038 throw new RestconfDocumentedException("Data specified for delete doesn't exist.", ErrorType.APPLICATION,
1039 ErrorTag.DATA_MISSING, e);
1042 throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), Throwables.getCauseAs(e,
1043 TransactionCommitFailedException.class));
1046 return Response.status(Status.OK).build();
1050 * Subscribes to some path in schema context (stream) to listen on changes
1054 * Additional parameters for subscribing to stream are loaded via rpc input
1057 * <li>datastore - default CONFIGURATION (other values of
1058 * {@link LogicalDatastoreType} enum type)</li>
1059 * <li>scope - default BASE (other values of {@link Scope})</li>
1063 public NormalizedNodeContext subscribeToStream(final String identifier, final UriInfo uriInfo) {
1064 boolean startTimeUsed = false;
1065 boolean stopTimeUsed = false;
1066 Instant start = Instant.now();
1067 Instant stop = null;
1068 boolean filterUsed = false;
1069 String filter = null;
1070 boolean leafNodesOnlyUsed = false;
1071 boolean leafNodesOnly = false;
1072 boolean skipNotificationDataUsed = false;
1073 boolean skipNotificationData = false;
1075 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
1076 switch (entry.getKey()) {
1078 if (!startTimeUsed) {
1079 startTimeUsed = true;
1080 start = parseDateFromQueryParam(entry);
1082 throw new RestconfDocumentedException("Start-time parameter can be used only once.");
1086 if (!stopTimeUsed) {
1087 stopTimeUsed = true;
1088 stop = parseDateFromQueryParam(entry);
1090 throw new RestconfDocumentedException("Stop-time parameter can be used only once.");
1096 filter = entry.getValue().iterator().next();
1098 throw new RestconfDocumentedException("Filter parameter can be used only once.");
1101 case "odl-leaf-nodes-only":
1102 if (!leafNodesOnlyUsed) {
1103 leafNodesOnlyUsed = true;
1104 leafNodesOnly = Boolean.parseBoolean(entry.getValue().iterator().next());
1106 throw new RestconfDocumentedException("Odl-leaf-nodes-only parameter can be used only once.");
1109 case "odl-skip-notification-data":
1110 if (!skipNotificationDataUsed) {
1111 skipNotificationDataUsed = true;
1112 skipNotificationData = Boolean.parseBoolean(entry.getValue().iterator().next());
1114 throw new RestconfDocumentedException(
1115 "Odl-skip-notification-data parameter can be used only once.");
1119 throw new RestconfDocumentedException("Bad parameter used with notifications: " + entry.getKey());
1122 if (!startTimeUsed && stopTimeUsed) {
1123 throw new RestconfDocumentedException("Stop-time parameter has to be used with start-time parameter.");
1125 URI response = null;
1126 if (identifier.contains(DATA_SUBSCR)) {
1127 response = dataSubs(identifier, uriInfo, start, stop, filter, leafNodesOnly, skipNotificationData);
1128 } else if (identifier.contains(NOTIFICATION_STREAM)) {
1129 response = notifStream(identifier, uriInfo, start, stop, filter);
1132 if (response != null) {
1133 // prepare node with value of location
1134 final InstanceIdentifierContext<?> iid = prepareIIDSubsStreamOutput();
1135 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> builder =
1136 ImmutableLeafNodeBuilder.create().withValue(response.toString());
1137 builder.withNodeIdentifier(
1138 NodeIdentifier.create(QName.create("subscribe:to:notification", "2016-10-28", "location")));
1140 // prepare new header with location
1141 return new NormalizedNodeContext(iid, builder.build(), ImmutableMap.of("Location", response));
1144 final String msg = "Bad type of notification of sal-remote";
1146 throw new RestconfDocumentedException(msg);
1149 private static Instant parseDateFromQueryParam(final Entry<String, List<String>> entry) {
1150 final DateAndTime event = new DateAndTime(entry.getValue().iterator().next());
1151 final String value = event.getValue();
1152 final TemporalAccessor p;
1154 p = FORMATTER.parse(value);
1155 } catch (final DateTimeParseException e) {
1156 throw new RestconfDocumentedException("Cannot parse of value in date: " + value, e);
1158 return Instant.from(p);
1162 * Prepare instance identifier.
1164 * @return {@link InstanceIdentifierContext} of location leaf for
1167 private InstanceIdentifierContext<?> prepareIIDSubsStreamOutput() {
1168 final QName qnameBase = QName.create("subscribe:to:notification", "2016-10-28", "notifi");
1169 final EffectiveModelContext schemaCtx = controllerContext.getGlobalSchema();
1170 final DataSchemaNode location = ((ContainerSchemaNode) schemaCtx
1171 .findModule(qnameBase.getModule()).orElse(null)
1172 .getDataChildByName(qnameBase)).getDataChildByName(QName.create(qnameBase, "location"));
1173 final List<PathArgument> path = new ArrayList<>();
1174 path.add(NodeIdentifier.create(qnameBase));
1175 path.add(NodeIdentifier.create(QName.create(qnameBase, "location")));
1177 return new InstanceIdentifierContext<SchemaNode>(YangInstanceIdentifier.create(path), location, null,
1182 * Register notification listener by stream name.
1189 * stop-time of getting notification
1191 * start-time of getting notification
1193 * indicate which subset of all possible events are of interest
1194 * @return {@link URI} of location
1196 private URI notifStream(final String identifier, final UriInfo uriInfo, final Instant start,
1197 final Instant stop, final String filter) {
1198 final String streamName = Notificator.createStreamNameFromUri(identifier);
1199 if (Strings.isNullOrEmpty(streamName)) {
1200 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1202 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
1203 if (listeners == null || listeners.isEmpty()) {
1204 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1205 ErrorTag.UNKNOWN_ELEMENT);
1208 for (final NotificationListenerAdapter listener : listeners) {
1209 broker.registerToListenNotification(listener);
1210 listener.setQueryParams(start, Optional.ofNullable(stop), Optional.ofNullable(filter), false, false);
1213 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1215 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance(NOTIFICATION_PORT);
1216 final int notificationPort = webSocketServerInstance.getPort();
1219 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme(getWsScheme(uriInfo));
1221 return uriToWebsocketServerBuilder.replacePath(streamName).build();
1224 private static String getWsScheme(final UriInfo uriInfo) {
1225 URI uri = uriInfo.getAbsolutePath();
1229 String subscriptionScheme = uri.getScheme().toLowerCase(Locale.ROOT);
1230 return subscriptionScheme.equals("https") ? "wss" : "ws";
1234 * Register data change listener by stream name.
1241 * start-time of getting notification
1243 * stop-time of getting notification
1245 * indicate which subset of all possible events are of interest
1246 * @return {@link URI} of location
1248 private URI dataSubs(final String identifier, final UriInfo uriInfo, final Instant start, final Instant stop,
1249 final String filter, final boolean leafNodesOnly, final boolean skipNotificationData) {
1250 final String streamName = Notificator.createStreamNameFromUri(identifier);
1251 if (Strings.isNullOrEmpty(streamName)) {
1252 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1255 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1256 if (listener == null) {
1257 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1258 ErrorTag.UNKNOWN_ELEMENT);
1260 listener.setQueryParams(start, Optional.ofNullable(stop), Optional.ofNullable(filter), leafNodesOnly,
1261 skipNotificationData);
1263 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1264 final LogicalDatastoreType datastore =
1265 parserURIEnumParameter(LogicalDatastoreType.class, paramToValues.get(DATASTORE_PARAM_NAME));
1266 if (datastore == null) {
1267 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1268 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1270 final Scope scope = parserURIEnumParameter(Scope.class, paramToValues.get(SCOPE_PARAM_NAME));
1271 if (scope == null) {
1272 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1273 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1276 broker.registerToListenDataChanges(datastore, scope, listener);
1278 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1280 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance(NOTIFICATION_PORT);
1281 final int notificationPort = webSocketServerInstance.getPort();
1283 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme(getWsScheme(uriInfo));
1285 return uriToWebsocketServerBuilder.replacePath(streamName).build();
1288 @SuppressWarnings("checkstyle:IllegalCatch")
1290 public PatchStatusContext patchConfigurationData(final String identifier, final PatchContext context,
1291 final UriInfo uriInfo) {
1292 if (context == null) {
1293 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1297 return broker.patchConfigurationDataWithinTransaction(context);
1298 } catch (final Exception e) {
1299 LOG.debug("Patch transaction failed", e);
1300 throw new RestconfDocumentedException(e.getMessage(), e);
1304 @SuppressWarnings("checkstyle:IllegalCatch")
1306 public PatchStatusContext patchConfigurationData(final PatchContext context, @Context final UriInfo uriInfo) {
1307 if (context == null) {
1308 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1312 return broker.patchConfigurationDataWithinTransaction(context);
1313 } catch (final Exception e) {
1314 LOG.debug("Patch transaction failed", e);
1315 throw new RestconfDocumentedException(e.getMessage(), e);
1320 * Load parameter for subscribing to stream from input composite node.
1324 * @return enum object if its string value is equal to {@code paramName}. In
1327 private static <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1328 final String paramName) {
1329 final Optional<DataContainerChild> optAugNode = value.findChildByArg(SAL_REMOTE_AUG_IDENTIFIER);
1330 if (optAugNode.isEmpty()) {
1333 final DataContainerChild augNode = optAugNode.get();
1334 if (!(augNode instanceof AugmentationNode)) {
1337 final Optional<DataContainerChild> enumNode = ((AugmentationNode) augNode).findChildByArg(
1338 new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1339 if (enumNode.isEmpty()) {
1342 final Object rawValue = enumNode.get().body();
1343 if (!(rawValue instanceof String)) {
1347 return resolveAsEnum(classDescriptor, (String) rawValue);
1351 * Checks whether {@code value} is one of the string representation of
1352 * enumeration {@code classDescriptor}.
1354 * @return enum object if string value of {@code classDescriptor}
1355 * enumeration is equal to {@code value}. Other cases null.
1357 private static <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1358 if (Strings.isNullOrEmpty(value)) {
1361 return resolveAsEnum(classDescriptor, value);
1364 private static <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1365 final T[] enumConstants = classDescriptor.getEnumConstants();
1366 if (enumConstants != null) {
1367 for (final T enm : classDescriptor.getEnumConstants()) {
1368 if (((Enum<?>) enm).name().equals(value)) {
1376 private static Map<String, String> resolveValuesFromUri(final String uri) {
1377 final Map<String, String> result = new HashMap<>();
1378 final String[] tokens = uri.split("/");
1379 for (int i = 1; i < tokens.length; i++) {
1380 final String[] parameterTokens = tokens[i].split("=");
1381 if (parameterTokens.length == 2) {
1382 result.put(parameterTokens[0], parameterTokens[1]);
1388 private MapNode makeModuleMapNode(final Collection<? extends Module> modules) {
1389 requireNonNull(modules);
1390 final Module restconfModule = getRestconfModule();
1391 final DataSchemaNode moduleSchemaNode = controllerContext
1392 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1393 checkState(moduleSchemaNode instanceof ListSchemaNode);
1395 final CollectionNodeBuilder<MapEntryNode, SystemMapNode> listModuleBuilder =
1396 SchemaAwareBuilders.mapBuilder((ListSchemaNode) moduleSchemaNode);
1398 for (final Module module : modules) {
1399 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1401 return listModuleBuilder.build();
1404 private static MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1405 checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1406 "moduleSchemaNode has to be of type ListSchemaNode");
1407 final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1408 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues =
1409 SchemaAwareBuilders.mapEntryBuilder(listModuleSchemaNode);
1411 List<DataSchemaNode> instanceDataChildrenByName =
1412 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "name");
1413 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1414 checkState(nameSchemaNode instanceof LeafSchemaNode);
1415 moduleNodeValues.withChild(
1416 SchemaAwareBuilders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName()).build());
1418 final QNameModule qNameModule = module.getQNameModule();
1420 instanceDataChildrenByName =
1421 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "revision");
1422 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1423 checkState(revisionSchemaNode instanceof LeafSchemaNode);
1424 final Optional<Revision> revision = qNameModule.getRevision();
1425 moduleNodeValues.withChild(SchemaAwareBuilders.leafBuilder((LeafSchemaNode) revisionSchemaNode)
1426 .withValue(revision.map(Revision::toString).orElse("")).build());
1428 instanceDataChildrenByName =
1429 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "namespace");
1430 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1431 checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1432 moduleNodeValues.withChild(SchemaAwareBuilders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1433 .withValue(qNameModule.getNamespace().toString()).build());
1435 instanceDataChildrenByName =
1436 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "feature");
1437 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1438 checkState(featureSchemaNode instanceof LeafListSchemaNode);
1439 final ListNodeBuilder<Object, SystemLeafSetNode<Object>> featuresBuilder =
1440 SchemaAwareBuilders.leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1441 for (final FeatureDefinition feature : module.getFeatures()) {
1442 featuresBuilder.withChild(SchemaAwareBuilders.leafSetEntryBuilder((LeafListSchemaNode) featureSchemaNode)
1443 .withValue(feature.getQName().getLocalName()).build());
1445 moduleNodeValues.withChild(featuresBuilder.build());
1447 return moduleNodeValues.build();
1450 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1451 checkArgument(streamSchemaNode instanceof ListSchemaNode,
1452 "streamSchemaNode has to be of type ListSchemaNode");
1453 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1454 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues =
1455 SchemaAwareBuilders.mapEntryBuilder(listStreamSchemaNode);
1457 List<DataSchemaNode> instanceDataChildrenByName =
1458 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "name");
1459 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1460 checkState(nameSchemaNode instanceof LeafSchemaNode);
1461 streamNodeValues.withChild(
1462 SchemaAwareBuilders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName).build());
1464 instanceDataChildrenByName =
1465 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "description");
1466 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1467 checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1468 streamNodeValues.withChild(SchemaAwareBuilders.leafBuilder((LeafSchemaNode) nameSchemaNode)
1469 .withValue("DESCRIPTION_PLACEHOLDER")
1472 instanceDataChildrenByName =
1473 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-support");
1474 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1475 checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1476 streamNodeValues.withChild(SchemaAwareBuilders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1477 .withValue(Boolean.TRUE).build());
1479 instanceDataChildrenByName =
1480 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-log-creation-time");
1481 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1482 checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1483 streamNodeValues.withChild(
1484 SchemaAwareBuilders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode).withValue("").build());
1486 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "events");
1487 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1488 checkState(eventsSchemaNode instanceof LeafSchemaNode);
1489 streamNodeValues.withChild(
1490 SchemaAwareBuilders.leafBuilder((LeafSchemaNode) eventsSchemaNode).withValue(Empty.value()).build());
1492 return streamNodeValues.build();
1496 * Prepare stream for notification.
1499 * contains list of qnames of notifications
1500 * @return - checked future object
1502 private ListenableFuture<DOMRpcResult> invokeSalRemoteRpcNotifiStrRPC(final NormalizedNodeContext payload) {
1503 final ContainerNode data = (ContainerNode) payload.getData();
1504 LeafSetNode leafSet = null;
1505 String outputType = "XML";
1506 for (final DataContainerChild dataChild : data.body()) {
1507 if (dataChild instanceof LeafSetNode) {
1508 leafSet = (LeafSetNode) dataChild;
1509 } else if (dataChild instanceof AugmentationNode) {
1510 outputType = (String) ((AugmentationNode) dataChild).body().iterator().next().body();
1514 final Collection<LeafSetEntryNode<?>> entryNodes = leafSet.body();
1515 final List<SchemaPath> paths = new ArrayList<>();
1516 String streamName = CREATE_NOTIFICATION_STREAM + "/";
1518 StringBuilder streamNameBuilder = new StringBuilder(streamName);
1519 final Iterator<LeafSetEntryNode<?>> iterator = entryNodes.iterator();
1520 while (iterator.hasNext()) {
1521 final QName valueQName = QName.create((String) iterator.next().body());
1522 final XMLNamespace namespace = valueQName.getModule().getNamespace();
1523 final Module module = controllerContext.findModuleByNamespace(namespace);
1524 checkNotNull(module, "Module for namespace %s does not exist", namespace);
1525 NotificationDefinition notifiDef = null;
1526 for (final NotificationDefinition notification : module.getNotifications()) {
1527 if (notification.getQName().equals(valueQName)) {
1528 notifiDef = notification;
1532 final String moduleName = module.getName();
1533 checkNotNull(notifiDef, "Notification %s does not exist in module %s", valueQName, moduleName);
1534 paths.add(notifiDef.getPath());
1535 streamNameBuilder.append(moduleName).append(':').append(valueQName.getLocalName());
1536 if (iterator.hasNext()) {
1537 streamNameBuilder.append(',');
1541 streamName = streamNameBuilder.toString();
1543 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
1544 final QName outputQname = QName.create(rpcQName, "output");
1545 final QName streamNameQname = QName.create(rpcQName, "notification-stream-identifier");
1547 final ContainerNode output =
1548 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
1549 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
1551 if (!Notificator.existNotificationListenerFor(streamName)) {
1552 Notificator.createNotificationListener(paths, streamName, outputType, controllerContext);
1555 return Futures.immediateFuture(new DefaultDOMRpcResult(output));
1558 private static EffectiveModelContext modelContext(final DOMMountPoint mountPoint) {
1559 return mountPoint.getService(DOMSchemaService.class)
1560 .flatMap(svc -> Optional.ofNullable(svc.getGlobalContext()))