2 * Copyright (c) 2014 - 2016 Brocade Communication Systems, Inc., Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.netconf.sal.restconf.impl;
11 import com.google.common.annotations.VisibleForTesting;
12 import com.google.common.base.CharMatcher;
13 import com.google.common.base.Optional;
14 import com.google.common.base.Preconditions;
15 import com.google.common.base.Predicates;
16 import com.google.common.base.Splitter;
17 import com.google.common.base.Strings;
18 import com.google.common.base.Throwables;
19 import com.google.common.collect.ImmutableSet;
20 import com.google.common.collect.Iterables;
21 import com.google.common.collect.Maps;
22 import com.google.common.util.concurrent.CheckedFuture;
23 import com.google.common.util.concurrent.Futures;
24 import com.google.common.util.concurrent.ListenableFuture;
26 import java.time.Instant;
27 import java.time.format.DateTimeFormatter;
28 import java.time.format.DateTimeFormatterBuilder;
29 import java.time.format.DateTimeParseException;
30 import java.time.temporal.ChronoField;
31 import java.time.temporal.TemporalAccessor;
32 import java.util.AbstractMap.SimpleImmutableEntry;
33 import java.util.ArrayList;
34 import java.util.Collection;
35 import java.util.Collections;
36 import java.util.HashMap;
37 import java.util.Iterator;
38 import java.util.List;
39 import java.util.Locale;
41 import java.util.Map.Entry;
42 import java.util.Objects;
44 import java.util.concurrent.CancellationException;
45 import java.util.concurrent.ExecutionException;
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.controller.md.sal.common.api.data.LogicalDatastoreType;
53 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
54 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
55 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
56 import org.opendaylight.controller.md.sal.dom.api.DOMRpcImplementationNotAvailableException;
57 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
58 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
59 import org.opendaylight.controller.md.sal.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.QName;
78 import org.opendaylight.yangtools.yang.common.QNameModule;
79 import org.opendaylight.yangtools.yang.common.Revision;
80 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
81 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
82 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
83 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
84 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
85 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
86 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
87 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
88 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
89 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
90 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
91 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
92 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
93 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
94 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
95 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
96 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
97 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
98 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
99 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
100 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
101 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
102 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
103 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
104 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
105 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
106 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
107 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
108 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
109 import org.opendaylight.yangtools.yang.model.api.Module;
110 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
111 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
112 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
113 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
114 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
115 import org.opendaylight.yangtools.yang.model.util.SimpleSchemaContext;
116 import org.slf4j.Logger;
117 import org.slf4j.LoggerFactory;
119 public final class RestconfImpl implements RestconfService {
121 * Notifications are served on port 8181.
123 private static final int NOTIFICATION_PORT = 8181;
125 private static final int CHAR_NOT_FOUND = -1;
127 private static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
129 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
131 private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
133 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
135 private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
137 private static final String DATASTORE_PARAM_NAME = "datastore";
139 private static final String SCOPE_PARAM_NAME = "scope";
141 private static final String OUTPUT_TYPE_PARAM_NAME = "notification-output-type";
143 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
145 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
147 private static final QName NETCONF_BASE_QNAME = QName.create(QNameModule.create(URI.create(NETCONF_BASE)),
148 NETCONF_BASE_PAYLOAD_NAME).intern();
150 private static final QNameModule SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
151 Revision.of("2014-07-08"));
153 private static final AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER =
154 new AugmentationIdentifier(ImmutableSet.of(
155 QName.create(SAL_REMOTE_AUGMENT, "scope"), QName.create(SAL_REMOTE_AUGMENT, "datastore"),
156 QName.create(SAL_REMOTE_AUGMENT, "notification-output-type")));
158 public static final CharSequence DATA_SUBSCR = "data-change-event-subscription";
159 private static final CharSequence CREATE_DATA_SUBSCR = "create-" + DATA_SUBSCR;
161 public static final CharSequence NOTIFICATION_STREAM = "notification-stream";
162 private static final CharSequence CREATE_NOTIFICATION_STREAM = "create-" + NOTIFICATION_STREAM;
164 private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
165 .appendValue(ChronoField.YEAR, 4).appendLiteral('-')
166 .appendValue(ChronoField.MONTH_OF_YEAR, 2).appendLiteral('-')
167 .appendValue(ChronoField.DAY_OF_MONTH, 2).appendLiteral('T')
168 .appendValue(ChronoField.HOUR_OF_DAY, 2).appendLiteral(':')
169 .appendValue(ChronoField.MINUTE_OF_HOUR, 2).appendLiteral(':')
170 .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
171 .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
172 .appendOffset("+HH:MM", "Z").toFormatter();
174 private final BrokerFacade broker;
176 private final ControllerContext controllerContext;
178 private RestconfImpl(final BrokerFacade broker, final ControllerContext controllerContext) {
179 this.broker = broker;
180 this.controllerContext = controllerContext;
183 public static RestconfImpl newInstance(final BrokerFacade broker, final ControllerContext controllerContext) {
184 return new RestconfImpl(broker, controllerContext);
188 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
189 final Set<Module> allModules = this.controllerContext.getAllModules();
190 final MapNode allModuleMap = makeModuleMapNode(allModules);
192 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
194 final Module restconfModule = getRestconfModule();
195 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
196 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
197 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
199 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
200 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
201 moduleContainerBuilder.withChild(allModuleMap);
203 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode, null, schemaContext),
204 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
208 * Valid only for mount point.
211 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
212 Preconditions.checkNotNull(identifier);
213 if (!identifier.contains(ControllerContext.MOUNT)) {
214 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
215 + " URI has to end with " + ControllerContext.MOUNT;
216 LOG.debug("{} for {}", errMsg, identifier);
217 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
220 final InstanceIdentifierContext<?> mountPointIdentifier =
221 this.controllerContext.toMountPointIdentifier(identifier);
222 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
223 final Set<Module> modules = this.controllerContext.getAllModules(mountPoint);
224 final MapNode mountPointModulesMap = makeModuleMapNode(modules);
226 final Module restconfModule = getRestconfModule();
227 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
228 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
229 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
231 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
232 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
233 moduleContainerBuilder.withChild(mountPointModulesMap);
235 return new NormalizedNodeContext(
236 new InstanceIdentifierContext<>(null, modulesSchemaNode, mountPoint,
237 this.controllerContext.getGlobalSchema()),
238 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
242 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
243 Preconditions.checkNotNull(identifier);
244 final Entry<String, Revision> nameRev = getModuleNameAndRevision(identifier);
245 Module module = null;
246 DOMMountPoint mountPoint = null;
247 final SchemaContext schemaContext;
248 if (identifier.contains(ControllerContext.MOUNT)) {
249 final InstanceIdentifierContext<?> mountPointIdentifier =
250 this.controllerContext.toMountPointIdentifier(identifier);
251 mountPoint = mountPointIdentifier.getMountPoint();
252 module = this.controllerContext.findModuleByNameAndRevision(mountPoint, nameRev.getKey(),
254 schemaContext = mountPoint.getSchemaContext();
256 module = this.controllerContext.findModuleByNameAndRevision(nameRev.getKey(), nameRev.getValue());
257 schemaContext = this.controllerContext.getGlobalSchema();
260 if (module == null) {
261 LOG.debug("Module with name '{}' and revision '{}' was not found.", nameRev.getKey(), nameRev.getValue());
262 throw new RestconfDocumentedException("Module with name '" + nameRev.getKey() + "' and revision '"
263 + nameRev.getValue() + "' was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
266 final Module restconfModule = getRestconfModule();
267 final Set<Module> modules = Collections.singleton(module);
268 final MapNode moduleMap = makeModuleMapNode(modules);
270 final DataSchemaNode moduleSchemaNode = this.controllerContext
271 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
272 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
274 return new NormalizedNodeContext(
275 new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint, schemaContext), moduleMap,
276 QueryParametersParser.parseWriterParameters(uriInfo));
280 public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
281 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
282 final Set<String> availableStreams = Notificator.getStreamNames();
283 final Module restconfModule = getRestconfModule();
284 final DataSchemaNode streamSchemaNode = this.controllerContext
285 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
286 Preconditions.checkState(streamSchemaNode instanceof ListSchemaNode);
288 final CollectionNodeBuilder<MapEntryNode, MapNode> listStreamsBuilder =
289 Builders.mapBuilder((ListSchemaNode) streamSchemaNode);
291 for (final String streamName : availableStreams) {
292 listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
295 final DataSchemaNode streamsContainerSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
296 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
297 Preconditions.checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
299 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
300 Builders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
301 streamsContainerBuilder.withChild(listStreamsBuilder.build());
303 return new NormalizedNodeContext(
304 new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null, schemaContext),
305 streamsContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
309 public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
310 final Set<Module> allModules = this.controllerContext.getAllModules();
311 return operationsFromModulesToNormalizedContext(allModules, null);
315 public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
316 Set<Module> modules = null;
317 DOMMountPoint mountPoint = null;
318 if (identifier.contains(ControllerContext.MOUNT)) {
319 final InstanceIdentifierContext<?> mountPointIdentifier =
320 this.controllerContext.toMountPointIdentifier(identifier);
321 mountPoint = mountPointIdentifier.getMountPoint();
322 modules = this.controllerContext.getAllModules(mountPoint);
325 final String errMsg = "URI has bad format. If operations behind mount point should be showed, URI has to "
326 + " end with " + ControllerContext.MOUNT;
327 LOG.debug("{} for {}", errMsg, identifier);
328 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
331 return operationsFromModulesToNormalizedContext(modules, mountPoint);
335 * Special case only for GET restconf/operations use (since moment of
336 * pre-Beryllium Yang parser and Yang model API removal). The method is
337 * creating fake schema context with fake module and fake data by use own
338 * implementations of schema nodes and module.
341 * set of modules for get RPCs from every module
343 * mount point, if in use otherwise null
344 * @return {@link NormalizedNodeContext}
346 private static NormalizedNodeContext operationsFromModulesToNormalizedContext(final Set<Module> modules,
347 final DOMMountPoint mountPoint) {
349 final Collection<Module> neededModules = new ArrayList<>(modules.size());
350 final ArrayList<LeafSchemaNode> fakeRpcSchema = new ArrayList<>();
352 for (final Module m : modules) {
353 final Set<RpcDefinition> rpcs = m.getRpcs();
354 if (!rpcs.isEmpty()) {
355 neededModules.add(m);
357 fakeRpcSchema.ensureCapacity(fakeRpcSchema.size() + rpcs.size());
358 rpcs.forEach(rpc -> fakeRpcSchema.add(new FakeLeafSchemaNode(rpc.getQName())));
362 final ContainerSchemaNode fakeCont = new FakeContainerSchemaNode(fakeRpcSchema);
363 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> containerBuilder =
364 Builders.containerBuilder(fakeCont);
366 for (final LeafSchemaNode leaf : fakeRpcSchema) {
367 containerBuilder.withChild(Builders.leafBuilder(leaf).build());
370 final Collection<Module> fakeModules = new ArrayList<>(neededModules.size() + 1);
371 neededModules.forEach(imp -> fakeModules.add(new FakeImportedModule(imp)));
372 fakeModules.add(new FakeRestconfModule(neededModules, fakeCont));
374 final SchemaContext fakeSchemaCtx = SimpleSchemaContext.forModules(ImmutableSet.copyOf(fakeModules));
375 final InstanceIdentifierContext<ContainerSchemaNode> instanceIdentifierContext =
376 new InstanceIdentifierContext<>(null, fakeCont, mountPoint, fakeSchemaCtx);
377 return new NormalizedNodeContext(instanceIdentifierContext, containerBuilder.build());
380 private Module getRestconfModule() {
381 final Module restconfModule = this.controllerContext.getRestconfModule();
382 if (restconfModule == null) {
383 LOG.debug("ietf-restconf module was not found.");
384 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
385 ErrorTag.OPERATION_NOT_SUPPORTED);
388 return restconfModule;
391 private static Entry<String, Revision> getModuleNameAndRevision(final String identifier) {
392 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
393 String moduleNameAndRevision = "";
394 if (mountIndex >= 0) {
395 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
397 moduleNameAndRevision = identifier;
400 final Splitter splitter = Splitter.on('/').omitEmptyStrings();
401 final List<String> pathArgs = splitter.splitToList(moduleNameAndRevision);
402 if (pathArgs.size() < 2) {
403 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' {}", identifier);
404 throw new RestconfDocumentedException(
405 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
406 ErrorTag.INVALID_VALUE);
410 return new SimpleImmutableEntry<>(pathArgs.get(0), Revision.of(pathArgs.get(1)));
411 } catch (final DateTimeParseException e) {
412 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' {}", identifier);
413 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
414 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
419 public Object getRoot() {
424 public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload,
425 final UriInfo uriInfo) {
426 final SchemaPath type = payload.getInstanceIdentifierContext().getSchemaNode().getPath();
427 final URI namespace = payload.getInstanceIdentifierContext().getSchemaNode().getQName().getNamespace();
428 final ListenableFuture<DOMRpcResult> response;
429 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
430 final SchemaContext schemaContext;
432 if (mountPoint != null) {
433 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
434 if (!mountRpcServices.isPresent()) {
435 LOG.debug("Error: Rpc service is missing.");
436 throw new RestconfDocumentedException("Rpc service is missing.");
438 schemaContext = mountPoint.getSchemaContext();
439 response = mountRpcServices.get().invokeRpc(type, payload.getData());
441 if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
442 if (identifier.contains(CREATE_DATA_SUBSCR)) {
443 response = invokeSalRemoteRpcSubscribeRPC(payload);
444 } else if (identifier.contains(CREATE_NOTIFICATION_STREAM)) {
445 response = invokeSalRemoteRpcNotifiStrRPC(payload);
447 final String msg = "Not supported operation";
449 throw new RestconfDocumentedException(msg, ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED);
452 response = this.broker.invokeRpc(type, payload.getData());
454 schemaContext = this.controllerContext.getGlobalSchema();
457 final DOMRpcResult result = checkRpcResponse(response);
459 RpcDefinition resultNodeSchema = null;
460 final NormalizedNode<?, ?> resultData;
461 if (result != null && result.getResult() != null) {
462 resultData = result.getResult();
463 resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
468 return new NormalizedNodeContext(
469 new InstanceIdentifierContext<>(null, resultNodeSchema, mountPoint, schemaContext),
470 resultData, QueryParametersParser.parseWriterParameters(uriInfo));
474 public NormalizedNodeContext invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
475 if (noPayload != null && !CharMatcher.whitespace().matchesAllOf(noPayload)) {
476 throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
479 String identifierEncoded = null;
480 DOMMountPoint mountPoint = null;
481 final SchemaContext schemaContext;
482 if (identifier.contains(ControllerContext.MOUNT)) {
483 // mounted RPC call - look up mount instance.
484 final InstanceIdentifierContext<?> mountPointId = this.controllerContext.toMountPointIdentifier(identifier);
485 mountPoint = mountPointId.getMountPoint();
486 schemaContext = mountPoint.getSchemaContext();
487 final int startOfRemoteRpcName =
488 identifier.lastIndexOf(ControllerContext.MOUNT) + ControllerContext.MOUNT.length() + 1;
489 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
490 identifierEncoded = remoteRpcName;
492 } else if (identifier.indexOf('/') != CHAR_NOT_FOUND) {
493 LOG.debug("Identifier {} cannot contain slash character (/).", identifier);
494 throw new RestconfDocumentedException(String.format("Identifier %n%s%ncan\'t contain slash character (/).%n"
495 + "If slash is part of identifier name then use %%2F placeholder.", identifier), ErrorType.PROTOCOL,
496 ErrorTag.INVALID_VALUE);
498 identifierEncoded = identifier;
499 schemaContext = this.controllerContext.getGlobalSchema();
502 final String identifierDecoded = this.controllerContext.urlPathArgDecode(identifierEncoded);
504 RpcDefinition rpc = null;
505 if (mountPoint == null) {
506 rpc = this.controllerContext.getRpcDefinition(identifierDecoded);
508 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
512 LOG.debug("RPC {} does not exist.", identifierDecoded);
513 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
516 if (!rpc.getInput().getChildNodes().isEmpty()) {
517 LOG.debug("RPC {} does not need input value.", rpc);
518 throw new RestconfDocumentedException("RPC " + rpc + " does not take any input value.",
519 ErrorType.RPC, ErrorTag.INVALID_VALUE);
522 final ListenableFuture<DOMRpcResult> response;
523 if (mountPoint != null) {
524 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
525 if (!mountRpcServices.isPresent()) {
526 throw new RestconfDocumentedException("Rpc service is missing.");
528 response = mountRpcServices.get().invokeRpc(rpc.getPath(), null);
530 response = this.broker.invokeRpc(rpc.getPath(), null);
533 final DOMRpcResult result = checkRpcResponse(response);
535 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpc, mountPoint, schemaContext),
536 result.getResult(), QueryParametersParser.parseWriterParameters(uriInfo));
539 @SuppressWarnings("checkstyle:avoidHidingCauseException")
540 private static DOMRpcResult checkRpcResponse(final ListenableFuture<DOMRpcResult> response) {
541 if (response == null) {
545 final DOMRpcResult retValue = response.get();
546 if (retValue.getErrors().isEmpty()) {
549 LOG.debug("RpcError message {}", retValue.getErrors());
550 throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
551 } catch (final InterruptedException e) {
552 final String errMsg = "The operation was interrupted while executing and did not complete.";
553 LOG.debug("Rpc Interrupt - {}", errMsg, e);
554 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION, e);
555 } catch (final ExecutionException e) {
556 LOG.debug("Execution RpcError: ", e);
557 Throwable cause = e.getCause();
559 while (cause.getCause() != null) {
560 cause = cause.getCause();
563 if (cause instanceof IllegalArgumentException) {
564 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL,
565 ErrorTag.INVALID_VALUE);
566 } else if (cause instanceof DOMRpcImplementationNotAvailableException) {
567 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.APPLICATION,
568 ErrorTag.OPERATION_NOT_SUPPORTED);
570 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
573 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
576 } catch (final CancellationException e) {
577 final String errMsg = "The operation was cancelled while executing.";
578 LOG.debug("Cancel RpcExecution: {}", errMsg, e);
579 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
583 private static void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
584 if (inputSchema != null && payload.getData() == null) {
585 // expected a non null payload
586 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
587 } else if (inputSchema == null && payload.getData() != null) {
588 // did not expect any input
589 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
593 private ListenableFuture<DOMRpcResult> invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
594 final ContainerNode value = (ContainerNode) payload.getData();
595 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
596 final java.util.Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(
597 new NodeIdentifier(QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(),
599 final Object pathValue = path.isPresent() ? path.get().getValue() : null;
601 if (!(pathValue instanceof YangInstanceIdentifier)) {
602 LOG.debug("Instance identifier {} was not normalized correctly", rpcQName);
603 throw new RestconfDocumentedException("Instance identifier was not normalized correctly",
604 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
607 final YangInstanceIdentifier pathIdentifier = (YangInstanceIdentifier) pathValue;
608 String streamName = (String) CREATE_DATA_SUBSCR;
609 NotificationOutputType outputType = null;
610 if (!pathIdentifier.isEmpty()) {
611 final String fullRestconfIdentifier =
612 DATA_SUBSCR + this.controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
614 LogicalDatastoreType datastore =
615 parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
616 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
618 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
619 scope = scope == null ? DEFAULT_SCOPE : scope;
621 outputType = parseEnumTypeParameter(value, NotificationOutputType.class, OUTPUT_TYPE_PARAM_NAME);
622 outputType = outputType == null ? NotificationOutputType.XML : outputType;
624 streamName = Notificator
625 .createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore + "/scope=" + scope);
628 if (Strings.isNullOrEmpty(streamName)) {
629 LOG.debug("Path is empty or contains value node which is not Container or List built-in type at {}",
631 throw new RestconfDocumentedException("Path is empty or contains value node which is not Container or List "
632 + "built-in type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
635 final QName outputQname = QName.create(rpcQName, "output");
636 final QName streamNameQname = QName.create(rpcQName, "stream-name");
638 final ContainerNode output =
639 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
640 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
642 if (!Notificator.existListenerFor(streamName)) {
643 Notificator.createListener(pathIdentifier, streamName, outputType, controllerContext);
646 return Futures.immediateFuture(new DefaultDOMRpcResult(output));
649 private static RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
650 final String[] splittedIdentifier = identifierDecoded.split(":");
651 if (splittedIdentifier.length != 2) {
652 LOG.debug("{} could not be split to 2 parts (module:rpc name)", identifierDecoded);
653 throw new RestconfDocumentedException(identifierDecoded + " could not be split to 2 parts "
654 + "(module:rpc name)", ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
656 for (final Module module : schemaContext.getModules()) {
657 if (module.getName().equals(splittedIdentifier[0])) {
658 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
659 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
660 return rpcDefinition;
669 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
670 boolean withDefaUsed = false;
671 String withDefa = null;
673 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
674 switch (entry.getKey()) {
675 case "with-defaults":
678 withDefa = entry.getValue().iterator().next();
680 throw new RestconfDocumentedException("With-defaults parameter can be used only once.");
684 LOG.info("Unknown key : {}.", entry.getKey());
688 boolean tagged = false;
690 if ("report-all-tagged".equals(withDefa)) {
694 if ("report-all".equals(withDefa)) {
699 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
700 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
701 NormalizedNode<?, ?> data = null;
702 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
703 if (mountPoint != null) {
704 data = this.broker.readConfigurationData(mountPoint, normalizedII, withDefa);
706 data = this.broker.readConfigurationData(normalizedII, withDefa);
709 throw dataMissing(identifier);
711 return new NormalizedNodeContext(iiWithData, data,
712 QueryParametersParser.parseWriterParameters(uriInfo, tagged));
716 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
717 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
718 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
719 NormalizedNode<?, ?> data = null;
720 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
721 if (mountPoint != null) {
722 data = this.broker.readOperationalData(mountPoint, normalizedII);
724 data = this.broker.readOperationalData(normalizedII);
727 throw dataMissing(identifier);
729 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
732 private static RestconfDocumentedException dataMissing(final String identifier) {
733 LOG.debug("Request could not be completed because the relevant data model content does not exist {}",
735 return new RestconfDocumentedException("Request could not be completed because the relevant data model content "
736 + "does not exist", ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
740 public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload,
741 final UriInfo uriInfo) {
742 boolean insertUsed = false;
743 boolean pointUsed = false;
744 String insert = null;
747 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
748 switch (entry.getKey()) {
752 insert = entry.getValue().iterator().next();
754 throw new RestconfDocumentedException("Insert parameter can be used only once.");
760 point = entry.getValue().iterator().next();
762 throw new RestconfDocumentedException("Point parameter can be used only once.");
766 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
770 if (pointUsed && !insertUsed) {
771 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
773 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
774 throw new RestconfDocumentedException(
775 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
778 Preconditions.checkNotNull(identifier);
780 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
782 validateInput(iiWithData.getSchemaNode(), payload);
783 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
784 validateListKeysEqualityInPayloadAndUri(payload);
786 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
787 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
790 * There is a small window where another write transaction could be
791 * updating the same data simultaneously and we get an
792 * OptimisticLockFailedException. This error is likely transient and The
793 * WriteTransaction#submit API docs state that a retry will likely
794 * succeed. So we'll try again if that scenario occurs. If it fails a
795 * third time then it probably will never succeed so we'll fail in that
798 * By retrying we're attempting to hide the internal implementation of
799 * the data store and how it handles concurrent updates from the
800 * restconf client. The client has instructed us to put the data and we
801 * should make every effort to do so without pushing optimistic lock
802 * failures back to the client and forcing them to handle it via retry
803 * (and having to document the behavior).
805 PutResult result = null;
808 if (mountPoint != null) {
810 result = this.broker.commitMountPointDataPut(mountPoint, normalizedII, payload.getData(), insert,
813 result = this.broker.commitConfigurationDataPut(this.controllerContext.getGlobalSchema(), normalizedII,
814 payload.getData(), insert, point);
818 result.getFutureOfPutData().checkedGet();
819 return Response.status(result.getStatus()).build();
820 } catch (final TransactionCommitFailedException e) {
821 if (e instanceof OptimisticLockFailedException) {
823 LOG.debug("Got OptimisticLockFailedException on last try - failing {}", identifier);
824 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
827 LOG.debug("Got OptimisticLockFailedException - trying again {}", identifier);
829 LOG.debug("Update failed for {}", identifier, e);
830 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
836 private static void validateTopLevelNodeName(final NormalizedNodeContext node,
837 final YangInstanceIdentifier identifier) {
839 final String payloadName = node.getData().getNodeType().getLocalName();
842 if (identifier.isEmpty()) {
844 if (!node.getData().getNodeType().equals(NETCONF_BASE_QNAME)) {
845 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
846 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
850 final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
851 if (!payloadName.equals(identifierName)) {
852 throw new RestconfDocumentedException(
853 "Payload name (" + payloadName + ") is different from identifier name (" + identifierName + ")",
854 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
860 * Validates whether keys in {@code payload} are equal to values of keys in
861 * {@code iiWithData} for list schema node.
863 * @throws RestconfDocumentedException
864 * if key values or key count in payload and URI isn't equal
867 private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
868 Preconditions.checkArgument(payload != null);
869 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
870 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
871 final SchemaNode schemaNode = iiWithData.getSchemaNode();
872 final NormalizedNode<?, ?> data = payload.getData();
873 if (schemaNode instanceof ListSchemaNode) {
874 final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
875 if (lastPathArgument instanceof NodeIdentifierWithPredicates && data instanceof MapEntryNode) {
876 final Map<QName, Object> uriKeyValues =
877 ((NodeIdentifierWithPredicates) lastPathArgument).getKeyValues();
878 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
884 public static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final MapEntryNode payload,
885 final List<QName> keyDefinitions) {
887 final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
888 for (final QName keyDefinition : keyDefinitions) {
889 final Object uriKeyValue = mutableCopyUriKeyValues.remove(keyDefinition);
890 // should be caught during parsing URI to InstanceIdentifier
891 RestconfValidationUtils.checkDocumentedError(uriKeyValue != null, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
892 "Missing key " + keyDefinition + " in URI.");
894 final Object dataKeyValue = payload.getIdentifier().getKeyValues().get(keyDefinition);
896 if (!Objects.deepEquals(uriKeyValue, dataKeyValue)) {
897 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName()
898 + "' specified in the URI doesn't match the value '" + dataKeyValue
899 + "' specified in the message body. ";
900 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
906 public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload,
907 final UriInfo uriInfo) {
908 return createConfigurationData(payload, uriInfo);
912 public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
913 if (payload == null) {
914 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
916 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
917 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
918 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
920 boolean insertUsed = false;
921 boolean pointUsed = false;
922 String insert = null;
925 if (uriInfo != null) {
926 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
927 switch (entry.getKey()) {
931 insert = entry.getValue().iterator().next();
933 throw new RestconfDocumentedException("Insert parameter can be used only once.");
939 point = entry.getValue().iterator().next();
941 throw new RestconfDocumentedException("Point parameter can be used only once.");
945 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
950 if (pointUsed && !insertUsed) {
951 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
953 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
954 throw new RestconfDocumentedException(
955 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
958 CheckedFuture<Void, TransactionCommitFailedException> future;
959 if (mountPoint != null) {
960 future = this.broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData(), insert,
963 future = this.broker.commitConfigurationDataPost(this.controllerContext.getGlobalSchema(), normalizedII,
964 payload.getData(), insert, point);
969 } catch (final RestconfDocumentedException e) {
971 } catch (final TransactionCommitFailedException e) {
972 LOG.info("Error creating data {}", uriInfo != null ? uriInfo.getPath() : "", e);
973 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
976 LOG.trace("Successfuly created data.");
978 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
979 // FIXME: Provide path to result.
980 final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
981 if (location != null) {
982 responseBuilder.location(location);
984 return responseBuilder.build();
987 @SuppressWarnings("checkstyle:IllegalCatch")
988 private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint,
989 final YangInstanceIdentifier normalizedII) {
990 if (uriInfo == null) {
991 // This is null if invoked internally
995 final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
996 uriBuilder.path("config");
998 uriBuilder.path(this.controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
999 } catch (final Exception e) {
1000 LOG.info("Location for instance identifier {} was not created", normalizedII, e);
1003 return uriBuilder.build();
1007 public Response deleteConfigurationData(final String identifier) {
1008 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
1009 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
1010 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
1012 final CheckedFuture<Void, TransactionCommitFailedException> future;
1013 if (mountPoint != null) {
1014 future = this.broker.commitConfigurationDataDelete(mountPoint, normalizedII);
1016 future = this.broker.commitConfigurationDataDelete(normalizedII);
1020 future.checkedGet();
1021 } catch (final TransactionCommitFailedException e) {
1022 final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
1023 Predicates.instanceOf(ModifiedNodeDoesNotExistException.class));
1024 if (searchedException.isPresent()) {
1025 throw new RestconfDocumentedException("Data specified for delete doesn't exist.",
1026 ErrorType.APPLICATION, ErrorTag.DATA_MISSING, e);
1029 final String errMsg = "Error while deleting data";
1030 LOG.info(errMsg, e);
1031 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
1034 return Response.status(Status.OK).build();
1038 * Subscribes to some path in schema context (stream) to listen on changes
1042 * Additional parameters for subscribing to stream are loaded via rpc input
1045 * <li>datastore - default CONFIGURATION (other values of
1046 * {@link LogicalDatastoreType} enum type)</li>
1047 * <li>scope - default BASE (other values of {@link DataChangeScope})</li>
1051 public NormalizedNodeContext subscribeToStream(final String identifier, final UriInfo uriInfo) {
1052 boolean startTimeUsed = false;
1053 boolean stopTimeUsed = false;
1054 Instant start = Instant.now();
1055 Instant stop = null;
1056 boolean filterUsed = false;
1057 String filter = null;
1058 boolean leafNodesOnlyUsed = false;
1059 boolean leafNodesOnly = false;
1061 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
1062 switch (entry.getKey()) {
1064 if (!startTimeUsed) {
1065 startTimeUsed = true;
1066 start = parseDateFromQueryParam(entry);
1068 throw new RestconfDocumentedException("Start-time parameter can be used only once.");
1072 if (!stopTimeUsed) {
1073 stopTimeUsed = true;
1074 stop = parseDateFromQueryParam(entry);
1076 throw new RestconfDocumentedException("Stop-time parameter can be used only once.");
1082 filter = entry.getValue().iterator().next();
1084 throw new RestconfDocumentedException("Filter parameter can be used only once.");
1087 case "odl-leaf-nodes-only":
1088 if (!leafNodesOnlyUsed) {
1089 leafNodesOnlyUsed = true;
1090 leafNodesOnly = Boolean.parseBoolean(entry.getValue().iterator().next());
1092 throw new RestconfDocumentedException("Odl-leaf-nodes-only parameter can be used only once.");
1096 throw new RestconfDocumentedException("Bad parameter used with notifications: " + entry.getKey());
1099 if (!startTimeUsed && stopTimeUsed) {
1100 throw new RestconfDocumentedException("Stop-time parameter has to be used with start-time parameter.");
1102 URI response = null;
1103 if (identifier.contains(DATA_SUBSCR)) {
1104 response = dataSubs(identifier, uriInfo, start, stop, filter, leafNodesOnly);
1105 } else if (identifier.contains(NOTIFICATION_STREAM)) {
1106 response = notifStream(identifier, uriInfo, start, stop, filter);
1109 if (response != null) {
1110 // prepare node with value of location
1111 final InstanceIdentifierContext<?> iid = prepareIIDSubsStreamOutput();
1112 final NormalizedNodeAttrBuilder<NodeIdentifier, Object, LeafNode<Object>> builder =
1113 ImmutableLeafNodeBuilder.create().withValue(response.toString());
1114 builder.withNodeIdentifier(
1115 NodeIdentifier.create(QName.create("subscribe:to:notification", "2016-10-28", "location")));
1117 // prepare new header with location
1118 final Map<String, Object> headers = new HashMap<>();
1119 headers.put("Location", response);
1121 return new NormalizedNodeContext(iid, builder.build(), headers);
1124 final String msg = "Bad type of notification of sal-remote";
1126 throw new RestconfDocumentedException(msg);
1129 private static Instant parseDateFromQueryParam(final Entry<String, List<String>> entry) {
1130 final DateAndTime event = new DateAndTime(entry.getValue().iterator().next());
1131 final String value = event.getValue();
1132 final TemporalAccessor p;
1134 p = FORMATTER.parse(value);
1135 } catch (final DateTimeParseException e) {
1136 throw new RestconfDocumentedException("Cannot parse of value in date: " + value, e);
1138 return Instant.from(p);
1142 * Prepare instance identifier.
1144 * @return {@link InstanceIdentifierContext} of location leaf for
1147 private InstanceIdentifierContext<?> prepareIIDSubsStreamOutput() {
1148 final QName qnameBase = QName.create("subscribe:to:notification", "2016-10-28", "notifi");
1149 final SchemaContext schemaCtx = controllerContext.getGlobalSchema();
1150 final DataSchemaNode location = ((ContainerSchemaNode) schemaCtx
1151 .findModule(qnameBase.getModule()).orElse(null)
1152 .getDataChildByName(qnameBase)).getDataChildByName(QName.create(qnameBase, "location"));
1153 final List<PathArgument> path = new ArrayList<>();
1154 path.add(NodeIdentifier.create(qnameBase));
1155 path.add(NodeIdentifier.create(QName.create(qnameBase, "location")));
1157 return new InstanceIdentifierContext<SchemaNode>(YangInstanceIdentifier.create(path), location, null,
1162 * Register notification listener by stream name.
1169 * stop-time of getting notification
1171 * start-time of getting notification
1173 * indicate which subset of all possible events are of interest
1174 * @return {@link URI} of location
1176 private URI notifStream(final String identifier, final UriInfo uriInfo, final Instant start,
1177 final Instant stop, final String filter) {
1178 final String streamName = Notificator.createStreamNameFromUri(identifier);
1179 if (Strings.isNullOrEmpty(streamName)) {
1180 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1182 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
1183 if (listeners == null || listeners.isEmpty()) {
1184 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1185 ErrorTag.UNKNOWN_ELEMENT);
1188 for (final NotificationListenerAdapter listener : listeners) {
1189 this.broker.registerToListenNotification(listener);
1190 listener.setQueryParams(start,
1191 java.util.Optional.ofNullable(stop), java.util.Optional.ofNullable(filter), false);
1194 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1196 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance(NOTIFICATION_PORT);
1197 final int notificationPort = webSocketServerInstance.getPort();
1200 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme(getWsScheme(uriInfo));
1202 return uriToWebsocketServerBuilder.replacePath(streamName).build();
1205 private String getWsScheme(final UriInfo uriInfo) {
1206 URI uri = uriInfo.getAbsolutePath();
1210 String subscriptionScheme = uri.getScheme().toLowerCase(Locale.ROOT);
1211 return subscriptionScheme.equals("https") ? "wss" : "ws";
1215 * Register data change listener by stream name.
1222 * start-time of getting notification
1224 * stop-time of getting notification
1226 * indicate which subset of all possible events are of interest
1227 * @return {@link URI} of location
1229 private URI dataSubs(final String identifier, final UriInfo uriInfo, final Instant start, final Instant stop,
1230 final String filter, final boolean leafNodesOnly) {
1231 final String streamName = Notificator.createStreamNameFromUri(identifier);
1232 if (Strings.isNullOrEmpty(streamName)) {
1233 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1236 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1237 if (listener == null) {
1238 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1239 ErrorTag.UNKNOWN_ELEMENT);
1241 listener.setQueryParams(start, java.util.Optional.ofNullable(stop),
1242 java.util.Optional.ofNullable(filter), leafNodesOnly);
1244 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1245 final LogicalDatastoreType datastore =
1246 parserURIEnumParameter(LogicalDatastoreType.class, paramToValues.get(DATASTORE_PARAM_NAME));
1247 if (datastore == null) {
1248 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1249 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1251 final DataChangeScope scope =
1252 parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
1253 if (scope == null) {
1254 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1255 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1258 this.broker.registerToListenDataChanges(datastore, scope, listener);
1260 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1262 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance(NOTIFICATION_PORT);
1263 final int notificationPort = webSocketServerInstance.getPort();
1265 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme(getWsScheme(uriInfo));
1267 return uriToWebsocketServerBuilder.replacePath(streamName).build();
1270 @SuppressWarnings("checkstyle:IllegalCatch")
1272 public PatchStatusContext patchConfigurationData(final String identifier, final PatchContext context,
1273 final UriInfo uriInfo) {
1274 if (context == null) {
1275 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1279 return this.broker.patchConfigurationDataWithinTransaction(context);
1280 } catch (final Exception e) {
1281 LOG.debug("Patch transaction failed", e);
1282 throw new RestconfDocumentedException(e.getMessage(), e);
1286 @SuppressWarnings("checkstyle:IllegalCatch")
1288 public PatchStatusContext patchConfigurationData(final PatchContext context, @Context final UriInfo uriInfo) {
1289 if (context == null) {
1290 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1294 return this.broker.patchConfigurationDataWithinTransaction(context);
1295 } catch (final Exception e) {
1296 LOG.debug("Patch transaction failed", e);
1297 throw new RestconfDocumentedException(e.getMessage(), e);
1302 * Load parameter for subscribing to stream from input composite node.
1306 * @return enum object if its string value is equal to {@code paramName}. In
1309 private static <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1310 final String paramName) {
1311 final java.util.Optional<DataContainerChild<? extends PathArgument, ?>> optAugNode = value.getChild(
1312 SAL_REMOTE_AUG_IDENTIFIER);
1313 if (!optAugNode.isPresent()) {
1316 final DataContainerChild<? extends PathArgument, ?> augNode = optAugNode.get();
1317 if (!(augNode instanceof AugmentationNode)) {
1320 final java.util.Optional<DataContainerChild<? extends PathArgument, ?>> enumNode = ((AugmentationNode) augNode)
1321 .getChild(new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1322 if (!enumNode.isPresent()) {
1325 final Object rawValue = enumNode.get().getValue();
1326 if (!(rawValue instanceof String)) {
1330 return resolveAsEnum(classDescriptor, (String) rawValue);
1334 * Checks whether {@code value} is one of the string representation of
1335 * enumeration {@code classDescriptor}.
1337 * @return enum object if string value of {@code classDescriptor}
1338 * enumeration is equal to {@code value}. Other cases null.
1340 private static <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1341 if (Strings.isNullOrEmpty(value)) {
1344 return resolveAsEnum(classDescriptor, value);
1347 private static <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1348 final T[] enumConstants = classDescriptor.getEnumConstants();
1349 if (enumConstants != null) {
1350 for (final T enm : classDescriptor.getEnumConstants()) {
1351 if (((Enum<?>) enm).name().equals(value)) {
1359 private static Map<String, String> resolveValuesFromUri(final String uri) {
1360 final Map<String, String> result = new HashMap<>();
1361 final String[] tokens = uri.split("/");
1362 for (int i = 1; i < tokens.length; i++) {
1363 final String[] parameterTokens = tokens[i].split("=");
1364 if (parameterTokens.length == 2) {
1365 result.put(parameterTokens[0], parameterTokens[1]);
1371 private MapNode makeModuleMapNode(final Set<Module> modules) {
1372 Preconditions.checkNotNull(modules);
1373 final Module restconfModule = getRestconfModule();
1374 final DataSchemaNode moduleSchemaNode = this.controllerContext
1375 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1376 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1378 final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder =
1379 Builders.mapBuilder((ListSchemaNode) moduleSchemaNode);
1381 for (final Module module : modules) {
1382 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1384 return listModuleBuilder.build();
1387 protected MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1388 Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1389 "moduleSchemaNode has to be of type ListSchemaNode");
1390 final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1391 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues =
1392 Builders.mapEntryBuilder(listModuleSchemaNode);
1394 List<DataSchemaNode> instanceDataChildrenByName =
1395 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "name");
1396 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1397 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1399 .withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName()).build());
1401 instanceDataChildrenByName =
1402 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "revision");
1403 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1404 Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1405 final java.util.Optional<Revision> revision = module.getQNameModule().getRevision();
1406 if (revision.isPresent()) {
1407 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode)
1408 .withValue(revision.get().toString()).build());
1411 instanceDataChildrenByName =
1412 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "namespace");
1413 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1414 Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1415 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1416 .withValue(module.getNamespace().toString()).build());
1418 instanceDataChildrenByName =
1419 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "feature");
1420 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1421 Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1422 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder =
1423 Builders.leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1424 for (final FeatureDefinition feature : module.getFeatures()) {
1425 featuresBuilder.withChild(Builders.leafSetEntryBuilder((LeafListSchemaNode) featureSchemaNode)
1426 .withValue(feature.getQName().getLocalName()).build());
1428 moduleNodeValues.withChild(featuresBuilder.build());
1430 return moduleNodeValues.build();
1433 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1434 Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1435 "streamSchemaNode has to be of type ListSchemaNode");
1436 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1437 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues =
1438 Builders.mapEntryBuilder(listStreamSchemaNode);
1440 List<DataSchemaNode> instanceDataChildrenByName =
1441 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "name");
1442 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1443 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1444 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName).build());
1446 instanceDataChildrenByName =
1447 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "description");
1448 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1449 Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1450 streamNodeValues.withChild(
1451 Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue("DESCRIPTION_PLACEHOLDER").build());
1453 instanceDataChildrenByName =
1454 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-support");
1455 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1456 Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1457 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1458 .withValue(Boolean.valueOf(true)).build());
1460 instanceDataChildrenByName =
1461 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-log-creation-time");
1462 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1463 Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1464 streamNodeValues.withChild(
1465 Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode).withValue("").build());
1467 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "events");
1468 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1469 Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1470 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode).build());
1472 return streamNodeValues.build();
1476 * Prepare stream for notification.
1479 * contains list of qnames of notifications
1480 * @return - checked future object
1482 private ListenableFuture<DOMRpcResult> invokeSalRemoteRpcNotifiStrRPC(final NormalizedNodeContext payload) {
1483 final ContainerNode data = (ContainerNode) payload.getData();
1484 LeafSetNode leafSet = null;
1485 String outputType = "XML";
1486 for (final DataContainerChild<? extends PathArgument, ?> dataChild : data.getValue()) {
1487 if (dataChild instanceof LeafSetNode) {
1488 leafSet = (LeafSetNode) dataChild;
1489 } else if (dataChild instanceof AugmentationNode) {
1490 outputType = (String) ((AugmentationNode) dataChild).getValue().iterator().next().getValue();
1494 final Collection<LeafSetEntryNode> entryNodes = leafSet.getValue();
1495 final List<SchemaPath> paths = new ArrayList<>();
1496 String streamName = CREATE_NOTIFICATION_STREAM + "/";
1498 StringBuilder streamNameBuilder = new StringBuilder(streamName);
1499 final Iterator<LeafSetEntryNode> iterator = entryNodes.iterator();
1500 while (iterator.hasNext()) {
1501 final QName valueQName = QName.create((String) iterator.next().getValue());
1502 final Module module = controllerContext.findModuleByNamespace(valueQName.getModule().getNamespace());
1503 Preconditions.checkNotNull(module,
1504 "Module for namespace " + valueQName.getModule().getNamespace() + " does not exist");
1505 NotificationDefinition notifiDef = null;
1506 for (final NotificationDefinition notification : module.getNotifications()) {
1507 if (notification.getQName().equals(valueQName)) {
1508 notifiDef = notification;
1512 final String moduleName = module.getName();
1513 Preconditions.checkNotNull(notifiDef,
1514 "Notification " + valueQName + "doesn't exist in module " + moduleName);
1515 paths.add(notifiDef.getPath());
1516 streamNameBuilder.append(moduleName).append(':').append(valueQName.getLocalName());
1517 if (iterator.hasNext()) {
1518 streamNameBuilder.append(',');
1522 streamName = streamNameBuilder.toString();
1524 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
1525 final QName outputQname = QName.create(rpcQName, "output");
1526 final QName streamNameQname = QName.create(rpcQName, "notification-stream-identifier");
1528 final ContainerNode output =
1529 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
1530 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
1532 if (!Notificator.existNotificationListenerFor(streamName)) {
1533 Notificator.createNotificationListener(paths, streamName, outputType, controllerContext);
1536 return Futures.immediateFuture(new DefaultDOMRpcResult(output));