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
9 package org.opendaylight.netconf.sal.restconf.impl;
11 import com.google.common.annotations.VisibleForTesting;
12 import com.google.common.base.CharMatcher;
13 import com.google.common.base.Optional;
14 import com.google.common.base.Preconditions;
15 import com.google.common.base.Predicates;
16 import com.google.common.base.Splitter;
17 import com.google.common.base.Strings;
18 import com.google.common.base.Throwables;
19 import com.google.common.collect.ImmutableSet;
20 import com.google.common.collect.Iterables;
21 import com.google.common.collect.Maps;
22 import com.google.common.util.concurrent.CheckedFuture;
23 import com.google.common.util.concurrent.Futures;
25 import java.time.Instant;
26 import java.time.format.DateTimeFormatter;
27 import java.time.format.DateTimeFormatterBuilder;
28 import java.time.format.DateTimeParseException;
29 import java.time.temporal.ChronoField;
30 import java.time.temporal.TemporalAccessor;
31 import java.util.AbstractMap.SimpleImmutableEntry;
32 import java.util.ArrayList;
33 import java.util.Collection;
34 import java.util.Collections;
35 import java.util.HashMap;
36 import java.util.Iterator;
37 import java.util.List;
38 import java.util.Locale;
40 import java.util.Map.Entry;
41 import java.util.Objects;
43 import java.util.concurrent.CancellationException;
44 import java.util.concurrent.ExecutionException;
45 import javax.ws.rs.core.Context;
46 import javax.ws.rs.core.Response;
47 import javax.ws.rs.core.Response.ResponseBuilder;
48 import javax.ws.rs.core.Response.Status;
49 import javax.ws.rs.core.UriBuilder;
50 import javax.ws.rs.core.UriInfo;
51 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
52 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
53 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
54 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
55 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
56 import org.opendaylight.controller.md.sal.dom.api.DOMRpcImplementationNotAvailableException;
57 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
58 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
59 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
60 import org.opendaylight.netconf.sal.rest.api.Draft02;
61 import org.opendaylight.netconf.sal.rest.api.RestconfService;
62 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
63 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
64 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
65 import org.opendaylight.netconf.sal.streams.websockets.WebSocketServer;
66 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
67 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
68 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
69 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
70 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
71 import org.opendaylight.restconf.common.patch.PatchContext;
72 import org.opendaylight.restconf.common.patch.PatchStatusContext;
73 import org.opendaylight.restconf.common.util.DataChangeScope;
74 import org.opendaylight.restconf.common.validation.RestconfValidationUtils;
75 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
76 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
77 import org.opendaylight.yangtools.yang.common.QName;
78 import org.opendaylight.yangtools.yang.common.QNameModule;
79 import org.opendaylight.yangtools.yang.common.Revision;
80 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
81 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
82 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
83 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
84 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
85 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
86 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
87 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
88 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
89 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
90 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
91 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
92 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
93 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
94 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
95 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
96 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
97 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
98 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
99 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
100 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
101 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
102 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
103 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
104 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
105 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
106 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
107 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
108 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
109 import org.opendaylight.yangtools.yang.model.api.Module;
110 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
111 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
112 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
113 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
114 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
115 import org.opendaylight.yangtools.yang.model.util.SimpleSchemaContext;
116 import org.slf4j.Logger;
117 import org.slf4j.LoggerFactory;
119 public final class RestconfImpl implements RestconfService {
121 * Notifications are served on port 8181.
123 private static final int NOTIFICATION_PORT = 8181;
125 private static final int CHAR_NOT_FOUND = -1;
127 private static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
129 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
131 private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
133 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
135 private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
137 private static final String DATASTORE_PARAM_NAME = "datastore";
139 private static final String SCOPE_PARAM_NAME = "scope";
141 private static final String OUTPUT_TYPE_PARAM_NAME = "notification-output-type";
143 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
145 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
147 private static final QName NETCONF_BASE_QNAME = QName.create(QNameModule.create(URI.create(NETCONF_BASE)),
148 NETCONF_BASE_PAYLOAD_NAME).intern();
150 private static final QNameModule SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
151 Revision.of("2014-07-08"));
153 private static final AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER =
154 new AugmentationIdentifier(ImmutableSet.of(
155 QName.create(SAL_REMOTE_AUGMENT, "scope"), QName.create(SAL_REMOTE_AUGMENT, "datastore"),
156 QName.create(SAL_REMOTE_AUGMENT, "notification-output-type")));
158 public static final CharSequence DATA_SUBSCR = "data-change-event-subscription";
159 private static final CharSequence CREATE_DATA_SUBSCR = "create-" + DATA_SUBSCR;
161 public static final CharSequence NOTIFICATION_STREAM = "notification-stream";
162 private static final CharSequence CREATE_NOTIFICATION_STREAM = "create-" + NOTIFICATION_STREAM;
164 private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
165 .appendValue(ChronoField.YEAR, 4).appendLiteral('-')
166 .appendValue(ChronoField.MONTH_OF_YEAR, 2).appendLiteral('-')
167 .appendValue(ChronoField.DAY_OF_MONTH, 2).appendLiteral('T')
168 .appendValue(ChronoField.HOUR_OF_DAY, 2).appendLiteral(':')
169 .appendValue(ChronoField.MINUTE_OF_HOUR, 2).appendLiteral(':')
170 .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
171 .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
172 .appendOffset("+HH:MM", "Z").toFormatter();
174 private final BrokerFacade broker;
176 private final ControllerContext controllerContext;
178 private RestconfImpl(BrokerFacade broker, ControllerContext controllerContext) {
179 this.broker = broker;
180 this.controllerContext = controllerContext;
183 public static RestconfImpl newInstance(BrokerFacade broker, ControllerContext controllerContext) {
184 return new RestconfImpl(broker, controllerContext);
188 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
189 final Set<Module> allModules = this.controllerContext.getAllModules();
190 final MapNode allModuleMap = makeModuleMapNode(allModules);
192 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
194 final Module restconfModule = getRestconfModule();
195 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
196 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
197 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
199 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
200 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
201 moduleContainerBuilder.withChild(allModuleMap);
203 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode, null, schemaContext),
204 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
208 * Valid only for mount point.
211 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
212 Preconditions.checkNotNull(identifier);
213 if (!identifier.contains(ControllerContext.MOUNT)) {
214 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
215 + " URI has to end with " + ControllerContext.MOUNT;
216 LOG.debug(errMsg + " for " + identifier);
217 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
220 final InstanceIdentifierContext<?> mountPointIdentifier =
221 this.controllerContext.toMountPointIdentifier(identifier);
222 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
223 final Set<Module> modules = this.controllerContext.getAllModules(mountPoint);
224 final MapNode mountPointModulesMap = makeModuleMapNode(modules);
226 final Module restconfModule = getRestconfModule();
227 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
228 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
229 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
231 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
232 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
233 moduleContainerBuilder.withChild(mountPointModulesMap);
235 return new NormalizedNodeContext(
236 new InstanceIdentifierContext<>(null, modulesSchemaNode, mountPoint,
237 this.controllerContext.getGlobalSchema()),
238 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
242 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
243 Preconditions.checkNotNull(identifier);
244 final Entry<String, Revision> nameRev = getModuleNameAndRevision(identifier);
245 Module module = null;
246 DOMMountPoint mountPoint = null;
247 final SchemaContext schemaContext;
248 if (identifier.contains(ControllerContext.MOUNT)) {
249 final InstanceIdentifierContext<?> mountPointIdentifier =
250 this.controllerContext.toMountPointIdentifier(identifier);
251 mountPoint = mountPointIdentifier.getMountPoint();
252 module = this.controllerContext.findModuleByNameAndRevision(mountPoint, nameRev.getKey(),
254 schemaContext = mountPoint.getSchemaContext();
256 module = this.controllerContext.findModuleByNameAndRevision(nameRev.getKey(), nameRev.getValue());
257 schemaContext = this.controllerContext.getGlobalSchema();
260 if (module == null) {
261 final String errMsg = "Module with name '" + nameRev.getKey() + "' and revision '"
262 + nameRev.getValue() + "' was not found.";
264 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
267 final Module restconfModule = getRestconfModule();
268 final Set<Module> modules = Collections.singleton(module);
269 final MapNode moduleMap = makeModuleMapNode(modules);
271 final DataSchemaNode moduleSchemaNode = this.controllerContext
272 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
273 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
275 return new NormalizedNodeContext(
276 new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint, schemaContext), moduleMap,
277 QueryParametersParser.parseWriterParameters(uriInfo));
281 public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
282 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
283 final Set<String> availableStreams = Notificator.getStreamNames();
284 final Module restconfModule = getRestconfModule();
285 final DataSchemaNode streamSchemaNode = this.controllerContext
286 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
287 Preconditions.checkState(streamSchemaNode instanceof ListSchemaNode);
289 final CollectionNodeBuilder<MapEntryNode, MapNode> listStreamsBuilder =
290 Builders.mapBuilder((ListSchemaNode) streamSchemaNode);
292 for (final String streamName : availableStreams) {
293 listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
296 final DataSchemaNode streamsContainerSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
297 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
298 Preconditions.checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
300 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
301 Builders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
302 streamsContainerBuilder.withChild(listStreamsBuilder.build());
304 return new NormalizedNodeContext(
305 new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null, schemaContext),
306 streamsContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
310 public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
311 final Set<Module> allModules = this.controllerContext.getAllModules();
312 return operationsFromModulesToNormalizedContext(allModules, null);
316 public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
317 Set<Module> modules = null;
318 DOMMountPoint mountPoint = null;
319 if (identifier.contains(ControllerContext.MOUNT)) {
320 final InstanceIdentifierContext<?> mountPointIdentifier =
321 this.controllerContext.toMountPointIdentifier(identifier);
322 mountPoint = mountPointIdentifier.getMountPoint();
323 modules = this.controllerContext.getAllModules(mountPoint);
326 final String errMsg =
327 "URI has bad format. If operations behind mount point should be showed, URI has to " + "end with ";
328 LOG.debug(errMsg + ControllerContext.MOUNT + " for " + identifier);
329 throw new RestconfDocumentedException(errMsg + ControllerContext.MOUNT, ErrorType.PROTOCOL,
330 ErrorTag.INVALID_VALUE);
333 return operationsFromModulesToNormalizedContext(modules, mountPoint);
337 * Special case only for GET restconf/operations use (since moment of
338 * pre-Beryllium Yang parser and Yang model API removal). The method is
339 * creating fake schema context with fake module and fake data by use own
340 * implementations of schema nodes and module.
343 * set of modules for get RPCs from every module
345 * mount point, if in use otherwise null
346 * @return {@link NormalizedNodeContext}
348 private static NormalizedNodeContext operationsFromModulesToNormalizedContext(final Set<Module> modules,
349 final DOMMountPoint mountPoint) {
351 final Collection<Module> neededModules = new ArrayList<>(modules.size());
352 final ArrayList<LeafSchemaNode> fakeRpcSchema = new ArrayList<>();
354 for (final Module m : modules) {
355 final Set<RpcDefinition> rpcs = m.getRpcs();
356 if (!rpcs.isEmpty()) {
357 neededModules.add(m);
359 fakeRpcSchema.ensureCapacity(fakeRpcSchema.size() + rpcs.size());
360 rpcs.forEach(rpc -> fakeRpcSchema.add(new FakeLeafSchemaNode(rpc.getQName())));
364 final ContainerSchemaNode fakeCont = new FakeContainerSchemaNode(fakeRpcSchema);
365 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> containerBuilder =
366 Builders.containerBuilder(fakeCont);
368 for (final LeafSchemaNode leaf : fakeRpcSchema) {
369 containerBuilder.withChild(Builders.leafBuilder(leaf).build());
372 final Collection<Module> fakeModules = new ArrayList<>(neededModules.size() + 1);
373 neededModules.forEach(imp -> fakeModules.add(new FakeImportedModule(imp)));
374 fakeModules.add(new FakeRestconfModule(neededModules, fakeCont));
376 final SchemaContext fakeSchemaCtx = SimpleSchemaContext.forModules(ImmutableSet.copyOf(fakeModules));
377 final InstanceIdentifierContext<ContainerSchemaNode> instanceIdentifierContext =
378 new InstanceIdentifierContext<>(null, fakeCont, mountPoint, fakeSchemaCtx);
379 return new NormalizedNodeContext(instanceIdentifierContext, containerBuilder.build());
382 private Module getRestconfModule() {
383 final Module restconfModule = this.controllerContext.getRestconfModule();
384 if (restconfModule == null) {
385 LOG.debug("ietf-restconf module was not found.");
386 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
387 ErrorTag.OPERATION_NOT_SUPPORTED);
390 return restconfModule;
393 private static Entry<String, Revision> getModuleNameAndRevision(final String identifier) {
394 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
395 String moduleNameAndRevision = "";
396 if (mountIndex >= 0) {
397 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
399 moduleNameAndRevision = identifier;
402 final Splitter splitter = Splitter.on('/').omitEmptyStrings();
403 final List<String> pathArgs = splitter.splitToList(moduleNameAndRevision);
404 if (pathArgs.size() < 2) {
405 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
406 throw new RestconfDocumentedException(
407 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
408 ErrorTag.INVALID_VALUE);
412 return new SimpleImmutableEntry<>(pathArgs.get(0), Revision.of(pathArgs.get(1)));
413 } catch (final DateTimeParseException e) {
414 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
415 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
416 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
421 public Object getRoot() {
426 public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload,
427 final UriInfo uriInfo) {
428 final SchemaPath type = payload.getInstanceIdentifierContext().getSchemaNode().getPath();
429 final URI namespace = payload.getInstanceIdentifierContext().getSchemaNode().getQName().getNamespace();
430 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
431 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
432 final SchemaContext schemaContext;
434 if (mountPoint != null) {
435 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
436 if (!mountRpcServices.isPresent()) {
437 LOG.debug("Error: Rpc service is missing.");
438 throw new RestconfDocumentedException("Rpc service is missing.");
440 schemaContext = mountPoint.getSchemaContext();
441 response = mountRpcServices.get().invokeRpc(type, payload.getData());
443 if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
444 if (identifier.contains(CREATE_DATA_SUBSCR)) {
445 response = invokeSalRemoteRpcSubscribeRPC(payload);
446 } else if (identifier.contains(CREATE_NOTIFICATION_STREAM)) {
447 response = invokeSalRemoteRpcNotifiStrRPC(payload);
449 final String msg = "Not supported operation";
451 throw new RestconfDocumentedException(msg, ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED);
454 response = this.broker.invokeRpc(type, payload.getData());
456 schemaContext = this.controllerContext.getGlobalSchema();
459 final DOMRpcResult result = checkRpcResponse(response);
461 RpcDefinition resultNodeSchema = null;
462 final NormalizedNode<?, ?> resultData;
463 if (result != null && result.getResult() != null) {
464 resultData = result.getResult();
465 resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
470 return new NormalizedNodeContext(
471 new InstanceIdentifierContext<>(null, resultNodeSchema, mountPoint, schemaContext),
472 resultData, QueryParametersParser.parseWriterParameters(uriInfo));
476 public NormalizedNodeContext invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
477 if (noPayload != null && !CharMatcher.WHITESPACE.matchesAllOf(noPayload)) {
478 throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
481 String identifierEncoded = null;
482 DOMMountPoint mountPoint = null;
483 final SchemaContext schemaContext;
484 if (identifier.contains(ControllerContext.MOUNT)) {
485 // mounted RPC call - look up mount instance.
486 final InstanceIdentifierContext<?> mountPointId = this.controllerContext.toMountPointIdentifier(identifier);
487 mountPoint = mountPointId.getMountPoint();
488 schemaContext = mountPoint.getSchemaContext();
489 final int startOfRemoteRpcName =
490 identifier.lastIndexOf(ControllerContext.MOUNT) + ControllerContext.MOUNT.length() + 1;
491 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
492 identifierEncoded = remoteRpcName;
494 } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
495 final String slashErrorMsg = String.format(
496 "Identifier %n%s%ncan\'t contain slash "
497 + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.",
499 LOG.debug(slashErrorMsg);
500 throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
502 identifierEncoded = identifier;
503 schemaContext = this.controllerContext.getGlobalSchema();
506 final String identifierDecoded = this.controllerContext.urlPathArgDecode(identifierEncoded);
508 RpcDefinition rpc = null;
509 if (mountPoint == null) {
510 rpc = this.controllerContext.getRpcDefinition(identifierDecoded);
512 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
516 LOG.debug("RPC " + identifierDecoded + " does not exist.");
517 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
520 if (!rpc.getInput().getChildNodes().isEmpty()) {
521 LOG.debug("RPC " + rpc + " does not need input value.");
522 throw new RestconfDocumentedException("RPC " + rpc + " does not take any input value.",
523 ErrorType.RPC, ErrorTag.INVALID_VALUE);
526 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
527 if (mountPoint != null) {
528 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
529 if (!mountRpcServices.isPresent()) {
530 throw new RestconfDocumentedException("Rpc service is missing.");
532 response = mountRpcServices.get().invokeRpc(rpc.getPath(), null);
534 response = this.broker.invokeRpc(rpc.getPath(), null);
537 final DOMRpcResult result = checkRpcResponse(response);
539 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpc, mountPoint, schemaContext),
540 result.getResult(), QueryParametersParser.parseWriterParameters(uriInfo));
543 @SuppressWarnings("checkstyle:avoidHidingCauseException")
544 private static DOMRpcResult checkRpcResponse(final CheckedFuture<DOMRpcResult, DOMRpcException> response) {
545 if (response == null) {
549 final DOMRpcResult retValue = response.get();
550 if (retValue.getErrors().isEmpty()) {
553 LOG.debug("RpcError message", retValue.getErrors());
554 throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
555 } catch (final InterruptedException e) {
556 final String errMsg = "The operation was interrupted while executing and did not complete.";
557 LOG.debug("Rpc Interrupt - " + errMsg, e);
558 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION, e);
559 } catch (final ExecutionException e) {
560 LOG.debug("Execution RpcError: ", e);
561 Throwable cause = e.getCause();
563 while (cause.getCause() != null) {
564 cause = cause.getCause();
567 if (cause instanceof IllegalArgumentException) {
568 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL,
569 ErrorTag.INVALID_VALUE);
570 } else if (cause instanceof DOMRpcImplementationNotAvailableException) {
571 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.APPLICATION,
572 ErrorTag.OPERATION_NOT_SUPPORTED);
574 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
577 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
580 } catch (final CancellationException e) {
581 final String errMsg = "The operation was cancelled while executing.";
582 LOG.debug("Cancel RpcExecution: " + errMsg, e);
583 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
587 private static void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
588 if (inputSchema != null && payload.getData() == null) {
589 // expected a non null payload
590 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
591 } else if (inputSchema == null && payload.getData() != null) {
592 // did not expect any input
593 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
597 private CheckedFuture<DOMRpcResult, DOMRpcException>
598 invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
599 final ContainerNode value = (ContainerNode) payload.getData();
600 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
601 final java.util.Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(
602 new NodeIdentifier(QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(),
604 final Object pathValue = path.isPresent() ? path.get().getValue() : null;
606 if (!(pathValue instanceof YangInstanceIdentifier)) {
607 final String errMsg = "Instance identifier was not normalized correctly ";
608 LOG.debug(errMsg + rpcQName);
609 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
612 final YangInstanceIdentifier pathIdentifier = (YangInstanceIdentifier) pathValue;
613 String streamName = (String) CREATE_DATA_SUBSCR;
614 NotificationOutputType outputType = null;
615 if (!pathIdentifier.isEmpty()) {
616 final String fullRestconfIdentifier =
617 DATA_SUBSCR + this.controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
619 LogicalDatastoreType datastore =
620 parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
621 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
623 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
624 scope = scope == null ? DEFAULT_SCOPE : scope;
626 outputType = parseEnumTypeParameter(value, NotificationOutputType.class, OUTPUT_TYPE_PARAM_NAME);
627 outputType = outputType == null ? NotificationOutputType.XML : outputType;
629 streamName = Notificator
630 .createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore + "/scope=" + scope);
633 if (Strings.isNullOrEmpty(streamName)) {
634 final String errMsg = "Path is empty or contains value node which is not Container or List build-in type.";
635 LOG.debug(errMsg + pathIdentifier);
636 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
639 final QName outputQname = QName.create(rpcQName, "output");
640 final QName streamNameQname = QName.create(rpcQName, "stream-name");
642 final ContainerNode output =
643 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
644 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
646 if (!Notificator.existListenerFor(streamName)) {
647 Notificator.createListener(pathIdentifier, streamName, outputType, controllerContext);
650 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
652 return Futures.immediateCheckedFuture(defaultDOMRpcResult);
655 private static RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
656 final String[] splittedIdentifier = identifierDecoded.split(":");
657 if (splittedIdentifier.length != 2) {
658 final String errMsg = identifierDecoded + " couldn't be splitted to 2 parts (module:rpc name)";
660 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
662 for (final Module module : schemaContext.getModules()) {
663 if (module.getName().equals(splittedIdentifier[0])) {
664 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
665 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
666 return rpcDefinition;
675 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
676 boolean withDefaUsed = false;
677 String withDefa = null;
679 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
680 switch (entry.getKey()) {
681 case "with-defaults":
684 withDefa = entry.getValue().iterator().next();
686 throw new RestconfDocumentedException("With-defaults parameter can be used only once.");
690 LOG.info("Unknown key : {}.", entry.getKey());
694 boolean tagged = false;
696 if ("report-all-tagged".equals(withDefa)) {
700 if ("report-all".equals(withDefa)) {
705 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
706 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
707 NormalizedNode<?, ?> data = null;
708 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
709 if (mountPoint != null) {
710 data = this.broker.readConfigurationData(mountPoint, normalizedII, withDefa);
712 data = this.broker.readConfigurationData(normalizedII, withDefa);
715 final String errMsg =
716 "Request could not be completed because the relevant data model content does not exist ";
717 LOG.debug(errMsg + identifier);
718 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
720 return new NormalizedNodeContext(iiWithData, data,
721 QueryParametersParser.parseWriterParameters(uriInfo, tagged));
725 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
726 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
727 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
728 NormalizedNode<?, ?> data = null;
729 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
730 if (mountPoint != null) {
731 data = this.broker.readOperationalData(mountPoint, normalizedII);
733 data = this.broker.readOperationalData(normalizedII);
736 final String errMsg =
737 "Request could not be completed because the relevant data model content does not exist ";
738 LOG.debug(errMsg + identifier);
739 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
741 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
745 public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload,
746 final UriInfo uriInfo) {
747 boolean insertUsed = false;
748 boolean pointUsed = false;
749 String insert = null;
752 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
753 switch (entry.getKey()) {
757 insert = entry.getValue().iterator().next();
759 throw new RestconfDocumentedException("Insert parameter can be used only once.");
765 point = entry.getValue().iterator().next();
767 throw new RestconfDocumentedException("Point parameter can be used only once.");
771 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
775 if (pointUsed && !insertUsed) {
776 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
778 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
779 throw new RestconfDocumentedException(
780 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
783 Preconditions.checkNotNull(identifier);
785 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
787 validateInput(iiWithData.getSchemaNode(), payload);
788 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
789 validateListKeysEqualityInPayloadAndUri(payload);
791 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
792 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
795 * There is a small window where another write transaction could be
796 * updating the same data simultaneously and we get an
797 * OptimisticLockFailedException. This error is likely transient and The
798 * WriteTransaction#submit API docs state that a retry will likely
799 * succeed. So we'll try again if that scenario occurs. If it fails a
800 * third time then it probably will never succeed so we'll fail in that
803 * By retrying we're attempting to hide the internal implementation of
804 * the data store and how it handles concurrent updates from the
805 * restconf client. The client has instructed us to put the data and we
806 * should make every effort to do so without pushing optimistic lock
807 * failures back to the client and forcing them to handle it via retry
808 * (and having to document the behavior).
810 PutResult result = null;
813 if (mountPoint != null) {
815 result = this.broker.commitMountPointDataPut(mountPoint, normalizedII, payload.getData(), insert,
818 result = this.broker.commitConfigurationDataPut(this.controllerContext.getGlobalSchema(), normalizedII,
819 payload.getData(), insert, point);
823 result.getFutureOfPutData().checkedGet();
824 return Response.status(result.getStatus()).build();
825 } catch (final TransactionCommitFailedException e) {
826 if (e instanceof OptimisticLockFailedException) {
828 LOG.debug("Got OptimisticLockFailedException on last try - failing " + identifier);
829 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
832 LOG.debug("Got OptimisticLockFailedException - trying again " + identifier);
834 LOG.debug("Update failed for " + identifier, e);
835 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
841 private static void validateTopLevelNodeName(final NormalizedNodeContext node,
842 final YangInstanceIdentifier identifier) {
844 final String payloadName = node.getData().getNodeType().getLocalName();
847 if (identifier.isEmpty()) {
849 if (!node.getData().getNodeType().equals(NETCONF_BASE_QNAME)) {
850 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
851 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
855 final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
856 if (!payloadName.equals(identifierName)) {
857 throw new RestconfDocumentedException(
858 "Payload name (" + payloadName + ") is different from identifier name (" + identifierName + ")",
859 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
865 * Validates whether keys in {@code payload} are equal to values of keys in
866 * {@code iiWithData} for list schema node.
868 * @throws RestconfDocumentedException
869 * if key values or key count in payload and URI isn't equal
872 private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
873 Preconditions.checkArgument(payload != null);
874 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
875 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
876 final SchemaNode schemaNode = iiWithData.getSchemaNode();
877 final NormalizedNode<?, ?> data = payload.getData();
878 if (schemaNode instanceof ListSchemaNode) {
879 final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
880 if (lastPathArgument instanceof NodeIdentifierWithPredicates && data instanceof MapEntryNode) {
881 final Map<QName, Object> uriKeyValues =
882 ((NodeIdentifierWithPredicates) lastPathArgument).getKeyValues();
883 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
889 public static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final MapEntryNode payload,
890 final List<QName> keyDefinitions) {
892 final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
893 for (final QName keyDefinition : keyDefinitions) {
894 final Object uriKeyValue = mutableCopyUriKeyValues.remove(keyDefinition);
895 // should be caught during parsing URI to InstanceIdentifier
896 RestconfValidationUtils.checkDocumentedError(uriKeyValue != null, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
897 "Missing key " + keyDefinition + " in URI.");
899 final Object dataKeyValue = payload.getIdentifier().getKeyValues().get(keyDefinition);
901 if (!Objects.deepEquals(uriKeyValue, dataKeyValue)) {
902 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName()
903 + "' specified in the URI doesn't match the value '" + dataKeyValue
904 + "' specified in the message body. ";
905 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
911 public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload,
912 final UriInfo uriInfo) {
913 return createConfigurationData(payload, uriInfo);
917 public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
918 if (payload == null) {
919 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
921 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
922 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
923 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
925 boolean insertUsed = false;
926 boolean pointUsed = false;
927 String insert = null;
930 if (uriInfo != null) {
931 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
932 switch (entry.getKey()) {
936 insert = entry.getValue().iterator().next();
938 throw new RestconfDocumentedException("Insert parameter can be used only once.");
944 point = entry.getValue().iterator().next();
946 throw new RestconfDocumentedException("Point parameter can be used only once.");
950 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
955 if (pointUsed && !insertUsed) {
956 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
958 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
959 throw new RestconfDocumentedException(
960 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
963 CheckedFuture<Void, TransactionCommitFailedException> future;
964 if (mountPoint != null) {
965 future = this.broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData(), insert,
968 future = this.broker.commitConfigurationDataPost(this.controllerContext.getGlobalSchema(), normalizedII,
969 payload.getData(), insert, point);
974 } catch (final RestconfDocumentedException e) {
976 } catch (final TransactionCommitFailedException e) {
977 LOG.info("Error creating data " + (uriInfo != null ? uriInfo.getPath() : ""), e);
978 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
981 LOG.trace("Successfuly created data.");
983 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
984 // FIXME: Provide path to result.
985 final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
986 if (location != null) {
987 responseBuilder.location(location);
989 return responseBuilder.build();
992 @SuppressWarnings("checkstyle:IllegalCatch")
993 private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint,
994 final YangInstanceIdentifier normalizedII) {
995 if (uriInfo == null) {
996 // This is null if invoked internally
1000 final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
1001 uriBuilder.path("config");
1003 uriBuilder.path(this.controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
1004 } catch (final Exception e) {
1005 LOG.info("Location for instance identifier" + normalizedII + "wasn't created", e);
1008 return uriBuilder.build();
1012 public Response deleteConfigurationData(final String identifier) {
1013 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
1014 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
1015 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
1017 final CheckedFuture<Void, TransactionCommitFailedException> future;
1018 if (mountPoint != null) {
1019 future = this.broker.commitConfigurationDataDelete(mountPoint, normalizedII);
1021 future = this.broker.commitConfigurationDataDelete(normalizedII);
1025 future.checkedGet();
1026 } catch (final TransactionCommitFailedException e) {
1027 final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
1028 Predicates.instanceOf(ModifiedNodeDoesNotExistException.class));
1029 if (searchedException.isPresent()) {
1030 throw new RestconfDocumentedException("Data specified for delete doesn't exist.",
1031 ErrorType.APPLICATION, ErrorTag.DATA_MISSING, e);
1034 final String errMsg = "Error while deleting data";
1035 LOG.info(errMsg, e);
1036 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
1039 return Response.status(Status.OK).build();
1043 * Subscribes to some path in schema context (stream) to listen on changes
1047 * Additional parameters for subscribing to stream are loaded via rpc input
1050 * <li>datastore - default CONFIGURATION (other values of
1051 * {@link LogicalDatastoreType} enum type)</li>
1052 * <li>scope - default BASE (other values of {@link DataChangeScope})</li>
1056 public NormalizedNodeContext subscribeToStream(final String identifier, final UriInfo uriInfo) {
1057 boolean startTimeUsed = false;
1058 boolean stopTimeUsed = false;
1059 Instant start = Instant.now();
1060 Instant stop = null;
1061 boolean filterUsed = false;
1062 String filter = null;
1063 boolean leafNodesOnlyUsed = false;
1064 boolean leafNodesOnly = false;
1066 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
1067 switch (entry.getKey()) {
1069 if (!startTimeUsed) {
1070 startTimeUsed = true;
1071 start = parseDateFromQueryParam(entry);
1073 throw new RestconfDocumentedException("Start-time parameter can be used only once.");
1077 if (!stopTimeUsed) {
1078 stopTimeUsed = true;
1079 stop = parseDateFromQueryParam(entry);
1081 throw new RestconfDocumentedException("Stop-time parameter can be used only once.");
1087 filter = entry.getValue().iterator().next();
1089 throw new RestconfDocumentedException("Filter parameter can be used only once.");
1092 case "odl-leaf-nodes-only":
1093 if (!leafNodesOnlyUsed) {
1094 leafNodesOnlyUsed = true;
1095 leafNodesOnly = Boolean.parseBoolean(entry.getValue().iterator().next());
1097 throw new RestconfDocumentedException("Odl-leaf-nodes-only parameter can be used only once.");
1101 throw new RestconfDocumentedException("Bad parameter used with notifications: " + entry.getKey());
1104 if (!startTimeUsed && stopTimeUsed) {
1105 throw new RestconfDocumentedException("Stop-time parameter has to be used with start-time parameter.");
1107 URI response = null;
1108 if (identifier.contains(DATA_SUBSCR)) {
1109 response = dataSubs(identifier, uriInfo, start, stop, filter, leafNodesOnly);
1110 } else if (identifier.contains(NOTIFICATION_STREAM)) {
1111 response = notifStream(identifier, uriInfo, start, stop, filter);
1114 if (response != null) {
1115 // prepare node with value of location
1116 final InstanceIdentifierContext<?> iid = prepareIIDSubsStreamOutput();
1117 final NormalizedNodeAttrBuilder<NodeIdentifier, Object, LeafNode<Object>> builder =
1118 ImmutableLeafNodeBuilder.create().withValue(response.toString());
1119 builder.withNodeIdentifier(
1120 NodeIdentifier.create(QName.create("subscribe:to:notification", "2016-10-28", "location")));
1122 // prepare new header with location
1123 final Map<String, Object> headers = new HashMap<>();
1124 headers.put("Location", response);
1126 return new NormalizedNodeContext(iid, builder.build(), headers);
1129 final String msg = "Bad type of notification of sal-remote";
1131 throw new RestconfDocumentedException(msg);
1134 private static Instant parseDateFromQueryParam(final Entry<String, List<String>> entry) {
1135 final DateAndTime event = new DateAndTime(entry.getValue().iterator().next());
1136 final String value = event.getValue();
1137 final TemporalAccessor p;
1139 p = FORMATTER.parse(value);
1140 } catch (final DateTimeParseException e) {
1141 throw new RestconfDocumentedException("Cannot parse of value in date: " + value, e);
1143 return Instant.from(p);
1147 * Prepare instance identifier.
1149 * @return {@link InstanceIdentifierContext} of location leaf for
1152 private InstanceIdentifierContext<?> prepareIIDSubsStreamOutput() {
1153 final QName qnameBase = QName.create("subscribe:to:notification", "2016-10-28", "notifi");
1154 final SchemaContext schemaCtx = controllerContext.getGlobalSchema();
1155 final DataSchemaNode location = ((ContainerSchemaNode) schemaCtx
1156 .findModule(qnameBase.getModule()).orElse(null)
1157 .getDataChildByName(qnameBase)).getDataChildByName(QName.create(qnameBase, "location"));
1158 final List<PathArgument> path = new ArrayList<>();
1159 path.add(NodeIdentifier.create(qnameBase));
1160 path.add(NodeIdentifier.create(QName.create(qnameBase, "location")));
1162 return new InstanceIdentifierContext<SchemaNode>(YangInstanceIdentifier.create(path), location, null,
1167 * Register notification listener by stream name.
1174 * stop-time of getting notification
1176 * start-time of getting notification
1178 * indicate which subset of all possible events are of interest
1179 * @return {@link URI} of location
1181 private URI notifStream(final String identifier, final UriInfo uriInfo, final Instant start,
1182 final Instant stop, final String filter) {
1183 final String streamName = Notificator.createStreamNameFromUri(identifier);
1184 if (Strings.isNullOrEmpty(streamName)) {
1185 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1187 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
1188 if (listeners == null || listeners.isEmpty()) {
1189 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1190 ErrorTag.UNKNOWN_ELEMENT);
1193 for (final NotificationListenerAdapter listener : listeners) {
1194 this.broker.registerToListenNotification(listener);
1195 listener.setQueryParams(start,
1196 java.util.Optional.ofNullable(stop), java.util.Optional.ofNullable(filter), false);
1199 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1201 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance(NOTIFICATION_PORT);
1202 final int notificationPort = webSocketServerInstance.getPort();
1205 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme(getWsScheme(uriInfo));
1207 return uriToWebsocketServerBuilder.replacePath(streamName).build();
1210 private String getWsScheme(UriInfo uriInfo) {
1211 URI uri = uriInfo.getAbsolutePath();
1215 String subscriptionScheme = uri.getScheme().toLowerCase(Locale.ROOT);
1216 return subscriptionScheme.equals("https") ? "wss" : "ws";
1220 * Register data change listener by stream name.
1227 * start-time of getting notification
1229 * stop-time of getting notification
1231 * indicate which subset of all possible events are of interest
1232 * @return {@link URI} of location
1234 private URI dataSubs(final String identifier, final UriInfo uriInfo, final Instant start, final Instant stop,
1235 final String filter, final boolean leafNodesOnly) {
1236 final String streamName = Notificator.createStreamNameFromUri(identifier);
1237 if (Strings.isNullOrEmpty(streamName)) {
1238 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1241 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1242 if (listener == null) {
1243 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1244 ErrorTag.UNKNOWN_ELEMENT);
1246 listener.setQueryParams(start, java.util.Optional.ofNullable(stop),
1247 java.util.Optional.ofNullable(filter), leafNodesOnly);
1249 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1250 final LogicalDatastoreType datastore =
1251 parserURIEnumParameter(LogicalDatastoreType.class, paramToValues.get(DATASTORE_PARAM_NAME));
1252 if (datastore == null) {
1253 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1254 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1256 final DataChangeScope scope =
1257 parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
1258 if (scope == null) {
1259 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1260 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1263 this.broker.registerToListenDataChanges(datastore, scope, listener);
1265 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1267 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance(NOTIFICATION_PORT);
1268 final int notificationPort = webSocketServerInstance.getPort();
1270 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme(getWsScheme(uriInfo));
1272 return uriToWebsocketServerBuilder.replacePath(streamName).build();
1275 @SuppressWarnings("checkstyle:IllegalCatch")
1277 public PatchStatusContext patchConfigurationData(final String identifier, final PatchContext context,
1278 final UriInfo uriInfo) {
1279 if (context == null) {
1280 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1284 return this.broker.patchConfigurationDataWithinTransaction(context);
1285 } catch (final Exception e) {
1286 LOG.debug("Patch transaction failed", e);
1287 throw new RestconfDocumentedException(e.getMessage(), e);
1291 @SuppressWarnings("checkstyle:IllegalCatch")
1293 public PatchStatusContext patchConfigurationData(final PatchContext context, @Context final UriInfo uriInfo) {
1294 if (context == null) {
1295 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1299 return this.broker.patchConfigurationDataWithinTransaction(context);
1300 } catch (final Exception e) {
1301 LOG.debug("Patch transaction failed", e);
1302 throw new RestconfDocumentedException(e.getMessage(), e);
1307 * Load parameter for subscribing to stream from input composite node.
1311 * @return enum object if its string value is equal to {@code paramName}. In
1314 private static <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1315 final String paramName) {
1316 final java.util.Optional<DataContainerChild<? extends PathArgument, ?>> optAugNode = value.getChild(
1317 SAL_REMOTE_AUG_IDENTIFIER);
1318 if (!optAugNode.isPresent()) {
1321 final DataContainerChild<? extends PathArgument, ?> augNode = optAugNode.get();
1322 if (!(augNode instanceof AugmentationNode)) {
1325 final java.util.Optional<DataContainerChild<? extends PathArgument, ?>> enumNode = ((AugmentationNode) augNode)
1326 .getChild(new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1327 if (!enumNode.isPresent()) {
1330 final Object rawValue = enumNode.get().getValue();
1331 if (!(rawValue instanceof String)) {
1335 return resolveAsEnum(classDescriptor, (String) rawValue);
1339 * Checks whether {@code value} is one of the string representation of
1340 * enumeration {@code classDescriptor}.
1342 * @return enum object if string value of {@code classDescriptor}
1343 * enumeration is equal to {@code value}. Other cases null.
1345 private static <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1346 if (Strings.isNullOrEmpty(value)) {
1349 return resolveAsEnum(classDescriptor, value);
1352 private static <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1353 final T[] enumConstants = classDescriptor.getEnumConstants();
1354 if (enumConstants != null) {
1355 for (final T enm : classDescriptor.getEnumConstants()) {
1356 if (((Enum<?>) enm).name().equals(value)) {
1364 private static Map<String, String> resolveValuesFromUri(final String uri) {
1365 final Map<String, String> result = new HashMap<>();
1366 final String[] tokens = uri.split("/");
1367 for (int i = 1; i < tokens.length; i++) {
1368 final String[] parameterTokens = tokens[i].split("=");
1369 if (parameterTokens.length == 2) {
1370 result.put(parameterTokens[0], parameterTokens[1]);
1376 private MapNode makeModuleMapNode(final Set<Module> modules) {
1377 Preconditions.checkNotNull(modules);
1378 final Module restconfModule = getRestconfModule();
1379 final DataSchemaNode moduleSchemaNode = this.controllerContext
1380 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1381 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1383 final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder =
1384 Builders.mapBuilder((ListSchemaNode) moduleSchemaNode);
1386 for (final Module module : modules) {
1387 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1389 return listModuleBuilder.build();
1392 protected MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1393 Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1394 "moduleSchemaNode has to be of type ListSchemaNode");
1395 final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1396 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues =
1397 Builders.mapEntryBuilder(listModuleSchemaNode);
1399 List<DataSchemaNode> instanceDataChildrenByName =
1400 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "name");
1401 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1402 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1404 .withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName()).build());
1406 instanceDataChildrenByName =
1407 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "revision");
1408 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1409 Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1410 final java.util.Optional<Revision> revision = module.getQNameModule().getRevision();
1411 if (revision.isPresent()) {
1412 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode)
1413 .withValue(revision.get().toString()).build());
1416 instanceDataChildrenByName =
1417 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "namespace");
1418 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1419 Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1420 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1421 .withValue(module.getNamespace().toString()).build());
1423 instanceDataChildrenByName =
1424 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "feature");
1425 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1426 Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1427 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder =
1428 Builders.leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1429 for (final FeatureDefinition feature : module.getFeatures()) {
1430 featuresBuilder.withChild(Builders.leafSetEntryBuilder((LeafListSchemaNode) featureSchemaNode)
1431 .withValue(feature.getQName().getLocalName()).build());
1433 moduleNodeValues.withChild(featuresBuilder.build());
1435 return moduleNodeValues.build();
1438 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1439 Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1440 "streamSchemaNode has to be of type ListSchemaNode");
1441 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1442 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues =
1443 Builders.mapEntryBuilder(listStreamSchemaNode);
1445 List<DataSchemaNode> instanceDataChildrenByName =
1446 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "name");
1447 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1448 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1449 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName).build());
1451 instanceDataChildrenByName =
1452 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "description");
1453 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1454 Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1455 streamNodeValues.withChild(
1456 Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue("DESCRIPTION_PLACEHOLDER").build());
1458 instanceDataChildrenByName =
1459 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-support");
1460 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1461 Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1462 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1463 .withValue(Boolean.valueOf(true)).build());
1465 instanceDataChildrenByName =
1466 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-log-creation-time");
1467 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1468 Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1469 streamNodeValues.withChild(
1470 Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode).withValue("").build());
1472 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "events");
1473 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1474 Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1475 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode).build());
1477 return streamNodeValues.build();
1481 * Prepare stream for notification.
1484 * contains list of qnames of notifications
1485 * @return - checked future object
1487 private CheckedFuture<DOMRpcResult, DOMRpcException> invokeSalRemoteRpcNotifiStrRPC(
1488 final NormalizedNodeContext payload) {
1489 final ContainerNode data = (ContainerNode) payload.getData();
1490 LeafSetNode leafSet = null;
1491 String outputType = "XML";
1492 for (final DataContainerChild<? extends PathArgument, ?> dataChild : data.getValue()) {
1493 if (dataChild instanceof LeafSetNode) {
1494 leafSet = (LeafSetNode) dataChild;
1495 } else if (dataChild instanceof AugmentationNode) {
1496 outputType = (String) ((AugmentationNode) dataChild).getValue().iterator().next().getValue();
1500 final Collection<LeafSetEntryNode> entryNodes = leafSet.getValue();
1501 final List<SchemaPath> paths = new ArrayList<>();
1502 String streamName = CREATE_NOTIFICATION_STREAM + "/";
1504 StringBuilder streamNameBuilder = new StringBuilder(streamName);
1505 final Iterator<LeafSetEntryNode> iterator = entryNodes.iterator();
1506 while (iterator.hasNext()) {
1507 final QName valueQName = QName.create((String) iterator.next().getValue());
1508 final Module module = controllerContext.findModuleByNamespace(valueQName.getModule().getNamespace());
1509 Preconditions.checkNotNull(module,
1510 "Module for namespace " + valueQName.getModule().getNamespace() + " does not exist");
1511 NotificationDefinition notifiDef = null;
1512 for (final NotificationDefinition notification : module.getNotifications()) {
1513 if (notification.getQName().equals(valueQName)) {
1514 notifiDef = notification;
1518 final String moduleName = module.getName();
1519 Preconditions.checkNotNull(notifiDef,
1520 "Notification " + valueQName + "doesn't exist in module " + moduleName);
1521 paths.add(notifiDef.getPath());
1522 streamNameBuilder.append(moduleName).append(':').append(valueQName.getLocalName());
1523 if (iterator.hasNext()) {
1524 streamNameBuilder.append(',');
1528 streamName = streamNameBuilder.toString();
1530 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
1531 final QName outputQname = QName.create(rpcQName, "output");
1532 final QName streamNameQname = QName.create(rpcQName, "notification-stream-identifier");
1534 final ContainerNode output =
1535 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
1536 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
1538 if (!Notificator.existNotificationListenerFor(streamName)) {
1539 Notificator.createNotificationListener(paths, streamName, outputType, controllerContext);
1542 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
1544 return Futures.immediateCheckedFuture(defaultDOMRpcResult);