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.CharMatcher;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Predicates;
14 import com.google.common.base.Splitter;
15 import com.google.common.base.Strings;
16 import com.google.common.base.Throwables;
17 import com.google.common.collect.ImmutableSet;
18 import com.google.common.collect.Iterables;
19 import com.google.common.collect.Maps;
20 import com.google.common.util.concurrent.FluentFuture;
21 import com.google.common.util.concurrent.Futures;
22 import com.google.common.util.concurrent.ListenableFuture;
24 import java.time.Instant;
25 import java.time.format.DateTimeFormatter;
26 import java.time.format.DateTimeFormatterBuilder;
27 import java.time.format.DateTimeParseException;
28 import java.time.temporal.ChronoField;
29 import java.time.temporal.TemporalAccessor;
30 import java.util.AbstractMap.SimpleImmutableEntry;
31 import java.util.ArrayList;
32 import java.util.Collection;
33 import java.util.Collections;
34 import java.util.HashMap;
35 import java.util.Iterator;
36 import java.util.List;
37 import java.util.Locale;
39 import java.util.Map.Entry;
40 import java.util.Objects;
41 import java.util.Optional;
43 import java.util.concurrent.CancellationException;
44 import java.util.concurrent.ExecutionException;
45 import javax.ws.rs.core.Context;
46 import javax.ws.rs.core.Response;
47 import javax.ws.rs.core.Response.ResponseBuilder;
48 import javax.ws.rs.core.Response.Status;
49 import javax.ws.rs.core.UriBuilder;
50 import javax.ws.rs.core.UriInfo;
51 import org.opendaylight.mdsal.common.api.CommitInfo;
52 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
53 import org.opendaylight.mdsal.common.api.OptimisticLockFailedException;
54 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
55 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
56 import org.opendaylight.mdsal.dom.api.DOMRpcImplementationNotAvailableException;
57 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
58 import org.opendaylight.mdsal.dom.api.DOMRpcService;
59 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
60 import org.opendaylight.netconf.sal.rest.api.Draft02;
61 import org.opendaylight.netconf.sal.rest.api.RestconfService;
62 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
63 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
64 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
65 import org.opendaylight.netconf.sal.streams.websockets.WebSocketServer;
66 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
67 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
68 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
69 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
70 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
71 import org.opendaylight.restconf.common.patch.PatchContext;
72 import org.opendaylight.restconf.common.patch.PatchStatusContext;
73 import org.opendaylight.restconf.common.util.DataChangeScope;
74 import org.opendaylight.restconf.common.validation.RestconfValidationUtils;
75 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
76 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
77 import org.opendaylight.yangtools.yang.common.Empty;
78 import org.opendaylight.yangtools.yang.common.QName;
79 import org.opendaylight.yangtools.yang.common.QNameModule;
80 import org.opendaylight.yangtools.yang.common.Revision;
81 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
82 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
83 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
84 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
85 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
86 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
87 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
88 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
89 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
90 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
91 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
92 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
93 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
94 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
95 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
96 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
97 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
98 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
99 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
100 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
101 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeBuilder;
102 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
103 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
104 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
105 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
106 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
107 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
108 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
109 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
110 import org.opendaylight.yangtools.yang.model.api.Module;
111 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
112 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
113 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
114 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
115 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
116 import org.opendaylight.yangtools.yang.model.util.SimpleSchemaContext;
117 import org.slf4j.Logger;
118 import org.slf4j.LoggerFactory;
120 public final class RestconfImpl implements RestconfService {
122 * Notifications are served on port 8181.
124 private static final int NOTIFICATION_PORT = 8181;
126 private static final int CHAR_NOT_FOUND = -1;
128 private static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
130 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
132 private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
134 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
136 private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
138 private static final String DATASTORE_PARAM_NAME = "datastore";
140 private static final String SCOPE_PARAM_NAME = "scope";
142 private static final String OUTPUT_TYPE_PARAM_NAME = "notification-output-type";
144 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
146 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
148 private static final QName NETCONF_BASE_QNAME = QName.create(QNameModule.create(URI.create(NETCONF_BASE)),
149 NETCONF_BASE_PAYLOAD_NAME).intern();
151 private static final QNameModule SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
152 Revision.of("2014-07-08"));
154 private static final AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER =
155 new AugmentationIdentifier(ImmutableSet.of(
156 QName.create(SAL_REMOTE_AUGMENT, "scope"), QName.create(SAL_REMOTE_AUGMENT, "datastore"),
157 QName.create(SAL_REMOTE_AUGMENT, "notification-output-type")));
159 public static final CharSequence DATA_SUBSCR = "data-change-event-subscription";
160 private static final CharSequence CREATE_DATA_SUBSCR = "create-" + DATA_SUBSCR;
162 public static final CharSequence NOTIFICATION_STREAM = "notification-stream";
163 private static final CharSequence CREATE_NOTIFICATION_STREAM = "create-" + NOTIFICATION_STREAM;
165 private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
166 .appendValue(ChronoField.YEAR, 4).appendLiteral('-')
167 .appendValue(ChronoField.MONTH_OF_YEAR, 2).appendLiteral('-')
168 .appendValue(ChronoField.DAY_OF_MONTH, 2).appendLiteral('T')
169 .appendValue(ChronoField.HOUR_OF_DAY, 2).appendLiteral(':')
170 .appendValue(ChronoField.MINUTE_OF_HOUR, 2).appendLiteral(':')
171 .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
172 .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
173 .appendOffset("+HH:MM", "Z").toFormatter();
175 private final BrokerFacade broker;
177 private final ControllerContext controllerContext;
179 private RestconfImpl(final BrokerFacade broker, final ControllerContext controllerContext) {
180 this.broker = broker;
181 this.controllerContext = controllerContext;
184 public static RestconfImpl newInstance(final BrokerFacade broker, final ControllerContext controllerContext) {
185 return new RestconfImpl(broker, controllerContext);
189 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
190 final Set<Module> allModules = this.controllerContext.getAllModules();
191 final MapNode allModuleMap = makeModuleMapNode(allModules);
193 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
195 final Module restconfModule = getRestconfModule();
196 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
197 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
198 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
200 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
201 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
202 moduleContainerBuilder.withChild(allModuleMap);
204 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode, null, schemaContext),
205 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
209 * Valid only for mount point.
212 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
213 Preconditions.checkNotNull(identifier);
214 if (!identifier.contains(ControllerContext.MOUNT)) {
215 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
216 + " URI has to end with " + ControllerContext.MOUNT;
217 LOG.debug("{} for {}", errMsg, identifier);
218 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
221 final InstanceIdentifierContext<?> mountPointIdentifier =
222 this.controllerContext.toMountPointIdentifier(identifier);
223 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
224 final Set<Module> modules = this.controllerContext.getAllModules(mountPoint);
225 final MapNode mountPointModulesMap = makeModuleMapNode(modules);
227 final Module restconfModule = getRestconfModule();
228 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
229 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
230 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
232 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
233 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
234 moduleContainerBuilder.withChild(mountPointModulesMap);
236 return new NormalizedNodeContext(
237 new InstanceIdentifierContext<>(null, modulesSchemaNode, mountPoint,
238 this.controllerContext.getGlobalSchema()),
239 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
243 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
244 Preconditions.checkNotNull(identifier);
245 final Entry<String, Revision> nameRev = getModuleNameAndRevision(identifier);
246 Module module = null;
247 DOMMountPoint mountPoint = null;
248 final SchemaContext schemaContext;
249 if (identifier.contains(ControllerContext.MOUNT)) {
250 final InstanceIdentifierContext<?> mountPointIdentifier =
251 this.controllerContext.toMountPointIdentifier(identifier);
252 mountPoint = mountPointIdentifier.getMountPoint();
253 module = this.controllerContext.findModuleByNameAndRevision(mountPoint, nameRev.getKey(),
255 schemaContext = mountPoint.getSchemaContext();
257 module = this.controllerContext.findModuleByNameAndRevision(nameRev.getKey(), nameRev.getValue());
258 schemaContext = this.controllerContext.getGlobalSchema();
261 if (module == null) {
262 LOG.debug("Module with name '{}' and revision '{}' was not found.", nameRev.getKey(), nameRev.getValue());
263 throw new RestconfDocumentedException("Module with name '" + nameRev.getKey() + "' and revision '"
264 + nameRev.getValue() + "' was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
267 final Module restconfModule = getRestconfModule();
268 final Set<Module> modules = Collections.singleton(module);
269 final MapNode moduleMap = makeModuleMapNode(modules);
271 final DataSchemaNode moduleSchemaNode = this.controllerContext
272 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
273 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
275 return new NormalizedNodeContext(
276 new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint, schemaContext), moduleMap,
277 QueryParametersParser.parseWriterParameters(uriInfo));
281 public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
282 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
283 final Set<String> availableStreams = Notificator.getStreamNames();
284 final Module restconfModule = getRestconfModule();
285 final DataSchemaNode streamSchemaNode = this.controllerContext
286 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
287 Preconditions.checkState(streamSchemaNode instanceof ListSchemaNode);
289 final CollectionNodeBuilder<MapEntryNode, MapNode> listStreamsBuilder =
290 Builders.mapBuilder((ListSchemaNode) streamSchemaNode);
292 for (final String streamName : availableStreams) {
293 listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
296 final DataSchemaNode streamsContainerSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
297 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
298 Preconditions.checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
300 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
301 Builders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
302 streamsContainerBuilder.withChild(listStreamsBuilder.build());
304 return new NormalizedNodeContext(
305 new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null, schemaContext),
306 streamsContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
310 public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
311 final Set<Module> allModules = this.controllerContext.getAllModules();
312 return operationsFromModulesToNormalizedContext(allModules, null);
316 public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
317 Set<Module> modules = null;
318 DOMMountPoint mountPoint = null;
319 if (identifier.contains(ControllerContext.MOUNT)) {
320 final InstanceIdentifierContext<?> mountPointIdentifier =
321 this.controllerContext.toMountPointIdentifier(identifier);
322 mountPoint = mountPointIdentifier.getMountPoint();
323 modules = this.controllerContext.getAllModules(mountPoint);
326 final String errMsg = "URI has bad format. If operations behind mount point should be showed, URI has to "
327 + " end with " + ControllerContext.MOUNT;
328 LOG.debug("{} for {}", errMsg, identifier);
329 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
332 return operationsFromModulesToNormalizedContext(modules, mountPoint);
336 * Special case only for GET restconf/operations use (since moment of
337 * pre-Beryllium Yang parser and Yang model API removal). The method is
338 * creating fake schema context with fake module and fake data by use own
339 * implementations of schema nodes and module.
342 * set of modules for get RPCs from every module
344 * mount point, if in use otherwise null
345 * @return {@link NormalizedNodeContext}
347 private static NormalizedNodeContext operationsFromModulesToNormalizedContext(final Set<Module> modules,
348 final DOMMountPoint mountPoint) {
350 final Collection<Module> neededModules = new ArrayList<>(modules.size());
351 final ArrayList<LeafSchemaNode> fakeRpcSchema = new ArrayList<>();
353 for (final Module m : modules) {
354 final Set<RpcDefinition> rpcs = m.getRpcs();
355 if (!rpcs.isEmpty()) {
356 neededModules.add(m);
358 fakeRpcSchema.ensureCapacity(fakeRpcSchema.size() + rpcs.size());
359 rpcs.forEach(rpc -> fakeRpcSchema.add(new FakeLeafSchemaNode(rpc.getQName())));
363 final ContainerSchemaNode fakeCont = new FakeContainerSchemaNode(fakeRpcSchema);
364 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> containerBuilder =
365 Builders.containerBuilder(fakeCont);
367 for (final LeafSchemaNode leaf : fakeRpcSchema) {
368 containerBuilder.withChild(Builders.leafBuilder(leaf).withValue(Empty.getInstance()).build());
371 final Collection<Module> fakeModules = new ArrayList<>(neededModules.size() + 1);
372 neededModules.forEach(imp -> fakeModules.add(new FakeImportedModule(imp)));
373 fakeModules.add(new FakeRestconfModule(neededModules, fakeCont));
375 final SchemaContext fakeSchemaCtx = SimpleSchemaContext.forModules(ImmutableSet.copyOf(fakeModules));
376 final InstanceIdentifierContext<ContainerSchemaNode> instanceIdentifierContext =
377 new InstanceIdentifierContext<>(null, fakeCont, mountPoint, fakeSchemaCtx);
378 return new NormalizedNodeContext(instanceIdentifierContext, containerBuilder.build());
381 private Module getRestconfModule() {
382 final Module restconfModule = this.controllerContext.getRestconfModule();
383 if (restconfModule == null) {
384 LOG.debug("ietf-restconf module was not found.");
385 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
386 ErrorTag.OPERATION_NOT_SUPPORTED);
389 return restconfModule;
392 private static Entry<String, Revision> getModuleNameAndRevision(final String identifier) {
393 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
394 String moduleNameAndRevision = "";
395 if (mountIndex >= 0) {
396 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
398 moduleNameAndRevision = identifier;
401 final Splitter splitter = Splitter.on('/').omitEmptyStrings();
402 final List<String> pathArgs = splitter.splitToList(moduleNameAndRevision);
403 if (pathArgs.size() < 2) {
404 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' {}", identifier);
405 throw new RestconfDocumentedException(
406 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
407 ErrorTag.INVALID_VALUE);
411 return new SimpleImmutableEntry<>(pathArgs.get(0), Revision.of(pathArgs.get(1)));
412 } catch (final DateTimeParseException e) {
413 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' {}", identifier);
414 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
415 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
420 public Object getRoot() {
425 public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload,
426 final UriInfo uriInfo) {
427 if (payload == null) {
428 // no payload specified, reroute this to no payload invokeRpc implementation
429 return invokeRpc(identifier, "", uriInfo);
432 final SchemaPath type = payload.getInstanceIdentifierContext().getSchemaNode().getPath();
433 final URI namespace = payload.getInstanceIdentifierContext().getSchemaNode().getQName().getNamespace();
434 final ListenableFuture<DOMRpcResult> response;
435 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
436 final SchemaContext schemaContext;
438 if (mountPoint != null) {
439 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
440 if (!mountRpcServices.isPresent()) {
441 LOG.debug("Error: Rpc service is missing.");
442 throw new RestconfDocumentedException("Rpc service is missing.");
444 schemaContext = mountPoint.getSchemaContext();
445 response = mountRpcServices.get().invokeRpc(type, payload.getData());
447 if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
448 if (identifier.contains(CREATE_DATA_SUBSCR)) {
449 response = invokeSalRemoteRpcSubscribeRPC(payload);
450 } else if (identifier.contains(CREATE_NOTIFICATION_STREAM)) {
451 response = invokeSalRemoteRpcNotifiStrRPC(payload);
453 final String msg = "Not supported operation";
455 throw new RestconfDocumentedException(msg, ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED);
458 response = this.broker.invokeRpc(type, payload.getData());
460 schemaContext = this.controllerContext.getGlobalSchema();
463 final DOMRpcResult result = checkRpcResponse(response);
465 RpcDefinition resultNodeSchema = null;
466 final NormalizedNode<?, ?> resultData;
467 if (result != null && result.getResult() != null) {
468 resultData = result.getResult();
469 resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
474 return new NormalizedNodeContext(
475 new InstanceIdentifierContext<>(null, resultNodeSchema, mountPoint, schemaContext),
476 resultData, QueryParametersParser.parseWriterParameters(uriInfo));
480 public NormalizedNodeContext invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
481 if (noPayload != null && !CharMatcher.whitespace().matchesAllOf(noPayload)) {
482 throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
485 String identifierEncoded = null;
486 DOMMountPoint mountPoint = null;
487 final SchemaContext schemaContext;
488 if (identifier.contains(ControllerContext.MOUNT)) {
489 // mounted RPC call - look up mount instance.
490 final InstanceIdentifierContext<?> mountPointId = this.controllerContext.toMountPointIdentifier(identifier);
491 mountPoint = mountPointId.getMountPoint();
492 schemaContext = mountPoint.getSchemaContext();
493 final int startOfRemoteRpcName =
494 identifier.lastIndexOf(ControllerContext.MOUNT) + ControllerContext.MOUNT.length() + 1;
495 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
496 identifierEncoded = remoteRpcName;
498 } else if (identifier.indexOf('/') != CHAR_NOT_FOUND) {
499 LOG.debug("Identifier {} cannot contain slash character (/).", identifier);
500 throw new RestconfDocumentedException(String.format("Identifier %n%s%ncan\'t contain slash character (/).%n"
501 + "If slash is part of identifier name then use %%2F placeholder.", identifier), ErrorType.PROTOCOL,
502 ErrorTag.INVALID_VALUE);
504 identifierEncoded = identifier;
505 schemaContext = this.controllerContext.getGlobalSchema();
508 final String identifierDecoded = this.controllerContext.urlPathArgDecode(identifierEncoded);
510 RpcDefinition rpc = null;
511 if (mountPoint == null) {
512 rpc = this.controllerContext.getRpcDefinition(identifierDecoded);
514 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
518 LOG.debug("RPC {} does not exist.", identifierDecoded);
519 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
522 if (!rpc.getInput().getChildNodes().isEmpty()) {
523 LOG.debug("RPC {} does not need input value.", rpc);
524 throw new RestconfDocumentedException("RPC " + rpc + " does not take any input value.",
525 ErrorType.RPC, ErrorTag.INVALID_VALUE);
528 final ListenableFuture<DOMRpcResult> response;
529 if (mountPoint != null) {
530 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
531 if (!mountRpcServices.isPresent()) {
532 throw new RestconfDocumentedException("Rpc service is missing.");
534 response = mountRpcServices.get().invokeRpc(rpc.getPath(), null);
536 response = this.broker.invokeRpc(rpc.getPath(), null);
539 final DOMRpcResult result = checkRpcResponse(response);
541 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpc, mountPoint, schemaContext),
542 result.getResult(), QueryParametersParser.parseWriterParameters(uriInfo));
545 @SuppressWarnings("checkstyle:avoidHidingCauseException")
546 private static DOMRpcResult checkRpcResponse(final ListenableFuture<DOMRpcResult> response) {
547 if (response == null) {
551 final DOMRpcResult retValue = response.get();
552 if (retValue.getErrors().isEmpty()) {
555 LOG.debug("RpcError message {}", retValue.getErrors());
556 throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
557 } catch (final InterruptedException e) {
558 final String errMsg = "The operation was interrupted while executing and did not complete.";
559 LOG.debug("Rpc Interrupt - {}", errMsg, e);
560 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION, e);
561 } catch (final ExecutionException e) {
562 LOG.debug("Execution RpcError: ", e);
563 Throwable cause = e.getCause();
565 while (cause.getCause() != null) {
566 cause = cause.getCause();
569 if (cause instanceof IllegalArgumentException) {
570 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL,
571 ErrorTag.INVALID_VALUE);
572 } else if (cause instanceof DOMRpcImplementationNotAvailableException) {
573 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.APPLICATION,
574 ErrorTag.OPERATION_NOT_SUPPORTED);
576 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
579 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
582 } catch (final CancellationException e) {
583 final String errMsg = "The operation was cancelled while executing.";
584 LOG.debug("Cancel RpcExecution: {}", errMsg, e);
585 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
589 private static void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
590 if (inputSchema != null && payload.getData() == null) {
591 // expected a non null payload
592 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
593 } else if (inputSchema == null && payload.getData() != null) {
594 // did not expect any input
595 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
599 private ListenableFuture<DOMRpcResult> invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
600 final ContainerNode value = (ContainerNode) payload.getData();
601 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
602 final java.util.Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(
603 new NodeIdentifier(QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(),
605 final Object pathValue = path.isPresent() ? path.get().getValue() : null;
607 if (!(pathValue instanceof YangInstanceIdentifier)) {
608 LOG.debug("Instance identifier {} was not normalized correctly", rpcQName);
609 throw new RestconfDocumentedException("Instance identifier was not normalized correctly",
610 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
613 final YangInstanceIdentifier pathIdentifier = (YangInstanceIdentifier) pathValue;
614 String streamName = (String) CREATE_DATA_SUBSCR;
615 NotificationOutputType outputType = null;
616 if (!pathIdentifier.isEmpty()) {
617 final String fullRestconfIdentifier =
618 DATA_SUBSCR + this.controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
620 LogicalDatastoreType datastore =
621 parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
622 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
624 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
625 scope = scope == null ? DEFAULT_SCOPE : scope;
627 outputType = parseEnumTypeParameter(value, NotificationOutputType.class, OUTPUT_TYPE_PARAM_NAME);
628 outputType = outputType == null ? NotificationOutputType.XML : outputType;
630 streamName = Notificator
631 .createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore + "/scope=" + scope);
634 if (Strings.isNullOrEmpty(streamName)) {
635 LOG.debug("Path is empty or contains value node which is not Container or List built-in type at {}",
637 throw new RestconfDocumentedException("Path is empty or contains value node which is not Container or List "
638 + "built-in type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
641 final QName outputQname = QName.create(rpcQName, "output");
642 final QName streamNameQname = QName.create(rpcQName, "stream-name");
644 final ContainerNode output =
645 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
646 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
648 if (!Notificator.existListenerFor(streamName)) {
649 Notificator.createListener(pathIdentifier, streamName, outputType, controllerContext);
652 return Futures.immediateFuture(new DefaultDOMRpcResult(output));
655 private static RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
656 final String[] splittedIdentifier = identifierDecoded.split(":");
657 if (splittedIdentifier.length != 2) {
658 LOG.debug("{} could not be split to 2 parts (module:rpc name)", identifierDecoded);
659 throw new RestconfDocumentedException(identifierDecoded + " could not be split to 2 parts "
660 + "(module:rpc name)", ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
662 for (final Module module : schemaContext.getModules()) {
663 if (module.getName().equals(splittedIdentifier[0])) {
664 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
665 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
666 return rpcDefinition;
675 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
676 boolean withDefaUsed = false;
677 String withDefa = null;
679 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
680 switch (entry.getKey()) {
681 case "with-defaults":
684 withDefa = entry.getValue().iterator().next();
686 throw new RestconfDocumentedException("With-defaults parameter can be used only once.");
690 LOG.info("Unknown key : {}.", entry.getKey());
694 boolean tagged = false;
696 if ("report-all-tagged".equals(withDefa)) {
700 if ("report-all".equals(withDefa)) {
705 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
706 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
707 NormalizedNode<?, ?> data = null;
708 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
709 if (mountPoint != null) {
710 data = this.broker.readConfigurationData(mountPoint, normalizedII, withDefa);
712 data = this.broker.readConfigurationData(normalizedII, withDefa);
715 throw dataMissing(identifier);
717 return new NormalizedNodeContext(iiWithData, data,
718 QueryParametersParser.parseWriterParameters(uriInfo, tagged));
722 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
723 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
724 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
725 NormalizedNode<?, ?> data = null;
726 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
727 if (mountPoint != null) {
728 data = this.broker.readOperationalData(mountPoint, normalizedII);
730 data = this.broker.readOperationalData(normalizedII);
733 throw dataMissing(identifier);
735 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
738 private static RestconfDocumentedException dataMissing(final String identifier) {
739 LOG.debug("Request could not be completed because the relevant data model content does not exist {}",
741 return new RestconfDocumentedException("Request could not be completed because the relevant data model content "
742 + "does not exist", ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
746 public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload,
747 final UriInfo uriInfo) {
748 boolean insertUsed = false;
749 boolean pointUsed = false;
750 String insert = null;
753 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
754 switch (entry.getKey()) {
758 insert = entry.getValue().iterator().next();
760 throw new RestconfDocumentedException("Insert parameter can be used only once.");
766 point = entry.getValue().iterator().next();
768 throw new RestconfDocumentedException("Point parameter can be used only once.");
772 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
776 if (pointUsed && !insertUsed) {
777 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
779 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
780 throw new RestconfDocumentedException(
781 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
784 Preconditions.checkNotNull(identifier);
786 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
788 validateInput(iiWithData.getSchemaNode(), payload);
789 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
790 validateListKeysEqualityInPayloadAndUri(payload);
792 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
793 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
796 * There is a small window where another write transaction could be
797 * updating the same data simultaneously and we get an
798 * OptimisticLockFailedException. This error is likely transient and The
799 * WriteTransaction#submit API docs state that a retry will likely
800 * succeed. So we'll try again if that scenario occurs. If it fails a
801 * third time then it probably will never succeed so we'll fail in that
804 * By retrying we're attempting to hide the internal implementation of
805 * the data store and how it handles concurrent updates from the
806 * restconf client. The client has instructed us to put the data and we
807 * should make every effort to do so without pushing optimistic lock
808 * failures back to the client and forcing them to handle it via retry
809 * (and having to document the behavior).
811 PutResult result = null;
814 if (mountPoint != null) {
816 result = this.broker.commitMountPointDataPut(mountPoint, normalizedII, payload.getData(), insert,
819 result = this.broker.commitConfigurationDataPut(this.controllerContext.getGlobalSchema(), normalizedII,
820 payload.getData(), insert, point);
824 result.getFutureOfPutData().get();
825 } catch (final InterruptedException e) {
826 LOG.debug("Update failed for {}", identifier, e);
827 throw new RestconfDocumentedException(e.getMessage(), e);
828 } catch (final ExecutionException e) {
829 final TransactionCommitFailedException failure = Throwables.getCauseAs(e,
830 TransactionCommitFailedException.class);
831 if (failure instanceof OptimisticLockFailedException) {
833 LOG.debug("Got OptimisticLockFailedException on last try - failing {}", identifier);
834 throw new RestconfDocumentedException(e.getMessage(), e, failure.getErrorList());
837 LOG.debug("Got OptimisticLockFailedException - trying again {}", identifier);
841 LOG.debug("Update failed for {}", identifier, e);
842 throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), failure);
845 return Response.status(result.getStatus()).build();
849 private static void validateTopLevelNodeName(final NormalizedNodeContext node,
850 final YangInstanceIdentifier identifier) {
852 final String payloadName = node.getData().getNodeType().getLocalName();
855 if (identifier.isEmpty()) {
857 if (!node.getData().getNodeType().equals(NETCONF_BASE_QNAME)) {
858 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
859 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
863 final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
864 if (!payloadName.equals(identifierName)) {
865 throw new RestconfDocumentedException(
866 "Payload name (" + payloadName + ") is different from identifier name (" + identifierName + ")",
867 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
873 * Validates whether keys in {@code payload} are equal to values of keys in
874 * {@code iiWithData} for list schema node.
876 * @throws RestconfDocumentedException
877 * if key values or key count in payload and URI isn't equal
880 private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
881 Preconditions.checkArgument(payload != null);
882 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
883 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
884 final SchemaNode schemaNode = iiWithData.getSchemaNode();
885 final NormalizedNode<?, ?> data = payload.getData();
886 if (schemaNode instanceof ListSchemaNode) {
887 final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
888 if (lastPathArgument instanceof NodeIdentifierWithPredicates && data instanceof MapEntryNode) {
889 final Map<QName, Object> uriKeyValues =
890 ((NodeIdentifierWithPredicates) lastPathArgument).getKeyValues();
891 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
897 public static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final MapEntryNode payload,
898 final List<QName> keyDefinitions) {
900 final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
901 for (final QName keyDefinition : keyDefinitions) {
902 final Object uriKeyValue = mutableCopyUriKeyValues.remove(keyDefinition);
903 // should be caught during parsing URI to InstanceIdentifier
904 RestconfValidationUtils.checkDocumentedError(uriKeyValue != null, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
905 "Missing key " + keyDefinition + " in URI.");
907 final Object dataKeyValue = payload.getIdentifier().getKeyValues().get(keyDefinition);
909 if (!Objects.deepEquals(uriKeyValue, dataKeyValue)) {
910 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName()
911 + "' specified in the URI doesn't match the value '" + dataKeyValue
912 + "' specified in the message body. ";
913 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
919 public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload,
920 final UriInfo uriInfo) {
921 return createConfigurationData(payload, uriInfo);
925 public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
926 if (payload == null) {
927 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
929 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
930 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
931 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
933 boolean insertUsed = false;
934 boolean pointUsed = false;
935 String insert = null;
938 if (uriInfo != null) {
939 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
940 switch (entry.getKey()) {
944 insert = entry.getValue().iterator().next();
946 throw new RestconfDocumentedException("Insert parameter can be used only once.");
952 point = entry.getValue().iterator().next();
954 throw new RestconfDocumentedException("Point parameter can be used only once.");
958 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
963 if (pointUsed && !insertUsed) {
964 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
966 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
967 throw new RestconfDocumentedException(
968 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
971 FluentFuture<? extends CommitInfo> future;
972 if (mountPoint != null) {
973 future = this.broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData(), insert,
976 future = this.broker.commitConfigurationDataPost(this.controllerContext.getGlobalSchema(), normalizedII,
977 payload.getData(), insert, point);
982 } catch (final InterruptedException e) {
983 LOG.info("Error creating data {}", uriInfo != null ? uriInfo.getPath() : "", e);
984 throw new RestconfDocumentedException(e.getMessage(), e);
985 } catch (final ExecutionException e) {
986 LOG.info("Error creating data {}", uriInfo != null ? uriInfo.getPath() : "", e);
987 throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), Throwables.getCauseAs(e,
988 TransactionCommitFailedException.class));
991 LOG.trace("Successfuly created data.");
993 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
994 // FIXME: Provide path to result.
995 final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
996 if (location != null) {
997 responseBuilder.location(location);
999 return responseBuilder.build();
1002 @SuppressWarnings("checkstyle:IllegalCatch")
1003 private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint,
1004 final YangInstanceIdentifier normalizedII) {
1005 if (uriInfo == null) {
1006 // This is null if invoked internally
1010 final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
1011 uriBuilder.path("config");
1013 uriBuilder.path(this.controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
1014 } catch (final Exception e) {
1015 LOG.info("Location for instance identifier {} was not created", normalizedII, e);
1018 return uriBuilder.build();
1022 public Response deleteConfigurationData(final String identifier) {
1023 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
1024 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
1025 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
1027 final FluentFuture<? extends CommitInfo> future;
1028 if (mountPoint != null) {
1029 future = this.broker.commitConfigurationDataDelete(mountPoint, normalizedII);
1031 future = this.broker.commitConfigurationDataDelete(normalizedII);
1036 } catch (final InterruptedException e) {
1037 throw new RestconfDocumentedException(e.getMessage(), e);
1038 } catch (final ExecutionException e) {
1039 final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
1040 Predicates.instanceOf(ModifiedNodeDoesNotExistException.class)).toJavaUtil();
1041 if (searchedException.isPresent()) {
1042 throw new RestconfDocumentedException("Data specified for delete doesn't exist.", ErrorType.APPLICATION,
1043 ErrorTag.DATA_MISSING, e);
1046 throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), Throwables.getCauseAs(e,
1047 TransactionCommitFailedException.class));
1050 return Response.status(Status.OK).build();
1054 * Subscribes to some path in schema context (stream) to listen on changes
1058 * Additional parameters for subscribing to stream are loaded via rpc input
1061 * <li>datastore - default CONFIGURATION (other values of
1062 * {@link LogicalDatastoreType} enum type)</li>
1063 * <li>scope - default BASE (other values of {@link DataChangeScope})</li>
1067 public NormalizedNodeContext subscribeToStream(final String identifier, final UriInfo uriInfo) {
1068 boolean startTimeUsed = false;
1069 boolean stopTimeUsed = false;
1070 Instant start = Instant.now();
1071 Instant stop = null;
1072 boolean filterUsed = false;
1073 String filter = null;
1074 boolean leafNodesOnlyUsed = false;
1075 boolean leafNodesOnly = false;
1077 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
1078 switch (entry.getKey()) {
1080 if (!startTimeUsed) {
1081 startTimeUsed = true;
1082 start = parseDateFromQueryParam(entry);
1084 throw new RestconfDocumentedException("Start-time parameter can be used only once.");
1088 if (!stopTimeUsed) {
1089 stopTimeUsed = true;
1090 stop = parseDateFromQueryParam(entry);
1092 throw new RestconfDocumentedException("Stop-time parameter can be used only once.");
1098 filter = entry.getValue().iterator().next();
1100 throw new RestconfDocumentedException("Filter parameter can be used only once.");
1103 case "odl-leaf-nodes-only":
1104 if (!leafNodesOnlyUsed) {
1105 leafNodesOnlyUsed = true;
1106 leafNodesOnly = Boolean.parseBoolean(entry.getValue().iterator().next());
1108 throw new RestconfDocumentedException("Odl-leaf-nodes-only parameter can be used only once.");
1112 throw new RestconfDocumentedException("Bad parameter used with notifications: " + entry.getKey());
1115 if (!startTimeUsed && stopTimeUsed) {
1116 throw new RestconfDocumentedException("Stop-time parameter has to be used with start-time parameter.");
1118 URI response = null;
1119 if (identifier.contains(DATA_SUBSCR)) {
1120 response = dataSubs(identifier, uriInfo, start, stop, filter, leafNodesOnly);
1121 } else if (identifier.contains(NOTIFICATION_STREAM)) {
1122 response = notifStream(identifier, uriInfo, start, stop, filter);
1125 if (response != null) {
1126 // prepare node with value of location
1127 final InstanceIdentifierContext<?> iid = prepareIIDSubsStreamOutput();
1128 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> builder =
1129 ImmutableLeafNodeBuilder.create().withValue(response.toString());
1130 builder.withNodeIdentifier(
1131 NodeIdentifier.create(QName.create("subscribe:to:notification", "2016-10-28", "location")));
1133 // prepare new header with location
1134 final Map<String, Object> headers = new HashMap<>();
1135 headers.put("Location", response);
1137 return new NormalizedNodeContext(iid, builder.build(), headers);
1140 final String msg = "Bad type of notification of sal-remote";
1142 throw new RestconfDocumentedException(msg);
1145 private static Instant parseDateFromQueryParam(final Entry<String, List<String>> entry) {
1146 final DateAndTime event = new DateAndTime(entry.getValue().iterator().next());
1147 final String value = event.getValue();
1148 final TemporalAccessor p;
1150 p = FORMATTER.parse(value);
1151 } catch (final DateTimeParseException e) {
1152 throw new RestconfDocumentedException("Cannot parse of value in date: " + value, e);
1154 return Instant.from(p);
1158 * Prepare instance identifier.
1160 * @return {@link InstanceIdentifierContext} of location leaf for
1163 private InstanceIdentifierContext<?> prepareIIDSubsStreamOutput() {
1164 final QName qnameBase = QName.create("subscribe:to:notification", "2016-10-28", "notifi");
1165 final SchemaContext schemaCtx = controllerContext.getGlobalSchema();
1166 final DataSchemaNode location = ((ContainerSchemaNode) schemaCtx
1167 .findModule(qnameBase.getModule()).orElse(null)
1168 .getDataChildByName(qnameBase)).getDataChildByName(QName.create(qnameBase, "location"));
1169 final List<PathArgument> path = new ArrayList<>();
1170 path.add(NodeIdentifier.create(qnameBase));
1171 path.add(NodeIdentifier.create(QName.create(qnameBase, "location")));
1173 return new InstanceIdentifierContext<SchemaNode>(YangInstanceIdentifier.create(path), location, null,
1178 * Register notification listener by stream name.
1185 * stop-time of getting notification
1187 * start-time of getting notification
1189 * indicate which subset of all possible events are of interest
1190 * @return {@link URI} of location
1192 private URI notifStream(final String identifier, final UriInfo uriInfo, final Instant start,
1193 final Instant stop, final String filter) {
1194 final String streamName = Notificator.createStreamNameFromUri(identifier);
1195 if (Strings.isNullOrEmpty(streamName)) {
1196 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1198 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
1199 if (listeners == null || listeners.isEmpty()) {
1200 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1201 ErrorTag.UNKNOWN_ELEMENT);
1204 for (final NotificationListenerAdapter listener : listeners) {
1205 this.broker.registerToListenNotification(listener);
1206 listener.setQueryParams(start,
1207 java.util.Optional.ofNullable(stop), java.util.Optional.ofNullable(filter), false);
1210 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1212 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance(NOTIFICATION_PORT);
1213 final int notificationPort = webSocketServerInstance.getPort();
1216 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme(getWsScheme(uriInfo));
1218 return uriToWebsocketServerBuilder.replacePath(streamName).build();
1221 private static String getWsScheme(final UriInfo uriInfo) {
1222 URI uri = uriInfo.getAbsolutePath();
1226 String subscriptionScheme = uri.getScheme().toLowerCase(Locale.ROOT);
1227 return subscriptionScheme.equals("https") ? "wss" : "ws";
1231 * Register data change listener by stream name.
1238 * start-time of getting notification
1240 * stop-time of getting notification
1242 * indicate which subset of all possible events are of interest
1243 * @return {@link URI} of location
1245 private URI dataSubs(final String identifier, final UriInfo uriInfo, final Instant start, final Instant stop,
1246 final String filter, final boolean leafNodesOnly) {
1247 final String streamName = Notificator.createStreamNameFromUri(identifier);
1248 if (Strings.isNullOrEmpty(streamName)) {
1249 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1252 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1253 if (listener == null) {
1254 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1255 ErrorTag.UNKNOWN_ELEMENT);
1257 listener.setQueryParams(start, java.util.Optional.ofNullable(stop),
1258 java.util.Optional.ofNullable(filter), leafNodesOnly);
1260 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1261 final LogicalDatastoreType datastore =
1262 parserURIEnumParameter(LogicalDatastoreType.class, paramToValues.get(DATASTORE_PARAM_NAME));
1263 if (datastore == null) {
1264 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1265 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1267 final DataChangeScope scope =
1268 parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
1269 if (scope == null) {
1270 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1271 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1274 this.broker.registerToListenDataChanges(datastore, scope, listener);
1276 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1278 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance(NOTIFICATION_PORT);
1279 final int notificationPort = webSocketServerInstance.getPort();
1281 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme(getWsScheme(uriInfo));
1283 return uriToWebsocketServerBuilder.replacePath(streamName).build();
1286 @SuppressWarnings("checkstyle:IllegalCatch")
1288 public PatchStatusContext patchConfigurationData(final String identifier, final PatchContext context,
1289 final UriInfo uriInfo) {
1290 if (context == null) {
1291 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1295 return this.broker.patchConfigurationDataWithinTransaction(context);
1296 } catch (final Exception e) {
1297 LOG.debug("Patch transaction failed", e);
1298 throw new RestconfDocumentedException(e.getMessage(), e);
1302 @SuppressWarnings("checkstyle:IllegalCatch")
1304 public PatchStatusContext patchConfigurationData(final PatchContext context, @Context final UriInfo uriInfo) {
1305 if (context == null) {
1306 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1310 return this.broker.patchConfigurationDataWithinTransaction(context);
1311 } catch (final Exception e) {
1312 LOG.debug("Patch transaction failed", e);
1313 throw new RestconfDocumentedException(e.getMessage(), e);
1318 * Load parameter for subscribing to stream from input composite node.
1322 * @return enum object if its string value is equal to {@code paramName}. In
1325 private static <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1326 final String paramName) {
1327 final java.util.Optional<DataContainerChild<? extends PathArgument, ?>> optAugNode = value.getChild(
1328 SAL_REMOTE_AUG_IDENTIFIER);
1329 if (!optAugNode.isPresent()) {
1332 final DataContainerChild<? extends PathArgument, ?> augNode = optAugNode.get();
1333 if (!(augNode instanceof AugmentationNode)) {
1336 final java.util.Optional<DataContainerChild<? extends PathArgument, ?>> enumNode = ((AugmentationNode) augNode)
1337 .getChild(new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1338 if (!enumNode.isPresent()) {
1341 final Object rawValue = enumNode.get().getValue();
1342 if (!(rawValue instanceof String)) {
1346 return resolveAsEnum(classDescriptor, (String) rawValue);
1350 * Checks whether {@code value} is one of the string representation of
1351 * enumeration {@code classDescriptor}.
1353 * @return enum object if string value of {@code classDescriptor}
1354 * enumeration is equal to {@code value}. Other cases null.
1356 private static <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1357 if (Strings.isNullOrEmpty(value)) {
1360 return resolveAsEnum(classDescriptor, value);
1363 private static <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1364 final T[] enumConstants = classDescriptor.getEnumConstants();
1365 if (enumConstants != null) {
1366 for (final T enm : classDescriptor.getEnumConstants()) {
1367 if (((Enum<?>) enm).name().equals(value)) {
1375 private static Map<String, String> resolveValuesFromUri(final String uri) {
1376 final Map<String, String> result = new HashMap<>();
1377 final String[] tokens = uri.split("/");
1378 for (int i = 1; i < tokens.length; i++) {
1379 final String[] parameterTokens = tokens[i].split("=");
1380 if (parameterTokens.length == 2) {
1381 result.put(parameterTokens[0], parameterTokens[1]);
1387 private MapNode makeModuleMapNode(final Set<Module> modules) {
1388 Preconditions.checkNotNull(modules);
1389 final Module restconfModule = getRestconfModule();
1390 final DataSchemaNode moduleSchemaNode = this.controllerContext
1391 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1392 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1394 final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder =
1395 Builders.mapBuilder((ListSchemaNode) moduleSchemaNode);
1397 for (final Module module : modules) {
1398 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1400 return listModuleBuilder.build();
1403 private MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1404 Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1405 "moduleSchemaNode has to be of type ListSchemaNode");
1406 final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1407 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues =
1408 Builders.mapEntryBuilder(listModuleSchemaNode);
1410 List<DataSchemaNode> instanceDataChildrenByName =
1411 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "name");
1412 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1413 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1415 .withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName()).build());
1417 final QNameModule qNameModule = module.getQNameModule();
1419 instanceDataChildrenByName =
1420 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "revision");
1421 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1422 Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1423 final java.util.Optional<Revision> revision = qNameModule.getRevision();
1424 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode)
1425 .withValue(revision.map(Revision::toString).orElse("")).build());
1427 instanceDataChildrenByName =
1428 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "namespace");
1429 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1430 Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1431 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1432 .withValue(qNameModule.getNamespace().toString()).build());
1434 instanceDataChildrenByName =
1435 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "feature");
1436 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1437 Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1438 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder =
1439 Builders.leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1440 for (final FeatureDefinition feature : module.getFeatures()) {
1441 featuresBuilder.withChild(Builders.leafSetEntryBuilder((LeafListSchemaNode) featureSchemaNode)
1442 .withValue(feature.getQName().getLocalName()).build());
1444 moduleNodeValues.withChild(featuresBuilder.build());
1446 return moduleNodeValues.build();
1449 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1450 Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1451 "streamSchemaNode has to be of type ListSchemaNode");
1452 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1453 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues =
1454 Builders.mapEntryBuilder(listStreamSchemaNode);
1456 List<DataSchemaNode> instanceDataChildrenByName =
1457 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "name");
1458 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1459 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1460 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName).build());
1462 instanceDataChildrenByName =
1463 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "description");
1464 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1465 Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1466 streamNodeValues.withChild(
1467 Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue("DESCRIPTION_PLACEHOLDER").build());
1469 instanceDataChildrenByName =
1470 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-support");
1471 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1472 Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1473 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1474 .withValue(Boolean.TRUE).build());
1476 instanceDataChildrenByName =
1477 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-log-creation-time");
1478 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1479 Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1480 streamNodeValues.withChild(
1481 Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode).withValue("").build());
1483 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "events");
1484 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1485 Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1486 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode).build());
1488 return streamNodeValues.build();
1492 * Prepare stream for notification.
1495 * contains list of qnames of notifications
1496 * @return - checked future object
1498 private ListenableFuture<DOMRpcResult> invokeSalRemoteRpcNotifiStrRPC(final NormalizedNodeContext payload) {
1499 final ContainerNode data = (ContainerNode) payload.getData();
1500 LeafSetNode leafSet = null;
1501 String outputType = "XML";
1502 for (final DataContainerChild<? extends PathArgument, ?> dataChild : data.getValue()) {
1503 if (dataChild instanceof LeafSetNode) {
1504 leafSet = (LeafSetNode) dataChild;
1505 } else if (dataChild instanceof AugmentationNode) {
1506 outputType = (String) ((AugmentationNode) dataChild).getValue().iterator().next().getValue();
1510 final Collection<LeafSetEntryNode> entryNodes = leafSet.getValue();
1511 final List<SchemaPath> paths = new ArrayList<>();
1512 String streamName = CREATE_NOTIFICATION_STREAM + "/";
1514 StringBuilder streamNameBuilder = new StringBuilder(streamName);
1515 final Iterator<LeafSetEntryNode> iterator = entryNodes.iterator();
1516 while (iterator.hasNext()) {
1517 final QName valueQName = QName.create((String) iterator.next().getValue());
1518 final Module module = controllerContext.findModuleByNamespace(valueQName.getModule().getNamespace());
1519 Preconditions.checkNotNull(module,
1520 "Module for namespace " + valueQName.getModule().getNamespace() + " does not exist");
1521 NotificationDefinition notifiDef = null;
1522 for (final NotificationDefinition notification : module.getNotifications()) {
1523 if (notification.getQName().equals(valueQName)) {
1524 notifiDef = notification;
1528 final String moduleName = module.getName();
1529 Preconditions.checkNotNull(notifiDef,
1530 "Notification " + valueQName + "doesn't exist in module " + moduleName);
1531 paths.add(notifiDef.getPath());
1532 streamNameBuilder.append(moduleName).append(':').append(valueQName.getLocalName());
1533 if (iterator.hasNext()) {
1534 streamNameBuilder.append(',');
1538 streamName = streamNameBuilder.toString();
1540 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
1541 final QName outputQname = QName.create(rpcQName, "output");
1542 final QName streamNameQname = QName.create(rpcQName, "notification-stream-identifier");
1544 final ContainerNode output =
1545 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
1546 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
1548 if (!Notificator.existNotificationListenerFor(streamName)) {
1549 Notificator.createNotificationListener(paths, streamName, outputType, controllerContext);
1552 return Futures.immediateFuture(new DefaultDOMRpcResult(output));