2 * Copyright (c) 2014 - 2016 Brocade Communication Systems, Inc., Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.netconf.sal.restconf.impl;
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Predicates;
13 import com.google.common.base.Splitter;
14 import com.google.common.base.Strings;
15 import com.google.common.base.Throwables;
16 import com.google.common.collect.ImmutableSet;
17 import com.google.common.collect.Iterables;
18 import com.google.common.collect.Maps;
19 import com.google.common.util.concurrent.FluentFuture;
20 import com.google.common.util.concurrent.Futures;
21 import com.google.common.util.concurrent.ListenableFuture;
23 import java.time.Instant;
24 import java.time.format.DateTimeFormatter;
25 import java.time.format.DateTimeFormatterBuilder;
26 import java.time.format.DateTimeParseException;
27 import java.time.temporal.ChronoField;
28 import java.time.temporal.TemporalAccessor;
29 import java.util.AbstractMap.SimpleImmutableEntry;
30 import java.util.ArrayList;
31 import java.util.Collection;
32 import java.util.Collections;
33 import java.util.HashMap;
34 import java.util.Iterator;
35 import java.util.List;
36 import java.util.Locale;
38 import java.util.Map.Entry;
39 import java.util.Objects;
40 import java.util.Optional;
42 import java.util.concurrent.CancellationException;
43 import java.util.concurrent.ExecutionException;
44 import javax.inject.Inject;
45 import javax.inject.Singleton;
46 import javax.ws.rs.WebApplicationException;
47 import javax.ws.rs.core.Context;
48 import javax.ws.rs.core.Response;
49 import javax.ws.rs.core.Response.ResponseBuilder;
50 import javax.ws.rs.core.Response.Status;
51 import javax.ws.rs.core.UriBuilder;
52 import javax.ws.rs.core.UriInfo;
53 import org.opendaylight.mdsal.common.api.CommitInfo;
54 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
55 import org.opendaylight.mdsal.common.api.OptimisticLockFailedException;
56 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
57 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
58 import org.opendaylight.mdsal.dom.api.DOMRpcImplementationNotAvailableException;
59 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
60 import org.opendaylight.mdsal.dom.api.DOMRpcService;
61 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
62 import org.opendaylight.netconf.sal.rest.api.Draft02;
63 import org.opendaylight.netconf.sal.rest.api.RestconfService;
64 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
65 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
66 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
67 import org.opendaylight.netconf.sal.streams.websockets.WebSocketServer;
68 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
69 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
70 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
71 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
72 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
73 import org.opendaylight.restconf.common.patch.PatchContext;
74 import org.opendaylight.restconf.common.patch.PatchStatusContext;
75 import org.opendaylight.restconf.common.util.DataChangeScope;
76 import org.opendaylight.restconf.common.validation.RestconfValidationUtils;
77 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
78 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
79 import org.opendaylight.yangtools.yang.common.QName;
80 import org.opendaylight.yangtools.yang.common.QNameModule;
81 import org.opendaylight.yangtools.yang.common.Revision;
82 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
83 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
84 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
85 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
86 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
87 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
88 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
89 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
90 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
91 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
92 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
93 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
94 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
95 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
96 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
97 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
98 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
99 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
100 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
101 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
102 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeBuilder;
103 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
104 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
105 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
106 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
107 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
108 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
109 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
110 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
111 import org.opendaylight.yangtools.yang.model.api.Module;
112 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
113 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
114 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
115 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
116 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
117 import org.opendaylight.yangtools.yang.model.util.SimpleSchemaContext;
118 import org.slf4j.Logger;
119 import org.slf4j.LoggerFactory;
122 public final class RestconfImpl implements RestconfService {
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 final BrokerFacade broker;
179 private final ControllerContext controllerContext;
182 public RestconfImpl(final BrokerFacade broker, final ControllerContext controllerContext) {
183 this.broker = broker;
184 this.controllerContext = controllerContext;
190 * @deprecated Just use {@link #RestconfImpl(BrokerFacade, ControllerContext)} constructor instead.
193 public static RestconfImpl newInstance(final BrokerFacade broker, final ControllerContext controllerContext) {
194 return new RestconfImpl(broker, controllerContext);
198 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
199 final Set<Module> allModules = this.controllerContext.getAllModules();
200 final MapNode allModuleMap = makeModuleMapNode(allModules);
202 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
204 final Module restconfModule = getRestconfModule();
205 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
206 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
207 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
209 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
210 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
211 moduleContainerBuilder.withChild(allModuleMap);
213 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode, null, schemaContext),
214 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
218 * Valid only for mount point.
221 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
222 Preconditions.checkNotNull(identifier);
223 if (!identifier.contains(ControllerContext.MOUNT)) {
224 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
225 + " URI has to end with " + ControllerContext.MOUNT;
226 LOG.debug("{} for {}", errMsg, identifier);
227 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
230 final InstanceIdentifierContext<?> mountPointIdentifier =
231 this.controllerContext.toMountPointIdentifier(identifier);
232 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
233 final Set<Module> modules = this.controllerContext.getAllModules(mountPoint);
234 final MapNode mountPointModulesMap = makeModuleMapNode(modules);
236 final Module restconfModule = getRestconfModule();
237 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
238 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
239 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
241 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
242 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
243 moduleContainerBuilder.withChild(mountPointModulesMap);
245 return new NormalizedNodeContext(
246 new InstanceIdentifierContext<>(null, modulesSchemaNode, mountPoint,
247 this.controllerContext.getGlobalSchema()),
248 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
252 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
253 Preconditions.checkNotNull(identifier);
254 final Entry<String, Revision> nameRev = getModuleNameAndRevision(identifier);
255 Module module = null;
256 DOMMountPoint mountPoint = null;
257 final SchemaContext schemaContext;
258 if (identifier.contains(ControllerContext.MOUNT)) {
259 final InstanceIdentifierContext<?> mountPointIdentifier =
260 this.controllerContext.toMountPointIdentifier(identifier);
261 mountPoint = mountPointIdentifier.getMountPoint();
262 module = this.controllerContext.findModuleByNameAndRevision(mountPoint, nameRev.getKey(),
264 schemaContext = mountPoint.getSchemaContext();
266 module = this.controllerContext.findModuleByNameAndRevision(nameRev.getKey(), nameRev.getValue());
267 schemaContext = this.controllerContext.getGlobalSchema();
270 if (module == null) {
271 LOG.debug("Module with name '{}' and revision '{}' was not found.", nameRev.getKey(), nameRev.getValue());
272 throw new RestconfDocumentedException("Module with name '" + nameRev.getKey() + "' and revision '"
273 + nameRev.getValue() + "' was not found.", 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 DataContainerNodeBuilder<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 = "URI has bad format. If operations behind mount point should be showed, URI has to "
336 + " end with " + ControllerContext.MOUNT;
337 LOG.debug("{} for {}", errMsg, identifier);
338 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
341 return operationsFromModulesToNormalizedContext(modules, mountPoint);
345 * Special case only for GET restconf/operations use (since moment of
346 * pre-Beryllium Yang parser and Yang model API removal). The method is
347 * creating fake schema context with fake module and fake data by use own
348 * implementations of schema nodes and module.
351 * set of modules for get RPCs from every module
353 * mount point, if in use otherwise null
354 * @return {@link NormalizedNodeContext}
356 private static NormalizedNodeContext operationsFromModulesToNormalizedContext(final Set<Module> modules,
357 final DOMMountPoint mountPoint) {
359 final Collection<Module> neededModules = new ArrayList<>(modules.size());
360 final ArrayList<LeafSchemaNode> fakeRpcSchema = new ArrayList<>();
362 for (final Module m : modules) {
363 final Set<RpcDefinition> rpcs = m.getRpcs();
364 if (!rpcs.isEmpty()) {
365 neededModules.add(m);
367 fakeRpcSchema.ensureCapacity(fakeRpcSchema.size() + rpcs.size());
368 rpcs.forEach(rpc -> fakeRpcSchema.add(new FakeLeafSchemaNode(rpc.getQName())));
372 final ContainerSchemaNode fakeCont = new FakeContainerSchemaNode(fakeRpcSchema);
373 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> containerBuilder =
374 Builders.containerBuilder(fakeCont);
376 for (final LeafSchemaNode leaf : fakeRpcSchema) {
377 containerBuilder.withChild(Builders.leafBuilder(leaf).build());
380 final Collection<Module> fakeModules = new ArrayList<>(neededModules.size() + 1);
381 neededModules.forEach(imp -> fakeModules.add(new FakeImportedModule(imp)));
382 fakeModules.add(new FakeRestconfModule(neededModules, fakeCont));
384 final SchemaContext fakeSchemaCtx = SimpleSchemaContext.forModules(ImmutableSet.copyOf(fakeModules));
385 final InstanceIdentifierContext<ContainerSchemaNode> instanceIdentifierContext =
386 new InstanceIdentifierContext<>(null, fakeCont, mountPoint, fakeSchemaCtx);
387 return new NormalizedNodeContext(instanceIdentifierContext, containerBuilder.build());
390 private Module getRestconfModule() {
391 final Module restconfModule = this.controllerContext.getRestconfModule();
392 if (restconfModule == null) {
393 LOG.debug("ietf-restconf module was not found.");
394 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
395 ErrorTag.OPERATION_NOT_SUPPORTED);
398 return restconfModule;
401 private static Entry<String, Revision> getModuleNameAndRevision(final String identifier) {
402 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
403 String moduleNameAndRevision = "";
404 if (mountIndex >= 0) {
405 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
407 moduleNameAndRevision = identifier;
410 final Splitter splitter = Splitter.on('/').omitEmptyStrings();
411 final List<String> pathArgs = splitter.splitToList(moduleNameAndRevision);
412 if (pathArgs.size() < 2) {
413 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' {}", identifier);
414 throw new RestconfDocumentedException(
415 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
416 ErrorTag.INVALID_VALUE);
420 return new SimpleImmutableEntry<>(pathArgs.get(0), Revision.of(pathArgs.get(1)));
421 } catch (final DateTimeParseException e) {
422 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' {}", identifier);
423 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
424 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
429 public Object getRoot() {
434 public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload,
435 final UriInfo uriInfo) {
436 if (payload == null) {
437 // no payload specified, reroute this to no payload invokeRpc implementation
438 return invokeRpc(identifier, uriInfo);
441 final SchemaPath type = payload.getInstanceIdentifierContext().getSchemaNode().getPath();
442 final URI namespace = payload.getInstanceIdentifierContext().getSchemaNode().getQName().getNamespace();
443 final ListenableFuture<DOMRpcResult> response;
444 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
445 final SchemaContext schemaContext;
447 if (mountPoint != null) {
448 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
449 if (!mountRpcServices.isPresent()) {
450 LOG.debug("Error: Rpc service is missing.");
451 throw new RestconfDocumentedException("Rpc service is missing.");
453 schemaContext = mountPoint.getSchemaContext();
454 response = mountRpcServices.get().invokeRpc(type, payload.getData());
456 if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
457 if (identifier.contains(CREATE_DATA_SUBSCR)) {
458 response = invokeSalRemoteRpcSubscribeRPC(payload);
459 } else if (identifier.contains(CREATE_NOTIFICATION_STREAM)) {
460 response = invokeSalRemoteRpcNotifiStrRPC(payload);
462 final String msg = "Not supported operation";
464 throw new RestconfDocumentedException(msg, ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED);
467 response = this.broker.invokeRpc(type, payload.getData());
469 schemaContext = this.controllerContext.getGlobalSchema();
472 final DOMRpcResult result = checkRpcResponse(response);
474 RpcDefinition resultNodeSchema = null;
475 final NormalizedNode<?, ?> resultData;
476 if (result != null && result.getResult() != null) {
477 resultData = result.getResult();
478 resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
483 if (resultData != null && ((ContainerNode) resultData).getValue().isEmpty()) {
484 throw new WebApplicationException(Response.Status.NO_CONTENT);
486 return new NormalizedNodeContext(
487 new InstanceIdentifierContext<>(null, resultNodeSchema, mountPoint, schemaContext),
488 resultData, QueryParametersParser.parseWriterParameters(uriInfo));
492 private NormalizedNodeContext invokeRpc(final String identifier, final UriInfo uriInfo) {
494 DOMMountPoint mountPoint = null;
495 final String identifierEncoded;
496 final SchemaContext schemaContext;
497 if (identifier.contains(ControllerContext.MOUNT)) {
498 // mounted RPC call - look up mount instance.
499 final InstanceIdentifierContext<?> mountPointId = this.controllerContext.toMountPointIdentifier(identifier);
500 mountPoint = mountPointId.getMountPoint();
501 schemaContext = mountPoint.getSchemaContext();
502 final int startOfRemoteRpcName =
503 identifier.lastIndexOf(ControllerContext.MOUNT) + ControllerContext.MOUNT.length() + 1;
504 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
505 identifierEncoded = remoteRpcName;
507 } else if (identifier.indexOf('/') != CHAR_NOT_FOUND) {
508 LOG.debug("Identifier {} cannot contain slash character (/).", identifier);
509 throw new RestconfDocumentedException(String.format("Identifier %n%s%ncan\'t contain slash character (/).%n"
510 + "If slash is part of identifier name then use %%2F placeholder.", identifier), ErrorType.PROTOCOL,
511 ErrorTag.INVALID_VALUE);
513 identifierEncoded = identifier;
514 schemaContext = this.controllerContext.getGlobalSchema();
517 final String identifierDecoded = this.controllerContext.urlPathArgDecode(identifierEncoded);
520 if (mountPoint == null) {
521 rpc = this.controllerContext.getRpcDefinition(identifierDecoded);
523 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
527 LOG.debug("RPC {} does not exist.", identifierDecoded);
528 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
531 if (!rpc.getInput().getChildNodes().isEmpty()) {
532 LOG.debug("No input specified for RPC {} with an input section", rpc);
533 throw new RestconfDocumentedException("No input specified for RPC " + rpc
534 + " with an input section defined", ErrorType.RPC, ErrorTag.MISSING_ELEMENT);
537 final ListenableFuture<DOMRpcResult> response;
538 if (mountPoint != null) {
539 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
540 if (!mountRpcServices.isPresent()) {
541 throw new RestconfDocumentedException("Rpc service is missing.");
543 response = mountRpcServices.get().invokeRpc(rpc.getPath(), null);
545 response = this.broker.invokeRpc(rpc.getPath(), null);
548 final DOMRpcResult result = checkRpcResponse(response);
550 if (result.getResult() != null && ((ContainerNode) result.getResult()).getValue().isEmpty()) {
551 throw new WebApplicationException(Response.Status.NO_CONTENT);
553 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpc, mountPoint, schemaContext),
554 result.getResult(), QueryParametersParser.parseWriterParameters(uriInfo));
558 @SuppressWarnings("checkstyle:avoidHidingCauseException")
559 private static DOMRpcResult checkRpcResponse(final ListenableFuture<DOMRpcResult> response) {
560 if (response == null) {
564 final DOMRpcResult retValue = response.get();
565 if (retValue.getErrors().isEmpty()) {
568 LOG.debug("RpcError message {}", retValue.getErrors());
569 throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
570 } catch (final InterruptedException e) {
571 final String errMsg = "The operation was interrupted while executing and did not complete.";
572 LOG.debug("Rpc Interrupt - {}", errMsg, e);
573 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION, e);
574 } catch (final ExecutionException e) {
575 LOG.debug("Execution RpcError: ", e);
576 Throwable cause = e.getCause();
578 while (cause.getCause() != null) {
579 cause = cause.getCause();
582 if (cause instanceof IllegalArgumentException) {
583 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL,
584 ErrorTag.INVALID_VALUE);
585 } else if (cause instanceof DOMRpcImplementationNotAvailableException) {
586 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.APPLICATION,
587 ErrorTag.OPERATION_NOT_SUPPORTED);
589 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
592 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
595 } catch (final CancellationException e) {
596 final String errMsg = "The operation was cancelled while executing.";
597 LOG.debug("Cancel RpcExecution: {}", errMsg, e);
598 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
602 private static void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
603 if (inputSchema != null && payload.getData() == null) {
604 // expected a non null payload
605 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
606 } else if (inputSchema == null && payload.getData() != null) {
607 // did not expect any input
608 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
612 private ListenableFuture<DOMRpcResult> invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
613 final ContainerNode value = (ContainerNode) payload.getData();
614 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
615 final Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(
616 new NodeIdentifier(QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(),
618 final Object pathValue = path.isPresent() ? path.get().getValue() : null;
620 if (!(pathValue instanceof YangInstanceIdentifier)) {
621 LOG.debug("Instance identifier {} was not normalized correctly", rpcQName);
622 throw new RestconfDocumentedException("Instance identifier was not normalized correctly",
623 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
626 final YangInstanceIdentifier pathIdentifier = (YangInstanceIdentifier) pathValue;
627 String streamName = (String) CREATE_DATA_SUBSCR;
628 NotificationOutputType outputType = null;
629 if (!pathIdentifier.isEmpty()) {
630 final String fullRestconfIdentifier =
631 DATA_SUBSCR + this.controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
633 LogicalDatastoreType datastore =
634 parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
635 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
637 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
638 scope = scope == null ? DEFAULT_SCOPE : scope;
640 outputType = parseEnumTypeParameter(value, NotificationOutputType.class, OUTPUT_TYPE_PARAM_NAME);
641 outputType = outputType == null ? NotificationOutputType.XML : outputType;
643 streamName = Notificator
644 .createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore + "/scope=" + scope);
647 if (Strings.isNullOrEmpty(streamName)) {
648 LOG.debug("Path is empty or contains value node which is not Container or List built-in type at {}",
650 throw new RestconfDocumentedException("Path is empty or contains value node which is not Container or List "
651 + "built-in type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
654 final QName outputQname = QName.create(rpcQName, "output");
655 final QName streamNameQname = QName.create(rpcQName, "stream-name");
657 final ContainerNode output =
658 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
659 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
661 if (!Notificator.existListenerFor(streamName)) {
662 Notificator.createListener(pathIdentifier, streamName, outputType, controllerContext);
665 return Futures.immediateFuture(new DefaultDOMRpcResult(output));
668 private static RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
669 final String[] splittedIdentifier = identifierDecoded.split(":");
670 if (splittedIdentifier.length != 2) {
671 LOG.debug("{} could not be split to 2 parts (module:rpc name)", identifierDecoded);
672 throw new RestconfDocumentedException(identifierDecoded + " could not be split to 2 parts "
673 + "(module:rpc name)", ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
675 for (final Module module : schemaContext.getModules()) {
676 if (module.getName().equals(splittedIdentifier[0])) {
677 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
678 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
679 return rpcDefinition;
688 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
689 boolean withDefaUsed = false;
690 String withDefa = null;
692 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
693 switch (entry.getKey()) {
694 case "with-defaults":
697 withDefa = entry.getValue().iterator().next();
699 throw new RestconfDocumentedException("With-defaults parameter can be used only once.");
703 LOG.info("Unknown key : {}.", entry.getKey());
707 boolean tagged = false;
709 if ("report-all-tagged".equals(withDefa)) {
713 if ("report-all".equals(withDefa)) {
718 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
719 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
720 NormalizedNode<?, ?> data = null;
721 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
722 if (mountPoint != null) {
723 data = this.broker.readConfigurationData(mountPoint, normalizedII, withDefa);
725 data = this.broker.readConfigurationData(normalizedII, withDefa);
728 throw dataMissing(identifier);
730 return new NormalizedNodeContext(iiWithData, data,
731 QueryParametersParser.parseWriterParameters(uriInfo, tagged));
735 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
736 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
737 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
738 NormalizedNode<?, ?> data = null;
739 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
740 if (mountPoint != null) {
741 data = this.broker.readOperationalData(mountPoint, normalizedII);
743 data = this.broker.readOperationalData(normalizedII);
746 throw dataMissing(identifier);
748 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
751 private static RestconfDocumentedException dataMissing(final String identifier) {
752 LOG.debug("Request could not be completed because the relevant data model content does not exist {}",
754 return new RestconfDocumentedException("Request could not be completed because the relevant data model content "
755 + "does not exist", ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
759 public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload,
760 final UriInfo uriInfo) {
761 boolean insertUsed = false;
762 boolean pointUsed = false;
763 String insert = null;
766 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
767 switch (entry.getKey()) {
771 insert = entry.getValue().iterator().next();
773 throw new RestconfDocumentedException("Insert parameter can be used only once.");
779 point = entry.getValue().iterator().next();
781 throw new RestconfDocumentedException("Point parameter can be used only once.");
785 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
789 if (pointUsed && !insertUsed) {
790 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
792 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
793 throw new RestconfDocumentedException(
794 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
797 Preconditions.checkNotNull(identifier);
799 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
801 validateInput(iiWithData.getSchemaNode(), payload);
802 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
803 validateListKeysEqualityInPayloadAndUri(payload);
805 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
806 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
809 * There is a small window where another write transaction could be
810 * updating the same data simultaneously and we get an
811 * OptimisticLockFailedException. This error is likely transient and The
812 * WriteTransaction#submit API docs state that a retry will likely
813 * succeed. So we'll try again if that scenario occurs. If it fails a
814 * third time then it probably will never succeed so we'll fail in that
817 * By retrying we're attempting to hide the internal implementation of
818 * the data store and how it handles concurrent updates from the
819 * restconf client. The client has instructed us to put the data and we
820 * should make every effort to do so without pushing optimistic lock
821 * failures back to the client and forcing them to handle it via retry
822 * (and having to document the behavior).
824 PutResult result = null;
827 if (mountPoint != null) {
829 result = this.broker.commitMountPointDataPut(mountPoint, normalizedII, payload.getData(), insert,
832 result = this.broker.commitConfigurationDataPut(this.controllerContext.getGlobalSchema(), normalizedII,
833 payload.getData(), insert, point);
837 result.getFutureOfPutData().get();
838 } catch (final InterruptedException e) {
839 LOG.debug("Update failed for {}", identifier, e);
840 throw new RestconfDocumentedException(e.getMessage(), e);
841 } catch (final ExecutionException e) {
842 final TransactionCommitFailedException failure = Throwables.getCauseAs(e,
843 TransactionCommitFailedException.class);
844 if (failure instanceof OptimisticLockFailedException) {
846 LOG.debug("Got OptimisticLockFailedException on last try - failing {}", identifier);
847 throw new RestconfDocumentedException(e.getMessage(), e, failure.getErrorList());
850 LOG.debug("Got OptimisticLockFailedException - trying again {}", identifier);
854 LOG.debug("Update failed for {}", identifier, e);
855 throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), failure);
858 return Response.status(result.getStatus()).build();
862 private static void validateTopLevelNodeName(final NormalizedNodeContext node,
863 final YangInstanceIdentifier identifier) {
865 final String payloadName = node.getData().getNodeType().getLocalName();
868 if (identifier.isEmpty()) {
870 if (!node.getData().getNodeType().equals(NETCONF_BASE_QNAME)) {
871 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
872 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
876 final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
877 if (!payloadName.equals(identifierName)) {
878 throw new RestconfDocumentedException(
879 "Payload name (" + payloadName + ") is different from identifier name (" + identifierName + ")",
880 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
886 * Validates whether keys in {@code payload} are equal to values of keys in
887 * {@code iiWithData} for list schema node.
889 * @throws RestconfDocumentedException
890 * if key values or key count in payload and URI isn't equal
893 private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
894 Preconditions.checkArgument(payload != null);
895 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
896 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
897 final SchemaNode schemaNode = iiWithData.getSchemaNode();
898 final NormalizedNode<?, ?> data = payload.getData();
899 if (schemaNode instanceof ListSchemaNode) {
900 final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
901 if (lastPathArgument instanceof NodeIdentifierWithPredicates && data instanceof MapEntryNode) {
902 final Map<QName, Object> uriKeyValues =
903 ((NodeIdentifierWithPredicates) lastPathArgument).getKeyValues();
904 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
910 public static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final MapEntryNode payload,
911 final List<QName> keyDefinitions) {
913 final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
914 for (final QName keyDefinition : keyDefinitions) {
915 final Object uriKeyValue = mutableCopyUriKeyValues.remove(keyDefinition);
916 // should be caught during parsing URI to InstanceIdentifier
917 RestconfValidationUtils.checkDocumentedError(uriKeyValue != null, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
918 "Missing key " + keyDefinition + " in URI.");
920 final Object dataKeyValue = payload.getIdentifier().getKeyValues().get(keyDefinition);
922 if (!Objects.deepEquals(uriKeyValue, dataKeyValue)) {
923 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName()
924 + "' specified in the URI doesn't match the value '" + dataKeyValue
925 + "' specified in the message body. ";
926 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
932 public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload,
933 final UriInfo uriInfo) {
934 return createConfigurationData(payload, uriInfo);
938 public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
939 if (payload == null) {
940 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
942 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
943 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
944 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
946 boolean insertUsed = false;
947 boolean pointUsed = false;
948 String insert = null;
951 if (uriInfo != null) {
952 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
953 switch (entry.getKey()) {
957 insert = entry.getValue().iterator().next();
959 throw new RestconfDocumentedException("Insert parameter can be used only once.");
965 point = entry.getValue().iterator().next();
967 throw new RestconfDocumentedException("Point parameter can be used only once.");
971 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
976 if (pointUsed && !insertUsed) {
977 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
979 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
980 throw new RestconfDocumentedException(
981 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
984 FluentFuture<? extends CommitInfo> future;
985 if (mountPoint != null) {
986 future = this.broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData(), insert,
989 future = this.broker.commitConfigurationDataPost(this.controllerContext.getGlobalSchema(), normalizedII,
990 payload.getData(), insert, point);
995 } catch (final InterruptedException e) {
996 LOG.info("Error creating data {}", uriInfo != null ? uriInfo.getPath() : "", e);
997 throw new RestconfDocumentedException(e.getMessage(), e);
998 } catch (final ExecutionException e) {
999 LOG.info("Error creating data {}", uriInfo != null ? uriInfo.getPath() : "", e);
1000 throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), Throwables.getCauseAs(e,
1001 TransactionCommitFailedException.class));
1004 LOG.trace("Successfuly created data.");
1006 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
1007 // FIXME: Provide path to result.
1008 final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
1009 if (location != null) {
1010 responseBuilder.location(location);
1012 return responseBuilder.build();
1015 @SuppressWarnings("checkstyle:IllegalCatch")
1016 private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint,
1017 final YangInstanceIdentifier normalizedII) {
1018 if (uriInfo == null) {
1019 // This is null if invoked internally
1023 final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
1024 uriBuilder.path("config");
1026 uriBuilder.path(this.controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
1027 } catch (final Exception e) {
1028 LOG.info("Location for instance identifier {} was not created", normalizedII, e);
1031 return uriBuilder.build();
1035 public Response deleteConfigurationData(final String identifier) {
1036 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
1037 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
1038 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
1040 final FluentFuture<? extends CommitInfo> future;
1041 if (mountPoint != null) {
1042 future = this.broker.commitConfigurationDataDelete(mountPoint, normalizedII);
1044 future = this.broker.commitConfigurationDataDelete(normalizedII);
1049 } catch (final InterruptedException e) {
1050 throw new RestconfDocumentedException(e.getMessage(), e);
1051 } catch (final ExecutionException e) {
1052 final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
1053 Predicates.instanceOf(ModifiedNodeDoesNotExistException.class)).toJavaUtil();
1054 if (searchedException.isPresent()) {
1055 throw new RestconfDocumentedException("Data specified for delete doesn't exist.", ErrorType.APPLICATION,
1056 ErrorTag.DATA_MISSING, e);
1059 throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), Throwables.getCauseAs(e,
1060 TransactionCommitFailedException.class));
1063 return Response.status(Status.OK).build();
1067 * Subscribes to some path in schema context (stream) to listen on changes
1071 * Additional parameters for subscribing to stream are loaded via rpc input
1074 * <li>datastore - default CONFIGURATION (other values of
1075 * {@link LogicalDatastoreType} enum type)</li>
1076 * <li>scope - default BASE (other values of {@link DataChangeScope})</li>
1080 public NormalizedNodeContext subscribeToStream(final String identifier, final UriInfo uriInfo) {
1081 boolean startTimeUsed = false;
1082 boolean stopTimeUsed = false;
1083 Instant start = Instant.now();
1084 Instant stop = null;
1085 boolean filterUsed = false;
1086 String filter = null;
1087 boolean leafNodesOnlyUsed = false;
1088 boolean leafNodesOnly = false;
1090 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
1091 switch (entry.getKey()) {
1093 if (!startTimeUsed) {
1094 startTimeUsed = true;
1095 start = parseDateFromQueryParam(entry);
1097 throw new RestconfDocumentedException("Start-time parameter can be used only once.");
1101 if (!stopTimeUsed) {
1102 stopTimeUsed = true;
1103 stop = parseDateFromQueryParam(entry);
1105 throw new RestconfDocumentedException("Stop-time parameter can be used only once.");
1111 filter = entry.getValue().iterator().next();
1113 throw new RestconfDocumentedException("Filter parameter can be used only once.");
1116 case "odl-leaf-nodes-only":
1117 if (!leafNodesOnlyUsed) {
1118 leafNodesOnlyUsed = true;
1119 leafNodesOnly = Boolean.parseBoolean(entry.getValue().iterator().next());
1121 throw new RestconfDocumentedException("Odl-leaf-nodes-only parameter can be used only once.");
1125 throw new RestconfDocumentedException("Bad parameter used with notifications: " + entry.getKey());
1128 if (!startTimeUsed && stopTimeUsed) {
1129 throw new RestconfDocumentedException("Stop-time parameter has to be used with start-time parameter.");
1131 URI response = null;
1132 if (identifier.contains(DATA_SUBSCR)) {
1133 response = dataSubs(identifier, uriInfo, start, stop, filter, leafNodesOnly);
1134 } else if (identifier.contains(NOTIFICATION_STREAM)) {
1135 response = notifStream(identifier, uriInfo, start, stop, filter);
1138 if (response != null) {
1139 // prepare node with value of location
1140 final InstanceIdentifierContext<?> iid = prepareIIDSubsStreamOutput();
1141 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> builder =
1142 ImmutableLeafNodeBuilder.create().withValue(response.toString());
1143 builder.withNodeIdentifier(
1144 NodeIdentifier.create(QName.create("subscribe:to:notification", "2016-10-28", "location")));
1146 // prepare new header with location
1147 final Map<String, Object> headers = new HashMap<>();
1148 headers.put("Location", response);
1150 return new NormalizedNodeContext(iid, builder.build(), headers);
1153 final String msg = "Bad type of notification of sal-remote";
1155 throw new RestconfDocumentedException(msg);
1158 private static Instant parseDateFromQueryParam(final Entry<String, List<String>> entry) {
1159 final DateAndTime event = new DateAndTime(entry.getValue().iterator().next());
1160 final String value = event.getValue();
1161 final TemporalAccessor p;
1163 p = FORMATTER.parse(value);
1164 } catch (final DateTimeParseException e) {
1165 throw new RestconfDocumentedException("Cannot parse of value in date: " + value, e);
1167 return Instant.from(p);
1171 * Prepare instance identifier.
1173 * @return {@link InstanceIdentifierContext} of location leaf for
1176 private InstanceIdentifierContext<?> prepareIIDSubsStreamOutput() {
1177 final QName qnameBase = QName.create("subscribe:to:notification", "2016-10-28", "notifi");
1178 final SchemaContext schemaCtx = controllerContext.getGlobalSchema();
1179 final DataSchemaNode location = ((ContainerSchemaNode) schemaCtx
1180 .findModule(qnameBase.getModule()).orElse(null)
1181 .getDataChildByName(qnameBase)).getDataChildByName(QName.create(qnameBase, "location"));
1182 final List<PathArgument> path = new ArrayList<>();
1183 path.add(NodeIdentifier.create(qnameBase));
1184 path.add(NodeIdentifier.create(QName.create(qnameBase, "location")));
1186 return new InstanceIdentifierContext<SchemaNode>(YangInstanceIdentifier.create(path), location, null,
1191 * Register notification listener by stream name.
1198 * stop-time of getting notification
1200 * start-time of getting notification
1202 * indicate which subset of all possible events are of interest
1203 * @return {@link URI} of location
1205 private URI notifStream(final String identifier, final UriInfo uriInfo, final Instant start,
1206 final Instant stop, final String filter) {
1207 final String streamName = Notificator.createStreamNameFromUri(identifier);
1208 if (Strings.isNullOrEmpty(streamName)) {
1209 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1211 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
1212 if (listeners == null || listeners.isEmpty()) {
1213 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1214 ErrorTag.UNKNOWN_ELEMENT);
1217 for (final NotificationListenerAdapter listener : listeners) {
1218 this.broker.registerToListenNotification(listener);
1219 listener.setQueryParams(start, Optional.ofNullable(stop), Optional.ofNullable(filter), false);
1222 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1224 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance(NOTIFICATION_PORT);
1225 final int notificationPort = webSocketServerInstance.getPort();
1228 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme(getWsScheme(uriInfo));
1230 return uriToWebsocketServerBuilder.replacePath(streamName).build();
1233 private static String getWsScheme(final UriInfo uriInfo) {
1234 URI uri = uriInfo.getAbsolutePath();
1238 String subscriptionScheme = uri.getScheme().toLowerCase(Locale.ROOT);
1239 return subscriptionScheme.equals("https") ? "wss" : "ws";
1243 * Register data change listener by stream name.
1250 * start-time of getting notification
1252 * stop-time of getting notification
1254 * indicate which subset of all possible events are of interest
1255 * @return {@link URI} of location
1257 private URI dataSubs(final String identifier, final UriInfo uriInfo, final Instant start, final Instant stop,
1258 final String filter, final boolean leafNodesOnly) {
1259 final String streamName = Notificator.createStreamNameFromUri(identifier);
1260 if (Strings.isNullOrEmpty(streamName)) {
1261 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1264 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1265 if (listener == null) {
1266 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1267 ErrorTag.UNKNOWN_ELEMENT);
1269 listener.setQueryParams(start, Optional.ofNullable(stop), Optional.ofNullable(filter), leafNodesOnly);
1271 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1272 final LogicalDatastoreType datastore =
1273 parserURIEnumParameter(LogicalDatastoreType.class, paramToValues.get(DATASTORE_PARAM_NAME));
1274 if (datastore == null) {
1275 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1276 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1278 final DataChangeScope scope =
1279 parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
1280 if (scope == null) {
1281 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1282 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1285 this.broker.registerToListenDataChanges(datastore, scope, listener);
1287 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1289 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance(NOTIFICATION_PORT);
1290 final int notificationPort = webSocketServerInstance.getPort();
1292 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme(getWsScheme(uriInfo));
1294 return uriToWebsocketServerBuilder.replacePath(streamName).build();
1297 @SuppressWarnings("checkstyle:IllegalCatch")
1299 public PatchStatusContext patchConfigurationData(final String identifier, final PatchContext context,
1300 final UriInfo uriInfo) {
1301 if (context == null) {
1302 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1306 return this.broker.patchConfigurationDataWithinTransaction(context);
1307 } catch (final Exception e) {
1308 LOG.debug("Patch transaction failed", e);
1309 throw new RestconfDocumentedException(e.getMessage(), e);
1313 @SuppressWarnings("checkstyle:IllegalCatch")
1315 public PatchStatusContext patchConfigurationData(final PatchContext context, @Context final UriInfo uriInfo) {
1316 if (context == null) {
1317 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1321 return this.broker.patchConfigurationDataWithinTransaction(context);
1322 } catch (final Exception e) {
1323 LOG.debug("Patch transaction failed", e);
1324 throw new RestconfDocumentedException(e.getMessage(), e);
1329 * Load parameter for subscribing to stream from input composite node.
1333 * @return enum object if its string value is equal to {@code paramName}. In
1336 private static <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1337 final String paramName) {
1338 final Optional<DataContainerChild<? extends PathArgument, ?>> optAugNode = value.getChild(
1339 SAL_REMOTE_AUG_IDENTIFIER);
1340 if (!optAugNode.isPresent()) {
1343 final DataContainerChild<? extends PathArgument, ?> augNode = optAugNode.get();
1344 if (!(augNode instanceof AugmentationNode)) {
1347 final Optional<DataContainerChild<? extends PathArgument, ?>> enumNode = ((AugmentationNode) augNode).getChild(
1348 new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1349 if (!enumNode.isPresent()) {
1352 final Object rawValue = enumNode.get().getValue();
1353 if (!(rawValue instanceof String)) {
1357 return resolveAsEnum(classDescriptor, (String) rawValue);
1361 * Checks whether {@code value} is one of the string representation of
1362 * enumeration {@code classDescriptor}.
1364 * @return enum object if string value of {@code classDescriptor}
1365 * enumeration is equal to {@code value}. Other cases null.
1367 private static <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1368 if (Strings.isNullOrEmpty(value)) {
1371 return resolveAsEnum(classDescriptor, value);
1374 private static <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1375 final T[] enumConstants = classDescriptor.getEnumConstants();
1376 if (enumConstants != null) {
1377 for (final T enm : classDescriptor.getEnumConstants()) {
1378 if (((Enum<?>) enm).name().equals(value)) {
1386 private static Map<String, String> resolveValuesFromUri(final String uri) {
1387 final Map<String, String> result = new HashMap<>();
1388 final String[] tokens = uri.split("/");
1389 for (int i = 1; i < tokens.length; i++) {
1390 final String[] parameterTokens = tokens[i].split("=");
1391 if (parameterTokens.length == 2) {
1392 result.put(parameterTokens[0], parameterTokens[1]);
1398 private MapNode makeModuleMapNode(final Set<Module> modules) {
1399 Preconditions.checkNotNull(modules);
1400 final Module restconfModule = getRestconfModule();
1401 final DataSchemaNode moduleSchemaNode = this.controllerContext
1402 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1403 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1405 final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder =
1406 Builders.mapBuilder((ListSchemaNode) moduleSchemaNode);
1408 for (final Module module : modules) {
1409 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1411 return listModuleBuilder.build();
1414 private MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1415 Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1416 "moduleSchemaNode has to be of type ListSchemaNode");
1417 final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1418 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues =
1419 Builders.mapEntryBuilder(listModuleSchemaNode);
1421 List<DataSchemaNode> instanceDataChildrenByName =
1422 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "name");
1423 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1424 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1426 .withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName()).build());
1428 final QNameModule qNameModule = module.getQNameModule();
1430 instanceDataChildrenByName =
1431 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "revision");
1432 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1433 Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1434 final Optional<Revision> revision = qNameModule.getRevision();
1435 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode)
1436 .withValue(revision.map(Revision::toString).orElse("")).build());
1438 instanceDataChildrenByName =
1439 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "namespace");
1440 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1441 Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1442 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1443 .withValue(qNameModule.getNamespace().toString()).build());
1445 instanceDataChildrenByName =
1446 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "feature");
1447 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1448 Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1449 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder =
1450 Builders.leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1451 for (final FeatureDefinition feature : module.getFeatures()) {
1452 featuresBuilder.withChild(Builders.leafSetEntryBuilder((LeafListSchemaNode) featureSchemaNode)
1453 .withValue(feature.getQName().getLocalName()).build());
1455 moduleNodeValues.withChild(featuresBuilder.build());
1457 return moduleNodeValues.build();
1460 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1461 Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1462 "streamSchemaNode has to be of type ListSchemaNode");
1463 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1464 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues =
1465 Builders.mapEntryBuilder(listStreamSchemaNode);
1467 List<DataSchemaNode> instanceDataChildrenByName =
1468 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "name");
1469 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1470 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1471 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName).build());
1473 instanceDataChildrenByName =
1474 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "description");
1475 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1476 Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1477 streamNodeValues.withChild(
1478 Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue("DESCRIPTION_PLACEHOLDER").build());
1480 instanceDataChildrenByName =
1481 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-support");
1482 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1483 Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1484 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1485 .withValue(Boolean.TRUE).build());
1487 instanceDataChildrenByName =
1488 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-log-creation-time");
1489 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1490 Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1491 streamNodeValues.withChild(
1492 Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode).withValue("").build());
1494 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "events");
1495 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1496 Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1497 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode).build());
1499 return streamNodeValues.build();
1503 * Prepare stream for notification.
1506 * contains list of qnames of notifications
1507 * @return - checked future object
1509 private ListenableFuture<DOMRpcResult> invokeSalRemoteRpcNotifiStrRPC(final NormalizedNodeContext payload) {
1510 final ContainerNode data = (ContainerNode) payload.getData();
1511 LeafSetNode leafSet = null;
1512 String outputType = "XML";
1513 for (final DataContainerChild<? extends PathArgument, ?> dataChild : data.getValue()) {
1514 if (dataChild instanceof LeafSetNode) {
1515 leafSet = (LeafSetNode) dataChild;
1516 } else if (dataChild instanceof AugmentationNode) {
1517 outputType = (String) ((AugmentationNode) dataChild).getValue().iterator().next().getValue();
1521 final Collection<LeafSetEntryNode> entryNodes = leafSet.getValue();
1522 final List<SchemaPath> paths = new ArrayList<>();
1523 String streamName = CREATE_NOTIFICATION_STREAM + "/";
1525 StringBuilder streamNameBuilder = new StringBuilder(streamName);
1526 final Iterator<LeafSetEntryNode> iterator = entryNodes.iterator();
1527 while (iterator.hasNext()) {
1528 final QName valueQName = QName.create((String) iterator.next().getValue());
1529 final Module module = controllerContext.findModuleByNamespace(valueQName.getModule().getNamespace());
1530 Preconditions.checkNotNull(module,
1531 "Module for namespace " + valueQName.getModule().getNamespace() + " does not exist");
1532 NotificationDefinition notifiDef = null;
1533 for (final NotificationDefinition notification : module.getNotifications()) {
1534 if (notification.getQName().equals(valueQName)) {
1535 notifiDef = notification;
1539 final String moduleName = module.getName();
1540 Preconditions.checkNotNull(notifiDef,
1541 "Notification " + valueQName + "doesn't exist in module " + moduleName);
1542 paths.add(notifiDef.getPath());
1543 streamNameBuilder.append(moduleName).append(':').append(valueQName.getLocalName());
1544 if (iterator.hasNext()) {
1545 streamNameBuilder.append(',');
1549 streamName = streamNameBuilder.toString();
1551 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
1552 final QName outputQname = QName.create(rpcQName, "output");
1553 final QName streamNameQname = QName.create(rpcQName, "notification-stream-identifier");
1555 final ContainerNode output =
1556 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
1557 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
1559 if (!Notificator.existNotificationListenerFor(streamName)) {
1560 Notificator.createNotificationListener(paths, streamName, outputType, controllerContext);
1563 return Futures.immediateFuture(new DefaultDOMRpcResult(output));