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.ImmutableSet;
21 import com.google.common.collect.Iterables;
22 import com.google.common.util.concurrent.FluentFuture;
23 import com.google.common.util.concurrent.Futures;
24 import com.google.common.util.concurrent.ListenableFuture;
25 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
27 import java.time.Instant;
28 import java.time.format.DateTimeFormatter;
29 import java.time.format.DateTimeFormatterBuilder;
30 import java.time.format.DateTimeParseException;
31 import java.time.temporal.ChronoField;
32 import java.time.temporal.TemporalAccessor;
33 import java.util.AbstractMap.SimpleImmutableEntry;
34 import java.util.ArrayList;
35 import java.util.Collection;
36 import java.util.Collections;
37 import java.util.HashMap;
38 import java.util.Iterator;
39 import java.util.List;
40 import java.util.Locale;
42 import java.util.Map.Entry;
43 import java.util.Objects;
44 import java.util.Optional;
46 import java.util.concurrent.CancellationException;
47 import java.util.concurrent.ExecutionException;
48 import javax.inject.Inject;
49 import javax.inject.Singleton;
50 import javax.ws.rs.WebApplicationException;
51 import javax.ws.rs.core.Context;
52 import javax.ws.rs.core.Response;
53 import javax.ws.rs.core.Response.ResponseBuilder;
54 import javax.ws.rs.core.Response.Status;
55 import javax.ws.rs.core.UriBuilder;
56 import javax.ws.rs.core.UriInfo;
57 import org.eclipse.jdt.annotation.NonNull;
58 import org.opendaylight.mdsal.common.api.CommitInfo;
59 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
60 import org.opendaylight.mdsal.common.api.OptimisticLockFailedException;
61 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
62 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
63 import org.opendaylight.mdsal.dom.api.DOMRpcImplementationNotAvailableException;
64 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
65 import org.opendaylight.mdsal.dom.api.DOMRpcService;
66 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
67 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
68 import org.opendaylight.netconf.sal.rest.api.Draft02;
69 import org.opendaylight.netconf.sal.rest.api.RestconfService;
70 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
71 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
72 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
73 import org.opendaylight.netconf.sal.streams.websockets.WebSocketServer;
74 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
75 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
76 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
77 import org.opendaylight.restconf.common.patch.PatchContext;
78 import org.opendaylight.restconf.common.patch.PatchStatusContext;
79 import org.opendaylight.restconf.common.util.OperationsResourceUtils;
80 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
81 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.CreateDataChangeEventSubscriptionInput1.Scope;
82 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
83 import org.opendaylight.yangtools.yang.common.Empty;
84 import org.opendaylight.yangtools.yang.common.ErrorTag;
85 import org.opendaylight.yangtools.yang.common.ErrorType;
86 import org.opendaylight.yangtools.yang.common.QName;
87 import org.opendaylight.yangtools.yang.common.QNameModule;
88 import org.opendaylight.yangtools.yang.common.Revision;
89 import org.opendaylight.yangtools.yang.common.XMLNamespace;
90 import org.opendaylight.yangtools.yang.common.YangConstants;
91 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
92 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
93 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
94 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
95 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
96 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
97 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
98 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
99 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
100 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
101 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
102 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
103 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
104 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
105 import org.opendaylight.yangtools.yang.data.api.schema.SystemLeafSetNode;
106 import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
107 import org.opendaylight.yangtools.yang.data.api.schema.builder.CollectionNodeBuilder;
108 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
109 import org.opendaylight.yangtools.yang.data.api.schema.builder.ListNodeBuilder;
110 import org.opendaylight.yangtools.yang.data.api.schema.builder.NormalizedNodeBuilder;
111 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
112 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
113 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaAwareBuilders;
114 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
115 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
116 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
117 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
118 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
119 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
120 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
121 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
122 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
123 import org.opendaylight.yangtools.yang.model.api.Module;
124 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
125 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
126 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
127 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
128 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
129 import org.slf4j.Logger;
130 import org.slf4j.LoggerFactory;
133 public final class RestconfImpl implements RestconfService {
135 * Notifications are served on port 8181.
137 private static final int NOTIFICATION_PORT = 8181;
139 private static final int CHAR_NOT_FOUND = -1;
141 private static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
143 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
145 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
147 private static final XMLNamespace NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT =
148 XMLNamespace.of("urn:sal:restconf:event:subscription");
150 private static final String DATASTORE_PARAM_NAME = "datastore";
152 private static final String SCOPE_PARAM_NAME = "scope";
154 private static final String OUTPUT_TYPE_PARAM_NAME = "notification-output-type";
156 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
158 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
160 private static final QName NETCONF_BASE_QNAME = QName.create(QNameModule.create(XMLNamespace.of(NETCONF_BASE)),
161 NETCONF_BASE_PAYLOAD_NAME).intern();
163 private static final QNameModule SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
164 Revision.of("2014-07-08"));
166 private static final AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER =
167 new AugmentationIdentifier(ImmutableSet.of(
168 QName.create(SAL_REMOTE_AUGMENT, "scope"), QName.create(SAL_REMOTE_AUGMENT, "datastore"),
169 QName.create(SAL_REMOTE_AUGMENT, "notification-output-type")));
171 public static final CharSequence DATA_SUBSCR = "data-change-event-subscription";
172 private static final CharSequence CREATE_DATA_SUBSCR = "create-" + DATA_SUBSCR;
174 public static final CharSequence NOTIFICATION_STREAM = "notification-stream";
175 private static final CharSequence CREATE_NOTIFICATION_STREAM = "create-" + NOTIFICATION_STREAM;
177 private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
178 .appendValue(ChronoField.YEAR, 4).appendLiteral('-')
179 .appendValue(ChronoField.MONTH_OF_YEAR, 2).appendLiteral('-')
180 .appendValue(ChronoField.DAY_OF_MONTH, 2).appendLiteral('T')
181 .appendValue(ChronoField.HOUR_OF_DAY, 2).appendLiteral(':')
182 .appendValue(ChronoField.MINUTE_OF_HOUR, 2).appendLiteral(':')
183 .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
184 .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
185 .appendOffset("+HH:MM", "Z").toFormatter();
187 private final BrokerFacade broker;
189 private final ControllerContext controllerContext;
192 public RestconfImpl(final BrokerFacade broker, final ControllerContext controllerContext) {
193 this.broker = broker;
194 this.controllerContext = controllerContext;
200 * @deprecated Just use {@link #RestconfImpl(BrokerFacade, ControllerContext)} constructor instead.
203 public static RestconfImpl newInstance(final BrokerFacade broker, final ControllerContext controllerContext) {
204 return new RestconfImpl(broker, controllerContext);
209 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
210 final MapNode allModuleMap = makeModuleMapNode(controllerContext.getAllModules());
212 final EffectiveModelContext schemaContext = this.controllerContext.getGlobalSchema();
214 final Module restconfModule = getRestconfModule();
215 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
216 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
217 checkState(modulesSchemaNode instanceof ContainerSchemaNode);
219 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
220 SchemaAwareBuilders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
221 moduleContainerBuilder.withChild(allModuleMap);
223 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode, null, schemaContext),
224 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
228 * Valid only for mount point.
232 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
233 if (!identifier.contains(ControllerContext.MOUNT)) {
234 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
235 + " URI has to end with " + ControllerContext.MOUNT;
236 LOG.debug("{} for {}", errMsg, identifier);
237 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
240 final InstanceIdentifierContext<?> mountPointIdentifier =
241 this.controllerContext.toMountPointIdentifier(identifier);
242 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
243 final MapNode mountPointModulesMap = makeModuleMapNode(controllerContext.getAllModules(mountPoint));
245 final Module restconfModule = getRestconfModule();
246 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
247 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
248 checkState(modulesSchemaNode instanceof ContainerSchemaNode);
250 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
251 SchemaAwareBuilders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
252 moduleContainerBuilder.withChild(mountPointModulesMap);
254 return new NormalizedNodeContext(
255 new InstanceIdentifierContext<>(null, modulesSchemaNode, mountPoint,
256 this.controllerContext.getGlobalSchema()),
257 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
262 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
263 final Entry<String, Revision> nameRev = getModuleNameAndRevision(requireNonNull(identifier));
264 Module module = null;
265 DOMMountPoint mountPoint = null;
266 final EffectiveModelContext schemaContext;
267 if (identifier.contains(ControllerContext.MOUNT)) {
268 final InstanceIdentifierContext<?> mountPointIdentifier =
269 this.controllerContext.toMountPointIdentifier(identifier);
270 mountPoint = mountPointIdentifier.getMountPoint();
271 module = this.controllerContext.findModuleByNameAndRevision(mountPoint, nameRev.getKey(),
273 schemaContext = modelContext(mountPoint);
275 module = this.controllerContext.findModuleByNameAndRevision(nameRev.getKey(), nameRev.getValue());
276 schemaContext = this.controllerContext.getGlobalSchema();
279 if (module == null) {
280 LOG.debug("Module with name '{}' and revision '{}' was not found.", nameRev.getKey(), nameRev.getValue());
281 throw new RestconfDocumentedException("Module with name '" + nameRev.getKey() + "' and revision '"
282 + nameRev.getValue() + "' was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
285 final Module restconfModule = getRestconfModule();
286 final Set<Module> modules = Collections.singleton(module);
287 final MapNode moduleMap = makeModuleMapNode(modules);
289 final DataSchemaNode moduleSchemaNode = this.controllerContext
290 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
291 checkState(moduleSchemaNode instanceof ListSchemaNode);
293 return new NormalizedNodeContext(
294 new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint, schemaContext), moduleMap,
295 QueryParametersParser.parseWriterParameters(uriInfo));
300 public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
301 final EffectiveModelContext schemaContext = this.controllerContext.getGlobalSchema();
302 final Set<String> availableStreams = Notificator.getStreamNames();
303 final Module restconfModule = getRestconfModule();
304 final DataSchemaNode streamSchemaNode = this.controllerContext
305 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
306 checkState(streamSchemaNode instanceof ListSchemaNode);
308 final CollectionNodeBuilder<MapEntryNode, SystemMapNode> listStreamsBuilder =
309 SchemaAwareBuilders.mapBuilder((ListSchemaNode) streamSchemaNode);
311 for (final String streamName : availableStreams) {
312 listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
315 final DataSchemaNode streamsContainerSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
316 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
317 checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
319 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
320 SchemaAwareBuilders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
321 streamsContainerBuilder.withChild(listStreamsBuilder.build());
323 return new NormalizedNodeContext(
324 new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null, schemaContext),
325 streamsContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
330 public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
331 return OperationsResourceUtils.contextForModelContext(controllerContext.getGlobalSchema(), null);
336 public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
337 if (!identifier.contains(ControllerContext.MOUNT)) {
338 final String errMsg = "URI has bad format. If operations behind mount point should be showed, URI has to "
339 + " end with " + ControllerContext.MOUNT;
340 LOG.debug("{} for {}", errMsg, identifier);
341 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
344 final InstanceIdentifierContext<?> mountPointIdentifier =
345 this.controllerContext.toMountPointIdentifier(identifier);
346 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
347 return OperationsResourceUtils.contextForModelContext(modelContext(mountPoint), mountPoint);
350 private Module getRestconfModule() {
351 final Module restconfModule = this.controllerContext.getRestconfModule();
352 if (restconfModule == null) {
353 LOG.debug("ietf-restconf module was not found.");
354 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
355 ErrorTag.OPERATION_NOT_SUPPORTED);
358 return restconfModule;
361 private static Entry<String, Revision> getModuleNameAndRevision(final String identifier) {
362 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
363 String moduleNameAndRevision = "";
364 if (mountIndex >= 0) {
365 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
367 moduleNameAndRevision = identifier;
370 final Splitter splitter = Splitter.on('/').omitEmptyStrings();
371 final List<String> pathArgs = splitter.splitToList(moduleNameAndRevision);
372 if (pathArgs.size() < 2) {
373 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' {}", identifier);
374 throw new RestconfDocumentedException(
375 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
376 ErrorTag.INVALID_VALUE);
380 return new SimpleImmutableEntry<>(pathArgs.get(0), Revision.of(pathArgs.get(1)));
381 } catch (final DateTimeParseException e) {
382 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' {}", identifier);
383 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
384 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
389 public Object getRoot() {
394 public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload,
395 final UriInfo uriInfo) {
396 if (payload == null) {
397 // no payload specified, reroute this to no payload invokeRpc implementation
398 return invokeRpc(identifier, uriInfo);
401 final SchemaNode schema = payload.getInstanceIdentifierContext().getSchemaNode();
402 final ListenableFuture<? extends DOMRpcResult> response;
403 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
404 final NormalizedNode input = nonnullInput(schema, payload.getData());
405 final EffectiveModelContext schemaContext;
407 if (mountPoint != null) {
408 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
409 if (mountRpcServices.isEmpty()) {
410 LOG.debug("Error: Rpc service is missing.");
411 throw new RestconfDocumentedException("Rpc service is missing.");
413 schemaContext = modelContext(mountPoint);
414 response = mountRpcServices.get().invokeRpc(schema.getQName(), input);
416 final XMLNamespace namespace = schema.getQName().getNamespace();
417 if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
418 if (identifier.contains(CREATE_DATA_SUBSCR)) {
419 response = invokeSalRemoteRpcSubscribeRPC(payload);
420 } else if (identifier.contains(CREATE_NOTIFICATION_STREAM)) {
421 response = invokeSalRemoteRpcNotifiStrRPC(payload);
423 final String msg = "Not supported operation";
425 throw new RestconfDocumentedException(msg, ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED);
428 response = this.broker.invokeRpc(schema.getQName(), input);
430 schemaContext = this.controllerContext.getGlobalSchema();
433 final DOMRpcResult result = checkRpcResponse(response);
435 RpcDefinition resultNodeSchema = null;
436 final NormalizedNode resultData;
437 if (result != null && result.getResult() != null) {
438 resultData = result.getResult();
439 resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
444 if (resultData != null && ((ContainerNode) resultData).isEmpty()) {
445 throw new WebApplicationException(Response.Status.NO_CONTENT);
447 return new NormalizedNodeContext(
448 new InstanceIdentifierContext<>(null, resultNodeSchema, mountPoint, schemaContext),
449 resultData, QueryParametersParser.parseWriterParameters(uriInfo));
453 @SuppressFBWarnings(value = "NP_LOAD_OF_KNOWN_NULL_VALUE",
454 justification = "Looks like a false positive, see below FIXME")
455 private NormalizedNodeContext invokeRpc(final String identifier, final UriInfo uriInfo) {
456 final DOMMountPoint mountPoint;
457 final String identifierEncoded;
458 final EffectiveModelContext schemaContext;
459 if (identifier.contains(ControllerContext.MOUNT)) {
460 // mounted RPC call - look up mount instance.
461 final InstanceIdentifierContext<?> mountPointId = this.controllerContext.toMountPointIdentifier(identifier);
462 mountPoint = mountPointId.getMountPoint();
463 schemaContext = modelContext(mountPoint);
464 final int startOfRemoteRpcName =
465 identifier.lastIndexOf(ControllerContext.MOUNT) + ControllerContext.MOUNT.length() + 1;
466 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
467 identifierEncoded = remoteRpcName;
469 } else if (identifier.indexOf('/') == CHAR_NOT_FOUND) {
470 identifierEncoded = identifier;
472 schemaContext = this.controllerContext.getGlobalSchema();
474 LOG.debug("Identifier {} cannot contain slash character (/).", identifier);
475 throw new RestconfDocumentedException(String.format("Identifier %n%s%ncan\'t contain slash character (/).%n"
476 + "If slash is part of identifier name then use %%2F placeholder.", identifier), ErrorType.PROTOCOL,
477 ErrorTag.INVALID_VALUE);
480 final String identifierDecoded = ControllerContext.urlPathArgDecode(identifierEncoded);
481 final RpcDefinition rpc;
482 if (mountPoint == null) {
483 rpc = this.controllerContext.getRpcDefinition(identifierDecoded);
485 rpc = findRpc(modelContext(mountPoint), identifierDecoded);
489 LOG.debug("RPC {} does not exist.", identifierDecoded);
490 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
493 if (!rpc.getInput().getChildNodes().isEmpty()) {
494 LOG.debug("No input specified for RPC {} with an input section", rpc);
495 throw new RestconfDocumentedException("No input specified for RPC " + rpc
496 + " with an input section defined", ErrorType.RPC, ErrorTag.MISSING_ELEMENT);
499 final ContainerNode input = defaultInput(rpc.getQName());
500 final ListenableFuture<? extends DOMRpcResult> response;
501 if (mountPoint != null) {
502 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
503 if (mountRpcServices.isEmpty()) {
504 throw new RestconfDocumentedException("Rpc service is missing.");
506 response = mountRpcServices.get().invokeRpc(rpc.getQName(), input);
508 response = this.broker.invokeRpc(rpc.getQName(), input);
511 final NormalizedNode result = checkRpcResponse(response).getResult();
512 if (result != null && ((ContainerNode) result).isEmpty()) {
513 throw new WebApplicationException(Response.Status.NO_CONTENT);
516 // FIXME: in reference to the above @SupressFBWarnings: "mountPoint" reference here trips up SpotBugs, as it
517 // thinks it can only ever be null. Except it can very much be non-null. The core problem is the horrible
518 // structure of this code where we have a sh*tload of checks for mountpoint above and all over the
519 // codebase where all that difference should have been properly encapsulated.
521 // This is legacy code, so if anybody cares to do that refactor, feel free to contribute, but I am not
523 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpc, mountPoint, schemaContext), result,
524 QueryParametersParser.parseWriterParameters(uriInfo));
527 private static @NonNull NormalizedNode nonnullInput(final SchemaNode rpc, final NormalizedNode input) {
528 return input != null ? input : defaultInput(rpc.getQName());
531 private static @NonNull ContainerNode defaultInput(final QName rpcName) {
532 return ImmutableNodes.containerNode(YangConstants.operationInputQName(rpcName.getModule()));
535 @SuppressWarnings("checkstyle:avoidHidingCauseException")
536 private static DOMRpcResult checkRpcResponse(final ListenableFuture<? extends DOMRpcResult> response) {
537 if (response == null) {
541 final DOMRpcResult retValue = response.get();
542 if (retValue.getErrors().isEmpty()) {
545 LOG.debug("RpcError message {}", retValue.getErrors());
546 throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
547 } catch (final InterruptedException e) {
548 final String errMsg = "The operation was interrupted while executing and did not complete.";
549 LOG.debug("Rpc Interrupt - {}", errMsg, e);
550 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION, e);
551 } catch (final ExecutionException e) {
552 LOG.debug("Execution RpcError: ", e);
553 Throwable cause = e.getCause();
555 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
558 while (cause.getCause() != null) {
559 cause = cause.getCause();
562 if (cause instanceof IllegalArgumentException) {
563 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
564 } else if (cause instanceof DOMRpcImplementationNotAvailableException) {
565 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.APPLICATION,
566 ErrorTag.OPERATION_NOT_SUPPORTED);
568 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
570 } catch (final CancellationException e) {
571 final String errMsg = "The operation was cancelled while executing.";
572 LOG.debug("Cancel RpcExecution: {}", errMsg, e);
573 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
577 private static void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
578 if (inputSchema != null && payload.getData() == null) {
579 // expected a non null payload
580 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
581 } else if (inputSchema == null && payload.getData() != null) {
582 // did not expect any input
583 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
587 private ListenableFuture<DOMRpcResult> invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
588 final ContainerNode value = (ContainerNode) payload.getData();
589 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
590 final Optional<DataContainerChild> path =
591 value.findChildByArg(new NodeIdentifier(QName.create(rpcQName, "path")));
592 final Object pathValue = path.isPresent() ? path.get().body() : null;
594 if (!(pathValue instanceof YangInstanceIdentifier)) {
595 LOG.debug("Instance identifier {} was not normalized correctly", rpcQName);
596 throw new RestconfDocumentedException("Instance identifier was not normalized correctly",
597 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
600 final YangInstanceIdentifier pathIdentifier = (YangInstanceIdentifier) pathValue;
601 String streamName = (String) CREATE_DATA_SUBSCR;
602 NotificationOutputType outputType = null;
603 if (!pathIdentifier.isEmpty()) {
604 final String fullRestconfIdentifier =
605 DATA_SUBSCR + this.controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
607 LogicalDatastoreType datastore =
608 parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
609 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
611 Scope scope = parseEnumTypeParameter(value, Scope.class, SCOPE_PARAM_NAME);
612 scope = scope == null ? Scope.BASE : scope;
614 outputType = parseEnumTypeParameter(value, NotificationOutputType.class, OUTPUT_TYPE_PARAM_NAME);
615 outputType = outputType == null ? NotificationOutputType.XML : outputType;
617 streamName = Notificator
618 .createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore + "/scope=" + scope);
621 if (Strings.isNullOrEmpty(streamName)) {
622 LOG.debug("Path is empty or contains value node which is not Container or List built-in type at {}",
624 throw new RestconfDocumentedException("Path is empty or contains value node which is not Container or List "
625 + "built-in type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
628 final QName outputQname = QName.create(rpcQName, "output");
629 final QName streamNameQname = QName.create(rpcQName, "stream-name");
631 final ContainerNode output =
632 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
633 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
635 if (!Notificator.existListenerFor(streamName)) {
636 Notificator.createListener(pathIdentifier, streamName, outputType, controllerContext);
639 return Futures.immediateFuture(new DefaultDOMRpcResult(output));
642 private static RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
643 final String[] splittedIdentifier = identifierDecoded.split(":");
644 if (splittedIdentifier.length != 2) {
645 LOG.debug("{} could not be split to 2 parts (module:rpc name)", identifierDecoded);
646 throw new RestconfDocumentedException(identifierDecoded + " could not be split to 2 parts "
647 + "(module:rpc name)", ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
649 for (final Module module : schemaContext.getModules()) {
650 if (module.getName().equals(splittedIdentifier[0])) {
651 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
652 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
653 return rpcDefinition;
662 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
663 boolean withDefaUsed = false;
664 String withDefa = null;
666 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
667 switch (entry.getKey()) {
668 case "with-defaults":
671 withDefa = entry.getValue().iterator().next();
673 throw new RestconfDocumentedException("With-defaults parameter can be used only once.");
677 LOG.info("Unknown key : {}.", entry.getKey());
681 boolean tagged = false;
683 if ("report-all-tagged".equals(withDefa)) {
687 if ("report-all".equals(withDefa)) {
692 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
693 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
694 NormalizedNode data = null;
695 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
696 if (mountPoint != null) {
697 data = this.broker.readConfigurationData(mountPoint, normalizedII, withDefa);
699 data = this.broker.readConfigurationData(normalizedII, withDefa);
702 throw dataMissing(identifier);
704 return new NormalizedNodeContext(iiWithData, data,
705 QueryParametersParser.parseWriterParameters(uriInfo, tagged));
709 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
710 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
711 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
712 NormalizedNode data = null;
713 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
714 if (mountPoint != null) {
715 data = this.broker.readOperationalData(mountPoint, normalizedII);
717 data = this.broker.readOperationalData(normalizedII);
720 throw dataMissing(identifier);
722 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
725 private static RestconfDocumentedException dataMissing(final String identifier) {
726 LOG.debug("Request could not be completed because the relevant data model content does not exist {}",
728 return new RestconfDocumentedException("Request could not be completed because the relevant data model content "
729 + "does not exist", ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
733 public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload,
734 final UriInfo uriInfo) {
735 boolean insertUsed = false;
736 boolean pointUsed = false;
737 String insert = null;
740 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
741 switch (entry.getKey()) {
745 insert = entry.getValue().iterator().next();
747 throw new RestconfDocumentedException("Insert parameter can be used only once.");
753 point = entry.getValue().iterator().next();
755 throw new RestconfDocumentedException("Point parameter can be used only once.");
759 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
763 if (pointUsed && !insertUsed) {
764 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
766 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
767 throw new RestconfDocumentedException(
768 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
771 requireNonNull(identifier);
773 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
775 validateInput(iiWithData.getSchemaNode(), payload);
776 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
777 validateListKeysEqualityInPayloadAndUri(payload);
779 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
780 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
783 * There is a small window where another write transaction could be
784 * updating the same data simultaneously and we get an
785 * OptimisticLockFailedException. This error is likely transient and The
786 * WriteTransaction#submit API docs state that a retry will likely
787 * succeed. So we'll try again if that scenario occurs. If it fails a
788 * third time then it probably will never succeed so we'll fail in that
791 * By retrying we're attempting to hide the internal implementation of
792 * the data store and how it handles concurrent updates from the
793 * restconf client. The client has instructed us to put the data and we
794 * should make every effort to do so without pushing optimistic lock
795 * failures back to the client and forcing them to handle it via retry
796 * (and having to document the behavior).
798 PutResult result = null;
801 if (mountPoint != null) {
803 result = this.broker.commitMountPointDataPut(mountPoint, normalizedII, payload.getData(), insert,
806 result = this.broker.commitConfigurationDataPut(this.controllerContext.getGlobalSchema(), normalizedII,
807 payload.getData(), insert, point);
811 result.getFutureOfPutData().get();
812 } catch (final InterruptedException e) {
813 LOG.debug("Update failed for {}", identifier, e);
814 throw new RestconfDocumentedException(e.getMessage(), e);
815 } catch (final ExecutionException e) {
816 final TransactionCommitFailedException failure = Throwables.getCauseAs(e,
817 TransactionCommitFailedException.class);
818 if (failure instanceof OptimisticLockFailedException) {
820 LOG.debug("Got OptimisticLockFailedException on last try - failing {}", identifier);
821 throw new RestconfDocumentedException(e.getMessage(), e, failure.getErrorList());
824 LOG.debug("Got OptimisticLockFailedException - trying again {}", identifier);
828 LOG.debug("Update failed for {}", identifier, e);
829 throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), failure);
832 return Response.status(result.getStatus()).build();
836 private static void validateTopLevelNodeName(final NormalizedNodeContext node,
837 final YangInstanceIdentifier identifier) {
839 final String payloadName = node.getData().getIdentifier().getNodeType().getLocalName();
842 if (identifier.isEmpty()) {
844 if (!node.getData().getIdentifier().getNodeType().equals(NETCONF_BASE_QNAME)) {
845 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
846 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
850 final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
851 if (!payloadName.equals(identifierName)) {
852 throw new RestconfDocumentedException(
853 "Payload name (" + payloadName + ") is different from identifier name (" + identifierName + ")",
854 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
860 * Validates whether keys in {@code payload} are equal to values of keys in
861 * {@code iiWithData} for list schema node.
863 * @throws RestconfDocumentedException
864 * if key values or key count in payload and URI isn't equal
867 private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
868 checkArgument(payload != null);
869 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
870 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
871 final SchemaNode schemaNode = iiWithData.getSchemaNode();
872 final NormalizedNode data = payload.getData();
873 if (schemaNode instanceof ListSchemaNode) {
874 final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
875 if (lastPathArgument instanceof NodeIdentifierWithPredicates && data instanceof MapEntryNode) {
876 final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument).asMap();
877 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
883 public static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final MapEntryNode payload,
884 final List<QName> keyDefinitions) {
886 final Map<QName, Object> mutableCopyUriKeyValues = new HashMap<>(uriKeyValues);
887 for (final QName keyDefinition : keyDefinitions) {
888 final Object uriKeyValue = RestconfDocumentedException.throwIfNull(
889 // should be caught during parsing URI to InstanceIdentifier
890 mutableCopyUriKeyValues.remove(keyDefinition), ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
891 "Missing key %s in URI.", keyDefinition);
893 final Object dataKeyValue = payload.getIdentifier().getValue(keyDefinition);
895 if (!Objects.deepEquals(uriKeyValue, dataKeyValue)) {
896 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName()
897 + "' specified in the URI doesn't match the value '" + dataKeyValue
898 + "' specified in the message body. ";
899 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
905 public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload,
906 final UriInfo uriInfo) {
907 return createConfigurationData(payload, uriInfo);
911 public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
912 if (payload == null) {
913 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
915 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
916 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
917 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
919 boolean insertUsed = false;
920 boolean pointUsed = false;
921 String insert = null;
924 if (uriInfo != null) {
925 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
926 switch (entry.getKey()) {
930 insert = entry.getValue().iterator().next();
932 throw new RestconfDocumentedException("Insert parameter can be used only once.");
938 point = entry.getValue().iterator().next();
940 throw new RestconfDocumentedException("Point parameter can be used only once.");
944 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
949 if (pointUsed && !insertUsed) {
950 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
952 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
953 throw new RestconfDocumentedException(
954 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
957 FluentFuture<? extends CommitInfo> future;
958 if (mountPoint != null) {
959 future = this.broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData(), insert,
962 future = this.broker.commitConfigurationDataPost(this.controllerContext.getGlobalSchema(), normalizedII,
963 payload.getData(), insert, point);
968 } catch (final InterruptedException e) {
969 LOG.info("Error creating data {}", uriInfo != null ? uriInfo.getPath() : "", e);
970 throw new RestconfDocumentedException(e.getMessage(), e);
971 } catch (final ExecutionException e) {
972 LOG.info("Error creating data {}", uriInfo != null ? uriInfo.getPath() : "", e);
973 throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), Throwables.getCauseAs(e,
974 TransactionCommitFailedException.class));
977 LOG.trace("Successfuly created data.");
979 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
980 // FIXME: Provide path to result.
981 final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
982 if (location != null) {
983 responseBuilder.location(location);
985 return responseBuilder.build();
988 @SuppressWarnings("checkstyle:IllegalCatch")
989 private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint,
990 final YangInstanceIdentifier normalizedII) {
991 if (uriInfo == null) {
992 // This is null if invoked internally
996 final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
997 uriBuilder.path("config");
999 uriBuilder.path(this.controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
1000 } catch (final Exception e) {
1001 LOG.info("Location for instance identifier {} was not created", normalizedII, e);
1004 return uriBuilder.build();
1008 public Response deleteConfigurationData(final String identifier) {
1009 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
1010 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
1011 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
1013 final FluentFuture<? extends CommitInfo> future;
1014 if (mountPoint != null) {
1015 future = this.broker.commitConfigurationDataDelete(mountPoint, normalizedII);
1017 future = this.broker.commitConfigurationDataDelete(normalizedII);
1022 } catch (final InterruptedException e) {
1023 throw new RestconfDocumentedException(e.getMessage(), e);
1024 } catch (final ExecutionException e) {
1025 final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
1026 Predicates.instanceOf(ModifiedNodeDoesNotExistException.class)).toJavaUtil();
1027 if (searchedException.isPresent()) {
1028 throw new RestconfDocumentedException("Data specified for delete doesn't exist.", ErrorType.APPLICATION,
1029 ErrorTag.DATA_MISSING, e);
1032 throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), Throwables.getCauseAs(e,
1033 TransactionCommitFailedException.class));
1036 return Response.status(Status.OK).build();
1040 * Subscribes to some path in schema context (stream) to listen on changes
1044 * Additional parameters for subscribing to stream are loaded via rpc input
1047 * <li>datastore - default CONFIGURATION (other values of
1048 * {@link LogicalDatastoreType} enum type)</li>
1049 * <li>scope - default BASE (other values of {@link Scope})</li>
1053 public NormalizedNodeContext subscribeToStream(final String identifier, final UriInfo uriInfo) {
1054 boolean startTimeUsed = false;
1055 boolean stopTimeUsed = false;
1056 Instant start = Instant.now();
1057 Instant stop = null;
1058 boolean filterUsed = false;
1059 String filter = null;
1060 boolean leafNodesOnlyUsed = false;
1061 boolean leafNodesOnly = false;
1062 boolean skipNotificationDataUsed = false;
1063 boolean skipNotificationData = false;
1065 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
1066 switch (entry.getKey()) {
1068 if (!startTimeUsed) {
1069 startTimeUsed = true;
1070 start = parseDateFromQueryParam(entry);
1072 throw new RestconfDocumentedException("Start-time parameter can be used only once.");
1076 if (!stopTimeUsed) {
1077 stopTimeUsed = true;
1078 stop = parseDateFromQueryParam(entry);
1080 throw new RestconfDocumentedException("Stop-time parameter can be used only once.");
1086 filter = entry.getValue().iterator().next();
1088 throw new RestconfDocumentedException("Filter parameter can be used only once.");
1091 case "odl-leaf-nodes-only":
1092 if (!leafNodesOnlyUsed) {
1093 leafNodesOnlyUsed = true;
1094 leafNodesOnly = Boolean.parseBoolean(entry.getValue().iterator().next());
1096 throw new RestconfDocumentedException("Odl-leaf-nodes-only parameter can be used only once.");
1099 case "odl-skip-notification-data":
1100 if (!skipNotificationDataUsed) {
1101 skipNotificationDataUsed = true;
1102 skipNotificationData = Boolean.parseBoolean(entry.getValue().iterator().next());
1104 throw new RestconfDocumentedException(
1105 "Odl-skip-notification-data parameter can be used only once.");
1109 throw new RestconfDocumentedException("Bad parameter used with notifications: " + entry.getKey());
1112 if (!startTimeUsed && stopTimeUsed) {
1113 throw new RestconfDocumentedException("Stop-time parameter has to be used with start-time parameter.");
1115 URI response = null;
1116 if (identifier.contains(DATA_SUBSCR)) {
1117 response = dataSubs(identifier, uriInfo, start, stop, filter, leafNodesOnly, skipNotificationData);
1118 } else if (identifier.contains(NOTIFICATION_STREAM)) {
1119 response = notifStream(identifier, uriInfo, start, stop, filter);
1122 if (response != null) {
1123 // prepare node with value of location
1124 final InstanceIdentifierContext<?> iid = prepareIIDSubsStreamOutput();
1125 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> builder =
1126 ImmutableLeafNodeBuilder.create().withValue(response.toString());
1127 builder.withNodeIdentifier(
1128 NodeIdentifier.create(QName.create("subscribe:to:notification", "2016-10-28", "location")));
1130 // prepare new header with location
1131 final Map<String, Object> headers = new HashMap<>();
1132 headers.put("Location", response);
1134 return new NormalizedNodeContext(iid, builder.build(), headers);
1137 final String msg = "Bad type of notification of sal-remote";
1139 throw new RestconfDocumentedException(msg);
1142 private static Instant parseDateFromQueryParam(final Entry<String, List<String>> entry) {
1143 final DateAndTime event = new DateAndTime(entry.getValue().iterator().next());
1144 final String value = event.getValue();
1145 final TemporalAccessor p;
1147 p = FORMATTER.parse(value);
1148 } catch (final DateTimeParseException e) {
1149 throw new RestconfDocumentedException("Cannot parse of value in date: " + value, e);
1151 return Instant.from(p);
1155 * Prepare instance identifier.
1157 * @return {@link InstanceIdentifierContext} of location leaf for
1160 private InstanceIdentifierContext<?> prepareIIDSubsStreamOutput() {
1161 final QName qnameBase = QName.create("subscribe:to:notification", "2016-10-28", "notifi");
1162 final EffectiveModelContext schemaCtx = controllerContext.getGlobalSchema();
1163 final DataSchemaNode location = ((ContainerSchemaNode) schemaCtx
1164 .findModule(qnameBase.getModule()).orElse(null)
1165 .getDataChildByName(qnameBase)).getDataChildByName(QName.create(qnameBase, "location"));
1166 final List<PathArgument> path = new ArrayList<>();
1167 path.add(NodeIdentifier.create(qnameBase));
1168 path.add(NodeIdentifier.create(QName.create(qnameBase, "location")));
1170 return new InstanceIdentifierContext<SchemaNode>(YangInstanceIdentifier.create(path), location, null,
1175 * Register notification listener by stream name.
1182 * stop-time of getting notification
1184 * start-time of getting notification
1186 * indicate which subset of all possible events are of interest
1187 * @return {@link URI} of location
1189 private URI notifStream(final String identifier, final UriInfo uriInfo, final Instant start,
1190 final Instant stop, final String filter) {
1191 final String streamName = Notificator.createStreamNameFromUri(identifier);
1192 if (Strings.isNullOrEmpty(streamName)) {
1193 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1195 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
1196 if (listeners == null || listeners.isEmpty()) {
1197 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1198 ErrorTag.UNKNOWN_ELEMENT);
1201 for (final NotificationListenerAdapter listener : listeners) {
1202 this.broker.registerToListenNotification(listener);
1203 listener.setQueryParams(start, Optional.ofNullable(stop), Optional.ofNullable(filter), false, false);
1206 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1208 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance(NOTIFICATION_PORT);
1209 final int notificationPort = webSocketServerInstance.getPort();
1212 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme(getWsScheme(uriInfo));
1214 return uriToWebsocketServerBuilder.replacePath(streamName).build();
1217 private static String getWsScheme(final UriInfo uriInfo) {
1218 URI uri = uriInfo.getAbsolutePath();
1222 String subscriptionScheme = uri.getScheme().toLowerCase(Locale.ROOT);
1223 return subscriptionScheme.equals("https") ? "wss" : "ws";
1227 * Register data change listener by stream name.
1234 * start-time of getting notification
1236 * stop-time of getting notification
1238 * indicate which subset of all possible events are of interest
1239 * @return {@link URI} of location
1241 private URI dataSubs(final String identifier, final UriInfo uriInfo, final Instant start, final Instant stop,
1242 final String filter, final boolean leafNodesOnly, final boolean skipNotificationData) {
1243 final String streamName = Notificator.createStreamNameFromUri(identifier);
1244 if (Strings.isNullOrEmpty(streamName)) {
1245 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1248 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1249 if (listener == null) {
1250 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1251 ErrorTag.UNKNOWN_ELEMENT);
1253 listener.setQueryParams(start, Optional.ofNullable(stop), Optional.ofNullable(filter), leafNodesOnly,
1254 skipNotificationData);
1256 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1257 final LogicalDatastoreType datastore =
1258 parserURIEnumParameter(LogicalDatastoreType.class, paramToValues.get(DATASTORE_PARAM_NAME));
1259 if (datastore == null) {
1260 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1261 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1263 final Scope scope = parserURIEnumParameter(Scope.class, paramToValues.get(SCOPE_PARAM_NAME));
1264 if (scope == null) {
1265 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1266 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1269 this.broker.registerToListenDataChanges(datastore, scope, listener);
1271 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1273 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance(NOTIFICATION_PORT);
1274 final int notificationPort = webSocketServerInstance.getPort();
1276 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme(getWsScheme(uriInfo));
1278 return uriToWebsocketServerBuilder.replacePath(streamName).build();
1281 @SuppressWarnings("checkstyle:IllegalCatch")
1283 public PatchStatusContext patchConfigurationData(final String identifier, final PatchContext context,
1284 final UriInfo uriInfo) {
1285 if (context == null) {
1286 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1290 return this.broker.patchConfigurationDataWithinTransaction(context);
1291 } catch (final Exception e) {
1292 LOG.debug("Patch transaction failed", e);
1293 throw new RestconfDocumentedException(e.getMessage(), e);
1297 @SuppressWarnings("checkstyle:IllegalCatch")
1299 public PatchStatusContext patchConfigurationData(final PatchContext context, @Context final UriInfo uriInfo) {
1300 if (context == null) {
1301 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1305 return this.broker.patchConfigurationDataWithinTransaction(context);
1306 } catch (final Exception e) {
1307 LOG.debug("Patch transaction failed", e);
1308 throw new RestconfDocumentedException(e.getMessage(), e);
1313 * Load parameter for subscribing to stream from input composite node.
1317 * @return enum object if its string value is equal to {@code paramName}. In
1320 private static <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1321 final String paramName) {
1322 final Optional<DataContainerChild> optAugNode = value.findChildByArg(SAL_REMOTE_AUG_IDENTIFIER);
1323 if (optAugNode.isEmpty()) {
1326 final DataContainerChild augNode = optAugNode.get();
1327 if (!(augNode instanceof AugmentationNode)) {
1330 final Optional<DataContainerChild> enumNode = ((AugmentationNode) augNode).findChildByArg(
1331 new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1332 if (enumNode.isEmpty()) {
1335 final Object rawValue = enumNode.get().body();
1336 if (!(rawValue instanceof String)) {
1340 return resolveAsEnum(classDescriptor, (String) rawValue);
1344 * Checks whether {@code value} is one of the string representation of
1345 * enumeration {@code classDescriptor}.
1347 * @return enum object if string value of {@code classDescriptor}
1348 * enumeration is equal to {@code value}. Other cases null.
1350 private static <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1351 if (Strings.isNullOrEmpty(value)) {
1354 return resolveAsEnum(classDescriptor, value);
1357 private static <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1358 final T[] enumConstants = classDescriptor.getEnumConstants();
1359 if (enumConstants != null) {
1360 for (final T enm : classDescriptor.getEnumConstants()) {
1361 if (((Enum<?>) enm).name().equals(value)) {
1369 private static Map<String, String> resolveValuesFromUri(final String uri) {
1370 final Map<String, String> result = new HashMap<>();
1371 final String[] tokens = uri.split("/");
1372 for (int i = 1; i < tokens.length; i++) {
1373 final String[] parameterTokens = tokens[i].split("=");
1374 if (parameterTokens.length == 2) {
1375 result.put(parameterTokens[0], parameterTokens[1]);
1381 private MapNode makeModuleMapNode(final Collection<? extends Module> modules) {
1382 requireNonNull(modules);
1383 final Module restconfModule = getRestconfModule();
1384 final DataSchemaNode moduleSchemaNode = this.controllerContext
1385 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1386 checkState(moduleSchemaNode instanceof ListSchemaNode);
1388 final CollectionNodeBuilder<MapEntryNode, SystemMapNode> listModuleBuilder =
1389 SchemaAwareBuilders.mapBuilder((ListSchemaNode) moduleSchemaNode);
1391 for (final Module module : modules) {
1392 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1394 return listModuleBuilder.build();
1397 private static MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1398 checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1399 "moduleSchemaNode has to be of type ListSchemaNode");
1400 final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1401 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues =
1402 SchemaAwareBuilders.mapEntryBuilder(listModuleSchemaNode);
1404 List<DataSchemaNode> instanceDataChildrenByName =
1405 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "name");
1406 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1407 checkState(nameSchemaNode instanceof LeafSchemaNode);
1408 moduleNodeValues.withChild(
1409 SchemaAwareBuilders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName()).build());
1411 final QNameModule qNameModule = module.getQNameModule();
1413 instanceDataChildrenByName =
1414 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "revision");
1415 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1416 checkState(revisionSchemaNode instanceof LeafSchemaNode);
1417 final Optional<Revision> revision = qNameModule.getRevision();
1418 moduleNodeValues.withChild(SchemaAwareBuilders.leafBuilder((LeafSchemaNode) revisionSchemaNode)
1419 .withValue(revision.map(Revision::toString).orElse("")).build());
1421 instanceDataChildrenByName =
1422 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "namespace");
1423 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1424 checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1425 moduleNodeValues.withChild(SchemaAwareBuilders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1426 .withValue(qNameModule.getNamespace().toString()).build());
1428 instanceDataChildrenByName =
1429 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "feature");
1430 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1431 checkState(featureSchemaNode instanceof LeafListSchemaNode);
1432 final ListNodeBuilder<Object, SystemLeafSetNode<Object>> featuresBuilder =
1433 SchemaAwareBuilders.leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1434 for (final FeatureDefinition feature : module.getFeatures()) {
1435 featuresBuilder.withChild(SchemaAwareBuilders.leafSetEntryBuilder((LeafListSchemaNode) featureSchemaNode)
1436 .withValue(feature.getQName().getLocalName()).build());
1438 moduleNodeValues.withChild(featuresBuilder.build());
1440 return moduleNodeValues.build();
1443 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1444 checkArgument(streamSchemaNode instanceof ListSchemaNode,
1445 "streamSchemaNode has to be of type ListSchemaNode");
1446 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1447 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues =
1448 SchemaAwareBuilders.mapEntryBuilder(listStreamSchemaNode);
1450 List<DataSchemaNode> instanceDataChildrenByName =
1451 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "name");
1452 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1453 checkState(nameSchemaNode instanceof LeafSchemaNode);
1454 streamNodeValues.withChild(
1455 SchemaAwareBuilders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName).build());
1457 instanceDataChildrenByName =
1458 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "description");
1459 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1460 checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1461 streamNodeValues.withChild(SchemaAwareBuilders.leafBuilder((LeafSchemaNode) nameSchemaNode)
1462 .withValue("DESCRIPTION_PLACEHOLDER")
1465 instanceDataChildrenByName =
1466 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-support");
1467 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1468 checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1469 streamNodeValues.withChild(SchemaAwareBuilders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1470 .withValue(Boolean.TRUE).build());
1472 instanceDataChildrenByName =
1473 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-log-creation-time");
1474 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1475 checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1476 streamNodeValues.withChild(
1477 SchemaAwareBuilders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode).withValue("").build());
1479 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "events");
1480 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1481 checkState(eventsSchemaNode instanceof LeafSchemaNode);
1482 streamNodeValues.withChild(
1483 SchemaAwareBuilders.leafBuilder((LeafSchemaNode) eventsSchemaNode).withValue(Empty.getInstance()).build());
1485 return streamNodeValues.build();
1489 * Prepare stream for notification.
1492 * contains list of qnames of notifications
1493 * @return - checked future object
1495 private ListenableFuture<DOMRpcResult> invokeSalRemoteRpcNotifiStrRPC(final NormalizedNodeContext payload) {
1496 final ContainerNode data = (ContainerNode) payload.getData();
1497 LeafSetNode leafSet = null;
1498 String outputType = "XML";
1499 for (final DataContainerChild dataChild : data.body()) {
1500 if (dataChild instanceof LeafSetNode) {
1501 leafSet = (LeafSetNode) dataChild;
1502 } else if (dataChild instanceof AugmentationNode) {
1503 outputType = (String) ((AugmentationNode) dataChild).body().iterator().next().body();
1507 final Collection<LeafSetEntryNode<?>> entryNodes = leafSet.body();
1508 final List<SchemaPath> paths = new ArrayList<>();
1509 String streamName = CREATE_NOTIFICATION_STREAM + "/";
1511 StringBuilder streamNameBuilder = new StringBuilder(streamName);
1512 final Iterator<LeafSetEntryNode<?>> iterator = entryNodes.iterator();
1513 while (iterator.hasNext()) {
1514 final QName valueQName = QName.create((String) iterator.next().body());
1515 final XMLNamespace namespace = valueQName.getModule().getNamespace();
1516 final Module module = controllerContext.findModuleByNamespace(namespace);
1517 checkNotNull(module, "Module for namespace %s does not exist", namespace);
1518 NotificationDefinition notifiDef = null;
1519 for (final NotificationDefinition notification : module.getNotifications()) {
1520 if (notification.getQName().equals(valueQName)) {
1521 notifiDef = notification;
1525 final String moduleName = module.getName();
1526 checkNotNull(notifiDef, "Notification %s does not exist in module %s", valueQName, moduleName);
1527 paths.add(notifiDef.getPath());
1528 streamNameBuilder.append(moduleName).append(':').append(valueQName.getLocalName());
1529 if (iterator.hasNext()) {
1530 streamNameBuilder.append(',');
1534 streamName = streamNameBuilder.toString();
1536 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
1537 final QName outputQname = QName.create(rpcQName, "output");
1538 final QName streamNameQname = QName.create(rpcQName, "notification-stream-identifier");
1540 final ContainerNode output =
1541 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
1542 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
1544 if (!Notificator.existNotificationListenerFor(streamName)) {
1545 Notificator.createNotificationListener(paths, streamName, outputType, controllerContext);
1548 return Futures.immediateFuture(new DefaultDOMRpcResult(output));
1551 private static EffectiveModelContext modelContext(final DOMMountPoint mountPoint) {
1552 return mountPoint.getService(DOMSchemaService.class)
1553 .flatMap(svc -> Optional.ofNullable(svc.getGlobalContext()))