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.DataChangeScope;
80 import org.opendaylight.restconf.common.util.OperationsResourceUtils;
81 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
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 DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
147 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
149 private static final XMLNamespace NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT =
150 XMLNamespace.of("urn:sal:restconf:event:subscription");
152 private static final String DATASTORE_PARAM_NAME = "datastore";
154 private static final String SCOPE_PARAM_NAME = "scope";
156 private static final String OUTPUT_TYPE_PARAM_NAME = "notification-output-type";
158 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
160 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
162 private static final QName NETCONF_BASE_QNAME = QName.create(QNameModule.create(XMLNamespace.of(NETCONF_BASE)),
163 NETCONF_BASE_PAYLOAD_NAME).intern();
165 private static final QNameModule SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
166 Revision.of("2014-07-08"));
168 private static final AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER =
169 new AugmentationIdentifier(ImmutableSet.of(
170 QName.create(SAL_REMOTE_AUGMENT, "scope"), QName.create(SAL_REMOTE_AUGMENT, "datastore"),
171 QName.create(SAL_REMOTE_AUGMENT, "notification-output-type")));
173 public static final CharSequence DATA_SUBSCR = "data-change-event-subscription";
174 private static final CharSequence CREATE_DATA_SUBSCR = "create-" + DATA_SUBSCR;
176 public static final CharSequence NOTIFICATION_STREAM = "notification-stream";
177 private static final CharSequence CREATE_NOTIFICATION_STREAM = "create-" + NOTIFICATION_STREAM;
179 private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
180 .appendValue(ChronoField.YEAR, 4).appendLiteral('-')
181 .appendValue(ChronoField.MONTH_OF_YEAR, 2).appendLiteral('-')
182 .appendValue(ChronoField.DAY_OF_MONTH, 2).appendLiteral('T')
183 .appendValue(ChronoField.HOUR_OF_DAY, 2).appendLiteral(':')
184 .appendValue(ChronoField.MINUTE_OF_HOUR, 2).appendLiteral(':')
185 .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
186 .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
187 .appendOffset("+HH:MM", "Z").toFormatter();
189 private final BrokerFacade broker;
191 private final ControllerContext controllerContext;
194 public RestconfImpl(final BrokerFacade broker, final ControllerContext controllerContext) {
195 this.broker = broker;
196 this.controllerContext = controllerContext;
202 * @deprecated Just use {@link #RestconfImpl(BrokerFacade, ControllerContext)} constructor instead.
205 public static RestconfImpl newInstance(final BrokerFacade broker, final ControllerContext controllerContext) {
206 return new RestconfImpl(broker, controllerContext);
211 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
212 final MapNode allModuleMap = makeModuleMapNode(controllerContext.getAllModules());
214 final EffectiveModelContext schemaContext = this.controllerContext.getGlobalSchema();
216 final Module restconfModule = getRestconfModule();
217 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
218 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
219 checkState(modulesSchemaNode instanceof ContainerSchemaNode);
221 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
222 SchemaAwareBuilders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
223 moduleContainerBuilder.withChild(allModuleMap);
225 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode, null, schemaContext),
226 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
230 * Valid only for mount point.
234 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
235 if (!identifier.contains(ControllerContext.MOUNT)) {
236 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
237 + " URI has to end with " + ControllerContext.MOUNT;
238 LOG.debug("{} for {}", errMsg, identifier);
239 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
242 final InstanceIdentifierContext<?> mountPointIdentifier =
243 this.controllerContext.toMountPointIdentifier(identifier);
244 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
245 final MapNode mountPointModulesMap = makeModuleMapNode(controllerContext.getAllModules(mountPoint));
247 final Module restconfModule = getRestconfModule();
248 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
249 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
250 checkState(modulesSchemaNode instanceof ContainerSchemaNode);
252 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
253 SchemaAwareBuilders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
254 moduleContainerBuilder.withChild(mountPointModulesMap);
256 return new NormalizedNodeContext(
257 new InstanceIdentifierContext<>(null, modulesSchemaNode, mountPoint,
258 this.controllerContext.getGlobalSchema()),
259 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
264 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
265 final Entry<String, Revision> nameRev = getModuleNameAndRevision(requireNonNull(identifier));
266 Module module = null;
267 DOMMountPoint mountPoint = null;
268 final EffectiveModelContext schemaContext;
269 if (identifier.contains(ControllerContext.MOUNT)) {
270 final InstanceIdentifierContext<?> mountPointIdentifier =
271 this.controllerContext.toMountPointIdentifier(identifier);
272 mountPoint = mountPointIdentifier.getMountPoint();
273 module = this.controllerContext.findModuleByNameAndRevision(mountPoint, nameRev.getKey(),
275 schemaContext = modelContext(mountPoint);
277 module = this.controllerContext.findModuleByNameAndRevision(nameRev.getKey(), nameRev.getValue());
278 schemaContext = this.controllerContext.getGlobalSchema();
281 if (module == null) {
282 LOG.debug("Module with name '{}' and revision '{}' was not found.", nameRev.getKey(), nameRev.getValue());
283 throw new RestconfDocumentedException("Module with name '" + nameRev.getKey() + "' and revision '"
284 + nameRev.getValue() + "' was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
287 final Module restconfModule = getRestconfModule();
288 final Set<Module> modules = Collections.singleton(module);
289 final MapNode moduleMap = makeModuleMapNode(modules);
291 final DataSchemaNode moduleSchemaNode = this.controllerContext
292 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
293 checkState(moduleSchemaNode instanceof ListSchemaNode);
295 return new NormalizedNodeContext(
296 new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint, schemaContext), moduleMap,
297 QueryParametersParser.parseWriterParameters(uriInfo));
302 public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
303 final EffectiveModelContext schemaContext = this.controllerContext.getGlobalSchema();
304 final Set<String> availableStreams = Notificator.getStreamNames();
305 final Module restconfModule = getRestconfModule();
306 final DataSchemaNode streamSchemaNode = this.controllerContext
307 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
308 checkState(streamSchemaNode instanceof ListSchemaNode);
310 final CollectionNodeBuilder<MapEntryNode, SystemMapNode> listStreamsBuilder =
311 SchemaAwareBuilders.mapBuilder((ListSchemaNode) streamSchemaNode);
313 for (final String streamName : availableStreams) {
314 listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
317 final DataSchemaNode streamsContainerSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
318 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
319 checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
321 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
322 SchemaAwareBuilders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
323 streamsContainerBuilder.withChild(listStreamsBuilder.build());
325 return new NormalizedNodeContext(
326 new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null, schemaContext),
327 streamsContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
332 public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
333 return OperationsResourceUtils.contextForModelContext(controllerContext.getGlobalSchema(), null);
338 public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
339 if (!identifier.contains(ControllerContext.MOUNT)) {
340 final String errMsg = "URI has bad format. If operations behind mount point should be showed, URI has to "
341 + " end with " + ControllerContext.MOUNT;
342 LOG.debug("{} for {}", errMsg, identifier);
343 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
346 final InstanceIdentifierContext<?> mountPointIdentifier =
347 this.controllerContext.toMountPointIdentifier(identifier);
348 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
349 return OperationsResourceUtils.contextForModelContext(modelContext(mountPoint), mountPoint);
352 private Module getRestconfModule() {
353 final Module restconfModule = this.controllerContext.getRestconfModule();
354 if (restconfModule == null) {
355 LOG.debug("ietf-restconf module was not found.");
356 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
357 ErrorTag.OPERATION_NOT_SUPPORTED);
360 return restconfModule;
363 private static Entry<String, Revision> getModuleNameAndRevision(final String identifier) {
364 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
365 String moduleNameAndRevision = "";
366 if (mountIndex >= 0) {
367 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
369 moduleNameAndRevision = identifier;
372 final Splitter splitter = Splitter.on('/').omitEmptyStrings();
373 final List<String> pathArgs = splitter.splitToList(moduleNameAndRevision);
374 if (pathArgs.size() < 2) {
375 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' {}", identifier);
376 throw new RestconfDocumentedException(
377 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
378 ErrorTag.INVALID_VALUE);
382 return new SimpleImmutableEntry<>(pathArgs.get(0), Revision.of(pathArgs.get(1)));
383 } catch (final DateTimeParseException e) {
384 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' {}", identifier);
385 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
386 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
391 public Object getRoot() {
396 public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload,
397 final UriInfo uriInfo) {
398 if (payload == null) {
399 // no payload specified, reroute this to no payload invokeRpc implementation
400 return invokeRpc(identifier, uriInfo);
403 final SchemaNode schema = payload.getInstanceIdentifierContext().getSchemaNode();
404 final ListenableFuture<? extends DOMRpcResult> response;
405 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
406 final NormalizedNode input = nonnullInput(schema, payload.getData());
407 final EffectiveModelContext schemaContext;
409 if (mountPoint != null) {
410 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
411 if (mountRpcServices.isEmpty()) {
412 LOG.debug("Error: Rpc service is missing.");
413 throw new RestconfDocumentedException("Rpc service is missing.");
415 schemaContext = modelContext(mountPoint);
416 response = mountRpcServices.get().invokeRpc(schema.getQName(), input);
418 final XMLNamespace namespace = schema.getQName().getNamespace();
419 if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
420 if (identifier.contains(CREATE_DATA_SUBSCR)) {
421 response = invokeSalRemoteRpcSubscribeRPC(payload);
422 } else if (identifier.contains(CREATE_NOTIFICATION_STREAM)) {
423 response = invokeSalRemoteRpcNotifiStrRPC(payload);
425 final String msg = "Not supported operation";
427 throw new RestconfDocumentedException(msg, ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED);
430 response = this.broker.invokeRpc(schema.getQName(), input);
432 schemaContext = this.controllerContext.getGlobalSchema();
435 final DOMRpcResult result = checkRpcResponse(response);
437 RpcDefinition resultNodeSchema = null;
438 final NormalizedNode resultData;
439 if (result != null && result.getResult() != null) {
440 resultData = result.getResult();
441 resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
446 if (resultData != null && ((ContainerNode) resultData).isEmpty()) {
447 throw new WebApplicationException(Response.Status.NO_CONTENT);
449 return new NormalizedNodeContext(
450 new InstanceIdentifierContext<>(null, resultNodeSchema, mountPoint, schemaContext),
451 resultData, QueryParametersParser.parseWriterParameters(uriInfo));
455 @SuppressFBWarnings(value = "NP_LOAD_OF_KNOWN_NULL_VALUE",
456 justification = "Looks like a false positive, see below FIXME")
457 private NormalizedNodeContext invokeRpc(final String identifier, final UriInfo uriInfo) {
458 final DOMMountPoint mountPoint;
459 final String identifierEncoded;
460 final EffectiveModelContext schemaContext;
461 if (identifier.contains(ControllerContext.MOUNT)) {
462 // mounted RPC call - look up mount instance.
463 final InstanceIdentifierContext<?> mountPointId = this.controllerContext.toMountPointIdentifier(identifier);
464 mountPoint = mountPointId.getMountPoint();
465 schemaContext = modelContext(mountPoint);
466 final int startOfRemoteRpcName =
467 identifier.lastIndexOf(ControllerContext.MOUNT) + ControllerContext.MOUNT.length() + 1;
468 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
469 identifierEncoded = remoteRpcName;
471 } else if (identifier.indexOf('/') == CHAR_NOT_FOUND) {
472 identifierEncoded = identifier;
474 schemaContext = this.controllerContext.getGlobalSchema();
476 LOG.debug("Identifier {} cannot contain slash character (/).", identifier);
477 throw new RestconfDocumentedException(String.format("Identifier %n%s%ncan\'t contain slash character (/).%n"
478 + "If slash is part of identifier name then use %%2F placeholder.", identifier), ErrorType.PROTOCOL,
479 ErrorTag.INVALID_VALUE);
482 final String identifierDecoded = ControllerContext.urlPathArgDecode(identifierEncoded);
483 final RpcDefinition rpc;
484 if (mountPoint == null) {
485 rpc = this.controllerContext.getRpcDefinition(identifierDecoded);
487 rpc = findRpc(modelContext(mountPoint), identifierDecoded);
491 LOG.debug("RPC {} does not exist.", identifierDecoded);
492 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
495 if (!rpc.getInput().getChildNodes().isEmpty()) {
496 LOG.debug("No input specified for RPC {} with an input section", rpc);
497 throw new RestconfDocumentedException("No input specified for RPC " + rpc
498 + " with an input section defined", ErrorType.RPC, ErrorTag.MISSING_ELEMENT);
501 final ContainerNode input = defaultInput(rpc.getQName());
502 final ListenableFuture<? extends DOMRpcResult> response;
503 if (mountPoint != null) {
504 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
505 if (mountRpcServices.isEmpty()) {
506 throw new RestconfDocumentedException("Rpc service is missing.");
508 response = mountRpcServices.get().invokeRpc(rpc.getQName(), input);
510 response = this.broker.invokeRpc(rpc.getQName(), input);
513 final NormalizedNode result = checkRpcResponse(response).getResult();
514 if (result != null && ((ContainerNode) result).isEmpty()) {
515 throw new WebApplicationException(Response.Status.NO_CONTENT);
518 // FIXME: in reference to the above @SupressFBWarnings: "mountPoint" reference here trips up SpotBugs, as it
519 // thinks it can only ever be null. Except it can very much be non-null. The core problem is the horrible
520 // structure of this code where we have a sh*tload of checks for mountpoint above and all over the
521 // codebase where all that difference should have been properly encapsulated.
523 // This is legacy code, so if anybody cares to do that refactor, feel free to contribute, but I am not
525 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpc, mountPoint, schemaContext), result,
526 QueryParametersParser.parseWriterParameters(uriInfo));
529 private static @NonNull NormalizedNode nonnullInput(final SchemaNode rpc, final NormalizedNode input) {
530 return input != null ? input : defaultInput(rpc.getQName());
533 private static @NonNull ContainerNode defaultInput(final QName rpcName) {
534 return ImmutableNodes.containerNode(YangConstants.operationInputQName(rpcName.getModule()));
537 @SuppressWarnings("checkstyle:avoidHidingCauseException")
538 private static DOMRpcResult checkRpcResponse(final ListenableFuture<? extends DOMRpcResult> response) {
539 if (response == null) {
543 final DOMRpcResult retValue = response.get();
544 if (retValue.getErrors().isEmpty()) {
547 LOG.debug("RpcError message {}", retValue.getErrors());
548 throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
549 } catch (final InterruptedException e) {
550 final String errMsg = "The operation was interrupted while executing and did not complete.";
551 LOG.debug("Rpc Interrupt - {}", errMsg, e);
552 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION, e);
553 } catch (final ExecutionException e) {
554 LOG.debug("Execution RpcError: ", e);
555 Throwable cause = e.getCause();
557 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
560 while (cause.getCause() != null) {
561 cause = cause.getCause();
564 if (cause instanceof IllegalArgumentException) {
565 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
566 } else if (cause instanceof DOMRpcImplementationNotAvailableException) {
567 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.APPLICATION,
568 ErrorTag.OPERATION_NOT_SUPPORTED);
570 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
572 } catch (final CancellationException e) {
573 final String errMsg = "The operation was cancelled while executing.";
574 LOG.debug("Cancel RpcExecution: {}", errMsg, e);
575 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
579 private static void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
580 if (inputSchema != null && payload.getData() == null) {
581 // expected a non null payload
582 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
583 } else if (inputSchema == null && payload.getData() != null) {
584 // did not expect any input
585 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
589 private ListenableFuture<DOMRpcResult> invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
590 final ContainerNode value = (ContainerNode) payload.getData();
591 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
592 final Optional<DataContainerChild> path =
593 value.findChildByArg(new NodeIdentifier(QName.create(rpcQName, "path")));
594 final Object pathValue = path.isPresent() ? path.get().body() : null;
596 if (!(pathValue instanceof YangInstanceIdentifier)) {
597 LOG.debug("Instance identifier {} was not normalized correctly", rpcQName);
598 throw new RestconfDocumentedException("Instance identifier was not normalized correctly",
599 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
602 final YangInstanceIdentifier pathIdentifier = (YangInstanceIdentifier) pathValue;
603 String streamName = (String) CREATE_DATA_SUBSCR;
604 NotificationOutputType outputType = null;
605 if (!pathIdentifier.isEmpty()) {
606 final String fullRestconfIdentifier =
607 DATA_SUBSCR + this.controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
609 LogicalDatastoreType datastore =
610 parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
611 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
613 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
614 scope = scope == null ? DEFAULT_SCOPE : scope;
616 outputType = parseEnumTypeParameter(value, NotificationOutputType.class, OUTPUT_TYPE_PARAM_NAME);
617 outputType = outputType == null ? NotificationOutputType.XML : outputType;
619 streamName = Notificator
620 .createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore + "/scope=" + scope);
623 if (Strings.isNullOrEmpty(streamName)) {
624 LOG.debug("Path is empty or contains value node which is not Container or List built-in type at {}",
626 throw new RestconfDocumentedException("Path is empty or contains value node which is not Container or List "
627 + "built-in type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
630 final QName outputQname = QName.create(rpcQName, "output");
631 final QName streamNameQname = QName.create(rpcQName, "stream-name");
633 final ContainerNode output =
634 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
635 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
637 if (!Notificator.existListenerFor(streamName)) {
638 Notificator.createListener(pathIdentifier, streamName, outputType, controllerContext);
641 return Futures.immediateFuture(new DefaultDOMRpcResult(output));
644 private static RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
645 final String[] splittedIdentifier = identifierDecoded.split(":");
646 if (splittedIdentifier.length != 2) {
647 LOG.debug("{} could not be split to 2 parts (module:rpc name)", identifierDecoded);
648 throw new RestconfDocumentedException(identifierDecoded + " could not be split to 2 parts "
649 + "(module:rpc name)", ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
651 for (final Module module : schemaContext.getModules()) {
652 if (module.getName().equals(splittedIdentifier[0])) {
653 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
654 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
655 return rpcDefinition;
664 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
665 boolean withDefaUsed = false;
666 String withDefa = null;
668 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
669 switch (entry.getKey()) {
670 case "with-defaults":
673 withDefa = entry.getValue().iterator().next();
675 throw new RestconfDocumentedException("With-defaults parameter can be used only once.");
679 LOG.info("Unknown key : {}.", entry.getKey());
683 boolean tagged = false;
685 if ("report-all-tagged".equals(withDefa)) {
689 if ("report-all".equals(withDefa)) {
694 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
695 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
696 NormalizedNode data = null;
697 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
698 if (mountPoint != null) {
699 data = this.broker.readConfigurationData(mountPoint, normalizedII, withDefa);
701 data = this.broker.readConfigurationData(normalizedII, withDefa);
704 throw dataMissing(identifier);
706 return new NormalizedNodeContext(iiWithData, data,
707 QueryParametersParser.parseWriterParameters(uriInfo, tagged));
711 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
712 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
713 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
714 NormalizedNode data = null;
715 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
716 if (mountPoint != null) {
717 data = this.broker.readOperationalData(mountPoint, normalizedII);
719 data = this.broker.readOperationalData(normalizedII);
722 throw dataMissing(identifier);
724 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
727 private static RestconfDocumentedException dataMissing(final String identifier) {
728 LOG.debug("Request could not be completed because the relevant data model content does not exist {}",
730 return new RestconfDocumentedException("Request could not be completed because the relevant data model content "
731 + "does not exist", ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
735 public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload,
736 final UriInfo uriInfo) {
737 boolean insertUsed = false;
738 boolean pointUsed = false;
739 String insert = null;
742 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
743 switch (entry.getKey()) {
747 insert = entry.getValue().iterator().next();
749 throw new RestconfDocumentedException("Insert parameter can be used only once.");
755 point = entry.getValue().iterator().next();
757 throw new RestconfDocumentedException("Point parameter can be used only once.");
761 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
765 if (pointUsed && !insertUsed) {
766 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
768 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
769 throw new RestconfDocumentedException(
770 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
773 requireNonNull(identifier);
775 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
777 validateInput(iiWithData.getSchemaNode(), payload);
778 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
779 validateListKeysEqualityInPayloadAndUri(payload);
781 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
782 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
785 * There is a small window where another write transaction could be
786 * updating the same data simultaneously and we get an
787 * OptimisticLockFailedException. This error is likely transient and The
788 * WriteTransaction#submit API docs state that a retry will likely
789 * succeed. So we'll try again if that scenario occurs. If it fails a
790 * third time then it probably will never succeed so we'll fail in that
793 * By retrying we're attempting to hide the internal implementation of
794 * the data store and how it handles concurrent updates from the
795 * restconf client. The client has instructed us to put the data and we
796 * should make every effort to do so without pushing optimistic lock
797 * failures back to the client and forcing them to handle it via retry
798 * (and having to document the behavior).
800 PutResult result = null;
803 if (mountPoint != null) {
805 result = this.broker.commitMountPointDataPut(mountPoint, normalizedII, payload.getData(), insert,
808 result = this.broker.commitConfigurationDataPut(this.controllerContext.getGlobalSchema(), normalizedII,
809 payload.getData(), insert, point);
813 result.getFutureOfPutData().get();
814 } catch (final InterruptedException e) {
815 LOG.debug("Update failed for {}", identifier, e);
816 throw new RestconfDocumentedException(e.getMessage(), e);
817 } catch (final ExecutionException e) {
818 final TransactionCommitFailedException failure = Throwables.getCauseAs(e,
819 TransactionCommitFailedException.class);
820 if (failure instanceof OptimisticLockFailedException) {
822 LOG.debug("Got OptimisticLockFailedException on last try - failing {}", identifier);
823 throw new RestconfDocumentedException(e.getMessage(), e, failure.getErrorList());
826 LOG.debug("Got OptimisticLockFailedException - trying again {}", identifier);
830 LOG.debug("Update failed for {}", identifier, e);
831 throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), failure);
834 return Response.status(result.getStatus()).build();
838 private static void validateTopLevelNodeName(final NormalizedNodeContext node,
839 final YangInstanceIdentifier identifier) {
841 final String payloadName = node.getData().getIdentifier().getNodeType().getLocalName();
844 if (identifier.isEmpty()) {
846 if (!node.getData().getIdentifier().getNodeType().equals(NETCONF_BASE_QNAME)) {
847 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
848 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
852 final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
853 if (!payloadName.equals(identifierName)) {
854 throw new RestconfDocumentedException(
855 "Payload name (" + payloadName + ") is different from identifier name (" + identifierName + ")",
856 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
862 * Validates whether keys in {@code payload} are equal to values of keys in
863 * {@code iiWithData} for list schema node.
865 * @throws RestconfDocumentedException
866 * if key values or key count in payload and URI isn't equal
869 private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
870 checkArgument(payload != null);
871 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
872 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
873 final SchemaNode schemaNode = iiWithData.getSchemaNode();
874 final NormalizedNode data = payload.getData();
875 if (schemaNode instanceof ListSchemaNode) {
876 final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
877 if (lastPathArgument instanceof NodeIdentifierWithPredicates && data instanceof MapEntryNode) {
878 final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument).asMap();
879 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
885 public static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final MapEntryNode payload,
886 final List<QName> keyDefinitions) {
888 final Map<QName, Object> mutableCopyUriKeyValues = new HashMap<>(uriKeyValues);
889 for (final QName keyDefinition : keyDefinitions) {
890 final Object uriKeyValue = RestconfDocumentedException.throwIfNull(
891 // should be caught during parsing URI to InstanceIdentifier
892 mutableCopyUriKeyValues.remove(keyDefinition), ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
893 "Missing key %s in URI.", keyDefinition);
895 final Object dataKeyValue = payload.getIdentifier().getValue(keyDefinition);
897 if (!Objects.deepEquals(uriKeyValue, dataKeyValue)) {
898 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName()
899 + "' specified in the URI doesn't match the value '" + dataKeyValue
900 + "' specified in the message body. ";
901 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
907 public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload,
908 final UriInfo uriInfo) {
909 return createConfigurationData(payload, uriInfo);
913 public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
914 if (payload == null) {
915 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
917 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
918 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
919 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
921 boolean insertUsed = false;
922 boolean pointUsed = false;
923 String insert = null;
926 if (uriInfo != null) {
927 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
928 switch (entry.getKey()) {
932 insert = entry.getValue().iterator().next();
934 throw new RestconfDocumentedException("Insert parameter can be used only once.");
940 point = entry.getValue().iterator().next();
942 throw new RestconfDocumentedException("Point parameter can be used only once.");
946 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
951 if (pointUsed && !insertUsed) {
952 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
954 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
955 throw new RestconfDocumentedException(
956 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
959 FluentFuture<? extends CommitInfo> future;
960 if (mountPoint != null) {
961 future = this.broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData(), insert,
964 future = this.broker.commitConfigurationDataPost(this.controllerContext.getGlobalSchema(), normalizedII,
965 payload.getData(), insert, point);
970 } catch (final InterruptedException e) {
971 LOG.info("Error creating data {}", uriInfo != null ? uriInfo.getPath() : "", e);
972 throw new RestconfDocumentedException(e.getMessage(), e);
973 } catch (final ExecutionException e) {
974 LOG.info("Error creating data {}", uriInfo != null ? uriInfo.getPath() : "", e);
975 throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), Throwables.getCauseAs(e,
976 TransactionCommitFailedException.class));
979 LOG.trace("Successfuly created data.");
981 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
982 // FIXME: Provide path to result.
983 final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
984 if (location != null) {
985 responseBuilder.location(location);
987 return responseBuilder.build();
990 @SuppressWarnings("checkstyle:IllegalCatch")
991 private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint,
992 final YangInstanceIdentifier normalizedII) {
993 if (uriInfo == null) {
994 // This is null if invoked internally
998 final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
999 uriBuilder.path("config");
1001 uriBuilder.path(this.controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
1002 } catch (final Exception e) {
1003 LOG.info("Location for instance identifier {} was not created", normalizedII, e);
1006 return uriBuilder.build();
1010 public Response deleteConfigurationData(final String identifier) {
1011 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
1012 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
1013 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
1015 final FluentFuture<? extends CommitInfo> future;
1016 if (mountPoint != null) {
1017 future = this.broker.commitConfigurationDataDelete(mountPoint, normalizedII);
1019 future = this.broker.commitConfigurationDataDelete(normalizedII);
1024 } catch (final InterruptedException e) {
1025 throw new RestconfDocumentedException(e.getMessage(), e);
1026 } catch (final ExecutionException e) {
1027 final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
1028 Predicates.instanceOf(ModifiedNodeDoesNotExistException.class)).toJavaUtil();
1029 if (searchedException.isPresent()) {
1030 throw new RestconfDocumentedException("Data specified for delete doesn't exist.", ErrorType.APPLICATION,
1031 ErrorTag.DATA_MISSING, e);
1034 throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), Throwables.getCauseAs(e,
1035 TransactionCommitFailedException.class));
1038 return Response.status(Status.OK).build();
1042 * Subscribes to some path in schema context (stream) to listen on changes
1046 * Additional parameters for subscribing to stream are loaded via rpc input
1049 * <li>datastore - default CONFIGURATION (other values of
1050 * {@link LogicalDatastoreType} enum type)</li>
1051 * <li>scope - default BASE (other values of {@link DataChangeScope})</li>
1055 public NormalizedNodeContext subscribeToStream(final String identifier, final UriInfo uriInfo) {
1056 boolean startTimeUsed = false;
1057 boolean stopTimeUsed = false;
1058 Instant start = Instant.now();
1059 Instant stop = null;
1060 boolean filterUsed = false;
1061 String filter = null;
1062 boolean leafNodesOnlyUsed = false;
1063 boolean leafNodesOnly = false;
1064 boolean skipNotificationDataUsed = false;
1065 boolean skipNotificationData = false;
1067 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
1068 switch (entry.getKey()) {
1070 if (!startTimeUsed) {
1071 startTimeUsed = true;
1072 start = parseDateFromQueryParam(entry);
1074 throw new RestconfDocumentedException("Start-time parameter can be used only once.");
1078 if (!stopTimeUsed) {
1079 stopTimeUsed = true;
1080 stop = parseDateFromQueryParam(entry);
1082 throw new RestconfDocumentedException("Stop-time parameter can be used only once.");
1088 filter = entry.getValue().iterator().next();
1090 throw new RestconfDocumentedException("Filter parameter can be used only once.");
1093 case "odl-leaf-nodes-only":
1094 if (!leafNodesOnlyUsed) {
1095 leafNodesOnlyUsed = true;
1096 leafNodesOnly = Boolean.parseBoolean(entry.getValue().iterator().next());
1098 throw new RestconfDocumentedException("Odl-leaf-nodes-only parameter can be used only once.");
1101 case "odl-skip-notification-data":
1102 if (!skipNotificationDataUsed) {
1103 skipNotificationDataUsed = true;
1104 skipNotificationData = Boolean.parseBoolean(entry.getValue().iterator().next());
1106 throw new RestconfDocumentedException(
1107 "Odl-skip-notification-data parameter can be used only once.");
1111 throw new RestconfDocumentedException("Bad parameter used with notifications: " + entry.getKey());
1114 if (!startTimeUsed && stopTimeUsed) {
1115 throw new RestconfDocumentedException("Stop-time parameter has to be used with start-time parameter.");
1117 URI response = null;
1118 if (identifier.contains(DATA_SUBSCR)) {
1119 response = dataSubs(identifier, uriInfo, start, stop, filter, leafNodesOnly, skipNotificationData);
1120 } else if (identifier.contains(NOTIFICATION_STREAM)) {
1121 response = notifStream(identifier, uriInfo, start, stop, filter);
1124 if (response != null) {
1125 // prepare node with value of location
1126 final InstanceIdentifierContext<?> iid = prepareIIDSubsStreamOutput();
1127 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> builder =
1128 ImmutableLeafNodeBuilder.create().withValue(response.toString());
1129 builder.withNodeIdentifier(
1130 NodeIdentifier.create(QName.create("subscribe:to:notification", "2016-10-28", "location")));
1132 // prepare new header with location
1133 final Map<String, Object> headers = new HashMap<>();
1134 headers.put("Location", response);
1136 return new NormalizedNodeContext(iid, builder.build(), headers);
1139 final String msg = "Bad type of notification of sal-remote";
1141 throw new RestconfDocumentedException(msg);
1144 private static Instant parseDateFromQueryParam(final Entry<String, List<String>> entry) {
1145 final DateAndTime event = new DateAndTime(entry.getValue().iterator().next());
1146 final String value = event.getValue();
1147 final TemporalAccessor p;
1149 p = FORMATTER.parse(value);
1150 } catch (final DateTimeParseException e) {
1151 throw new RestconfDocumentedException("Cannot parse of value in date: " + value, e);
1153 return Instant.from(p);
1157 * Prepare instance identifier.
1159 * @return {@link InstanceIdentifierContext} of location leaf for
1162 private InstanceIdentifierContext<?> prepareIIDSubsStreamOutput() {
1163 final QName qnameBase = QName.create("subscribe:to:notification", "2016-10-28", "notifi");
1164 final EffectiveModelContext schemaCtx = controllerContext.getGlobalSchema();
1165 final DataSchemaNode location = ((ContainerSchemaNode) schemaCtx
1166 .findModule(qnameBase.getModule()).orElse(null)
1167 .getDataChildByName(qnameBase)).getDataChildByName(QName.create(qnameBase, "location"));
1168 final List<PathArgument> path = new ArrayList<>();
1169 path.add(NodeIdentifier.create(qnameBase));
1170 path.add(NodeIdentifier.create(QName.create(qnameBase, "location")));
1172 return new InstanceIdentifierContext<SchemaNode>(YangInstanceIdentifier.create(path), location, null,
1177 * Register notification listener by stream name.
1184 * stop-time of getting notification
1186 * start-time of getting notification
1188 * indicate which subset of all possible events are of interest
1189 * @return {@link URI} of location
1191 private URI notifStream(final String identifier, final UriInfo uriInfo, final Instant start,
1192 final Instant stop, final String filter) {
1193 final String streamName = Notificator.createStreamNameFromUri(identifier);
1194 if (Strings.isNullOrEmpty(streamName)) {
1195 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1197 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
1198 if (listeners == null || listeners.isEmpty()) {
1199 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1200 ErrorTag.UNKNOWN_ELEMENT);
1203 for (final NotificationListenerAdapter listener : listeners) {
1204 this.broker.registerToListenNotification(listener);
1205 listener.setQueryParams(start, Optional.ofNullable(stop), Optional.ofNullable(filter), false, false);
1208 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1210 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance(NOTIFICATION_PORT);
1211 final int notificationPort = webSocketServerInstance.getPort();
1214 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme(getWsScheme(uriInfo));
1216 return uriToWebsocketServerBuilder.replacePath(streamName).build();
1219 private static String getWsScheme(final UriInfo uriInfo) {
1220 URI uri = uriInfo.getAbsolutePath();
1224 String subscriptionScheme = uri.getScheme().toLowerCase(Locale.ROOT);
1225 return subscriptionScheme.equals("https") ? "wss" : "ws";
1229 * Register data change listener by stream name.
1236 * start-time of getting notification
1238 * stop-time of getting notification
1240 * indicate which subset of all possible events are of interest
1241 * @return {@link URI} of location
1243 private URI dataSubs(final String identifier, final UriInfo uriInfo, final Instant start, final Instant stop,
1244 final String filter, final boolean leafNodesOnly, final boolean skipNotificationData) {
1245 final String streamName = Notificator.createStreamNameFromUri(identifier);
1246 if (Strings.isNullOrEmpty(streamName)) {
1247 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1250 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1251 if (listener == null) {
1252 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1253 ErrorTag.UNKNOWN_ELEMENT);
1255 listener.setQueryParams(start, Optional.ofNullable(stop), Optional.ofNullable(filter), leafNodesOnly,
1256 skipNotificationData);
1258 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1259 final LogicalDatastoreType datastore =
1260 parserURIEnumParameter(LogicalDatastoreType.class, paramToValues.get(DATASTORE_PARAM_NAME));
1261 if (datastore == null) {
1262 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1263 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1265 final DataChangeScope scope =
1266 parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
1267 if (scope == null) {
1268 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1269 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1272 this.broker.registerToListenDataChanges(datastore, scope, listener);
1274 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1276 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance(NOTIFICATION_PORT);
1277 final int notificationPort = webSocketServerInstance.getPort();
1279 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme(getWsScheme(uriInfo));
1281 return uriToWebsocketServerBuilder.replacePath(streamName).build();
1284 @SuppressWarnings("checkstyle:IllegalCatch")
1286 public PatchStatusContext patchConfigurationData(final String identifier, final PatchContext context,
1287 final UriInfo uriInfo) {
1288 if (context == null) {
1289 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1293 return this.broker.patchConfigurationDataWithinTransaction(context);
1294 } catch (final Exception e) {
1295 LOG.debug("Patch transaction failed", e);
1296 throw new RestconfDocumentedException(e.getMessage(), e);
1300 @SuppressWarnings("checkstyle:IllegalCatch")
1302 public PatchStatusContext patchConfigurationData(final PatchContext context, @Context final UriInfo uriInfo) {
1303 if (context == null) {
1304 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1308 return this.broker.patchConfigurationDataWithinTransaction(context);
1309 } catch (final Exception e) {
1310 LOG.debug("Patch transaction failed", e);
1311 throw new RestconfDocumentedException(e.getMessage(), e);
1316 * Load parameter for subscribing to stream from input composite node.
1320 * @return enum object if its string value is equal to {@code paramName}. In
1323 private static <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1324 final String paramName) {
1325 final Optional<DataContainerChild> optAugNode = value.findChildByArg(SAL_REMOTE_AUG_IDENTIFIER);
1326 if (optAugNode.isEmpty()) {
1329 final DataContainerChild augNode = optAugNode.get();
1330 if (!(augNode instanceof AugmentationNode)) {
1333 final Optional<DataContainerChild> enumNode = ((AugmentationNode) augNode).findChildByArg(
1334 new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1335 if (enumNode.isEmpty()) {
1338 final Object rawValue = enumNode.get().body();
1339 if (!(rawValue instanceof String)) {
1343 return resolveAsEnum(classDescriptor, (String) rawValue);
1347 * Checks whether {@code value} is one of the string representation of
1348 * enumeration {@code classDescriptor}.
1350 * @return enum object if string value of {@code classDescriptor}
1351 * enumeration is equal to {@code value}. Other cases null.
1353 private static <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1354 if (Strings.isNullOrEmpty(value)) {
1357 return resolveAsEnum(classDescriptor, value);
1360 private static <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1361 final T[] enumConstants = classDescriptor.getEnumConstants();
1362 if (enumConstants != null) {
1363 for (final T enm : classDescriptor.getEnumConstants()) {
1364 if (((Enum<?>) enm).name().equals(value)) {
1372 private static Map<String, String> resolveValuesFromUri(final String uri) {
1373 final Map<String, String> result = new HashMap<>();
1374 final String[] tokens = uri.split("/");
1375 for (int i = 1; i < tokens.length; i++) {
1376 final String[] parameterTokens = tokens[i].split("=");
1377 if (parameterTokens.length == 2) {
1378 result.put(parameterTokens[0], parameterTokens[1]);
1384 private MapNode makeModuleMapNode(final Collection<? extends Module> modules) {
1385 requireNonNull(modules);
1386 final Module restconfModule = getRestconfModule();
1387 final DataSchemaNode moduleSchemaNode = this.controllerContext
1388 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1389 checkState(moduleSchemaNode instanceof ListSchemaNode);
1391 final CollectionNodeBuilder<MapEntryNode, SystemMapNode> listModuleBuilder =
1392 SchemaAwareBuilders.mapBuilder((ListSchemaNode) moduleSchemaNode);
1394 for (final Module module : modules) {
1395 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1397 return listModuleBuilder.build();
1400 private static MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1401 checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1402 "moduleSchemaNode has to be of type ListSchemaNode");
1403 final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1404 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues =
1405 SchemaAwareBuilders.mapEntryBuilder(listModuleSchemaNode);
1407 List<DataSchemaNode> instanceDataChildrenByName =
1408 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "name");
1409 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1410 checkState(nameSchemaNode instanceof LeafSchemaNode);
1411 moduleNodeValues.withChild(
1412 SchemaAwareBuilders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName()).build());
1414 final QNameModule qNameModule = module.getQNameModule();
1416 instanceDataChildrenByName =
1417 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "revision");
1418 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1419 checkState(revisionSchemaNode instanceof LeafSchemaNode);
1420 final Optional<Revision> revision = qNameModule.getRevision();
1421 moduleNodeValues.withChild(SchemaAwareBuilders.leafBuilder((LeafSchemaNode) revisionSchemaNode)
1422 .withValue(revision.map(Revision::toString).orElse("")).build());
1424 instanceDataChildrenByName =
1425 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "namespace");
1426 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1427 checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1428 moduleNodeValues.withChild(SchemaAwareBuilders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1429 .withValue(qNameModule.getNamespace().toString()).build());
1431 instanceDataChildrenByName =
1432 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "feature");
1433 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1434 checkState(featureSchemaNode instanceof LeafListSchemaNode);
1435 final ListNodeBuilder<Object, SystemLeafSetNode<Object>> featuresBuilder =
1436 SchemaAwareBuilders.leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1437 for (final FeatureDefinition feature : module.getFeatures()) {
1438 featuresBuilder.withChild(SchemaAwareBuilders.leafSetEntryBuilder((LeafListSchemaNode) featureSchemaNode)
1439 .withValue(feature.getQName().getLocalName()).build());
1441 moduleNodeValues.withChild(featuresBuilder.build());
1443 return moduleNodeValues.build();
1446 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1447 checkArgument(streamSchemaNode instanceof ListSchemaNode,
1448 "streamSchemaNode has to be of type ListSchemaNode");
1449 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1450 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues =
1451 SchemaAwareBuilders.mapEntryBuilder(listStreamSchemaNode);
1453 List<DataSchemaNode> instanceDataChildrenByName =
1454 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "name");
1455 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1456 checkState(nameSchemaNode instanceof LeafSchemaNode);
1457 streamNodeValues.withChild(
1458 SchemaAwareBuilders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName).build());
1460 instanceDataChildrenByName =
1461 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "description");
1462 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1463 checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1464 streamNodeValues.withChild(SchemaAwareBuilders.leafBuilder((LeafSchemaNode) nameSchemaNode)
1465 .withValue("DESCRIPTION_PLACEHOLDER")
1468 instanceDataChildrenByName =
1469 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-support");
1470 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1471 checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1472 streamNodeValues.withChild(SchemaAwareBuilders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1473 .withValue(Boolean.TRUE).build());
1475 instanceDataChildrenByName =
1476 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-log-creation-time");
1477 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1478 checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1479 streamNodeValues.withChild(
1480 SchemaAwareBuilders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode).withValue("").build());
1482 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "events");
1483 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1484 checkState(eventsSchemaNode instanceof LeafSchemaNode);
1485 streamNodeValues.withChild(
1486 SchemaAwareBuilders.leafBuilder((LeafSchemaNode) eventsSchemaNode).withValue(Empty.getInstance()).build());
1488 return streamNodeValues.build();
1492 * Prepare stream for notification.
1495 * contains list of qnames of notifications
1496 * @return - checked future object
1498 private ListenableFuture<DOMRpcResult> invokeSalRemoteRpcNotifiStrRPC(final NormalizedNodeContext payload) {
1499 final ContainerNode data = (ContainerNode) payload.getData();
1500 LeafSetNode leafSet = null;
1501 String outputType = "XML";
1502 for (final DataContainerChild dataChild : data.body()) {
1503 if (dataChild instanceof LeafSetNode) {
1504 leafSet = (LeafSetNode) dataChild;
1505 } else if (dataChild instanceof AugmentationNode) {
1506 outputType = (String) ((AugmentationNode) dataChild).body().iterator().next().body();
1510 final Collection<LeafSetEntryNode<?>> entryNodes = leafSet.body();
1511 final List<SchemaPath> paths = new ArrayList<>();
1512 String streamName = CREATE_NOTIFICATION_STREAM + "/";
1514 StringBuilder streamNameBuilder = new StringBuilder(streamName);
1515 final Iterator<LeafSetEntryNode<?>> iterator = entryNodes.iterator();
1516 while (iterator.hasNext()) {
1517 final QName valueQName = QName.create((String) iterator.next().body());
1518 final XMLNamespace namespace = valueQName.getModule().getNamespace();
1519 final Module module = controllerContext.findModuleByNamespace(namespace);
1520 checkNotNull(module, "Module for namespace %s does not exist", namespace);
1521 NotificationDefinition notifiDef = null;
1522 for (final NotificationDefinition notification : module.getNotifications()) {
1523 if (notification.getQName().equals(valueQName)) {
1524 notifiDef = notification;
1528 final String moduleName = module.getName();
1529 checkNotNull(notifiDef, "Notification %s does not exist in module %s", valueQName, moduleName);
1530 paths.add(notifiDef.getPath());
1531 streamNameBuilder.append(moduleName).append(':').append(valueQName.getLocalName());
1532 if (iterator.hasNext()) {
1533 streamNameBuilder.append(',');
1537 streamName = streamNameBuilder.toString();
1539 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
1540 final QName outputQname = QName.create(rpcQName, "output");
1541 final QName streamNameQname = QName.create(rpcQName, "notification-stream-identifier");
1543 final ContainerNode output =
1544 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
1545 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
1547 if (!Notificator.existNotificationListenerFor(streamName)) {
1548 Notificator.createNotificationListener(paths, streamName, outputType, controllerContext);
1551 return Futures.immediateFuture(new DefaultDOMRpcResult(output));
1554 private static EffectiveModelContext modelContext(final DOMMountPoint mountPoint) {
1555 return mountPoint.getService(DOMSchemaService.class)
1556 .flatMap(svc -> Optional.ofNullable(svc.getGlobalContext()))