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.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
77 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
78 import org.opendaylight.yangtools.yang.common.Empty;
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).withValue(Empty.getInstance()).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 = ((NodeIdentifierWithPredicates) lastPathArgument).asMap();
903 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
909 public static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final MapEntryNode payload,
910 final List<QName> keyDefinitions) {
912 final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
913 for (final QName keyDefinition : keyDefinitions) {
914 final Object uriKeyValue = RestconfDocumentedException.throwIfNull(
915 // should be caught during parsing URI to InstanceIdentifier
916 mutableCopyUriKeyValues.remove(keyDefinition), ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
917 "Missing key %s in URI.", keyDefinition);
919 final Object dataKeyValue = payload.getIdentifier().getValue(keyDefinition);
921 if (!Objects.deepEquals(uriKeyValue, dataKeyValue)) {
922 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName()
923 + "' specified in the URI doesn't match the value '" + dataKeyValue
924 + "' specified in the message body. ";
925 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
931 public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload,
932 final UriInfo uriInfo) {
933 return createConfigurationData(payload, uriInfo);
937 public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
938 if (payload == null) {
939 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
941 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
942 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
943 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
945 boolean insertUsed = false;
946 boolean pointUsed = false;
947 String insert = null;
950 if (uriInfo != null) {
951 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
952 switch (entry.getKey()) {
956 insert = entry.getValue().iterator().next();
958 throw new RestconfDocumentedException("Insert parameter can be used only once.");
964 point = entry.getValue().iterator().next();
966 throw new RestconfDocumentedException("Point parameter can be used only once.");
970 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
975 if (pointUsed && !insertUsed) {
976 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
978 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
979 throw new RestconfDocumentedException(
980 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
983 FluentFuture<? extends CommitInfo> future;
984 if (mountPoint != null) {
985 future = this.broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData(), insert,
988 future = this.broker.commitConfigurationDataPost(this.controllerContext.getGlobalSchema(), normalizedII,
989 payload.getData(), insert, point);
994 } catch (final InterruptedException e) {
995 LOG.info("Error creating data {}", uriInfo != null ? uriInfo.getPath() : "", e);
996 throw new RestconfDocumentedException(e.getMessage(), e);
997 } catch (final ExecutionException e) {
998 LOG.info("Error creating data {}", uriInfo != null ? uriInfo.getPath() : "", e);
999 throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), Throwables.getCauseAs(e,
1000 TransactionCommitFailedException.class));
1003 LOG.trace("Successfuly created data.");
1005 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
1006 // FIXME: Provide path to result.
1007 final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
1008 if (location != null) {
1009 responseBuilder.location(location);
1011 return responseBuilder.build();
1014 @SuppressWarnings("checkstyle:IllegalCatch")
1015 private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint,
1016 final YangInstanceIdentifier normalizedII) {
1017 if (uriInfo == null) {
1018 // This is null if invoked internally
1022 final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
1023 uriBuilder.path("config");
1025 uriBuilder.path(this.controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
1026 } catch (final Exception e) {
1027 LOG.info("Location for instance identifier {} was not created", normalizedII, e);
1030 return uriBuilder.build();
1034 public Response deleteConfigurationData(final String identifier) {
1035 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
1036 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
1037 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
1039 final FluentFuture<? extends CommitInfo> future;
1040 if (mountPoint != null) {
1041 future = this.broker.commitConfigurationDataDelete(mountPoint, normalizedII);
1043 future = this.broker.commitConfigurationDataDelete(normalizedII);
1048 } catch (final InterruptedException e) {
1049 throw new RestconfDocumentedException(e.getMessage(), e);
1050 } catch (final ExecutionException e) {
1051 final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
1052 Predicates.instanceOf(ModifiedNodeDoesNotExistException.class)).toJavaUtil();
1053 if (searchedException.isPresent()) {
1054 throw new RestconfDocumentedException("Data specified for delete doesn't exist.", ErrorType.APPLICATION,
1055 ErrorTag.DATA_MISSING, e);
1058 throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), Throwables.getCauseAs(e,
1059 TransactionCommitFailedException.class));
1062 return Response.status(Status.OK).build();
1066 * Subscribes to some path in schema context (stream) to listen on changes
1070 * Additional parameters for subscribing to stream are loaded via rpc input
1073 * <li>datastore - default CONFIGURATION (other values of
1074 * {@link LogicalDatastoreType} enum type)</li>
1075 * <li>scope - default BASE (other values of {@link DataChangeScope})</li>
1079 public NormalizedNodeContext subscribeToStream(final String identifier, final UriInfo uriInfo) {
1080 boolean startTimeUsed = false;
1081 boolean stopTimeUsed = false;
1082 Instant start = Instant.now();
1083 Instant stop = null;
1084 boolean filterUsed = false;
1085 String filter = null;
1086 boolean leafNodesOnlyUsed = false;
1087 boolean leafNodesOnly = false;
1089 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
1090 switch (entry.getKey()) {
1092 if (!startTimeUsed) {
1093 startTimeUsed = true;
1094 start = parseDateFromQueryParam(entry);
1096 throw new RestconfDocumentedException("Start-time parameter can be used only once.");
1100 if (!stopTimeUsed) {
1101 stopTimeUsed = true;
1102 stop = parseDateFromQueryParam(entry);
1104 throw new RestconfDocumentedException("Stop-time parameter can be used only once.");
1110 filter = entry.getValue().iterator().next();
1112 throw new RestconfDocumentedException("Filter parameter can be used only once.");
1115 case "odl-leaf-nodes-only":
1116 if (!leafNodesOnlyUsed) {
1117 leafNodesOnlyUsed = true;
1118 leafNodesOnly = Boolean.parseBoolean(entry.getValue().iterator().next());
1120 throw new RestconfDocumentedException("Odl-leaf-nodes-only parameter can be used only once.");
1124 throw new RestconfDocumentedException("Bad parameter used with notifications: " + entry.getKey());
1127 if (!startTimeUsed && stopTimeUsed) {
1128 throw new RestconfDocumentedException("Stop-time parameter has to be used with start-time parameter.");
1130 URI response = null;
1131 if (identifier.contains(DATA_SUBSCR)) {
1132 response = dataSubs(identifier, uriInfo, start, stop, filter, leafNodesOnly);
1133 } else if (identifier.contains(NOTIFICATION_STREAM)) {
1134 response = notifStream(identifier, uriInfo, start, stop, filter);
1137 if (response != null) {
1138 // prepare node with value of location
1139 final InstanceIdentifierContext<?> iid = prepareIIDSubsStreamOutput();
1140 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> builder =
1141 ImmutableLeafNodeBuilder.create().withValue(response.toString());
1142 builder.withNodeIdentifier(
1143 NodeIdentifier.create(QName.create("subscribe:to:notification", "2016-10-28", "location")));
1145 // prepare new header with location
1146 final Map<String, Object> headers = new HashMap<>();
1147 headers.put("Location", response);
1149 return new NormalizedNodeContext(iid, builder.build(), headers);
1152 final String msg = "Bad type of notification of sal-remote";
1154 throw new RestconfDocumentedException(msg);
1157 private static Instant parseDateFromQueryParam(final Entry<String, List<String>> entry) {
1158 final DateAndTime event = new DateAndTime(entry.getValue().iterator().next());
1159 final String value = event.getValue();
1160 final TemporalAccessor p;
1162 p = FORMATTER.parse(value);
1163 } catch (final DateTimeParseException e) {
1164 throw new RestconfDocumentedException("Cannot parse of value in date: " + value, e);
1166 return Instant.from(p);
1170 * Prepare instance identifier.
1172 * @return {@link InstanceIdentifierContext} of location leaf for
1175 private InstanceIdentifierContext<?> prepareIIDSubsStreamOutput() {
1176 final QName qnameBase = QName.create("subscribe:to:notification", "2016-10-28", "notifi");
1177 final SchemaContext schemaCtx = controllerContext.getGlobalSchema();
1178 final DataSchemaNode location = ((ContainerSchemaNode) schemaCtx
1179 .findModule(qnameBase.getModule()).orElse(null)
1180 .getDataChildByName(qnameBase)).getDataChildByName(QName.create(qnameBase, "location"));
1181 final List<PathArgument> path = new ArrayList<>();
1182 path.add(NodeIdentifier.create(qnameBase));
1183 path.add(NodeIdentifier.create(QName.create(qnameBase, "location")));
1185 return new InstanceIdentifierContext<SchemaNode>(YangInstanceIdentifier.create(path), location, null,
1190 * Register notification listener by stream name.
1197 * stop-time of getting notification
1199 * start-time of getting notification
1201 * indicate which subset of all possible events are of interest
1202 * @return {@link URI} of location
1204 private URI notifStream(final String identifier, final UriInfo uriInfo, final Instant start,
1205 final Instant stop, final String filter) {
1206 final String streamName = Notificator.createStreamNameFromUri(identifier);
1207 if (Strings.isNullOrEmpty(streamName)) {
1208 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1210 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
1211 if (listeners == null || listeners.isEmpty()) {
1212 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1213 ErrorTag.UNKNOWN_ELEMENT);
1216 for (final NotificationListenerAdapter listener : listeners) {
1217 this.broker.registerToListenNotification(listener);
1218 listener.setQueryParams(start, Optional.ofNullable(stop), Optional.ofNullable(filter), false);
1221 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1223 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance(NOTIFICATION_PORT);
1224 final int notificationPort = webSocketServerInstance.getPort();
1227 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme(getWsScheme(uriInfo));
1229 return uriToWebsocketServerBuilder.replacePath(streamName).build();
1232 private static String getWsScheme(final UriInfo uriInfo) {
1233 URI uri = uriInfo.getAbsolutePath();
1237 String subscriptionScheme = uri.getScheme().toLowerCase(Locale.ROOT);
1238 return subscriptionScheme.equals("https") ? "wss" : "ws";
1242 * Register data change listener by stream name.
1249 * start-time of getting notification
1251 * stop-time of getting notification
1253 * indicate which subset of all possible events are of interest
1254 * @return {@link URI} of location
1256 private URI dataSubs(final String identifier, final UriInfo uriInfo, final Instant start, final Instant stop,
1257 final String filter, final boolean leafNodesOnly) {
1258 final String streamName = Notificator.createStreamNameFromUri(identifier);
1259 if (Strings.isNullOrEmpty(streamName)) {
1260 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1263 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1264 if (listener == null) {
1265 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1266 ErrorTag.UNKNOWN_ELEMENT);
1268 listener.setQueryParams(start, Optional.ofNullable(stop), Optional.ofNullable(filter), leafNodesOnly);
1270 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1271 final LogicalDatastoreType datastore =
1272 parserURIEnumParameter(LogicalDatastoreType.class, paramToValues.get(DATASTORE_PARAM_NAME));
1273 if (datastore == null) {
1274 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1275 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1277 final DataChangeScope scope =
1278 parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
1279 if (scope == null) {
1280 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1281 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1284 this.broker.registerToListenDataChanges(datastore, scope, listener);
1286 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1288 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance(NOTIFICATION_PORT);
1289 final int notificationPort = webSocketServerInstance.getPort();
1291 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme(getWsScheme(uriInfo));
1293 return uriToWebsocketServerBuilder.replacePath(streamName).build();
1296 @SuppressWarnings("checkstyle:IllegalCatch")
1298 public PatchStatusContext patchConfigurationData(final String identifier, final PatchContext context,
1299 final UriInfo uriInfo) {
1300 if (context == null) {
1301 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1305 return this.broker.patchConfigurationDataWithinTransaction(context);
1306 } catch (final Exception e) {
1307 LOG.debug("Patch transaction failed", e);
1308 throw new RestconfDocumentedException(e.getMessage(), e);
1312 @SuppressWarnings("checkstyle:IllegalCatch")
1314 public PatchStatusContext patchConfigurationData(final PatchContext context, @Context final UriInfo uriInfo) {
1315 if (context == null) {
1316 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1320 return this.broker.patchConfigurationDataWithinTransaction(context);
1321 } catch (final Exception e) {
1322 LOG.debug("Patch transaction failed", e);
1323 throw new RestconfDocumentedException(e.getMessage(), e);
1328 * Load parameter for subscribing to stream from input composite node.
1332 * @return enum object if its string value is equal to {@code paramName}. In
1335 private static <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1336 final String paramName) {
1337 final Optional<DataContainerChild<? extends PathArgument, ?>> optAugNode = value.getChild(
1338 SAL_REMOTE_AUG_IDENTIFIER);
1339 if (!optAugNode.isPresent()) {
1342 final DataContainerChild<? extends PathArgument, ?> augNode = optAugNode.get();
1343 if (!(augNode instanceof AugmentationNode)) {
1346 final Optional<DataContainerChild<? extends PathArgument, ?>> enumNode = ((AugmentationNode) augNode).getChild(
1347 new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1348 if (!enumNode.isPresent()) {
1351 final Object rawValue = enumNode.get().getValue();
1352 if (!(rawValue instanceof String)) {
1356 return resolveAsEnum(classDescriptor, (String) rawValue);
1360 * Checks whether {@code value} is one of the string representation of
1361 * enumeration {@code classDescriptor}.
1363 * @return enum object if string value of {@code classDescriptor}
1364 * enumeration is equal to {@code value}. Other cases null.
1366 private static <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1367 if (Strings.isNullOrEmpty(value)) {
1370 return resolveAsEnum(classDescriptor, value);
1373 private static <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1374 final T[] enumConstants = classDescriptor.getEnumConstants();
1375 if (enumConstants != null) {
1376 for (final T enm : classDescriptor.getEnumConstants()) {
1377 if (((Enum<?>) enm).name().equals(value)) {
1385 private static Map<String, String> resolveValuesFromUri(final String uri) {
1386 final Map<String, String> result = new HashMap<>();
1387 final String[] tokens = uri.split("/");
1388 for (int i = 1; i < tokens.length; i++) {
1389 final String[] parameterTokens = tokens[i].split("=");
1390 if (parameterTokens.length == 2) {
1391 result.put(parameterTokens[0], parameterTokens[1]);
1397 private MapNode makeModuleMapNode(final Set<Module> modules) {
1398 Preconditions.checkNotNull(modules);
1399 final Module restconfModule = getRestconfModule();
1400 final DataSchemaNode moduleSchemaNode = this.controllerContext
1401 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1402 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1404 final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder =
1405 Builders.mapBuilder((ListSchemaNode) moduleSchemaNode);
1407 for (final Module module : modules) {
1408 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1410 return listModuleBuilder.build();
1413 private MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1414 Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1415 "moduleSchemaNode has to be of type ListSchemaNode");
1416 final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1417 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues =
1418 Builders.mapEntryBuilder(listModuleSchemaNode);
1420 List<DataSchemaNode> instanceDataChildrenByName =
1421 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "name");
1422 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1423 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1425 .withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName()).build());
1427 final QNameModule qNameModule = module.getQNameModule();
1429 instanceDataChildrenByName =
1430 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "revision");
1431 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1432 Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1433 final Optional<Revision> revision = qNameModule.getRevision();
1434 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode)
1435 .withValue(revision.map(Revision::toString).orElse("")).build());
1437 instanceDataChildrenByName =
1438 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "namespace");
1439 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1440 Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1441 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1442 .withValue(qNameModule.getNamespace().toString()).build());
1444 instanceDataChildrenByName =
1445 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "feature");
1446 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1447 Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1448 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder =
1449 Builders.leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1450 for (final FeatureDefinition feature : module.getFeatures()) {
1451 featuresBuilder.withChild(Builders.leafSetEntryBuilder((LeafListSchemaNode) featureSchemaNode)
1452 .withValue(feature.getQName().getLocalName()).build());
1454 moduleNodeValues.withChild(featuresBuilder.build());
1456 return moduleNodeValues.build();
1459 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1460 Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1461 "streamSchemaNode has to be of type ListSchemaNode");
1462 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1463 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues =
1464 Builders.mapEntryBuilder(listStreamSchemaNode);
1466 List<DataSchemaNode> instanceDataChildrenByName =
1467 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "name");
1468 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1469 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1470 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName).build());
1472 instanceDataChildrenByName =
1473 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "description");
1474 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1475 Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1476 streamNodeValues.withChild(
1477 Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue("DESCRIPTION_PLACEHOLDER").build());
1479 instanceDataChildrenByName =
1480 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-support");
1481 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1482 Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1483 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1484 .withValue(Boolean.TRUE).build());
1486 instanceDataChildrenByName =
1487 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-log-creation-time");
1488 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1489 Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1490 streamNodeValues.withChild(
1491 Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode).withValue("").build());
1493 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "events");
1494 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1495 Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1496 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode).build());
1498 return streamNodeValues.build();
1502 * Prepare stream for notification.
1505 * contains list of qnames of notifications
1506 * @return - checked future object
1508 private ListenableFuture<DOMRpcResult> invokeSalRemoteRpcNotifiStrRPC(final NormalizedNodeContext payload) {
1509 final ContainerNode data = (ContainerNode) payload.getData();
1510 LeafSetNode leafSet = null;
1511 String outputType = "XML";
1512 for (final DataContainerChild<? extends PathArgument, ?> dataChild : data.getValue()) {
1513 if (dataChild instanceof LeafSetNode) {
1514 leafSet = (LeafSetNode) dataChild;
1515 } else if (dataChild instanceof AugmentationNode) {
1516 outputType = (String) ((AugmentationNode) dataChild).getValue().iterator().next().getValue();
1520 final Collection<LeafSetEntryNode> entryNodes = leafSet.getValue();
1521 final List<SchemaPath> paths = new ArrayList<>();
1522 String streamName = CREATE_NOTIFICATION_STREAM + "/";
1524 StringBuilder streamNameBuilder = new StringBuilder(streamName);
1525 final Iterator<LeafSetEntryNode> iterator = entryNodes.iterator();
1526 while (iterator.hasNext()) {
1527 final QName valueQName = QName.create((String) iterator.next().getValue());
1528 final Module module = controllerContext.findModuleByNamespace(valueQName.getModule().getNamespace());
1529 Preconditions.checkNotNull(module,
1530 "Module for namespace " + valueQName.getModule().getNamespace() + " does not exist");
1531 NotificationDefinition notifiDef = null;
1532 for (final NotificationDefinition notification : module.getNotifications()) {
1533 if (notification.getQName().equals(valueQName)) {
1534 notifiDef = notification;
1538 final String moduleName = module.getName();
1539 Preconditions.checkNotNull(notifiDef,
1540 "Notification " + valueQName + "doesn't exist in module " + moduleName);
1541 paths.add(notifiDef.getPath());
1542 streamNameBuilder.append(moduleName).append(':').append(valueQName.getLocalName());
1543 if (iterator.hasNext()) {
1544 streamNameBuilder.append(',');
1548 streamName = streamNameBuilder.toString();
1550 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
1551 final QName outputQname = QName.create(rpcQName, "output");
1552 final QName streamNameQname = QName.create(rpcQName, "notification-stream-identifier");
1554 final ContainerNode output =
1555 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
1556 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
1558 if (!Notificator.existNotificationListenerFor(streamName)) {
1559 Notificator.createNotificationListener(paths, streamName, outputType, controllerContext);
1562 return Futures.immediateFuture(new DefaultDOMRpcResult(output));