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.AsyncDataBroker.DataChangeScope;
52 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
53 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
54 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
55 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
56 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
57 import org.opendaylight.controller.md.sal.dom.api.DOMRpcImplementationNotAvailableException;
58 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
59 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
60 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
61 import org.opendaylight.netconf.sal.rest.api.Draft02;
62 import org.opendaylight.netconf.sal.rest.api.RestconfService;
63 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
64 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
65 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
66 import org.opendaylight.netconf.sal.streams.websockets.WebSocketServer;
67 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
68 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
69 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
70 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
71 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
72 import org.opendaylight.restconf.common.patch.PatchContext;
73 import org.opendaylight.restconf.common.patch.PatchStatusContext;
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 private static final RestconfImpl INSTANCE = new RestconfImpl();
124 * Notifications are served on port 8181.
126 private static final int NOTIFICATION_PORT = 8181;
128 private static final int CHAR_NOT_FOUND = -1;
130 private static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
132 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
134 private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
136 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
138 private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
140 private static final String DATASTORE_PARAM_NAME = "datastore";
142 private static final String SCOPE_PARAM_NAME = "scope";
144 private static final String OUTPUT_TYPE_PARAM_NAME = "notification-output-type";
146 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
148 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
150 private static final QName NETCONF_BASE_QNAME = QName.create(QNameModule.create(URI.create(NETCONF_BASE)),
151 NETCONF_BASE_PAYLOAD_NAME).intern();
153 private static final QNameModule SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
154 Revision.of("2014-07-08"));
156 private static final AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER =
157 new AugmentationIdentifier(ImmutableSet.of(
158 QName.create(SAL_REMOTE_AUGMENT, "scope"), QName.create(SAL_REMOTE_AUGMENT, "datastore"),
159 QName.create(SAL_REMOTE_AUGMENT, "notification-output-type")));
161 public static final CharSequence DATA_SUBSCR = "data-change-event-subscription";
162 private static final CharSequence CREATE_DATA_SUBSCR = "create-" + DATA_SUBSCR;
164 public static final CharSequence NOTIFICATION_STREAM = "notification-stream";
165 private static final CharSequence CREATE_NOTIFICATION_STREAM = "create-" + NOTIFICATION_STREAM;
167 private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
168 .appendValue(ChronoField.YEAR, 4).appendLiteral('-')
169 .appendValue(ChronoField.MONTH_OF_YEAR, 2).appendLiteral('-')
170 .appendValue(ChronoField.DAY_OF_MONTH, 2).appendLiteral('T')
171 .appendValue(ChronoField.HOUR_OF_DAY, 2).appendLiteral(':')
172 .appendValue(ChronoField.MINUTE_OF_HOUR, 2).appendLiteral(':')
173 .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
174 .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
175 .appendOffset("+HH:MM", "Z").toFormatter();
177 private BrokerFacade broker;
179 private ControllerContext controllerContext;
181 public void setBroker(final BrokerFacade broker) {
182 this.broker = broker;
185 public void setControllerContext(final ControllerContext controllerContext) {
186 this.controllerContext = controllerContext;
189 private RestconfImpl() {
192 public static RestconfImpl getInstance() {
197 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
198 final Set<Module> allModules = this.controllerContext.getAllModules();
199 final MapNode allModuleMap = makeModuleMapNode(allModules);
201 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
203 final Module restconfModule = getRestconfModule();
204 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
205 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
206 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
208 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
209 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
210 moduleContainerBuilder.withChild(allModuleMap);
212 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode, null, schemaContext),
213 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
217 * Valid only for mount point.
220 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
221 Preconditions.checkNotNull(identifier);
222 if (!identifier.contains(ControllerContext.MOUNT)) {
223 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
224 + " URI has to end with " + ControllerContext.MOUNT;
225 LOG.debug(errMsg + " for " + identifier);
226 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
229 final InstanceIdentifierContext<?> mountPointIdentifier =
230 this.controllerContext.toMountPointIdentifier(identifier);
231 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
232 final Set<Module> modules = this.controllerContext.getAllModules(mountPoint);
233 final MapNode mountPointModulesMap = makeModuleMapNode(modules);
235 final Module restconfModule = getRestconfModule();
236 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
237 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
238 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
240 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
241 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
242 moduleContainerBuilder.withChild(mountPointModulesMap);
244 return new NormalizedNodeContext(
245 new InstanceIdentifierContext<>(null, modulesSchemaNode, mountPoint,
246 this.controllerContext.getGlobalSchema()),
247 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
251 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
252 Preconditions.checkNotNull(identifier);
253 final Entry<String, Revision> nameRev = getModuleNameAndRevision(identifier);
254 Module module = null;
255 DOMMountPoint mountPoint = null;
256 final SchemaContext schemaContext;
257 if (identifier.contains(ControllerContext.MOUNT)) {
258 final InstanceIdentifierContext<?> mountPointIdentifier =
259 this.controllerContext.toMountPointIdentifier(identifier);
260 mountPoint = mountPointIdentifier.getMountPoint();
261 module = this.controllerContext.findModuleByNameAndRevision(mountPoint, nameRev.getKey(),
263 schemaContext = mountPoint.getSchemaContext();
265 module = this.controllerContext.findModuleByNameAndRevision(nameRev.getKey(), nameRev.getValue());
266 schemaContext = this.controllerContext.getGlobalSchema();
269 if (module == null) {
270 final String errMsg = "Module with name '" + nameRev.getKey() + "' and revision '"
271 + nameRev.getValue() + "' was not found.";
273 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
276 final Module restconfModule = getRestconfModule();
277 final Set<Module> modules = Collections.singleton(module);
278 final MapNode moduleMap = makeModuleMapNode(modules);
280 final DataSchemaNode moduleSchemaNode = this.controllerContext
281 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
282 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
284 return new NormalizedNodeContext(
285 new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint, schemaContext), moduleMap,
286 QueryParametersParser.parseWriterParameters(uriInfo));
290 public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
291 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
292 final Set<String> availableStreams = Notificator.getStreamNames();
293 final Module restconfModule = getRestconfModule();
294 final DataSchemaNode streamSchemaNode = this.controllerContext
295 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
296 Preconditions.checkState(streamSchemaNode instanceof ListSchemaNode);
298 final CollectionNodeBuilder<MapEntryNode, MapNode> listStreamsBuilder =
299 Builders.mapBuilder((ListSchemaNode) streamSchemaNode);
301 for (final String streamName : availableStreams) {
302 listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
305 final DataSchemaNode streamsContainerSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
306 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
307 Preconditions.checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
309 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
310 Builders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
311 streamsContainerBuilder.withChild(listStreamsBuilder.build());
313 return new NormalizedNodeContext(
314 new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null, schemaContext),
315 streamsContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
319 public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
320 final Set<Module> allModules = this.controllerContext.getAllModules();
321 return operationsFromModulesToNormalizedContext(allModules, null);
325 public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
326 Set<Module> modules = null;
327 DOMMountPoint mountPoint = null;
328 if (identifier.contains(ControllerContext.MOUNT)) {
329 final InstanceIdentifierContext<?> mountPointIdentifier =
330 this.controllerContext.toMountPointIdentifier(identifier);
331 mountPoint = mountPointIdentifier.getMountPoint();
332 modules = this.controllerContext.getAllModules(mountPoint);
335 final String errMsg =
336 "URI has bad format. If operations behind mount point should be showed, URI has to " + "end with ";
337 LOG.debug(errMsg + ControllerContext.MOUNT + " for " + identifier);
338 throw new RestconfDocumentedException(errMsg + ControllerContext.MOUNT, ErrorType.PROTOCOL,
339 ErrorTag.INVALID_VALUE);
342 return operationsFromModulesToNormalizedContext(modules, mountPoint);
346 * Special case only for GET restconf/operations use (since moment of
347 * pre-Beryllium Yang parser and Yang model API removal). The method is
348 * creating fake schema context with fake module and fake data by use own
349 * implementations of schema nodes and module.
352 * set of modules for get RPCs from every module
354 * mount point, if in use otherwise null
355 * @return {@link NormalizedNodeContext}
357 private static NormalizedNodeContext operationsFromModulesToNormalizedContext(final Set<Module> modules,
358 final DOMMountPoint mountPoint) {
360 final Collection<Module> neededModules = new ArrayList<>(modules.size());
361 final ArrayList<LeafSchemaNode> fakeRpcSchema = new ArrayList<>();
363 for (final Module m : modules) {
364 final Set<RpcDefinition> rpcs = m.getRpcs();
365 if (!rpcs.isEmpty()) {
366 neededModules.add(m);
368 fakeRpcSchema.ensureCapacity(fakeRpcSchema.size() + rpcs.size());
369 rpcs.forEach(rpc -> fakeRpcSchema.add(new FakeLeafSchemaNode(rpc.getQName())));
373 final ContainerSchemaNode fakeCont = new FakeContainerSchemaNode(fakeRpcSchema);
374 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> containerBuilder =
375 Builders.containerBuilder(fakeCont);
377 for (final LeafSchemaNode leaf : fakeRpcSchema) {
378 containerBuilder.withChild(Builders.leafBuilder(leaf).build());
381 final Collection<Module> fakeModules = new ArrayList<>(neededModules.size() + 1);
382 neededModules.forEach(imp -> fakeModules.add(new FakeImportedModule(imp)));
383 fakeModules.add(new FakeRestconfModule(neededModules, fakeCont));
385 final SchemaContext fakeSchemaCtx = SimpleSchemaContext.forModules(ImmutableSet.copyOf(fakeModules));
386 final InstanceIdentifierContext<ContainerSchemaNode> instanceIdentifierContext =
387 new InstanceIdentifierContext<>(null, fakeCont, mountPoint, fakeSchemaCtx);
388 return new NormalizedNodeContext(instanceIdentifierContext, containerBuilder.build());
391 private Module getRestconfModule() {
392 final Module restconfModule = this.controllerContext.getRestconfModule();
393 if (restconfModule == null) {
394 LOG.debug("ietf-restconf module was not found.");
395 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
396 ErrorTag.OPERATION_NOT_SUPPORTED);
399 return restconfModule;
402 private static Entry<String, Revision> getModuleNameAndRevision(final String identifier) {
403 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
404 String moduleNameAndRevision = "";
405 if (mountIndex >= 0) {
406 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
408 moduleNameAndRevision = identifier;
411 final Splitter splitter = Splitter.on('/').omitEmptyStrings();
412 final List<String> pathArgs = splitter.splitToList(moduleNameAndRevision);
413 if (pathArgs.size() < 2) {
414 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
415 throw new RestconfDocumentedException(
416 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
417 ErrorTag.INVALID_VALUE);
421 return new SimpleImmutableEntry<>(pathArgs.get(0), Revision.of(pathArgs.get(1)));
422 } catch (final DateTimeParseException e) {
423 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
424 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
425 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
430 public Object getRoot() {
435 public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload,
436 final UriInfo uriInfo) {
437 final SchemaPath type = payload.getInstanceIdentifierContext().getSchemaNode().getPath();
438 final URI namespace = payload.getInstanceIdentifierContext().getSchemaNode().getQName().getNamespace();
439 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
440 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
441 final SchemaContext schemaContext;
443 if (mountPoint != null) {
444 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
445 if (!mountRpcServices.isPresent()) {
446 LOG.debug("Error: Rpc service is missing.");
447 throw new RestconfDocumentedException("Rpc service is missing.");
449 schemaContext = mountPoint.getSchemaContext();
450 response = mountRpcServices.get().invokeRpc(type, payload.getData());
452 if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
453 if (identifier.contains(CREATE_DATA_SUBSCR)) {
454 response = invokeSalRemoteRpcSubscribeRPC(payload);
455 } else if (identifier.contains(CREATE_NOTIFICATION_STREAM)) {
456 response = invokeSalRemoteRpcNotifiStrRPC(payload);
458 final String msg = "Not supported operation";
460 throw new RestconfDocumentedException(msg, ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED);
463 response = this.broker.invokeRpc(type, payload.getData());
465 schemaContext = this.controllerContext.getGlobalSchema();
468 final DOMRpcResult result = checkRpcResponse(response);
470 RpcDefinition resultNodeSchema = null;
471 final NormalizedNode<?, ?> resultData;
472 if (result != null && result.getResult() != null) {
473 resultData = result.getResult();
474 resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
479 return new NormalizedNodeContext(
480 new InstanceIdentifierContext<>(null, resultNodeSchema, mountPoint, schemaContext),
481 resultData, QueryParametersParser.parseWriterParameters(uriInfo));
485 public NormalizedNodeContext invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
486 if (noPayload != null && !CharMatcher.WHITESPACE.matchesAllOf(noPayload)) {
487 throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
490 String identifierEncoded = null;
491 DOMMountPoint mountPoint = null;
492 final SchemaContext schemaContext;
493 if (identifier.contains(ControllerContext.MOUNT)) {
494 // mounted RPC call - look up mount instance.
495 final InstanceIdentifierContext<?> mountPointId = this.controllerContext.toMountPointIdentifier(identifier);
496 mountPoint = mountPointId.getMountPoint();
497 schemaContext = mountPoint.getSchemaContext();
498 final int startOfRemoteRpcName =
499 identifier.lastIndexOf(ControllerContext.MOUNT) + ControllerContext.MOUNT.length() + 1;
500 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
501 identifierEncoded = remoteRpcName;
503 } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
504 final String slashErrorMsg = String.format(
505 "Identifier %n%s%ncan\'t contain slash "
506 + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.",
508 LOG.debug(slashErrorMsg);
509 throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
511 identifierEncoded = identifier;
512 schemaContext = this.controllerContext.getGlobalSchema();
515 final String identifierDecoded = this.controllerContext.urlPathArgDecode(identifierEncoded);
517 RpcDefinition rpc = null;
518 if (mountPoint == null) {
519 rpc = this.controllerContext.getRpcDefinition(identifierDecoded);
521 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
525 LOG.debug("RPC " + identifierDecoded + " does not exist.");
526 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
529 if (!rpc.getInput().getChildNodes().isEmpty()) {
530 LOG.debug("RPC " + rpc + " does not need input value.");
531 throw new RestconfDocumentedException("RPC " + rpc + " does not take any input value.",
532 ErrorType.RPC, ErrorTag.INVALID_VALUE);
535 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
536 if (mountPoint != null) {
537 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
538 if (!mountRpcServices.isPresent()) {
539 throw new RestconfDocumentedException("Rpc service is missing.");
541 response = mountRpcServices.get().invokeRpc(rpc.getPath(), null);
543 response = this.broker.invokeRpc(rpc.getPath(), null);
546 final DOMRpcResult result = checkRpcResponse(response);
548 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpc, mountPoint, schemaContext),
549 result.getResult(), QueryParametersParser.parseWriterParameters(uriInfo));
552 @SuppressWarnings("checkstyle:avoidHidingCauseException")
553 private static DOMRpcResult checkRpcResponse(final CheckedFuture<DOMRpcResult, DOMRpcException> response) {
554 if (response == null) {
558 final DOMRpcResult retValue = response.get();
559 if (retValue.getErrors().isEmpty()) {
562 LOG.debug("RpcError message", retValue.getErrors());
563 throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
564 } catch (final InterruptedException e) {
565 final String errMsg = "The operation was interrupted while executing and did not complete.";
566 LOG.debug("Rpc Interrupt - " + errMsg, e);
567 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION, e);
568 } catch (final ExecutionException e) {
569 LOG.debug("Execution RpcError: ", e);
570 Throwable cause = e.getCause();
572 while (cause.getCause() != null) {
573 cause = cause.getCause();
576 if (cause instanceof IllegalArgumentException) {
577 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL,
578 ErrorTag.INVALID_VALUE);
579 } else if (cause instanceof DOMRpcImplementationNotAvailableException) {
580 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.APPLICATION,
581 ErrorTag.OPERATION_NOT_SUPPORTED);
583 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
586 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
589 } catch (final CancellationException e) {
590 final String errMsg = "The operation was cancelled while executing.";
591 LOG.debug("Cancel RpcExecution: " + errMsg, e);
592 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
596 private static void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
597 if (inputSchema != null && payload.getData() == null) {
598 // expected a non null payload
599 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
600 } else if (inputSchema == null && payload.getData() != null) {
601 // did not expect any input
602 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
606 private CheckedFuture<DOMRpcResult, DOMRpcException>
607 invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
608 final ContainerNode value = (ContainerNode) payload.getData();
609 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
610 final java.util.Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(
611 new NodeIdentifier(QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(),
613 final Object pathValue = path.isPresent() ? path.get().getValue() : null;
615 if (!(pathValue instanceof YangInstanceIdentifier)) {
616 final String errMsg = "Instance identifier was not normalized correctly ";
617 LOG.debug(errMsg + rpcQName);
618 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
621 final YangInstanceIdentifier pathIdentifier = (YangInstanceIdentifier) pathValue;
622 String streamName = (String) CREATE_DATA_SUBSCR;
623 NotificationOutputType outputType = null;
624 if (!pathIdentifier.isEmpty()) {
625 final String fullRestconfIdentifier =
626 DATA_SUBSCR + this.controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
628 LogicalDatastoreType datastore =
629 parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
630 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
632 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
633 scope = scope == null ? DEFAULT_SCOPE : scope;
635 outputType = parseEnumTypeParameter(value, NotificationOutputType.class, OUTPUT_TYPE_PARAM_NAME);
636 outputType = outputType == null ? NotificationOutputType.XML : outputType;
638 streamName = Notificator
639 .createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore + "/scope=" + scope);
642 if (Strings.isNullOrEmpty(streamName)) {
643 final String errMsg = "Path is empty or contains value node which is not Container or List build-in type.";
644 LOG.debug(errMsg + pathIdentifier);
645 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
648 final QName outputQname = QName.create(rpcQName, "output");
649 final QName streamNameQname = QName.create(rpcQName, "stream-name");
651 final ContainerNode output =
652 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
653 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
655 if (!Notificator.existListenerFor(streamName)) {
656 Notificator.createListener(pathIdentifier, streamName, outputType, controllerContext);
659 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
661 return Futures.immediateCheckedFuture(defaultDOMRpcResult);
664 private static RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
665 final String[] splittedIdentifier = identifierDecoded.split(":");
666 if (splittedIdentifier.length != 2) {
667 final String errMsg = identifierDecoded + " couldn't be splitted to 2 parts (module:rpc name)";
669 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
671 for (final Module module : schemaContext.getModules()) {
672 if (module.getName().equals(splittedIdentifier[0])) {
673 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
674 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
675 return rpcDefinition;
684 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
685 boolean withDefaUsed = false;
686 String withDefa = null;
688 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
689 switch (entry.getKey()) {
690 case "with-defaults":
693 withDefa = entry.getValue().iterator().next();
695 throw new RestconfDocumentedException("With-defaults parameter can be used only once.");
699 LOG.info("Unknown key : {}.", entry.getKey());
703 boolean tagged = false;
705 if ("report-all-tagged".equals(withDefa)) {
709 if ("report-all".equals(withDefa)) {
714 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
715 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
716 NormalizedNode<?, ?> data = null;
717 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
718 if (mountPoint != null) {
719 data = this.broker.readConfigurationData(mountPoint, normalizedII, withDefa);
721 data = this.broker.readConfigurationData(normalizedII, withDefa);
724 final String errMsg =
725 "Request could not be completed because the relevant data model content does not exist ";
726 LOG.debug(errMsg + identifier);
727 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
729 return new NormalizedNodeContext(iiWithData, data,
730 QueryParametersParser.parseWriterParameters(uriInfo, tagged));
734 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
735 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
736 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
737 NormalizedNode<?, ?> data = null;
738 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
739 if (mountPoint != null) {
740 data = this.broker.readOperationalData(mountPoint, normalizedII);
742 data = this.broker.readOperationalData(normalizedII);
745 final String errMsg =
746 "Request could not be completed because the relevant data model content does not exist ";
747 LOG.debug(errMsg + identifier);
748 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
750 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
754 public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload,
755 final UriInfo uriInfo) {
756 boolean insertUsed = false;
757 boolean pointUsed = false;
758 String insert = null;
761 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
762 switch (entry.getKey()) {
766 insert = entry.getValue().iterator().next();
768 throw new RestconfDocumentedException("Insert parameter can be used only once.");
774 point = entry.getValue().iterator().next();
776 throw new RestconfDocumentedException("Point parameter can be used only once.");
780 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
784 if (pointUsed && !insertUsed) {
785 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
787 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
788 throw new RestconfDocumentedException(
789 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
792 Preconditions.checkNotNull(identifier);
794 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
796 validateInput(iiWithData.getSchemaNode(), payload);
797 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
798 validateListKeysEqualityInPayloadAndUri(payload);
800 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
801 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
804 * There is a small window where another write transaction could be
805 * updating the same data simultaneously and we get an
806 * OptimisticLockFailedException. This error is likely transient and The
807 * WriteTransaction#submit API docs state that a retry will likely
808 * succeed. So we'll try again if that scenario occurs. If it fails a
809 * third time then it probably will never succeed so we'll fail in that
812 * By retrying we're attempting to hide the internal implementation of
813 * the data store and how it handles concurrent updates from the
814 * restconf client. The client has instructed us to put the data and we
815 * should make every effort to do so without pushing optimistic lock
816 * failures back to the client and forcing them to handle it via retry
817 * (and having to document the behavior).
819 PutResult result = null;
822 if (mountPoint != null) {
824 result = this.broker.commitMountPointDataPut(mountPoint, normalizedII, payload.getData(), insert,
827 result = this.broker.commitConfigurationDataPut(this.controllerContext.getGlobalSchema(), normalizedII,
828 payload.getData(), insert, point);
832 result.getFutureOfPutData().checkedGet();
833 return Response.status(result.getStatus()).build();
834 } catch (final TransactionCommitFailedException e) {
835 if (e instanceof OptimisticLockFailedException) {
837 LOG.debug("Got OptimisticLockFailedException on last try - failing " + identifier);
838 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
841 LOG.debug("Got OptimisticLockFailedException - trying again " + identifier);
843 LOG.debug("Update failed for " + identifier, e);
844 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
850 private static void validateTopLevelNodeName(final NormalizedNodeContext node,
851 final YangInstanceIdentifier identifier) {
853 final String payloadName = node.getData().getNodeType().getLocalName();
856 if (identifier.isEmpty()) {
858 if (!node.getData().getNodeType().equals(NETCONF_BASE_QNAME)) {
859 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
860 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
864 final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
865 if (!payloadName.equals(identifierName)) {
866 throw new RestconfDocumentedException(
867 "Payload name (" + payloadName + ") is different from identifier name (" + identifierName + ")",
868 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
874 * Validates whether keys in {@code payload} are equal to values of keys in
875 * {@code iiWithData} for list schema node.
877 * @throws RestconfDocumentedException
878 * if key values or key count in payload and URI isn't equal
881 private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
882 Preconditions.checkArgument(payload != null);
883 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
884 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
885 final SchemaNode schemaNode = iiWithData.getSchemaNode();
886 final NormalizedNode<?, ?> data = payload.getData();
887 if (schemaNode instanceof ListSchemaNode) {
888 final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
889 if (lastPathArgument instanceof NodeIdentifierWithPredicates && data instanceof MapEntryNode) {
890 final Map<QName, Object> uriKeyValues =
891 ((NodeIdentifierWithPredicates) lastPathArgument).getKeyValues();
892 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
898 public static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final MapEntryNode payload,
899 final List<QName> keyDefinitions) {
901 final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
902 for (final QName keyDefinition : keyDefinitions) {
903 final Object uriKeyValue = mutableCopyUriKeyValues.remove(keyDefinition);
904 // should be caught during parsing URI to InstanceIdentifier
905 RestconfValidationUtils.checkDocumentedError(uriKeyValue != null, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
906 "Missing key " + keyDefinition + " in URI.");
908 final Object dataKeyValue = payload.getIdentifier().getKeyValues().get(keyDefinition);
910 if (!Objects.deepEquals(uriKeyValue, dataKeyValue)) {
911 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName()
912 + "' specified in the URI doesn't match the value '" + dataKeyValue
913 + "' specified in the message body. ";
914 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
920 public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload,
921 final UriInfo uriInfo) {
922 return createConfigurationData(payload, uriInfo);
926 public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
927 if (payload == null) {
928 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
930 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
931 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
932 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
934 boolean insertUsed = false;
935 boolean pointUsed = false;
936 String insert = null;
939 if (uriInfo != null) {
940 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
941 switch (entry.getKey()) {
945 insert = entry.getValue().iterator().next();
947 throw new RestconfDocumentedException("Insert parameter can be used only once.");
953 point = entry.getValue().iterator().next();
955 throw new RestconfDocumentedException("Point parameter can be used only once.");
959 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
964 if (pointUsed && !insertUsed) {
965 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
967 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
968 throw new RestconfDocumentedException(
969 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
972 CheckedFuture<Void, TransactionCommitFailedException> future;
973 if (mountPoint != null) {
974 future = this.broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData(), insert,
977 future = this.broker.commitConfigurationDataPost(this.controllerContext.getGlobalSchema(), normalizedII,
978 payload.getData(), insert, point);
983 } catch (final RestconfDocumentedException e) {
985 } catch (final TransactionCommitFailedException e) {
986 LOG.info("Error creating data " + (uriInfo != null ? uriInfo.getPath() : ""), e);
987 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
990 LOG.trace("Successfuly created data.");
992 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
993 // FIXME: Provide path to result.
994 final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
995 if (location != null) {
996 responseBuilder.location(location);
998 return responseBuilder.build();
1001 @SuppressWarnings("checkstyle:IllegalCatch")
1002 private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint,
1003 final YangInstanceIdentifier normalizedII) {
1004 if (uriInfo == null) {
1005 // This is null if invoked internally
1009 final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
1010 uriBuilder.path("config");
1012 uriBuilder.path(this.controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
1013 } catch (final Exception e) {
1014 LOG.info("Location for instance identifier" + normalizedII + "wasn't created", e);
1017 return uriBuilder.build();
1021 public Response deleteConfigurationData(final String identifier) {
1022 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
1023 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
1024 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
1026 final CheckedFuture<Void, TransactionCommitFailedException> future;
1027 if (mountPoint != null) {
1028 future = this.broker.commitConfigurationDataDelete(mountPoint, normalizedII);
1030 future = this.broker.commitConfigurationDataDelete(normalizedII);
1034 future.checkedGet();
1035 } catch (final TransactionCommitFailedException e) {
1036 final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
1037 Predicates.instanceOf(ModifiedNodeDoesNotExistException.class));
1038 if (searchedException.isPresent()) {
1039 throw new RestconfDocumentedException("Data specified for delete doesn't exist.",
1040 ErrorType.APPLICATION, ErrorTag.DATA_MISSING, e);
1043 final String errMsg = "Error while deleting data";
1044 LOG.info(errMsg, e);
1045 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
1048 return Response.status(Status.OK).build();
1052 * Subscribes to some path in schema context (stream) to listen on changes
1056 * Additional parameters for subscribing to stream are loaded via rpc input
1059 * <li>datastore - default CONFIGURATION (other values of
1060 * {@link LogicalDatastoreType} enum type)</li>
1061 * <li>scope - default BASE (other values of {@link DataChangeScope})</li>
1065 public NormalizedNodeContext subscribeToStream(final String identifier, final UriInfo uriInfo) {
1066 boolean startTimeUsed = false;
1067 boolean stopTimeUsed = false;
1068 Instant start = Instant.now();
1069 Instant stop = null;
1070 boolean filterUsed = false;
1071 String filter = null;
1072 boolean leafNodesOnlyUsed = false;
1073 boolean leafNodesOnly = false;
1075 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
1076 switch (entry.getKey()) {
1078 if (!startTimeUsed) {
1079 startTimeUsed = true;
1080 start = parseDateFromQueryParam(entry);
1082 throw new RestconfDocumentedException("Start-time parameter can be used only once.");
1086 if (!stopTimeUsed) {
1087 stopTimeUsed = true;
1088 stop = parseDateFromQueryParam(entry);
1090 throw new RestconfDocumentedException("Stop-time parameter can be used only once.");
1096 filter = entry.getValue().iterator().next();
1098 throw new RestconfDocumentedException("Filter parameter can be used only once.");
1101 case "odl-leaf-nodes-only":
1102 if (!leafNodesOnlyUsed) {
1103 leafNodesOnlyUsed = true;
1104 leafNodesOnly = Boolean.parseBoolean(entry.getValue().iterator().next());
1106 throw new RestconfDocumentedException("Odl-leaf-nodes-only parameter can be used only once.");
1110 throw new RestconfDocumentedException("Bad parameter used with notifications: " + entry.getKey());
1113 if (!startTimeUsed && stopTimeUsed) {
1114 throw new RestconfDocumentedException("Stop-time parameter has to be used with start-time parameter.");
1116 URI response = null;
1117 if (identifier.contains(DATA_SUBSCR)) {
1118 response = dataSubs(identifier, uriInfo, start, stop, filter, leafNodesOnly);
1119 } else if (identifier.contains(NOTIFICATION_STREAM)) {
1120 response = notifStream(identifier, uriInfo, start, stop, filter);
1123 if (response != null) {
1124 // prepare node with value of location
1125 final InstanceIdentifierContext<?> iid = prepareIIDSubsStreamOutput();
1126 final NormalizedNodeAttrBuilder<NodeIdentifier, Object, LeafNode<Object>> builder =
1127 ImmutableLeafNodeBuilder.create().withValue(response.toString());
1128 builder.withNodeIdentifier(
1129 NodeIdentifier.create(QName.create("subscribe:to:notification", "2016-10-28", "location")));
1131 // prepare new header with location
1132 final Map<String, Object> headers = new HashMap<>();
1133 headers.put("Location", response);
1135 return new NormalizedNodeContext(iid, builder.build(), headers);
1138 final String msg = "Bad type of notification of sal-remote";
1140 throw new RestconfDocumentedException(msg);
1143 private static Instant parseDateFromQueryParam(final Entry<String, List<String>> entry) {
1144 final DateAndTime event = new DateAndTime(entry.getValue().iterator().next());
1145 final String value = event.getValue();
1146 final TemporalAccessor p;
1148 p = FORMATTER.parse(value);
1149 } catch (final DateTimeParseException e) {
1150 throw new RestconfDocumentedException("Cannot parse of value in date: " + value, e);
1152 return Instant.from(p);
1156 * Prepare instance identifier.
1158 * @return {@link InstanceIdentifierContext} of location leaf for
1161 private InstanceIdentifierContext<?> prepareIIDSubsStreamOutput() {
1162 final QName qnameBase = QName.create("subscribe:to:notification", "2016-10-28", "notifi");
1163 final SchemaContext schemaCtx = controllerContext.getGlobalSchema();
1164 final DataSchemaNode location = ((ContainerSchemaNode) schemaCtx
1165 .findModule(qnameBase.getModule()).orElse(null)
1166 .getDataChildByName(qnameBase)).getDataChildByName(QName.create(qnameBase, "location"));
1167 final List<PathArgument> path = new ArrayList<>();
1168 path.add(NodeIdentifier.create(qnameBase));
1169 path.add(NodeIdentifier.create(QName.create(qnameBase, "location")));
1171 return new InstanceIdentifierContext<SchemaNode>(YangInstanceIdentifier.create(path), location, null,
1176 * Register notification listener by stream name.
1183 * stop-time of getting notification
1185 * start-time of getting notification
1187 * indicate which subset of all possible events are of interest
1188 * @return {@link URI} of location
1190 private URI notifStream(final String identifier, final UriInfo uriInfo, final Instant start,
1191 final Instant stop, final String filter) {
1192 final String streamName = Notificator.createStreamNameFromUri(identifier);
1193 if (Strings.isNullOrEmpty(streamName)) {
1194 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1196 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
1197 if (listeners == null || listeners.isEmpty()) {
1198 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1199 ErrorTag.UNKNOWN_ELEMENT);
1202 for (final NotificationListenerAdapter listener : listeners) {
1203 this.broker.registerToListenNotification(listener);
1204 listener.setQueryParams(start,
1205 java.util.Optional.ofNullable(stop), java.util.Optional.ofNullable(filter), 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 String getWsScheme(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) {
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, java.util.Optional.ofNullable(stop),
1256 java.util.Optional.ofNullable(filter), leafNodesOnly);
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 java.util.Optional<DataContainerChild<? extends PathArgument, ?>> optAugNode = value.getChild(
1326 SAL_REMOTE_AUG_IDENTIFIER);
1327 if (!optAugNode.isPresent()) {
1330 final DataContainerChild<? extends PathArgument, ?> augNode = optAugNode.get();
1331 if (!(augNode instanceof AugmentationNode)) {
1334 final java.util.Optional<DataContainerChild<? extends PathArgument, ?>> enumNode = ((AugmentationNode) augNode)
1335 .getChild(new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1336 if (!enumNode.isPresent()) {
1339 final Object rawValue = enumNode.get().getValue();
1340 if (!(rawValue instanceof String)) {
1344 return resolveAsEnum(classDescriptor, (String) rawValue);
1348 * Checks whether {@code value} is one of the string representation of
1349 * enumeration {@code classDescriptor}.
1351 * @return enum object if string value of {@code classDescriptor}
1352 * enumeration is equal to {@code value}. Other cases null.
1354 private static <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1355 if (Strings.isNullOrEmpty(value)) {
1358 return resolveAsEnum(classDescriptor, value);
1361 private static <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1362 final T[] enumConstants = classDescriptor.getEnumConstants();
1363 if (enumConstants != null) {
1364 for (final T enm : classDescriptor.getEnumConstants()) {
1365 if (((Enum<?>) enm).name().equals(value)) {
1373 private static Map<String, String> resolveValuesFromUri(final String uri) {
1374 final Map<String, String> result = new HashMap<>();
1375 final String[] tokens = uri.split("/");
1376 for (int i = 1; i < tokens.length; i++) {
1377 final String[] parameterTokens = tokens[i].split("=");
1378 if (parameterTokens.length == 2) {
1379 result.put(parameterTokens[0], parameterTokens[1]);
1385 private MapNode makeModuleMapNode(final Set<Module> modules) {
1386 Preconditions.checkNotNull(modules);
1387 final Module restconfModule = getRestconfModule();
1388 final DataSchemaNode moduleSchemaNode = this.controllerContext
1389 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1390 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1392 final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder =
1393 Builders.mapBuilder((ListSchemaNode) moduleSchemaNode);
1395 for (final Module module : modules) {
1396 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1398 return listModuleBuilder.build();
1401 protected MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1402 Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1403 "moduleSchemaNode has to be of type ListSchemaNode");
1404 final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1405 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues =
1406 Builders.mapEntryBuilder(listModuleSchemaNode);
1408 List<DataSchemaNode> instanceDataChildrenByName =
1409 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "name");
1410 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1411 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1413 .withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName()).build());
1415 instanceDataChildrenByName =
1416 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "revision");
1417 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1418 Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1419 final java.util.Optional<Revision> revision = module.getQNameModule().getRevision();
1420 if (revision.isPresent()) {
1421 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode)
1422 .withValue(revision.get().toString()).build());
1425 instanceDataChildrenByName =
1426 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "namespace");
1427 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1428 Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1429 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1430 .withValue(module.getNamespace().toString()).build());
1432 instanceDataChildrenByName =
1433 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "feature");
1434 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1435 Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1436 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder =
1437 Builders.leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1438 for (final FeatureDefinition feature : module.getFeatures()) {
1439 featuresBuilder.withChild(Builders.leafSetEntryBuilder((LeafListSchemaNode) featureSchemaNode)
1440 .withValue(feature.getQName().getLocalName()).build());
1442 moduleNodeValues.withChild(featuresBuilder.build());
1444 return moduleNodeValues.build();
1447 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1448 Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1449 "streamSchemaNode has to be of type ListSchemaNode");
1450 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1451 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues =
1452 Builders.mapEntryBuilder(listStreamSchemaNode);
1454 List<DataSchemaNode> instanceDataChildrenByName =
1455 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "name");
1456 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1457 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1458 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName).build());
1460 instanceDataChildrenByName =
1461 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "description");
1462 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1463 Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1464 streamNodeValues.withChild(
1465 Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue("DESCRIPTION_PLACEHOLDER").build());
1467 instanceDataChildrenByName =
1468 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-support");
1469 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1470 Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1471 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1472 .withValue(Boolean.valueOf(true)).build());
1474 instanceDataChildrenByName =
1475 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-log-creation-time");
1476 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1477 Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1478 streamNodeValues.withChild(
1479 Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode).withValue("").build());
1481 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "events");
1482 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1483 Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1484 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode).build());
1486 return streamNodeValues.build();
1490 * Prepare stream for notification.
1493 * contains list of qnames of notifications
1494 * @return - checked future object
1496 private CheckedFuture<DOMRpcResult, DOMRpcException> invokeSalRemoteRpcNotifiStrRPC(
1497 final NormalizedNodeContext payload) {
1498 final ContainerNode data = (ContainerNode) payload.getData();
1499 LeafSetNode leafSet = null;
1500 String outputType = "XML";
1501 for (final DataContainerChild<? extends PathArgument, ?> dataChild : data.getValue()) {
1502 if (dataChild instanceof LeafSetNode) {
1503 leafSet = (LeafSetNode) dataChild;
1504 } else if (dataChild instanceof AugmentationNode) {
1505 outputType = (String) ((AugmentationNode) dataChild).getValue().iterator().next().getValue();
1509 final Collection<LeafSetEntryNode> entryNodes = leafSet.getValue();
1510 final List<SchemaPath> paths = new ArrayList<>();
1511 String streamName = CREATE_NOTIFICATION_STREAM + "/";
1513 StringBuilder streamNameBuilder = new StringBuilder(streamName);
1514 final Iterator<LeafSetEntryNode> iterator = entryNodes.iterator();
1515 while (iterator.hasNext()) {
1516 final QName valueQName = QName.create((String) iterator.next().getValue());
1517 final Module module = controllerContext.findModuleByNamespace(valueQName.getModule().getNamespace());
1518 Preconditions.checkNotNull(module,
1519 "Module for namespace " + valueQName.getModule().getNamespace() + " does not exist");
1520 NotificationDefinition notifiDef = null;
1521 for (final NotificationDefinition notification : module.getNotifications()) {
1522 if (notification.getQName().equals(valueQName)) {
1523 notifiDef = notification;
1527 final String moduleName = module.getName();
1528 Preconditions.checkNotNull(notifiDef,
1529 "Notification " + valueQName + "doesn't exist in module " + 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 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
1553 return Futures.immediateCheckedFuture(defaultDOMRpcResult);