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.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
132 import org.slf4j.Logger;
133 import org.slf4j.LoggerFactory;
136 public final class RestconfImpl implements RestconfService {
138 * Notifications are served on port 8181.
140 private static final int NOTIFICATION_PORT = 8181;
142 private static final int CHAR_NOT_FOUND = -1;
144 private static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
146 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
148 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
150 private static final XMLNamespace NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT =
151 XMLNamespace.of("urn:sal:restconf:event:subscription");
153 private static final String DATASTORE_PARAM_NAME = "datastore";
155 private static final String SCOPE_PARAM_NAME = "scope";
157 private static final String OUTPUT_TYPE_PARAM_NAME = "notification-output-type";
159 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
161 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
163 private static final QName NETCONF_BASE_QNAME = QName.create(QNameModule.create(XMLNamespace.of(NETCONF_BASE)),
164 NETCONF_BASE_PAYLOAD_NAME).intern();
166 private static final QNameModule SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
167 Revision.of("2014-07-08"));
169 private static final AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER =
170 new AugmentationIdentifier(ImmutableSet.of(
171 QName.create(SAL_REMOTE_AUGMENT, "scope"), QName.create(SAL_REMOTE_AUGMENT, "datastore"),
172 QName.create(SAL_REMOTE_AUGMENT, "notification-output-type")));
174 public static final CharSequence DATA_SUBSCR = "data-change-event-subscription";
175 private static final CharSequence CREATE_DATA_SUBSCR = "create-" + DATA_SUBSCR;
177 public static final CharSequence NOTIFICATION_STREAM = "notification-stream";
178 private static final CharSequence CREATE_NOTIFICATION_STREAM = "create-" + NOTIFICATION_STREAM;
180 private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
181 .appendValue(ChronoField.YEAR, 4).appendLiteral('-')
182 .appendValue(ChronoField.MONTH_OF_YEAR, 2).appendLiteral('-')
183 .appendValue(ChronoField.DAY_OF_MONTH, 2).appendLiteral('T')
184 .appendValue(ChronoField.HOUR_OF_DAY, 2).appendLiteral(':')
185 .appendValue(ChronoField.MINUTE_OF_HOUR, 2).appendLiteral(':')
186 .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
187 .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
188 .appendOffset("+HH:MM", "Z").toFormatter();
190 private final BrokerFacade broker;
192 private final ControllerContext controllerContext;
195 public RestconfImpl(final BrokerFacade broker, final ControllerContext controllerContext) {
196 this.broker = broker;
197 this.controllerContext = controllerContext;
203 * @deprecated Just use {@link #RestconfImpl(BrokerFacade, ControllerContext)} constructor instead.
206 public static RestconfImpl newInstance(final BrokerFacade broker, final ControllerContext controllerContext) {
207 return new RestconfImpl(broker, controllerContext);
212 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
213 final MapNode allModuleMap = makeModuleMapNode(controllerContext.getAllModules());
215 final EffectiveModelContext schemaContext = controllerContext.getGlobalSchema();
217 final Module restconfModule = getRestconfModule();
218 final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
219 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
220 checkState(modulesSchemaNode instanceof ContainerSchemaNode);
222 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
223 SchemaAwareBuilders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
224 moduleContainerBuilder.withChild(allModuleMap);
226 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode, null, schemaContext),
227 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
231 * Valid only for mount point.
235 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
236 if (!identifier.contains(ControllerContext.MOUNT)) {
237 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
238 + " URI has to end with " + ControllerContext.MOUNT;
239 LOG.debug("{} for {}", errMsg, identifier);
240 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
243 final InstanceIdentifierContext<?> mountPointIdentifier =
244 controllerContext.toMountPointIdentifier(identifier);
245 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
246 final MapNode mountPointModulesMap = makeModuleMapNode(controllerContext.getAllModules(mountPoint));
248 final Module restconfModule = getRestconfModule();
249 final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
250 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
251 checkState(modulesSchemaNode instanceof ContainerSchemaNode);
253 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
254 SchemaAwareBuilders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
255 moduleContainerBuilder.withChild(mountPointModulesMap);
257 return new NormalizedNodeContext(
258 new InstanceIdentifierContext<>(null, modulesSchemaNode, mountPoint,
259 controllerContext.getGlobalSchema()),
260 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
265 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
266 final Entry<String, Revision> nameRev = getModuleNameAndRevision(requireNonNull(identifier));
267 Module module = null;
268 DOMMountPoint mountPoint = null;
269 final EffectiveModelContext schemaContext;
270 if (identifier.contains(ControllerContext.MOUNT)) {
271 final InstanceIdentifierContext<?> mountPointIdentifier =
272 controllerContext.toMountPointIdentifier(identifier);
273 mountPoint = mountPointIdentifier.getMountPoint();
274 module = controllerContext.findModuleByNameAndRevision(mountPoint, nameRev.getKey(),
276 schemaContext = modelContext(mountPoint);
278 module = controllerContext.findModuleByNameAndRevision(nameRev.getKey(), nameRev.getValue());
279 schemaContext = controllerContext.getGlobalSchema();
282 if (module == null) {
283 LOG.debug("Module with name '{}' and revision '{}' was not found.", nameRev.getKey(), nameRev.getValue());
284 throw new RestconfDocumentedException("Module with name '" + nameRev.getKey() + "' and revision '"
285 + nameRev.getValue() + "' was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
288 final Module restconfModule = getRestconfModule();
289 final Set<Module> modules = Collections.singleton(module);
290 final MapNode moduleMap = makeModuleMapNode(modules);
292 final DataSchemaNode moduleSchemaNode = controllerContext
293 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
294 checkState(moduleSchemaNode instanceof ListSchemaNode);
296 return new NormalizedNodeContext(
297 new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint, schemaContext), moduleMap,
298 QueryParametersParser.parseWriterParameters(uriInfo));
303 public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
304 final EffectiveModelContext schemaContext = controllerContext.getGlobalSchema();
305 final Set<String> availableStreams = Notificator.getStreamNames();
306 final Module restconfModule = getRestconfModule();
307 final DataSchemaNode streamSchemaNode = controllerContext
308 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
309 checkState(streamSchemaNode instanceof ListSchemaNode);
311 final CollectionNodeBuilder<MapEntryNode, SystemMapNode> listStreamsBuilder =
312 SchemaAwareBuilders.mapBuilder((ListSchemaNode) streamSchemaNode);
314 for (final String streamName : availableStreams) {
315 listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
318 final DataSchemaNode streamsContainerSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
319 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
320 checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
322 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
323 SchemaAwareBuilders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
324 streamsContainerBuilder.withChild(listStreamsBuilder.build());
326 return new NormalizedNodeContext(
327 new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null, schemaContext),
328 streamsContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
333 public String getOperationsJSON() {
334 return OperationsContent.JSON.bodyFor(controllerContext.getGlobalSchema());
339 public String getOperationsXML() {
340 return OperationsContent.XML.bodyFor(controllerContext.getGlobalSchema());
345 public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
346 if (!identifier.contains(ControllerContext.MOUNT)) {
347 final String errMsg = "URI has bad format. If operations behind mount point should be showed, URI has to "
348 + " end with " + ControllerContext.MOUNT;
349 LOG.debug("{} for {}", errMsg, identifier);
350 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
353 final InstanceIdentifierContext<?> mountPointIdentifier =
354 controllerContext.toMountPointIdentifier(identifier);
355 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
356 final var entry = OperationsResourceUtils.contextForModelContext(modelContext(mountPoint), mountPoint);
357 return new NormalizedNodeContext(entry.getKey(), entry.getValue());
360 private Module getRestconfModule() {
361 final Module restconfModule = controllerContext.getRestconfModule();
362 if (restconfModule == null) {
363 LOG.debug("ietf-restconf module was not found.");
364 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
365 ErrorTag.OPERATION_NOT_SUPPORTED);
368 return restconfModule;
371 private static Entry<String, Revision> getModuleNameAndRevision(final String identifier) {
372 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
373 String moduleNameAndRevision = "";
374 if (mountIndex >= 0) {
375 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
377 moduleNameAndRevision = identifier;
380 final Splitter splitter = Splitter.on('/').omitEmptyStrings();
381 final List<String> pathArgs = splitter.splitToList(moduleNameAndRevision);
382 if (pathArgs.size() < 2) {
383 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' {}", identifier);
384 throw new RestconfDocumentedException(
385 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
386 ErrorTag.INVALID_VALUE);
390 return new SimpleImmutableEntry<>(pathArgs.get(0), Revision.of(pathArgs.get(1)));
391 } catch (final DateTimeParseException e) {
392 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' {}", identifier);
393 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
394 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
399 public Object getRoot() {
404 public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload,
405 final UriInfo uriInfo) {
406 if (payload == null) {
407 // no payload specified, reroute this to no payload invokeRpc implementation
408 return invokeRpc(identifier, uriInfo);
411 final SchemaNode schema = payload.getInstanceIdentifierContext().getSchemaNode();
412 final ListenableFuture<? extends DOMRpcResult> response;
413 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
414 final NormalizedNode input = nonnullInput(schema, payload.getData());
415 final EffectiveModelContext schemaContext;
417 if (mountPoint != null) {
418 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
419 if (mountRpcServices.isEmpty()) {
420 LOG.debug("Error: Rpc service is missing.");
421 throw new RestconfDocumentedException("Rpc service is missing.");
423 schemaContext = modelContext(mountPoint);
424 response = mountRpcServices.get().invokeRpc(schema.getQName(), input);
426 final XMLNamespace namespace = schema.getQName().getNamespace();
427 if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
428 if (identifier.contains(CREATE_DATA_SUBSCR)) {
429 response = invokeSalRemoteRpcSubscribeRPC(payload);
430 } else if (identifier.contains(CREATE_NOTIFICATION_STREAM)) {
431 response = invokeSalRemoteRpcNotifiStrRPC(payload);
433 final String msg = "Not supported operation";
435 throw new RestconfDocumentedException(msg, ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED);
438 response = broker.invokeRpc(schema.getQName(), input);
440 schemaContext = controllerContext.getGlobalSchema();
443 final DOMRpcResult result = checkRpcResponse(response);
445 RpcDefinition resultNodeSchema = null;
446 final NormalizedNode resultData;
447 if (result != null && result.getResult() != null) {
448 resultData = result.getResult();
449 resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
454 if (resultData != null && ((ContainerNode) resultData).isEmpty()) {
455 throw new WebApplicationException(Response.Status.NO_CONTENT);
457 return new NormalizedNodeContext(
458 new InstanceIdentifierContext<>(null, resultNodeSchema, mountPoint, schemaContext),
459 resultData, QueryParametersParser.parseWriterParameters(uriInfo));
463 @SuppressFBWarnings(value = "NP_LOAD_OF_KNOWN_NULL_VALUE",
464 justification = "Looks like a false positive, see below FIXME")
465 private NormalizedNodeContext invokeRpc(final String identifier, final UriInfo uriInfo) {
466 final DOMMountPoint mountPoint;
467 final String identifierEncoded;
468 final EffectiveModelContext schemaContext;
469 if (identifier.contains(ControllerContext.MOUNT)) {
470 // mounted RPC call - look up mount instance.
471 final InstanceIdentifierContext<?> mountPointId = controllerContext.toMountPointIdentifier(identifier);
472 mountPoint = mountPointId.getMountPoint();
473 schemaContext = modelContext(mountPoint);
474 final int startOfRemoteRpcName =
475 identifier.lastIndexOf(ControllerContext.MOUNT) + ControllerContext.MOUNT.length() + 1;
476 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
477 identifierEncoded = remoteRpcName;
479 } else if (identifier.indexOf('/') == CHAR_NOT_FOUND) {
480 identifierEncoded = identifier;
482 schemaContext = controllerContext.getGlobalSchema();
484 LOG.debug("Identifier {} cannot contain slash character (/).", identifier);
485 throw new RestconfDocumentedException(String.format("Identifier %n%s%ncan\'t contain slash character (/).%n"
486 + "If slash is part of identifier name then use %%2F placeholder.", identifier), ErrorType.PROTOCOL,
487 ErrorTag.INVALID_VALUE);
490 final String identifierDecoded = ControllerContext.urlPathArgDecode(identifierEncoded);
491 final RpcDefinition rpc;
492 if (mountPoint == null) {
493 rpc = controllerContext.getRpcDefinition(identifierDecoded);
495 rpc = findRpc(modelContext(mountPoint), identifierDecoded);
499 LOG.debug("RPC {} does not exist.", identifierDecoded);
500 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
503 if (!rpc.getInput().getChildNodes().isEmpty()) {
504 LOG.debug("No input specified for RPC {} with an input section", rpc);
505 throw new RestconfDocumentedException("No input specified for RPC " + rpc
506 + " with an input section defined", ErrorType.RPC, ErrorTag.MISSING_ELEMENT);
509 final ContainerNode input = defaultInput(rpc.getQName());
510 final ListenableFuture<? extends DOMRpcResult> response;
511 if (mountPoint != null) {
512 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
513 if (mountRpcServices.isEmpty()) {
514 throw new RestconfDocumentedException("Rpc service is missing.");
516 response = mountRpcServices.get().invokeRpc(rpc.getQName(), input);
518 response = broker.invokeRpc(rpc.getQName(), input);
521 final NormalizedNode result = checkRpcResponse(response).getResult();
522 if (result != null && ((ContainerNode) result).isEmpty()) {
523 throw new WebApplicationException(Response.Status.NO_CONTENT);
526 // FIXME: in reference to the above @SupressFBWarnings: "mountPoint" reference here trips up SpotBugs, as it
527 // thinks it can only ever be null. Except it can very much be non-null. The core problem is the horrible
528 // structure of this code where we have a sh*tload of checks for mountpoint above and all over the
529 // codebase where all that difference should have been properly encapsulated.
531 // This is legacy code, so if anybody cares to do that refactor, feel free to contribute, but I am not
533 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpc, mountPoint, schemaContext), result,
534 QueryParametersParser.parseWriterParameters(uriInfo));
537 private static @NonNull NormalizedNode nonnullInput(final SchemaNode rpc, final NormalizedNode input) {
538 return input != null ? input : defaultInput(rpc.getQName());
541 private static @NonNull ContainerNode defaultInput(final QName rpcName) {
542 return ImmutableNodes.containerNode(YangConstants.operationInputQName(rpcName.getModule()));
545 @SuppressWarnings("checkstyle:avoidHidingCauseException")
546 private static DOMRpcResult checkRpcResponse(final ListenableFuture<? extends DOMRpcResult> response) {
547 if (response == null) {
551 final DOMRpcResult retValue = response.get();
552 if (retValue.getErrors().isEmpty()) {
555 LOG.debug("RpcError message {}", retValue.getErrors());
556 throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
557 } catch (final InterruptedException e) {
558 final String errMsg = "The operation was interrupted while executing and did not complete.";
559 LOG.debug("Rpc Interrupt - {}", errMsg, e);
560 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION, e);
561 } catch (final ExecutionException e) {
562 LOG.debug("Execution RpcError: ", e);
563 Throwable cause = e.getCause();
565 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
568 while (cause.getCause() != null) {
569 cause = cause.getCause();
572 if (cause instanceof IllegalArgumentException) {
573 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
574 } else if (cause instanceof DOMRpcImplementationNotAvailableException) {
575 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.APPLICATION,
576 ErrorTag.OPERATION_NOT_SUPPORTED);
578 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
580 } catch (final CancellationException e) {
581 final String errMsg = "The operation was cancelled while executing.";
582 LOG.debug("Cancel RpcExecution: {}", errMsg, e);
583 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
587 private static void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
588 if (inputSchema != null && payload.getData() == null) {
589 // expected a non null payload
590 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
591 } else if (inputSchema == null && payload.getData() != null) {
592 // did not expect any input
593 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
597 private ListenableFuture<DOMRpcResult> invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
598 final ContainerNode value = (ContainerNode) payload.getData();
599 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
600 final Optional<DataContainerChild> path =
601 value.findChildByArg(new NodeIdentifier(QName.create(rpcQName, "path")));
602 final Object pathValue = path.isPresent() ? path.get().body() : null;
604 if (!(pathValue instanceof YangInstanceIdentifier)) {
605 LOG.debug("Instance identifier {} was not normalized correctly", rpcQName);
606 throw new RestconfDocumentedException("Instance identifier was not normalized correctly",
607 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
610 final YangInstanceIdentifier pathIdentifier = (YangInstanceIdentifier) pathValue;
611 String streamName = (String) CREATE_DATA_SUBSCR;
612 NotificationOutputType outputType = null;
613 if (!pathIdentifier.isEmpty()) {
614 final String fullRestconfIdentifier =
615 DATA_SUBSCR + controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
617 LogicalDatastoreType datastore =
618 parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
619 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
621 Scope scope = parseEnumTypeParameter(value, Scope.class, SCOPE_PARAM_NAME);
622 scope = scope == null ? Scope.BASE : scope;
624 outputType = parseEnumTypeParameter(value, NotificationOutputType.class, OUTPUT_TYPE_PARAM_NAME);
625 outputType = outputType == null ? NotificationOutputType.XML : outputType;
627 streamName = Notificator
628 .createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore + "/scope=" + scope);
631 if (Strings.isNullOrEmpty(streamName)) {
632 LOG.debug("Path is empty or contains value node which is not Container or List built-in type at {}",
634 throw new RestconfDocumentedException("Path is empty or contains value node which is not Container or List "
635 + "built-in type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
638 final QName outputQname = QName.create(rpcQName, "output");
639 final QName streamNameQname = QName.create(rpcQName, "stream-name");
641 final ContainerNode output =
642 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
643 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
645 if (!Notificator.existListenerFor(streamName)) {
646 Notificator.createListener(pathIdentifier, streamName, outputType, controllerContext);
649 return Futures.immediateFuture(new DefaultDOMRpcResult(output));
652 private static RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
653 final String[] splittedIdentifier = identifierDecoded.split(":");
654 if (splittedIdentifier.length != 2) {
655 LOG.debug("{} could not be split to 2 parts (module:rpc name)", identifierDecoded);
656 throw new RestconfDocumentedException(identifierDecoded + " could not be split to 2 parts "
657 + "(module:rpc name)", ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
659 for (final Module module : schemaContext.getModules()) {
660 if (module.getName().equals(splittedIdentifier[0])) {
661 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
662 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
663 return rpcDefinition;
672 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
673 boolean withDefaUsed = false;
674 String withDefa = null;
676 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
677 switch (entry.getKey()) {
678 case "with-defaults":
681 withDefa = entry.getValue().iterator().next();
683 throw new RestconfDocumentedException("With-defaults parameter can be used only once.");
687 LOG.info("Unknown key : {}.", entry.getKey());
692 // TODO: this flag is always ignored
693 boolean tagged = false;
695 if ("report-all-tagged".equals(withDefa)) {
699 if ("report-all".equals(withDefa)) {
704 final InstanceIdentifierContext<?> iiWithData = controllerContext.toInstanceIdentifier(identifier);
705 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
706 NormalizedNode data = null;
707 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
708 if (mountPoint != null) {
709 data = broker.readConfigurationData(mountPoint, normalizedII, withDefa);
711 data = broker.readConfigurationData(normalizedII, withDefa);
714 throw dataMissing(identifier);
716 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
720 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
721 final InstanceIdentifierContext<?> iiWithData = controllerContext.toInstanceIdentifier(identifier);
722 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
723 NormalizedNode data = null;
724 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
725 if (mountPoint != null) {
726 data = broker.readOperationalData(mountPoint, normalizedII);
728 data = broker.readOperationalData(normalizedII);
731 throw dataMissing(identifier);
733 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
736 private static RestconfDocumentedException dataMissing(final String identifier) {
737 LOG.debug("Request could not be completed because the relevant data model content does not exist {}",
739 return new RestconfDocumentedException("Request could not be completed because the relevant data model content "
740 + "does not exist", ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
744 public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload,
745 final UriInfo uriInfo) {
746 boolean insertUsed = false;
747 boolean pointUsed = false;
748 String insert = null;
751 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
752 switch (entry.getKey()) {
756 insert = entry.getValue().iterator().next();
758 throw new RestconfDocumentedException("Insert parameter can be used only once.");
764 point = entry.getValue().iterator().next();
766 throw new RestconfDocumentedException("Point parameter can be used only once.");
770 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
774 if (pointUsed && !insertUsed) {
775 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
777 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
778 throw new RestconfDocumentedException(
779 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
782 requireNonNull(identifier);
784 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
786 validateInput(iiWithData.getSchemaNode(), payload);
787 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
788 validateListKeysEqualityInPayloadAndUri(payload);
790 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
791 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
794 * There is a small window where another write transaction could be
795 * updating the same data simultaneously and we get an
796 * OptimisticLockFailedException. This error is likely transient and The
797 * WriteTransaction#submit API docs state that a retry will likely
798 * succeed. So we'll try again if that scenario occurs. If it fails a
799 * third time then it probably will never succeed so we'll fail in that
802 * By retrying we're attempting to hide the internal implementation of
803 * the data store and how it handles concurrent updates from the
804 * restconf client. The client has instructed us to put the data and we
805 * should make every effort to do so without pushing optimistic lock
806 * failures back to the client and forcing them to handle it via retry
807 * (and having to document the behavior).
809 PutResult result = null;
812 if (mountPoint != null) {
814 result = broker.commitMountPointDataPut(mountPoint, normalizedII, payload.getData(), insert,
817 result = broker.commitConfigurationDataPut(controllerContext.getGlobalSchema(), normalizedII,
818 payload.getData(), insert, point);
822 result.getFutureOfPutData().get();
823 } catch (final InterruptedException e) {
824 LOG.debug("Update failed for {}", identifier, e);
825 throw new RestconfDocumentedException(e.getMessage(), e);
826 } catch (final ExecutionException e) {
827 final TransactionCommitFailedException failure = Throwables.getCauseAs(e,
828 TransactionCommitFailedException.class);
829 if (failure instanceof OptimisticLockFailedException) {
831 LOG.debug("Got OptimisticLockFailedException on last try - failing {}", identifier);
832 throw new RestconfDocumentedException(e.getMessage(), e, failure.getErrorList());
835 LOG.debug("Got OptimisticLockFailedException - trying again {}", identifier);
839 LOG.debug("Update failed for {}", identifier, e);
840 throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), failure);
843 return Response.status(result.getStatus()).build();
847 private static void validateTopLevelNodeName(final NormalizedNodeContext node,
848 final YangInstanceIdentifier identifier) {
850 final String payloadName = node.getData().getIdentifier().getNodeType().getLocalName();
853 if (identifier.isEmpty()) {
855 if (!node.getData().getIdentifier().getNodeType().equals(NETCONF_BASE_QNAME)) {
856 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
857 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
861 final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
862 if (!payloadName.equals(identifierName)) {
863 throw new RestconfDocumentedException(
864 "Payload name (" + payloadName + ") is different from identifier name (" + identifierName + ")",
865 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
871 * Validates whether keys in {@code payload} are equal to values of keys in
872 * {@code iiWithData} for list schema node.
874 * @throws RestconfDocumentedException
875 * if key values or key count in payload and URI isn't equal
878 private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
879 checkArgument(payload != null);
880 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
881 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
882 final SchemaNode schemaNode = iiWithData.getSchemaNode();
883 final NormalizedNode data = payload.getData();
884 if (schemaNode instanceof ListSchemaNode) {
885 final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
886 if (lastPathArgument instanceof NodeIdentifierWithPredicates && data instanceof MapEntryNode) {
887 final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument).asMap();
888 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
894 public static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final MapEntryNode payload,
895 final List<QName> keyDefinitions) {
897 final Map<QName, Object> mutableCopyUriKeyValues = new HashMap<>(uriKeyValues);
898 for (final QName keyDefinition : keyDefinitions) {
899 final Object uriKeyValue = RestconfDocumentedException.throwIfNull(
900 // should be caught during parsing URI to InstanceIdentifier
901 mutableCopyUriKeyValues.remove(keyDefinition), ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
902 "Missing key %s in URI.", keyDefinition);
904 final Object dataKeyValue = payload.getIdentifier().getValue(keyDefinition);
906 if (!Objects.deepEquals(uriKeyValue, dataKeyValue)) {
907 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName()
908 + "' specified in the URI doesn't match the value '" + dataKeyValue
909 + "' specified in the message body. ";
910 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
916 public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload,
917 final UriInfo uriInfo) {
918 return createConfigurationData(payload, uriInfo);
922 public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
923 if (payload == null) {
924 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
926 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
927 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
928 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
930 boolean insertUsed = false;
931 boolean pointUsed = false;
932 String insert = null;
935 if (uriInfo != null) {
936 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
937 switch (entry.getKey()) {
941 insert = entry.getValue().iterator().next();
943 throw new RestconfDocumentedException("Insert parameter can be used only once.");
949 point = entry.getValue().iterator().next();
951 throw new RestconfDocumentedException("Point parameter can be used only once.");
955 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
960 if (pointUsed && !insertUsed) {
961 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
963 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
964 throw new RestconfDocumentedException(
965 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
968 FluentFuture<? extends CommitInfo> future;
969 if (mountPoint != null) {
970 future = broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData(), insert,
973 future = broker.commitConfigurationDataPost(controllerContext.getGlobalSchema(), normalizedII,
974 payload.getData(), insert, point);
979 } catch (final InterruptedException e) {
980 LOG.info("Error creating data {}", uriInfo != null ? uriInfo.getPath() : "", e);
981 throw new RestconfDocumentedException(e.getMessage(), e);
982 } catch (final ExecutionException e) {
983 LOG.info("Error creating data {}", uriInfo != null ? uriInfo.getPath() : "", e);
984 throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), Throwables.getCauseAs(e,
985 TransactionCommitFailedException.class));
988 LOG.trace("Successfuly created data.");
990 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
991 // FIXME: Provide path to result.
992 final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
993 if (location != null) {
994 responseBuilder.location(location);
996 return responseBuilder.build();
999 @SuppressWarnings("checkstyle:IllegalCatch")
1000 private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint,
1001 final YangInstanceIdentifier normalizedII) {
1002 if (uriInfo == null) {
1003 // This is null if invoked internally
1007 final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
1008 uriBuilder.path("config");
1010 uriBuilder.path(controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
1011 } catch (final Exception e) {
1012 LOG.info("Location for instance identifier {} was not created", normalizedII, e);
1015 return uriBuilder.build();
1019 public Response deleteConfigurationData(final String identifier) {
1020 final InstanceIdentifierContext<?> iiWithData = controllerContext.toInstanceIdentifier(identifier);
1021 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
1022 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
1024 final FluentFuture<? extends CommitInfo> future;
1025 if (mountPoint != null) {
1026 future = broker.commitConfigurationDataDelete(mountPoint, normalizedII);
1028 future = broker.commitConfigurationDataDelete(normalizedII);
1033 } catch (final InterruptedException e) {
1034 throw new RestconfDocumentedException(e.getMessage(), e);
1035 } catch (final ExecutionException e) {
1036 final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
1037 Predicates.instanceOf(ModifiedNodeDoesNotExistException.class)).toJavaUtil();
1038 if (searchedException.isPresent()) {
1039 throw new RestconfDocumentedException("Data specified for delete doesn't exist.", ErrorType.APPLICATION,
1040 ErrorTag.DATA_MISSING, e);
1043 throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), Throwables.getCauseAs(e,
1044 TransactionCommitFailedException.class));
1047 return Response.status(Status.OK).build();
1051 * Subscribes to some path in schema context (stream) to listen on changes
1055 * Additional parameters for subscribing to stream are loaded via rpc input
1058 * <li>datastore - default CONFIGURATION (other values of
1059 * {@link LogicalDatastoreType} enum type)</li>
1060 * <li>scope - default BASE (other values of {@link Scope})</li>
1064 public NormalizedNodeContext subscribeToStream(final String identifier, final UriInfo uriInfo) {
1065 boolean startTimeUsed = false;
1066 boolean stopTimeUsed = false;
1067 Instant start = Instant.now();
1068 Instant stop = null;
1069 boolean filterUsed = false;
1070 String filter = null;
1071 boolean leafNodesOnlyUsed = false;
1072 boolean leafNodesOnly = false;
1073 boolean skipNotificationDataUsed = false;
1074 boolean skipNotificationData = false;
1076 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
1077 switch (entry.getKey()) {
1079 if (!startTimeUsed) {
1080 startTimeUsed = true;
1081 start = parseDateFromQueryParam(entry);
1083 throw new RestconfDocumentedException("Start-time parameter can be used only once.");
1087 if (!stopTimeUsed) {
1088 stopTimeUsed = true;
1089 stop = parseDateFromQueryParam(entry);
1091 throw new RestconfDocumentedException("Stop-time parameter can be used only once.");
1097 filter = entry.getValue().iterator().next();
1099 throw new RestconfDocumentedException("Filter parameter can be used only once.");
1102 case "odl-leaf-nodes-only":
1103 if (!leafNodesOnlyUsed) {
1104 leafNodesOnlyUsed = true;
1105 leafNodesOnly = Boolean.parseBoolean(entry.getValue().iterator().next());
1107 throw new RestconfDocumentedException("Odl-leaf-nodes-only parameter can be used only once.");
1110 case "odl-skip-notification-data":
1111 if (!skipNotificationDataUsed) {
1112 skipNotificationDataUsed = true;
1113 skipNotificationData = Boolean.parseBoolean(entry.getValue().iterator().next());
1115 throw new RestconfDocumentedException(
1116 "Odl-skip-notification-data parameter can be used only once.");
1120 throw new RestconfDocumentedException("Bad parameter used with notifications: " + entry.getKey());
1123 if (!startTimeUsed && stopTimeUsed) {
1124 throw new RestconfDocumentedException("Stop-time parameter has to be used with start-time parameter.");
1126 URI response = null;
1127 if (identifier.contains(DATA_SUBSCR)) {
1128 response = dataSubs(identifier, uriInfo, start, stop, filter, leafNodesOnly, skipNotificationData);
1129 } else if (identifier.contains(NOTIFICATION_STREAM)) {
1130 response = notifStream(identifier, uriInfo, start, stop, filter);
1133 if (response != null) {
1134 // prepare node with value of location
1135 final InstanceIdentifierContext<?> iid = prepareIIDSubsStreamOutput();
1136 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> builder =
1137 ImmutableLeafNodeBuilder.create().withValue(response.toString());
1138 builder.withNodeIdentifier(
1139 NodeIdentifier.create(QName.create("subscribe:to:notification", "2016-10-28", "location")));
1141 // prepare new header with location
1142 return new NormalizedNodeContext(iid, builder.build(), ImmutableMap.of("Location", response));
1145 final String msg = "Bad type of notification of sal-remote";
1147 throw new RestconfDocumentedException(msg);
1150 private static Instant parseDateFromQueryParam(final Entry<String, List<String>> entry) {
1151 final DateAndTime event = new DateAndTime(entry.getValue().iterator().next());
1152 final String value = event.getValue();
1153 final TemporalAccessor p;
1155 p = FORMATTER.parse(value);
1156 } catch (final DateTimeParseException e) {
1157 throw new RestconfDocumentedException("Cannot parse of value in date: " + value, e);
1159 return Instant.from(p);
1163 * Prepare instance identifier.
1165 * @return {@link InstanceIdentifierContext} of location leaf for
1168 private InstanceIdentifierContext<?> prepareIIDSubsStreamOutput() {
1169 final QName qnameBase = QName.create("subscribe:to:notification", "2016-10-28", "notifi");
1170 final EffectiveModelContext schemaCtx = controllerContext.getGlobalSchema();
1171 final DataSchemaNode location = ((ContainerSchemaNode) schemaCtx
1172 .findModule(qnameBase.getModule()).orElse(null)
1173 .getDataChildByName(qnameBase)).getDataChildByName(QName.create(qnameBase, "location"));
1174 final List<PathArgument> path = new ArrayList<>();
1175 path.add(NodeIdentifier.create(qnameBase));
1176 path.add(NodeIdentifier.create(QName.create(qnameBase, "location")));
1178 return new InstanceIdentifierContext<SchemaNode>(YangInstanceIdentifier.create(path), location, null,
1183 * Register notification listener by stream name.
1190 * stop-time of getting notification
1192 * start-time of getting notification
1194 * indicate which subset of all possible events are of interest
1195 * @return {@link URI} of location
1197 private URI notifStream(final String identifier, final UriInfo uriInfo, final Instant start,
1198 final Instant stop, final String filter) {
1199 final String streamName = Notificator.createStreamNameFromUri(identifier);
1200 if (Strings.isNullOrEmpty(streamName)) {
1201 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1203 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
1204 if (listeners == null || listeners.isEmpty()) {
1205 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1206 ErrorTag.UNKNOWN_ELEMENT);
1209 for (final NotificationListenerAdapter listener : listeners) {
1210 broker.registerToListenNotification(listener);
1211 listener.setQueryParams(start, Optional.ofNullable(stop), Optional.ofNullable(filter), false, false);
1214 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1216 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance(NOTIFICATION_PORT);
1217 final int notificationPort = webSocketServerInstance.getPort();
1220 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme(getWsScheme(uriInfo));
1222 return uriToWebsocketServerBuilder.replacePath(streamName).build();
1225 private static String getWsScheme(final UriInfo uriInfo) {
1226 URI uri = uriInfo.getAbsolutePath();
1230 String subscriptionScheme = uri.getScheme().toLowerCase(Locale.ROOT);
1231 return subscriptionScheme.equals("https") ? "wss" : "ws";
1235 * Register data change listener by stream name.
1242 * start-time of getting notification
1244 * stop-time of getting notification
1246 * indicate which subset of all possible events are of interest
1247 * @return {@link URI} of location
1249 private URI dataSubs(final String identifier, final UriInfo uriInfo, final Instant start, final Instant stop,
1250 final String filter, final boolean leafNodesOnly, final boolean skipNotificationData) {
1251 final String streamName = Notificator.createStreamNameFromUri(identifier);
1252 if (Strings.isNullOrEmpty(streamName)) {
1253 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1256 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1257 if (listener == null) {
1258 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1259 ErrorTag.UNKNOWN_ELEMENT);
1261 listener.setQueryParams(start, Optional.ofNullable(stop), Optional.ofNullable(filter), leafNodesOnly,
1262 skipNotificationData);
1264 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1265 final LogicalDatastoreType datastore =
1266 parserURIEnumParameter(LogicalDatastoreType.class, paramToValues.get(DATASTORE_PARAM_NAME));
1267 if (datastore == null) {
1268 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1269 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1271 final Scope scope = parserURIEnumParameter(Scope.class, paramToValues.get(SCOPE_PARAM_NAME));
1272 if (scope == null) {
1273 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1274 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1277 broker.registerToListenDataChanges(datastore, scope, listener);
1279 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1281 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance(NOTIFICATION_PORT);
1282 final int notificationPort = webSocketServerInstance.getPort();
1284 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme(getWsScheme(uriInfo));
1286 return uriToWebsocketServerBuilder.replacePath(streamName).build();
1289 @SuppressWarnings("checkstyle:IllegalCatch")
1291 public PatchStatusContext patchConfigurationData(final String identifier, final PatchContext context,
1292 final UriInfo uriInfo) {
1293 if (context == null) {
1294 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1298 return broker.patchConfigurationDataWithinTransaction(context);
1299 } catch (final Exception e) {
1300 LOG.debug("Patch transaction failed", e);
1301 throw new RestconfDocumentedException(e.getMessage(), e);
1305 @SuppressWarnings("checkstyle:IllegalCatch")
1307 public PatchStatusContext patchConfigurationData(final PatchContext context, @Context final UriInfo uriInfo) {
1308 if (context == null) {
1309 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1313 return broker.patchConfigurationDataWithinTransaction(context);
1314 } catch (final Exception e) {
1315 LOG.debug("Patch transaction failed", e);
1316 throw new RestconfDocumentedException(e.getMessage(), e);
1321 * Load parameter for subscribing to stream from input composite node.
1325 * @return enum object if its string value is equal to {@code paramName}. In
1328 private static <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1329 final String paramName) {
1330 final Optional<DataContainerChild> optAugNode = value.findChildByArg(SAL_REMOTE_AUG_IDENTIFIER);
1331 if (optAugNode.isEmpty()) {
1334 final DataContainerChild augNode = optAugNode.get();
1335 if (!(augNode instanceof AugmentationNode)) {
1338 final Optional<DataContainerChild> enumNode = ((AugmentationNode) augNode).findChildByArg(
1339 new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1340 if (enumNode.isEmpty()) {
1343 final Object rawValue = enumNode.get().body();
1344 if (!(rawValue instanceof String)) {
1348 return resolveAsEnum(classDescriptor, (String) rawValue);
1352 * Checks whether {@code value} is one of the string representation of
1353 * enumeration {@code classDescriptor}.
1355 * @return enum object if string value of {@code classDescriptor}
1356 * enumeration is equal to {@code value}. Other cases null.
1358 private static <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1359 if (Strings.isNullOrEmpty(value)) {
1362 return resolveAsEnum(classDescriptor, value);
1365 private static <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1366 final T[] enumConstants = classDescriptor.getEnumConstants();
1367 if (enumConstants != null) {
1368 for (final T enm : classDescriptor.getEnumConstants()) {
1369 if (((Enum<?>) enm).name().equals(value)) {
1377 private static Map<String, String> resolveValuesFromUri(final String uri) {
1378 final Map<String, String> result = new HashMap<>();
1379 final String[] tokens = uri.split("/");
1380 for (int i = 1; i < tokens.length; i++) {
1381 final String[] parameterTokens = tokens[i].split("=");
1382 if (parameterTokens.length == 2) {
1383 result.put(parameterTokens[0], parameterTokens[1]);
1389 private MapNode makeModuleMapNode(final Collection<? extends Module> modules) {
1390 requireNonNull(modules);
1391 final Module restconfModule = getRestconfModule();
1392 final DataSchemaNode moduleSchemaNode = controllerContext
1393 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1394 checkState(moduleSchemaNode instanceof ListSchemaNode);
1396 final CollectionNodeBuilder<MapEntryNode, SystemMapNode> listModuleBuilder =
1397 SchemaAwareBuilders.mapBuilder((ListSchemaNode) moduleSchemaNode);
1399 for (final Module module : modules) {
1400 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1402 return listModuleBuilder.build();
1405 private static MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1406 checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1407 "moduleSchemaNode has to be of type ListSchemaNode");
1408 final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1409 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues =
1410 SchemaAwareBuilders.mapEntryBuilder(listModuleSchemaNode);
1412 List<DataSchemaNode> instanceDataChildrenByName =
1413 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "name");
1414 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1415 checkState(nameSchemaNode instanceof LeafSchemaNode);
1416 moduleNodeValues.withChild(
1417 SchemaAwareBuilders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName()).build());
1419 final QNameModule qNameModule = module.getQNameModule();
1421 instanceDataChildrenByName =
1422 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "revision");
1423 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1424 checkState(revisionSchemaNode instanceof LeafSchemaNode);
1425 final Optional<Revision> revision = qNameModule.getRevision();
1426 moduleNodeValues.withChild(SchemaAwareBuilders.leafBuilder((LeafSchemaNode) revisionSchemaNode)
1427 .withValue(revision.map(Revision::toString).orElse("")).build());
1429 instanceDataChildrenByName =
1430 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "namespace");
1431 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1432 checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1433 moduleNodeValues.withChild(SchemaAwareBuilders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1434 .withValue(qNameModule.getNamespace().toString()).build());
1436 instanceDataChildrenByName =
1437 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "feature");
1438 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1439 checkState(featureSchemaNode instanceof LeafListSchemaNode);
1440 final ListNodeBuilder<Object, SystemLeafSetNode<Object>> featuresBuilder =
1441 SchemaAwareBuilders.leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1442 for (final FeatureDefinition feature : module.getFeatures()) {
1443 featuresBuilder.withChild(SchemaAwareBuilders.leafSetEntryBuilder((LeafListSchemaNode) featureSchemaNode)
1444 .withValue(feature.getQName().getLocalName()).build());
1446 moduleNodeValues.withChild(featuresBuilder.build());
1448 return moduleNodeValues.build();
1451 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1452 checkArgument(streamSchemaNode instanceof ListSchemaNode,
1453 "streamSchemaNode has to be of type ListSchemaNode");
1454 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1455 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues =
1456 SchemaAwareBuilders.mapEntryBuilder(listStreamSchemaNode);
1458 List<DataSchemaNode> instanceDataChildrenByName =
1459 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "name");
1460 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1461 checkState(nameSchemaNode instanceof LeafSchemaNode);
1462 streamNodeValues.withChild(
1463 SchemaAwareBuilders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName).build());
1465 instanceDataChildrenByName =
1466 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "description");
1467 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1468 checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1469 streamNodeValues.withChild(SchemaAwareBuilders.leafBuilder((LeafSchemaNode) nameSchemaNode)
1470 .withValue("DESCRIPTION_PLACEHOLDER")
1473 instanceDataChildrenByName =
1474 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-support");
1475 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1476 checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1477 streamNodeValues.withChild(SchemaAwareBuilders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1478 .withValue(Boolean.TRUE).build());
1480 instanceDataChildrenByName =
1481 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-log-creation-time");
1482 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1483 checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1484 streamNodeValues.withChild(
1485 SchemaAwareBuilders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode).withValue("").build());
1487 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "events");
1488 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1489 checkState(eventsSchemaNode instanceof LeafSchemaNode);
1490 streamNodeValues.withChild(
1491 SchemaAwareBuilders.leafBuilder((LeafSchemaNode) eventsSchemaNode).withValue(Empty.value()).build());
1493 return streamNodeValues.build();
1497 * Prepare stream for notification.
1500 * contains list of qnames of notifications
1501 * @return - checked future object
1503 private ListenableFuture<DOMRpcResult> invokeSalRemoteRpcNotifiStrRPC(final NormalizedNodeContext payload) {
1504 final ContainerNode data = (ContainerNode) payload.getData();
1505 LeafSetNode leafSet = null;
1506 String outputType = "XML";
1507 for (final DataContainerChild dataChild : data.body()) {
1508 if (dataChild instanceof LeafSetNode) {
1509 leafSet = (LeafSetNode) dataChild;
1510 } else if (dataChild instanceof AugmentationNode) {
1511 outputType = (String) ((AugmentationNode) dataChild).body().iterator().next().body();
1515 final Collection<LeafSetEntryNode<?>> entryNodes = leafSet.body();
1516 final List<SchemaPath> paths = new ArrayList<>();
1517 String streamName = CREATE_NOTIFICATION_STREAM + "/";
1519 StringBuilder streamNameBuilder = new StringBuilder(streamName);
1520 final Iterator<LeafSetEntryNode<?>> iterator = entryNodes.iterator();
1521 while (iterator.hasNext()) {
1522 final QName valueQName = QName.create((String) iterator.next().body());
1523 final XMLNamespace namespace = valueQName.getModule().getNamespace();
1524 final Module module = controllerContext.findModuleByNamespace(namespace);
1525 checkNotNull(module, "Module for namespace %s does not exist", namespace);
1526 NotificationDefinition notifiDef = null;
1527 for (final NotificationDefinition notification : module.getNotifications()) {
1528 if (notification.getQName().equals(valueQName)) {
1529 notifiDef = notification;
1533 final String moduleName = module.getName();
1534 checkNotNull(notifiDef, "Notification %s does not exist in module %s", valueQName, moduleName);
1535 paths.add(SchemaPath.of(Absolute.of(notifiDef.getQName())));
1536 streamNameBuilder.append(moduleName).append(':').append(valueQName.getLocalName());
1537 if (iterator.hasNext()) {
1538 streamNameBuilder.append(',');
1542 streamName = streamNameBuilder.toString();
1544 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
1545 final QName outputQname = QName.create(rpcQName, "output");
1546 final QName streamNameQname = QName.create(rpcQName, "notification-stream-identifier");
1548 final ContainerNode output =
1549 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
1550 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
1552 if (!Notificator.existNotificationListenerFor(streamName)) {
1553 Notificator.createNotificationListener(paths, streamName, outputType, controllerContext);
1556 return Futures.immediateFuture(new DefaultDOMRpcResult(output));
1559 private static EffectiveModelContext modelContext(final DOMMountPoint mountPoint) {
1560 return mountPoint.getService(DOMSchemaService.class)
1561 .flatMap(svc -> Optional.ofNullable(svc.getGlobalContext()))