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.core.Context;
47 import javax.ws.rs.core.Response;
48 import javax.ws.rs.core.Response.ResponseBuilder;
49 import javax.ws.rs.core.Response.Status;
50 import javax.ws.rs.core.UriBuilder;
51 import javax.ws.rs.core.UriInfo;
52 import org.opendaylight.mdsal.common.api.CommitInfo;
53 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
54 import org.opendaylight.mdsal.common.api.OptimisticLockFailedException;
55 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
56 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
57 import org.opendaylight.mdsal.dom.api.DOMRpcImplementationNotAvailableException;
58 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
59 import org.opendaylight.mdsal.dom.api.DOMRpcService;
60 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
61 import org.opendaylight.netconf.sal.rest.api.Draft02;
62 import org.opendaylight.netconf.sal.rest.api.RestconfService;
63 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
64 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
65 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
66 import org.opendaylight.netconf.sal.streams.websockets.WebSocketServer;
67 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
68 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
69 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
70 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
71 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
72 import org.opendaylight.restconf.common.patch.PatchContext;
73 import org.opendaylight.restconf.common.patch.PatchStatusContext;
74 import org.opendaylight.restconf.common.util.DataChangeScope;
75 import org.opendaylight.restconf.common.validation.RestconfValidationUtils;
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.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.DataContainerNodeAttrBuilder;
100 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
101 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
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;
121 public final class RestconfImpl implements RestconfService {
123 * Notifications are served on port 8181.
125 private static final int NOTIFICATION_PORT = 8181;
127 private static final int CHAR_NOT_FOUND = -1;
129 private static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
131 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
133 private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
135 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
137 private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
139 private static final String DATASTORE_PARAM_NAME = "datastore";
141 private static final String SCOPE_PARAM_NAME = "scope";
143 private static final String OUTPUT_TYPE_PARAM_NAME = "notification-output-type";
145 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
147 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
149 private static final QName NETCONF_BASE_QNAME = QName.create(QNameModule.create(URI.create(NETCONF_BASE)),
150 NETCONF_BASE_PAYLOAD_NAME).intern();
152 private static final QNameModule SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
153 Revision.of("2014-07-08"));
155 private static final AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER =
156 new AugmentationIdentifier(ImmutableSet.of(
157 QName.create(SAL_REMOTE_AUGMENT, "scope"), QName.create(SAL_REMOTE_AUGMENT, "datastore"),
158 QName.create(SAL_REMOTE_AUGMENT, "notification-output-type")));
160 public static final CharSequence DATA_SUBSCR = "data-change-event-subscription";
161 private static final CharSequence CREATE_DATA_SUBSCR = "create-" + DATA_SUBSCR;
163 public static final CharSequence NOTIFICATION_STREAM = "notification-stream";
164 private static final CharSequence CREATE_NOTIFICATION_STREAM = "create-" + NOTIFICATION_STREAM;
166 private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
167 .appendValue(ChronoField.YEAR, 4).appendLiteral('-')
168 .appendValue(ChronoField.MONTH_OF_YEAR, 2).appendLiteral('-')
169 .appendValue(ChronoField.DAY_OF_MONTH, 2).appendLiteral('T')
170 .appendValue(ChronoField.HOUR_OF_DAY, 2).appendLiteral(':')
171 .appendValue(ChronoField.MINUTE_OF_HOUR, 2).appendLiteral(':')
172 .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
173 .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
174 .appendOffset("+HH:MM", "Z").toFormatter();
176 private final BrokerFacade broker;
178 private final ControllerContext controllerContext;
181 public RestconfImpl(final BrokerFacade broker, final ControllerContext controllerContext) {
182 this.broker = broker;
183 this.controllerContext = controllerContext;
189 * @deprecated Just use {@link #RestconfImpl(BrokerFacade, ControllerContext)} constructor instead.
192 public static RestconfImpl newInstance(final BrokerFacade broker, final ControllerContext controllerContext) {
193 return new RestconfImpl(broker, controllerContext);
197 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
198 final Set<Module> allModules = this.controllerContext.getAllModules();
199 final MapNode allModuleMap = makeModuleMapNode(allModules);
201 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
203 final Module restconfModule = getRestconfModule();
204 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
205 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
206 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
208 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
209 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
210 moduleContainerBuilder.withChild(allModuleMap);
212 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode, null, schemaContext),
213 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
217 * Valid only for mount point.
220 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
221 Preconditions.checkNotNull(identifier);
222 if (!identifier.contains(ControllerContext.MOUNT)) {
223 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
224 + " URI has to end with " + ControllerContext.MOUNT;
225 LOG.debug("{} for {}", errMsg, identifier);
226 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
229 final InstanceIdentifierContext<?> mountPointIdentifier =
230 this.controllerContext.toMountPointIdentifier(identifier);
231 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
232 final Set<Module> modules = this.controllerContext.getAllModules(mountPoint);
233 final MapNode mountPointModulesMap = makeModuleMapNode(modules);
235 final Module restconfModule = getRestconfModule();
236 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
237 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
238 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
240 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
241 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
242 moduleContainerBuilder.withChild(mountPointModulesMap);
244 return new NormalizedNodeContext(
245 new InstanceIdentifierContext<>(null, modulesSchemaNode, mountPoint,
246 this.controllerContext.getGlobalSchema()),
247 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
251 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
252 Preconditions.checkNotNull(identifier);
253 final Entry<String, Revision> nameRev = getModuleNameAndRevision(identifier);
254 Module module = null;
255 DOMMountPoint mountPoint = null;
256 final SchemaContext schemaContext;
257 if (identifier.contains(ControllerContext.MOUNT)) {
258 final InstanceIdentifierContext<?> mountPointIdentifier =
259 this.controllerContext.toMountPointIdentifier(identifier);
260 mountPoint = mountPointIdentifier.getMountPoint();
261 module = this.controllerContext.findModuleByNameAndRevision(mountPoint, nameRev.getKey(),
263 schemaContext = mountPoint.getSchemaContext();
265 module = this.controllerContext.findModuleByNameAndRevision(nameRev.getKey(), nameRev.getValue());
266 schemaContext = this.controllerContext.getGlobalSchema();
269 if (module == null) {
270 LOG.debug("Module with name '{}' and revision '{}' was not found.", nameRev.getKey(), nameRev.getValue());
271 throw new RestconfDocumentedException("Module with name '" + nameRev.getKey() + "' and revision '"
272 + nameRev.getValue() + "' was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
275 final Module restconfModule = getRestconfModule();
276 final Set<Module> modules = Collections.singleton(module);
277 final MapNode moduleMap = makeModuleMapNode(modules);
279 final DataSchemaNode moduleSchemaNode = this.controllerContext
280 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
281 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
283 return new NormalizedNodeContext(
284 new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint, schemaContext), moduleMap,
285 QueryParametersParser.parseWriterParameters(uriInfo));
289 public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
290 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
291 final Set<String> availableStreams = Notificator.getStreamNames();
292 final Module restconfModule = getRestconfModule();
293 final DataSchemaNode streamSchemaNode = this.controllerContext
294 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
295 Preconditions.checkState(streamSchemaNode instanceof ListSchemaNode);
297 final CollectionNodeBuilder<MapEntryNode, MapNode> listStreamsBuilder =
298 Builders.mapBuilder((ListSchemaNode) streamSchemaNode);
300 for (final String streamName : availableStreams) {
301 listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
304 final DataSchemaNode streamsContainerSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
305 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
306 Preconditions.checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
308 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
309 Builders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
310 streamsContainerBuilder.withChild(listStreamsBuilder.build());
312 return new NormalizedNodeContext(
313 new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null, schemaContext),
314 streamsContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
318 public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
319 final Set<Module> allModules = this.controllerContext.getAllModules();
320 return operationsFromModulesToNormalizedContext(allModules, null);
324 public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
325 Set<Module> modules = null;
326 DOMMountPoint mountPoint = null;
327 if (identifier.contains(ControllerContext.MOUNT)) {
328 final InstanceIdentifierContext<?> mountPointIdentifier =
329 this.controllerContext.toMountPointIdentifier(identifier);
330 mountPoint = mountPointIdentifier.getMountPoint();
331 modules = this.controllerContext.getAllModules(mountPoint);
334 final String errMsg = "URI has bad format. If operations behind mount point should be showed, URI has to "
335 + " end with " + ControllerContext.MOUNT;
336 LOG.debug("{} for {}", errMsg, identifier);
337 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
340 return operationsFromModulesToNormalizedContext(modules, mountPoint);
344 * Special case only for GET restconf/operations use (since moment of
345 * pre-Beryllium Yang parser and Yang model API removal). The method is
346 * creating fake schema context with fake module and fake data by use own
347 * implementations of schema nodes and module.
350 * set of modules for get RPCs from every module
352 * mount point, if in use otherwise null
353 * @return {@link NormalizedNodeContext}
355 private static NormalizedNodeContext operationsFromModulesToNormalizedContext(final Set<Module> modules,
356 final DOMMountPoint mountPoint) {
358 final Collection<Module> neededModules = new ArrayList<>(modules.size());
359 final ArrayList<LeafSchemaNode> fakeRpcSchema = new ArrayList<>();
361 for (final Module m : modules) {
362 final Set<RpcDefinition> rpcs = m.getRpcs();
363 if (!rpcs.isEmpty()) {
364 neededModules.add(m);
366 fakeRpcSchema.ensureCapacity(fakeRpcSchema.size() + rpcs.size());
367 rpcs.forEach(rpc -> fakeRpcSchema.add(new FakeLeafSchemaNode(rpc.getQName())));
371 final ContainerSchemaNode fakeCont = new FakeContainerSchemaNode(fakeRpcSchema);
372 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> containerBuilder =
373 Builders.containerBuilder(fakeCont);
375 for (final LeafSchemaNode leaf : fakeRpcSchema) {
376 containerBuilder.withChild(Builders.leafBuilder(leaf).build());
379 final Collection<Module> fakeModules = new ArrayList<>(neededModules.size() + 1);
380 neededModules.forEach(imp -> fakeModules.add(new FakeImportedModule(imp)));
381 fakeModules.add(new FakeRestconfModule(neededModules, fakeCont));
383 final SchemaContext fakeSchemaCtx = SimpleSchemaContext.forModules(ImmutableSet.copyOf(fakeModules));
384 final InstanceIdentifierContext<ContainerSchemaNode> instanceIdentifierContext =
385 new InstanceIdentifierContext<>(null, fakeCont, mountPoint, fakeSchemaCtx);
386 return new NormalizedNodeContext(instanceIdentifierContext, containerBuilder.build());
389 private Module getRestconfModule() {
390 final Module restconfModule = this.controllerContext.getRestconfModule();
391 if (restconfModule == null) {
392 LOG.debug("ietf-restconf module was not found.");
393 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
394 ErrorTag.OPERATION_NOT_SUPPORTED);
397 return restconfModule;
400 private static Entry<String, Revision> getModuleNameAndRevision(final String identifier) {
401 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
402 String moduleNameAndRevision = "";
403 if (mountIndex >= 0) {
404 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
406 moduleNameAndRevision = identifier;
409 final Splitter splitter = Splitter.on('/').omitEmptyStrings();
410 final List<String> pathArgs = splitter.splitToList(moduleNameAndRevision);
411 if (pathArgs.size() < 2) {
412 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' {}", identifier);
413 throw new RestconfDocumentedException(
414 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
415 ErrorTag.INVALID_VALUE);
419 return new SimpleImmutableEntry<>(pathArgs.get(0), Revision.of(pathArgs.get(1)));
420 } catch (final DateTimeParseException e) {
421 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' {}", identifier);
422 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
423 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
428 public Object getRoot() {
433 public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload,
434 final UriInfo uriInfo) {
435 if (payload == null) {
436 // no payload specified, reroute this to no payload invokeRpc implementation
437 return invokeRpc(identifier, uriInfo);
440 final SchemaPath type = payload.getInstanceIdentifierContext().getSchemaNode().getPath();
441 final URI namespace = payload.getInstanceIdentifierContext().getSchemaNode().getQName().getNamespace();
442 final ListenableFuture<DOMRpcResult> response;
443 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
444 final SchemaContext schemaContext;
446 if (mountPoint != null) {
447 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
448 if (!mountRpcServices.isPresent()) {
449 LOG.debug("Error: Rpc service is missing.");
450 throw new RestconfDocumentedException("Rpc service is missing.");
452 schemaContext = mountPoint.getSchemaContext();
453 response = mountRpcServices.get().invokeRpc(type, payload.getData());
455 if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
456 if (identifier.contains(CREATE_DATA_SUBSCR)) {
457 response = invokeSalRemoteRpcSubscribeRPC(payload);
458 } else if (identifier.contains(CREATE_NOTIFICATION_STREAM)) {
459 response = invokeSalRemoteRpcNotifiStrRPC(payload);
461 final String msg = "Not supported operation";
463 throw new RestconfDocumentedException(msg, ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED);
466 response = this.broker.invokeRpc(type, payload.getData());
468 schemaContext = this.controllerContext.getGlobalSchema();
471 final DOMRpcResult result = checkRpcResponse(response);
473 RpcDefinition resultNodeSchema = null;
474 final NormalizedNode<?, ?> resultData;
475 if (result != null && result.getResult() != null) {
476 resultData = result.getResult();
477 resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
482 return new NormalizedNodeContext(
483 new InstanceIdentifierContext<>(null, resultNodeSchema, mountPoint, schemaContext),
484 resultData, QueryParametersParser.parseWriterParameters(uriInfo));
487 private NormalizedNodeContext invokeRpc(final String identifier, final UriInfo uriInfo) {
489 DOMMountPoint mountPoint = null;
490 final String identifierEncoded;
491 final SchemaContext schemaContext;
492 if (identifier.contains(ControllerContext.MOUNT)) {
493 // mounted RPC call - look up mount instance.
494 final InstanceIdentifierContext<?> mountPointId = this.controllerContext.toMountPointIdentifier(identifier);
495 mountPoint = mountPointId.getMountPoint();
496 schemaContext = mountPoint.getSchemaContext();
497 final int startOfRemoteRpcName =
498 identifier.lastIndexOf(ControllerContext.MOUNT) + ControllerContext.MOUNT.length() + 1;
499 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
500 identifierEncoded = remoteRpcName;
502 } else if (identifier.indexOf('/') != CHAR_NOT_FOUND) {
503 LOG.debug("Identifier {} cannot contain slash character (/).", identifier);
504 throw new RestconfDocumentedException(String.format("Identifier %n%s%ncan\'t contain slash character (/).%n"
505 + "If slash is part of identifier name then use %%2F placeholder.", identifier), ErrorType.PROTOCOL,
506 ErrorTag.INVALID_VALUE);
508 identifierEncoded = identifier;
509 schemaContext = this.controllerContext.getGlobalSchema();
512 final String identifierDecoded = this.controllerContext.urlPathArgDecode(identifierEncoded);
515 if (mountPoint == null) {
516 rpc = this.controllerContext.getRpcDefinition(identifierDecoded);
518 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
522 LOG.debug("RPC {} does not exist.", identifierDecoded);
523 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
526 if (!rpc.getInput().getChildNodes().isEmpty()) {
527 LOG.debug("No input specified for RPC {} with an input section", rpc);
528 throw new RestconfDocumentedException("No input specified for RPC " + rpc
529 + " with an input section defined", ErrorType.RPC, ErrorTag.MISSING_ELEMENT);
532 final ListenableFuture<DOMRpcResult> response;
533 if (mountPoint != null) {
534 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
535 if (!mountRpcServices.isPresent()) {
536 throw new RestconfDocumentedException("Rpc service is missing.");
538 response = mountRpcServices.get().invokeRpc(rpc.getPath(), null);
540 response = this.broker.invokeRpc(rpc.getPath(), null);
543 final DOMRpcResult result = checkRpcResponse(response);
545 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpc, mountPoint, schemaContext),
546 result.getResult(), QueryParametersParser.parseWriterParameters(uriInfo));
549 @SuppressWarnings("checkstyle:avoidHidingCauseException")
550 private static DOMRpcResult checkRpcResponse(final ListenableFuture<DOMRpcResult> response) {
551 if (response == null) {
555 final DOMRpcResult retValue = response.get();
556 if (retValue.getErrors().isEmpty()) {
559 LOG.debug("RpcError message {}", retValue.getErrors());
560 throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
561 } catch (final InterruptedException e) {
562 final String errMsg = "The operation was interrupted while executing and did not complete.";
563 LOG.debug("Rpc Interrupt - {}", errMsg, e);
564 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION, e);
565 } catch (final ExecutionException e) {
566 LOG.debug("Execution RpcError: ", e);
567 Throwable cause = e.getCause();
569 while (cause.getCause() != null) {
570 cause = cause.getCause();
573 if (cause instanceof IllegalArgumentException) {
574 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL,
575 ErrorTag.INVALID_VALUE);
576 } else if (cause instanceof DOMRpcImplementationNotAvailableException) {
577 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.APPLICATION,
578 ErrorTag.OPERATION_NOT_SUPPORTED);
580 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
583 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
586 } catch (final CancellationException e) {
587 final String errMsg = "The operation was cancelled while executing.";
588 LOG.debug("Cancel RpcExecution: {}", errMsg, e);
589 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
593 private static void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
594 if (inputSchema != null && payload.getData() == null) {
595 // expected a non null payload
596 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
597 } else if (inputSchema == null && payload.getData() != null) {
598 // did not expect any input
599 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
603 private ListenableFuture<DOMRpcResult> invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
604 final ContainerNode value = (ContainerNode) payload.getData();
605 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
606 final java.util.Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(
607 new NodeIdentifier(QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(),
609 final Object pathValue = path.isPresent() ? path.get().getValue() : null;
611 if (!(pathValue instanceof YangInstanceIdentifier)) {
612 LOG.debug("Instance identifier {} was not normalized correctly", rpcQName);
613 throw new RestconfDocumentedException("Instance identifier was not normalized correctly",
614 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
617 final YangInstanceIdentifier pathIdentifier = (YangInstanceIdentifier) pathValue;
618 String streamName = (String) CREATE_DATA_SUBSCR;
619 NotificationOutputType outputType = null;
620 if (!pathIdentifier.isEmpty()) {
621 final String fullRestconfIdentifier =
622 DATA_SUBSCR + this.controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
624 LogicalDatastoreType datastore =
625 parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
626 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
628 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
629 scope = scope == null ? DEFAULT_SCOPE : scope;
631 outputType = parseEnumTypeParameter(value, NotificationOutputType.class, OUTPUT_TYPE_PARAM_NAME);
632 outputType = outputType == null ? NotificationOutputType.XML : outputType;
634 streamName = Notificator
635 .createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore + "/scope=" + scope);
638 if (Strings.isNullOrEmpty(streamName)) {
639 LOG.debug("Path is empty or contains value node which is not Container or List built-in type at {}",
641 throw new RestconfDocumentedException("Path is empty or contains value node which is not Container or List "
642 + "built-in type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
645 final QName outputQname = QName.create(rpcQName, "output");
646 final QName streamNameQname = QName.create(rpcQName, "stream-name");
648 final ContainerNode output =
649 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
650 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
652 if (!Notificator.existListenerFor(streamName)) {
653 Notificator.createListener(pathIdentifier, streamName, outputType, controllerContext);
656 return Futures.immediateFuture(new DefaultDOMRpcResult(output));
659 private static RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
660 final String[] splittedIdentifier = identifierDecoded.split(":");
661 if (splittedIdentifier.length != 2) {
662 LOG.debug("{} could not be split to 2 parts (module:rpc name)", identifierDecoded);
663 throw new RestconfDocumentedException(identifierDecoded + " could not be split to 2 parts "
664 + "(module:rpc name)", ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
666 for (final Module module : schemaContext.getModules()) {
667 if (module.getName().equals(splittedIdentifier[0])) {
668 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
669 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
670 return rpcDefinition;
679 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
680 boolean withDefaUsed = false;
681 String withDefa = null;
683 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
684 switch (entry.getKey()) {
685 case "with-defaults":
688 withDefa = entry.getValue().iterator().next();
690 throw new RestconfDocumentedException("With-defaults parameter can be used only once.");
694 LOG.info("Unknown key : {}.", entry.getKey());
698 boolean tagged = false;
700 if ("report-all-tagged".equals(withDefa)) {
704 if ("report-all".equals(withDefa)) {
709 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
710 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
711 NormalizedNode<?, ?> data = null;
712 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
713 if (mountPoint != null) {
714 data = this.broker.readConfigurationData(mountPoint, normalizedII, withDefa);
716 data = this.broker.readConfigurationData(normalizedII, withDefa);
719 throw dataMissing(identifier);
721 return new NormalizedNodeContext(iiWithData, data,
722 QueryParametersParser.parseWriterParameters(uriInfo, tagged));
726 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
727 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
728 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
729 NormalizedNode<?, ?> data = null;
730 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
731 if (mountPoint != null) {
732 data = this.broker.readOperationalData(mountPoint, normalizedII);
734 data = this.broker.readOperationalData(normalizedII);
737 throw dataMissing(identifier);
739 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
742 private static RestconfDocumentedException dataMissing(final String identifier) {
743 LOG.debug("Request could not be completed because the relevant data model content does not exist {}",
745 return new RestconfDocumentedException("Request could not be completed because the relevant data model content "
746 + "does not exist", ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
750 public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload,
751 final UriInfo uriInfo) {
752 boolean insertUsed = false;
753 boolean pointUsed = false;
754 String insert = null;
757 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
758 switch (entry.getKey()) {
762 insert = entry.getValue().iterator().next();
764 throw new RestconfDocumentedException("Insert parameter can be used only once.");
770 point = entry.getValue().iterator().next();
772 throw new RestconfDocumentedException("Point parameter can be used only once.");
776 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
780 if (pointUsed && !insertUsed) {
781 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
783 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
784 throw new RestconfDocumentedException(
785 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
788 Preconditions.checkNotNull(identifier);
790 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
792 validateInput(iiWithData.getSchemaNode(), payload);
793 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
794 validateListKeysEqualityInPayloadAndUri(payload);
796 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
797 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
800 * There is a small window where another write transaction could be
801 * updating the same data simultaneously and we get an
802 * OptimisticLockFailedException. This error is likely transient and The
803 * WriteTransaction#submit API docs state that a retry will likely
804 * succeed. So we'll try again if that scenario occurs. If it fails a
805 * third time then it probably will never succeed so we'll fail in that
808 * By retrying we're attempting to hide the internal implementation of
809 * the data store and how it handles concurrent updates from the
810 * restconf client. The client has instructed us to put the data and we
811 * should make every effort to do so without pushing optimistic lock
812 * failures back to the client and forcing them to handle it via retry
813 * (and having to document the behavior).
815 PutResult result = null;
818 if (mountPoint != null) {
820 result = this.broker.commitMountPointDataPut(mountPoint, normalizedII, payload.getData(), insert,
823 result = this.broker.commitConfigurationDataPut(this.controllerContext.getGlobalSchema(), normalizedII,
824 payload.getData(), insert, point);
828 result.getFutureOfPutData().get();
829 } catch (final InterruptedException e) {
830 LOG.debug("Update failed for {}", identifier, e);
831 throw new RestconfDocumentedException(e.getMessage(), e);
832 } catch (final ExecutionException e) {
833 final TransactionCommitFailedException failure = Throwables.getCauseAs(e,
834 TransactionCommitFailedException.class);
835 if (failure instanceof OptimisticLockFailedException) {
837 LOG.debug("Got OptimisticLockFailedException on last try - failing {}", identifier);
838 throw new RestconfDocumentedException(e.getMessage(), e, failure.getErrorList());
841 LOG.debug("Got OptimisticLockFailedException - trying again {}", identifier);
845 LOG.debug("Update failed for {}", identifier, e);
846 throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), failure);
849 return Response.status(result.getStatus()).build();
853 private static void validateTopLevelNodeName(final NormalizedNodeContext node,
854 final YangInstanceIdentifier identifier) {
856 final String payloadName = node.getData().getNodeType().getLocalName();
859 if (identifier.isEmpty()) {
861 if (!node.getData().getNodeType().equals(NETCONF_BASE_QNAME)) {
862 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
863 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
867 final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
868 if (!payloadName.equals(identifierName)) {
869 throw new RestconfDocumentedException(
870 "Payload name (" + payloadName + ") is different from identifier name (" + identifierName + ")",
871 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
877 * Validates whether keys in {@code payload} are equal to values of keys in
878 * {@code iiWithData} for list schema node.
880 * @throws RestconfDocumentedException
881 * if key values or key count in payload and URI isn't equal
884 private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
885 Preconditions.checkArgument(payload != null);
886 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
887 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
888 final SchemaNode schemaNode = iiWithData.getSchemaNode();
889 final NormalizedNode<?, ?> data = payload.getData();
890 if (schemaNode instanceof ListSchemaNode) {
891 final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
892 if (lastPathArgument instanceof NodeIdentifierWithPredicates && data instanceof MapEntryNode) {
893 final Map<QName, Object> uriKeyValues =
894 ((NodeIdentifierWithPredicates) lastPathArgument).getKeyValues();
895 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
901 public static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final MapEntryNode payload,
902 final List<QName> keyDefinitions) {
904 final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
905 for (final QName keyDefinition : keyDefinitions) {
906 final Object uriKeyValue = mutableCopyUriKeyValues.remove(keyDefinition);
907 // should be caught during parsing URI to InstanceIdentifier
908 RestconfValidationUtils.checkDocumentedError(uriKeyValue != null, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
909 "Missing key " + keyDefinition + " in URI.");
911 final Object dataKeyValue = payload.getIdentifier().getKeyValues().get(keyDefinition);
913 if (!Objects.deepEquals(uriKeyValue, dataKeyValue)) {
914 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName()
915 + "' specified in the URI doesn't match the value '" + dataKeyValue
916 + "' specified in the message body. ";
917 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
923 public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload,
924 final UriInfo uriInfo) {
925 return createConfigurationData(payload, uriInfo);
929 public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
930 if (payload == null) {
931 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
933 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
934 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
935 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
937 boolean insertUsed = false;
938 boolean pointUsed = false;
939 String insert = null;
942 if (uriInfo != null) {
943 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
944 switch (entry.getKey()) {
948 insert = entry.getValue().iterator().next();
950 throw new RestconfDocumentedException("Insert parameter can be used only once.");
956 point = entry.getValue().iterator().next();
958 throw new RestconfDocumentedException("Point parameter can be used only once.");
962 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
967 if (pointUsed && !insertUsed) {
968 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
970 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
971 throw new RestconfDocumentedException(
972 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
975 FluentFuture<? extends CommitInfo> future;
976 if (mountPoint != null) {
977 future = this.broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData(), insert,
980 future = this.broker.commitConfigurationDataPost(this.controllerContext.getGlobalSchema(), normalizedII,
981 payload.getData(), insert, point);
986 } catch (final InterruptedException e) {
987 LOG.info("Error creating data {}", uriInfo != null ? uriInfo.getPath() : "", e);
988 throw new RestconfDocumentedException(e.getMessage(), e);
989 } catch (final ExecutionException e) {
990 LOG.info("Error creating data {}", uriInfo != null ? uriInfo.getPath() : "", e);
991 throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), Throwables.getCauseAs(e,
992 TransactionCommitFailedException.class));
995 LOG.trace("Successfuly created data.");
997 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
998 // FIXME: Provide path to result.
999 final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
1000 if (location != null) {
1001 responseBuilder.location(location);
1003 return responseBuilder.build();
1006 @SuppressWarnings("checkstyle:IllegalCatch")
1007 private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint,
1008 final YangInstanceIdentifier normalizedII) {
1009 if (uriInfo == null) {
1010 // This is null if invoked internally
1014 final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
1015 uriBuilder.path("config");
1017 uriBuilder.path(this.controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
1018 } catch (final Exception e) {
1019 LOG.info("Location for instance identifier {} was not created", normalizedII, e);
1022 return uriBuilder.build();
1026 public Response deleteConfigurationData(final String identifier) {
1027 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
1028 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
1029 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
1031 final FluentFuture<? extends CommitInfo> future;
1032 if (mountPoint != null) {
1033 future = this.broker.commitConfigurationDataDelete(mountPoint, normalizedII);
1035 future = this.broker.commitConfigurationDataDelete(normalizedII);
1040 } catch (final InterruptedException e) {
1041 throw new RestconfDocumentedException(e.getMessage(), e);
1042 } catch (final ExecutionException e) {
1043 final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
1044 Predicates.instanceOf(ModifiedNodeDoesNotExistException.class)).toJavaUtil();
1045 if (searchedException.isPresent()) {
1046 throw new RestconfDocumentedException("Data specified for delete doesn't exist.", ErrorType.APPLICATION,
1047 ErrorTag.DATA_MISSING, e);
1050 throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), Throwables.getCauseAs(e,
1051 TransactionCommitFailedException.class));
1054 return Response.status(Status.OK).build();
1058 * Subscribes to some path in schema context (stream) to listen on changes
1062 * Additional parameters for subscribing to stream are loaded via rpc input
1065 * <li>datastore - default CONFIGURATION (other values of
1066 * {@link LogicalDatastoreType} enum type)</li>
1067 * <li>scope - default BASE (other values of {@link DataChangeScope})</li>
1071 public NormalizedNodeContext subscribeToStream(final String identifier, final UriInfo uriInfo) {
1072 boolean startTimeUsed = false;
1073 boolean stopTimeUsed = false;
1074 Instant start = Instant.now();
1075 Instant stop = null;
1076 boolean filterUsed = false;
1077 String filter = null;
1078 boolean leafNodesOnlyUsed = false;
1079 boolean leafNodesOnly = false;
1081 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
1082 switch (entry.getKey()) {
1084 if (!startTimeUsed) {
1085 startTimeUsed = true;
1086 start = parseDateFromQueryParam(entry);
1088 throw new RestconfDocumentedException("Start-time parameter can be used only once.");
1092 if (!stopTimeUsed) {
1093 stopTimeUsed = true;
1094 stop = parseDateFromQueryParam(entry);
1096 throw new RestconfDocumentedException("Stop-time parameter can be used only once.");
1102 filter = entry.getValue().iterator().next();
1104 throw new RestconfDocumentedException("Filter parameter can be used only once.");
1107 case "odl-leaf-nodes-only":
1108 if (!leafNodesOnlyUsed) {
1109 leafNodesOnlyUsed = true;
1110 leafNodesOnly = Boolean.parseBoolean(entry.getValue().iterator().next());
1112 throw new RestconfDocumentedException("Odl-leaf-nodes-only parameter can be used only once.");
1116 throw new RestconfDocumentedException("Bad parameter used with notifications: " + entry.getKey());
1119 if (!startTimeUsed && stopTimeUsed) {
1120 throw new RestconfDocumentedException("Stop-time parameter has to be used with start-time parameter.");
1122 URI response = null;
1123 if (identifier.contains(DATA_SUBSCR)) {
1124 response = dataSubs(identifier, uriInfo, start, stop, filter, leafNodesOnly);
1125 } else if (identifier.contains(NOTIFICATION_STREAM)) {
1126 response = notifStream(identifier, uriInfo, start, stop, filter);
1129 if (response != null) {
1130 // prepare node with value of location
1131 final InstanceIdentifierContext<?> iid = prepareIIDSubsStreamOutput();
1132 final NormalizedNodeAttrBuilder<NodeIdentifier, Object, LeafNode<Object>> builder =
1133 ImmutableLeafNodeBuilder.create().withValue(response.toString());
1134 builder.withNodeIdentifier(
1135 NodeIdentifier.create(QName.create("subscribe:to:notification", "2016-10-28", "location")));
1137 // prepare new header with location
1138 final Map<String, Object> headers = new HashMap<>();
1139 headers.put("Location", response);
1141 return new NormalizedNodeContext(iid, builder.build(), headers);
1144 final String msg = "Bad type of notification of sal-remote";
1146 throw new RestconfDocumentedException(msg);
1149 private static Instant parseDateFromQueryParam(final Entry<String, List<String>> entry) {
1150 final DateAndTime event = new DateAndTime(entry.getValue().iterator().next());
1151 final String value = event.getValue();
1152 final TemporalAccessor p;
1154 p = FORMATTER.parse(value);
1155 } catch (final DateTimeParseException e) {
1156 throw new RestconfDocumentedException("Cannot parse of value in date: " + value, e);
1158 return Instant.from(p);
1162 * Prepare instance identifier.
1164 * @return {@link InstanceIdentifierContext} of location leaf for
1167 private InstanceIdentifierContext<?> prepareIIDSubsStreamOutput() {
1168 final QName qnameBase = QName.create("subscribe:to:notification", "2016-10-28", "notifi");
1169 final SchemaContext schemaCtx = controllerContext.getGlobalSchema();
1170 final DataSchemaNode location = ((ContainerSchemaNode) schemaCtx
1171 .findModule(qnameBase.getModule()).orElse(null)
1172 .getDataChildByName(qnameBase)).getDataChildByName(QName.create(qnameBase, "location"));
1173 final List<PathArgument> path = new ArrayList<>();
1174 path.add(NodeIdentifier.create(qnameBase));
1175 path.add(NodeIdentifier.create(QName.create(qnameBase, "location")));
1177 return new InstanceIdentifierContext<SchemaNode>(YangInstanceIdentifier.create(path), location, null,
1182 * Register notification listener by stream name.
1189 * stop-time of getting notification
1191 * start-time of getting notification
1193 * indicate which subset of all possible events are of interest
1194 * @return {@link URI} of location
1196 private URI notifStream(final String identifier, final UriInfo uriInfo, final Instant start,
1197 final Instant stop, final String filter) {
1198 final String streamName = Notificator.createStreamNameFromUri(identifier);
1199 if (Strings.isNullOrEmpty(streamName)) {
1200 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1202 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
1203 if (listeners == null || listeners.isEmpty()) {
1204 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1205 ErrorTag.UNKNOWN_ELEMENT);
1208 for (final NotificationListenerAdapter listener : listeners) {
1209 this.broker.registerToListenNotification(listener);
1210 listener.setQueryParams(start,
1211 java.util.Optional.ofNullable(stop), java.util.Optional.ofNullable(filter), false);
1214 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1216 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance(NOTIFICATION_PORT);
1217 final int notificationPort = webSocketServerInstance.getPort();
1220 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme(getWsScheme(uriInfo));
1222 return uriToWebsocketServerBuilder.replacePath(streamName).build();
1225 private static String getWsScheme(final UriInfo uriInfo) {
1226 URI uri = uriInfo.getAbsolutePath();
1230 String subscriptionScheme = uri.getScheme().toLowerCase(Locale.ROOT);
1231 return subscriptionScheme.equals("https") ? "wss" : "ws";
1235 * Register data change listener by stream name.
1242 * start-time of getting notification
1244 * stop-time of getting notification
1246 * indicate which subset of all possible events are of interest
1247 * @return {@link URI} of location
1249 private URI dataSubs(final String identifier, final UriInfo uriInfo, final Instant start, final Instant stop,
1250 final String filter, final boolean leafNodesOnly) {
1251 final String streamName = Notificator.createStreamNameFromUri(identifier);
1252 if (Strings.isNullOrEmpty(streamName)) {
1253 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1256 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1257 if (listener == null) {
1258 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1259 ErrorTag.UNKNOWN_ELEMENT);
1261 listener.setQueryParams(start, java.util.Optional.ofNullable(stop),
1262 java.util.Optional.ofNullable(filter), leafNodesOnly);
1264 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1265 final LogicalDatastoreType datastore =
1266 parserURIEnumParameter(LogicalDatastoreType.class, paramToValues.get(DATASTORE_PARAM_NAME));
1267 if (datastore == null) {
1268 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1269 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1271 final DataChangeScope scope =
1272 parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
1273 if (scope == null) {
1274 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1275 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1278 this.broker.registerToListenDataChanges(datastore, scope, listener);
1280 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1282 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance(NOTIFICATION_PORT);
1283 final int notificationPort = webSocketServerInstance.getPort();
1285 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme(getWsScheme(uriInfo));
1287 return uriToWebsocketServerBuilder.replacePath(streamName).build();
1290 @SuppressWarnings("checkstyle:IllegalCatch")
1292 public PatchStatusContext patchConfigurationData(final String identifier, final PatchContext context,
1293 final UriInfo uriInfo) {
1294 if (context == null) {
1295 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1299 return this.broker.patchConfigurationDataWithinTransaction(context);
1300 } catch (final Exception e) {
1301 LOG.debug("Patch transaction failed", e);
1302 throw new RestconfDocumentedException(e.getMessage(), e);
1306 @SuppressWarnings("checkstyle:IllegalCatch")
1308 public PatchStatusContext patchConfigurationData(final PatchContext context, @Context final UriInfo uriInfo) {
1309 if (context == null) {
1310 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1314 return this.broker.patchConfigurationDataWithinTransaction(context);
1315 } catch (final Exception e) {
1316 LOG.debug("Patch transaction failed", e);
1317 throw new RestconfDocumentedException(e.getMessage(), e);
1322 * Load parameter for subscribing to stream from input composite node.
1326 * @return enum object if its string value is equal to {@code paramName}. In
1329 private static <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1330 final String paramName) {
1331 final java.util.Optional<DataContainerChild<? extends PathArgument, ?>> optAugNode = value.getChild(
1332 SAL_REMOTE_AUG_IDENTIFIER);
1333 if (!optAugNode.isPresent()) {
1336 final DataContainerChild<? extends PathArgument, ?> augNode = optAugNode.get();
1337 if (!(augNode instanceof AugmentationNode)) {
1340 final java.util.Optional<DataContainerChild<? extends PathArgument, ?>> enumNode = ((AugmentationNode) augNode)
1341 .getChild(new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1342 if (!enumNode.isPresent()) {
1345 final Object rawValue = enumNode.get().getValue();
1346 if (!(rawValue instanceof String)) {
1350 return resolveAsEnum(classDescriptor, (String) rawValue);
1354 * Checks whether {@code value} is one of the string representation of
1355 * enumeration {@code classDescriptor}.
1357 * @return enum object if string value of {@code classDescriptor}
1358 * enumeration is equal to {@code value}. Other cases null.
1360 private static <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1361 if (Strings.isNullOrEmpty(value)) {
1364 return resolveAsEnum(classDescriptor, value);
1367 private static <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1368 final T[] enumConstants = classDescriptor.getEnumConstants();
1369 if (enumConstants != null) {
1370 for (final T enm : classDescriptor.getEnumConstants()) {
1371 if (((Enum<?>) enm).name().equals(value)) {
1379 private static Map<String, String> resolveValuesFromUri(final String uri) {
1380 final Map<String, String> result = new HashMap<>();
1381 final String[] tokens = uri.split("/");
1382 for (int i = 1; i < tokens.length; i++) {
1383 final String[] parameterTokens = tokens[i].split("=");
1384 if (parameterTokens.length == 2) {
1385 result.put(parameterTokens[0], parameterTokens[1]);
1391 private MapNode makeModuleMapNode(final Set<Module> modules) {
1392 Preconditions.checkNotNull(modules);
1393 final Module restconfModule = getRestconfModule();
1394 final DataSchemaNode moduleSchemaNode = this.controllerContext
1395 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1396 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1398 final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder =
1399 Builders.mapBuilder((ListSchemaNode) moduleSchemaNode);
1401 for (final Module module : modules) {
1402 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1404 return listModuleBuilder.build();
1407 private MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1408 Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1409 "moduleSchemaNode has to be of type ListSchemaNode");
1410 final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1411 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues =
1412 Builders.mapEntryBuilder(listModuleSchemaNode);
1414 List<DataSchemaNode> instanceDataChildrenByName =
1415 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "name");
1416 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1417 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1419 .withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName()).build());
1421 final QNameModule qNameModule = module.getQNameModule();
1423 instanceDataChildrenByName =
1424 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "revision");
1425 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1426 Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1427 final java.util.Optional<Revision> revision = qNameModule.getRevision();
1428 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode)
1429 .withValue(revision.map(Revision::toString).orElse("")).build());
1431 instanceDataChildrenByName =
1432 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "namespace");
1433 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1434 Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1435 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1436 .withValue(qNameModule.getNamespace().toString()).build());
1438 instanceDataChildrenByName =
1439 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "feature");
1440 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1441 Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1442 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder =
1443 Builders.leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1444 for (final FeatureDefinition feature : module.getFeatures()) {
1445 featuresBuilder.withChild(Builders.leafSetEntryBuilder((LeafListSchemaNode) featureSchemaNode)
1446 .withValue(feature.getQName().getLocalName()).build());
1448 moduleNodeValues.withChild(featuresBuilder.build());
1450 return moduleNodeValues.build();
1453 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1454 Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1455 "streamSchemaNode has to be of type ListSchemaNode");
1456 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1457 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues =
1458 Builders.mapEntryBuilder(listStreamSchemaNode);
1460 List<DataSchemaNode> instanceDataChildrenByName =
1461 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "name");
1462 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1463 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1464 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName).build());
1466 instanceDataChildrenByName =
1467 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "description");
1468 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1469 Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1470 streamNodeValues.withChild(
1471 Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue("DESCRIPTION_PLACEHOLDER").build());
1473 instanceDataChildrenByName =
1474 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-support");
1475 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1476 Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1477 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1478 .withValue(Boolean.TRUE).build());
1480 instanceDataChildrenByName =
1481 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-log-creation-time");
1482 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1483 Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1484 streamNodeValues.withChild(
1485 Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode).withValue("").build());
1487 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "events");
1488 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1489 Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1490 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode).build());
1492 return streamNodeValues.build();
1496 * Prepare stream for notification.
1499 * contains list of qnames of notifications
1500 * @return - checked future object
1502 private ListenableFuture<DOMRpcResult> invokeSalRemoteRpcNotifiStrRPC(final NormalizedNodeContext payload) {
1503 final ContainerNode data = (ContainerNode) payload.getData();
1504 LeafSetNode leafSet = null;
1505 String outputType = "XML";
1506 for (final DataContainerChild<? extends PathArgument, ?> dataChild : data.getValue()) {
1507 if (dataChild instanceof LeafSetNode) {
1508 leafSet = (LeafSetNode) dataChild;
1509 } else if (dataChild instanceof AugmentationNode) {
1510 outputType = (String) ((AugmentationNode) dataChild).getValue().iterator().next().getValue();
1514 final Collection<LeafSetEntryNode> entryNodes = leafSet.getValue();
1515 final List<SchemaPath> paths = new ArrayList<>();
1516 String streamName = CREATE_NOTIFICATION_STREAM + "/";
1518 StringBuilder streamNameBuilder = new StringBuilder(streamName);
1519 final Iterator<LeafSetEntryNode> iterator = entryNodes.iterator();
1520 while (iterator.hasNext()) {
1521 final QName valueQName = QName.create((String) iterator.next().getValue());
1522 final Module module = controllerContext.findModuleByNamespace(valueQName.getModule().getNamespace());
1523 Preconditions.checkNotNull(module,
1524 "Module for namespace " + valueQName.getModule().getNamespace() + " does not exist");
1525 NotificationDefinition notifiDef = null;
1526 for (final NotificationDefinition notification : module.getNotifications()) {
1527 if (notification.getQName().equals(valueQName)) {
1528 notifiDef = notification;
1532 final String moduleName = module.getName();
1533 Preconditions.checkNotNull(notifiDef,
1534 "Notification " + valueQName + "doesn't exist in module " + moduleName);
1535 paths.add(notifiDef.getPath());
1536 streamNameBuilder.append(moduleName).append(':').append(valueQName.getLocalName());
1537 if (iterator.hasNext()) {
1538 streamNameBuilder.append(',');
1542 streamName = streamNameBuilder.toString();
1544 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
1545 final QName outputQname = QName.create(rpcQName, "output");
1546 final QName streamNameQname = QName.create(rpcQName, "notification-stream-identifier");
1548 final ContainerNode output =
1549 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
1550 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
1552 if (!Notificator.existNotificationListenerFor(streamName)) {
1553 Notificator.createNotificationListener(paths, streamName, outputType, controllerContext);
1556 return Futures.immediateFuture(new DefaultDOMRpcResult(output));