2 * Copyright (c) 2014 - 2016 Brocade Communication Systems, Inc., Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.netconf.sal.restconf.impl;
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Predicates;
13 import com.google.common.base.Splitter;
14 import com.google.common.base.Strings;
15 import com.google.common.base.Throwables;
16 import com.google.common.collect.ImmutableSet;
17 import com.google.common.collect.Iterables;
18 import com.google.common.collect.Maps;
19 import com.google.common.util.concurrent.FluentFuture;
20 import com.google.common.util.concurrent.Futures;
21 import com.google.common.util.concurrent.ListenableFuture;
23 import java.time.Instant;
24 import java.time.format.DateTimeFormatter;
25 import java.time.format.DateTimeFormatterBuilder;
26 import java.time.format.DateTimeParseException;
27 import java.time.temporal.ChronoField;
28 import java.time.temporal.TemporalAccessor;
29 import java.util.AbstractMap.SimpleImmutableEntry;
30 import java.util.ArrayList;
31 import java.util.Collection;
32 import java.util.Collections;
33 import java.util.HashMap;
34 import java.util.Iterator;
35 import java.util.List;
36 import java.util.Locale;
38 import java.util.Map.Entry;
39 import java.util.Objects;
40 import java.util.Optional;
42 import java.util.concurrent.CancellationException;
43 import java.util.concurrent.ExecutionException;
44 import javax.inject.Inject;
45 import javax.inject.Singleton;
46 import javax.ws.rs.WebApplicationException;
47 import javax.ws.rs.core.Context;
48 import javax.ws.rs.core.Response;
49 import javax.ws.rs.core.Response.ResponseBuilder;
50 import javax.ws.rs.core.Response.Status;
51 import javax.ws.rs.core.UriBuilder;
52 import javax.ws.rs.core.UriInfo;
53 import org.opendaylight.mdsal.common.api.CommitInfo;
54 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
55 import org.opendaylight.mdsal.common.api.OptimisticLockFailedException;
56 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
57 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
58 import org.opendaylight.mdsal.dom.api.DOMRpcImplementationNotAvailableException;
59 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
60 import org.opendaylight.mdsal.dom.api.DOMRpcService;
61 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
62 import org.opendaylight.netconf.sal.rest.api.Draft02;
63 import org.opendaylight.netconf.sal.rest.api.RestconfService;
64 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
65 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
66 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
67 import org.opendaylight.netconf.sal.streams.websockets.WebSocketServer;
68 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
69 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
70 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
71 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
72 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
73 import org.opendaylight.restconf.common.patch.PatchContext;
74 import org.opendaylight.restconf.common.patch.PatchStatusContext;
75 import org.opendaylight.restconf.common.util.DataChangeScope;
76 import org.opendaylight.restconf.common.validation.RestconfValidationUtils;
77 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
78 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
79 import org.opendaylight.yangtools.yang.common.Empty;
80 import org.opendaylight.yangtools.yang.common.QName;
81 import org.opendaylight.yangtools.yang.common.QNameModule;
82 import org.opendaylight.yangtools.yang.common.Revision;
83 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
84 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
85 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
86 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
87 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
88 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
89 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
90 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
91 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
92 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
93 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
94 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
95 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
96 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
97 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
98 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
99 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
100 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
101 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
102 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
103 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeBuilder;
104 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
105 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
106 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
107 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
108 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
109 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
110 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
111 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
112 import org.opendaylight.yangtools.yang.model.api.Module;
113 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
114 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
115 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
116 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
117 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
118 import org.opendaylight.yangtools.yang.model.util.SimpleSchemaContext;
119 import org.slf4j.Logger;
120 import org.slf4j.LoggerFactory;
123 public final class RestconfImpl implements RestconfService {
125 * Notifications are served on port 8181.
127 private static final int NOTIFICATION_PORT = 8181;
129 private static final int CHAR_NOT_FOUND = -1;
131 private static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
133 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
135 private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
137 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
139 private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
141 private static final String DATASTORE_PARAM_NAME = "datastore";
143 private static final String SCOPE_PARAM_NAME = "scope";
145 private static final String OUTPUT_TYPE_PARAM_NAME = "notification-output-type";
147 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
149 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
151 private static final QName NETCONF_BASE_QNAME = QName.create(QNameModule.create(URI.create(NETCONF_BASE)),
152 NETCONF_BASE_PAYLOAD_NAME).intern();
154 private static final QNameModule SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
155 Revision.of("2014-07-08"));
157 private static final AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER =
158 new AugmentationIdentifier(ImmutableSet.of(
159 QName.create(SAL_REMOTE_AUGMENT, "scope"), QName.create(SAL_REMOTE_AUGMENT, "datastore"),
160 QName.create(SAL_REMOTE_AUGMENT, "notification-output-type")));
162 public static final CharSequence DATA_SUBSCR = "data-change-event-subscription";
163 private static final CharSequence CREATE_DATA_SUBSCR = "create-" + DATA_SUBSCR;
165 public static final CharSequence NOTIFICATION_STREAM = "notification-stream";
166 private static final CharSequence CREATE_NOTIFICATION_STREAM = "create-" + NOTIFICATION_STREAM;
168 private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
169 .appendValue(ChronoField.YEAR, 4).appendLiteral('-')
170 .appendValue(ChronoField.MONTH_OF_YEAR, 2).appendLiteral('-')
171 .appendValue(ChronoField.DAY_OF_MONTH, 2).appendLiteral('T')
172 .appendValue(ChronoField.HOUR_OF_DAY, 2).appendLiteral(':')
173 .appendValue(ChronoField.MINUTE_OF_HOUR, 2).appendLiteral(':')
174 .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
175 .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
176 .appendOffset("+HH:MM", "Z").toFormatter();
178 private final BrokerFacade broker;
180 private final ControllerContext controllerContext;
183 public RestconfImpl(final BrokerFacade broker, final ControllerContext controllerContext) {
184 this.broker = broker;
185 this.controllerContext = controllerContext;
191 * @deprecated Just use {@link #RestconfImpl(BrokerFacade, ControllerContext)} constructor instead.
194 public static RestconfImpl newInstance(final BrokerFacade broker, final ControllerContext controllerContext) {
195 return new RestconfImpl(broker, controllerContext);
199 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
200 final Set<Module> allModules = this.controllerContext.getAllModules();
201 final MapNode allModuleMap = makeModuleMapNode(allModules);
203 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
205 final Module restconfModule = getRestconfModule();
206 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
207 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
208 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
210 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
211 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
212 moduleContainerBuilder.withChild(allModuleMap);
214 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode, null, schemaContext),
215 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
219 * Valid only for mount point.
222 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
223 Preconditions.checkNotNull(identifier);
224 if (!identifier.contains(ControllerContext.MOUNT)) {
225 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
226 + " URI has to end with " + ControllerContext.MOUNT;
227 LOG.debug("{} for {}", errMsg, identifier);
228 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
231 final InstanceIdentifierContext<?> mountPointIdentifier =
232 this.controllerContext.toMountPointIdentifier(identifier);
233 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
234 final Set<Module> modules = this.controllerContext.getAllModules(mountPoint);
235 final MapNode mountPointModulesMap = makeModuleMapNode(modules);
237 final Module restconfModule = getRestconfModule();
238 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
239 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
240 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
242 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
243 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
244 moduleContainerBuilder.withChild(mountPointModulesMap);
246 return new NormalizedNodeContext(
247 new InstanceIdentifierContext<>(null, modulesSchemaNode, mountPoint,
248 this.controllerContext.getGlobalSchema()),
249 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
253 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
254 Preconditions.checkNotNull(identifier);
255 final Entry<String, Revision> nameRev = getModuleNameAndRevision(identifier);
256 Module module = null;
257 DOMMountPoint mountPoint = null;
258 final SchemaContext schemaContext;
259 if (identifier.contains(ControllerContext.MOUNT)) {
260 final InstanceIdentifierContext<?> mountPointIdentifier =
261 this.controllerContext.toMountPointIdentifier(identifier);
262 mountPoint = mountPointIdentifier.getMountPoint();
263 module = this.controllerContext.findModuleByNameAndRevision(mountPoint, nameRev.getKey(),
265 schemaContext = mountPoint.getSchemaContext();
267 module = this.controllerContext.findModuleByNameAndRevision(nameRev.getKey(), nameRev.getValue());
268 schemaContext = this.controllerContext.getGlobalSchema();
271 if (module == null) {
272 LOG.debug("Module with name '{}' and revision '{}' was not found.", nameRev.getKey(), nameRev.getValue());
273 throw new RestconfDocumentedException("Module with name '" + nameRev.getKey() + "' and revision '"
274 + nameRev.getValue() + "' was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
277 final Module restconfModule = getRestconfModule();
278 final Set<Module> modules = Collections.singleton(module);
279 final MapNode moduleMap = makeModuleMapNode(modules);
281 final DataSchemaNode moduleSchemaNode = this.controllerContext
282 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
283 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
285 return new NormalizedNodeContext(
286 new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint, schemaContext), moduleMap,
287 QueryParametersParser.parseWriterParameters(uriInfo));
291 public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
292 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
293 final Set<String> availableStreams = Notificator.getStreamNames();
294 final Module restconfModule = getRestconfModule();
295 final DataSchemaNode streamSchemaNode = this.controllerContext
296 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
297 Preconditions.checkState(streamSchemaNode instanceof ListSchemaNode);
299 final CollectionNodeBuilder<MapEntryNode, MapNode> listStreamsBuilder =
300 Builders.mapBuilder((ListSchemaNode) streamSchemaNode);
302 for (final String streamName : availableStreams) {
303 listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
306 final DataSchemaNode streamsContainerSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
307 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
308 Preconditions.checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
310 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
311 Builders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
312 streamsContainerBuilder.withChild(listStreamsBuilder.build());
314 return new NormalizedNodeContext(
315 new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null, schemaContext),
316 streamsContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
320 public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
321 final Set<Module> allModules = this.controllerContext.getAllModules();
322 return operationsFromModulesToNormalizedContext(allModules, null);
326 public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
327 Set<Module> modules = null;
328 DOMMountPoint mountPoint = null;
329 if (identifier.contains(ControllerContext.MOUNT)) {
330 final InstanceIdentifierContext<?> mountPointIdentifier =
331 this.controllerContext.toMountPointIdentifier(identifier);
332 mountPoint = mountPointIdentifier.getMountPoint();
333 modules = this.controllerContext.getAllModules(mountPoint);
336 final String errMsg = "URI has bad format. If operations behind mount point should be showed, URI has to "
337 + " end with " + ControllerContext.MOUNT;
338 LOG.debug("{} for {}", errMsg, identifier);
339 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
342 return operationsFromModulesToNormalizedContext(modules, mountPoint);
346 * Special case only for GET restconf/operations use (since moment of
347 * pre-Beryllium Yang parser and Yang model API removal). The method is
348 * creating fake schema context with fake module and fake data by use own
349 * implementations of schema nodes and module.
352 * set of modules for get RPCs from every module
354 * mount point, if in use otherwise null
355 * @return {@link NormalizedNodeContext}
357 private static NormalizedNodeContext operationsFromModulesToNormalizedContext(final Set<Module> modules,
358 final DOMMountPoint mountPoint) {
360 final Collection<Module> neededModules = new ArrayList<>(modules.size());
361 final ArrayList<LeafSchemaNode> fakeRpcSchema = new ArrayList<>();
363 for (final Module m : modules) {
364 final Set<RpcDefinition> rpcs = m.getRpcs();
365 if (!rpcs.isEmpty()) {
366 neededModules.add(m);
368 fakeRpcSchema.ensureCapacity(fakeRpcSchema.size() + rpcs.size());
369 rpcs.forEach(rpc -> fakeRpcSchema.add(new FakeLeafSchemaNode(rpc.getQName())));
373 final ContainerSchemaNode fakeCont = new FakeContainerSchemaNode(fakeRpcSchema);
374 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> containerBuilder =
375 Builders.containerBuilder(fakeCont);
377 for (final LeafSchemaNode leaf : fakeRpcSchema) {
378 containerBuilder.withChild(Builders.leafBuilder(leaf).withValue(Empty.getInstance()).build());
381 final Collection<Module> fakeModules = new ArrayList<>(neededModules.size() + 1);
382 neededModules.forEach(imp -> fakeModules.add(new FakeImportedModule(imp)));
383 fakeModules.add(new FakeRestconfModule(neededModules, fakeCont));
385 final SchemaContext fakeSchemaCtx = SimpleSchemaContext.forModules(ImmutableSet.copyOf(fakeModules));
386 final InstanceIdentifierContext<ContainerSchemaNode> instanceIdentifierContext =
387 new InstanceIdentifierContext<>(null, fakeCont, mountPoint, fakeSchemaCtx);
388 return new NormalizedNodeContext(instanceIdentifierContext, containerBuilder.build());
391 private Module getRestconfModule() {
392 final Module restconfModule = this.controllerContext.getRestconfModule();
393 if (restconfModule == null) {
394 LOG.debug("ietf-restconf module was not found.");
395 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
396 ErrorTag.OPERATION_NOT_SUPPORTED);
399 return restconfModule;
402 private static Entry<String, Revision> getModuleNameAndRevision(final String identifier) {
403 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
404 String moduleNameAndRevision = "";
405 if (mountIndex >= 0) {
406 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
408 moduleNameAndRevision = identifier;
411 final Splitter splitter = Splitter.on('/').omitEmptyStrings();
412 final List<String> pathArgs = splitter.splitToList(moduleNameAndRevision);
413 if (pathArgs.size() < 2) {
414 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' {}", identifier);
415 throw new RestconfDocumentedException(
416 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
417 ErrorTag.INVALID_VALUE);
421 return new SimpleImmutableEntry<>(pathArgs.get(0), Revision.of(pathArgs.get(1)));
422 } catch (final DateTimeParseException e) {
423 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' {}", identifier);
424 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
425 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
430 public Object getRoot() {
435 public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload,
436 final UriInfo uriInfo) {
437 if (payload == null) {
438 // no payload specified, reroute this to no payload invokeRpc implementation
439 return invokeRpc(identifier, uriInfo);
442 final SchemaPath type = payload.getInstanceIdentifierContext().getSchemaNode().getPath();
443 final URI namespace = payload.getInstanceIdentifierContext().getSchemaNode().getQName().getNamespace();
444 final ListenableFuture<DOMRpcResult> response;
445 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
446 final SchemaContext schemaContext;
448 if (mountPoint != null) {
449 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
450 if (!mountRpcServices.isPresent()) {
451 LOG.debug("Error: Rpc service is missing.");
452 throw new RestconfDocumentedException("Rpc service is missing.");
454 schemaContext = mountPoint.getSchemaContext();
455 response = mountRpcServices.get().invokeRpc(type, payload.getData());
457 if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
458 if (identifier.contains(CREATE_DATA_SUBSCR)) {
459 response = invokeSalRemoteRpcSubscribeRPC(payload);
460 } else if (identifier.contains(CREATE_NOTIFICATION_STREAM)) {
461 response = invokeSalRemoteRpcNotifiStrRPC(payload);
463 final String msg = "Not supported operation";
465 throw new RestconfDocumentedException(msg, ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED);
468 response = this.broker.invokeRpc(type, payload.getData());
470 schemaContext = this.controllerContext.getGlobalSchema();
473 final DOMRpcResult result = checkRpcResponse(response);
475 RpcDefinition resultNodeSchema = null;
476 final NormalizedNode<?, ?> resultData;
477 if (result != null && result.getResult() != null) {
478 resultData = result.getResult();
479 resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
484 if (resultData != null && ((ContainerNode) resultData).getValue().isEmpty()) {
485 throw new WebApplicationException(Response.Status.NO_CONTENT);
487 return new NormalizedNodeContext(
488 new InstanceIdentifierContext<>(null, resultNodeSchema, mountPoint, schemaContext),
489 resultData, QueryParametersParser.parseWriterParameters(uriInfo));
493 private NormalizedNodeContext invokeRpc(final String identifier, final UriInfo uriInfo) {
495 DOMMountPoint mountPoint = null;
496 final String identifierEncoded;
497 final SchemaContext schemaContext;
498 if (identifier.contains(ControllerContext.MOUNT)) {
499 // mounted RPC call - look up mount instance.
500 final InstanceIdentifierContext<?> mountPointId = this.controllerContext.toMountPointIdentifier(identifier);
501 mountPoint = mountPointId.getMountPoint();
502 schemaContext = mountPoint.getSchemaContext();
503 final int startOfRemoteRpcName =
504 identifier.lastIndexOf(ControllerContext.MOUNT) + ControllerContext.MOUNT.length() + 1;
505 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
506 identifierEncoded = remoteRpcName;
508 } else if (identifier.indexOf('/') != CHAR_NOT_FOUND) {
509 LOG.debug("Identifier {} cannot contain slash character (/).", identifier);
510 throw new RestconfDocumentedException(String.format("Identifier %n%s%ncan\'t contain slash character (/).%n"
511 + "If slash is part of identifier name then use %%2F placeholder.", identifier), ErrorType.PROTOCOL,
512 ErrorTag.INVALID_VALUE);
514 identifierEncoded = identifier;
515 schemaContext = this.controllerContext.getGlobalSchema();
518 final String identifierDecoded = this.controllerContext.urlPathArgDecode(identifierEncoded);
521 if (mountPoint == null) {
522 rpc = this.controllerContext.getRpcDefinition(identifierDecoded);
524 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
528 LOG.debug("RPC {} does not exist.", identifierDecoded);
529 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
532 if (!rpc.getInput().getChildNodes().isEmpty()) {
533 LOG.debug("No input specified for RPC {} with an input section", rpc);
534 throw new RestconfDocumentedException("No input specified for RPC " + rpc
535 + " with an input section defined", ErrorType.RPC, ErrorTag.MISSING_ELEMENT);
538 final ListenableFuture<DOMRpcResult> response;
539 if (mountPoint != null) {
540 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
541 if (!mountRpcServices.isPresent()) {
542 throw new RestconfDocumentedException("Rpc service is missing.");
544 response = mountRpcServices.get().invokeRpc(rpc.getPath(), null);
546 response = this.broker.invokeRpc(rpc.getPath(), null);
549 final DOMRpcResult result = checkRpcResponse(response);
551 if (result.getResult() != null && ((ContainerNode) result.getResult()).getValue().isEmpty()) {
552 throw new WebApplicationException(Response.Status.NO_CONTENT);
554 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpc, mountPoint, schemaContext),
555 result.getResult(), QueryParametersParser.parseWriterParameters(uriInfo));
559 @SuppressWarnings("checkstyle:avoidHidingCauseException")
560 private static DOMRpcResult checkRpcResponse(final ListenableFuture<DOMRpcResult> response) {
561 if (response == null) {
565 final DOMRpcResult retValue = response.get();
566 if (retValue.getErrors().isEmpty()) {
569 LOG.debug("RpcError message {}", retValue.getErrors());
570 throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
571 } catch (final InterruptedException e) {
572 final String errMsg = "The operation was interrupted while executing and did not complete.";
573 LOG.debug("Rpc Interrupt - {}", errMsg, e);
574 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION, e);
575 } catch (final ExecutionException e) {
576 LOG.debug("Execution RpcError: ", e);
577 Throwable cause = e.getCause();
579 while (cause.getCause() != null) {
580 cause = cause.getCause();
583 if (cause instanceof IllegalArgumentException) {
584 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL,
585 ErrorTag.INVALID_VALUE);
586 } else if (cause instanceof DOMRpcImplementationNotAvailableException) {
587 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.APPLICATION,
588 ErrorTag.OPERATION_NOT_SUPPORTED);
590 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
593 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
596 } catch (final CancellationException e) {
597 final String errMsg = "The operation was cancelled while executing.";
598 LOG.debug("Cancel RpcExecution: {}", errMsg, e);
599 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
603 private static void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
604 if (inputSchema != null && payload.getData() == null) {
605 // expected a non null payload
606 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
607 } else if (inputSchema == null && payload.getData() != null) {
608 // did not expect any input
609 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
613 private ListenableFuture<DOMRpcResult> invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
614 final ContainerNode value = (ContainerNode) payload.getData();
615 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
616 final Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(
617 new NodeIdentifier(QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(),
619 final Object pathValue = path.isPresent() ? path.get().getValue() : null;
621 if (!(pathValue instanceof YangInstanceIdentifier)) {
622 LOG.debug("Instance identifier {} was not normalized correctly", rpcQName);
623 throw new RestconfDocumentedException("Instance identifier was not normalized correctly",
624 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
627 final YangInstanceIdentifier pathIdentifier = (YangInstanceIdentifier) pathValue;
628 String streamName = (String) CREATE_DATA_SUBSCR;
629 NotificationOutputType outputType = null;
630 if (!pathIdentifier.isEmpty()) {
631 final String fullRestconfIdentifier =
632 DATA_SUBSCR + this.controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
634 LogicalDatastoreType datastore =
635 parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
636 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
638 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
639 scope = scope == null ? DEFAULT_SCOPE : scope;
641 outputType = parseEnumTypeParameter(value, NotificationOutputType.class, OUTPUT_TYPE_PARAM_NAME);
642 outputType = outputType == null ? NotificationOutputType.XML : outputType;
644 streamName = Notificator
645 .createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore + "/scope=" + scope);
648 if (Strings.isNullOrEmpty(streamName)) {
649 LOG.debug("Path is empty or contains value node which is not Container or List built-in type at {}",
651 throw new RestconfDocumentedException("Path is empty or contains value node which is not Container or List "
652 + "built-in type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
655 final QName outputQname = QName.create(rpcQName, "output");
656 final QName streamNameQname = QName.create(rpcQName, "stream-name");
658 final ContainerNode output =
659 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
660 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
662 if (!Notificator.existListenerFor(streamName)) {
663 Notificator.createListener(pathIdentifier, streamName, outputType, controllerContext);
666 return Futures.immediateFuture(new DefaultDOMRpcResult(output));
669 private static RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
670 final String[] splittedIdentifier = identifierDecoded.split(":");
671 if (splittedIdentifier.length != 2) {
672 LOG.debug("{} could not be split to 2 parts (module:rpc name)", identifierDecoded);
673 throw new RestconfDocumentedException(identifierDecoded + " could not be split to 2 parts "
674 + "(module:rpc name)", ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
676 for (final Module module : schemaContext.getModules()) {
677 if (module.getName().equals(splittedIdentifier[0])) {
678 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
679 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
680 return rpcDefinition;
689 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
690 boolean withDefaUsed = false;
691 String withDefa = null;
693 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
694 switch (entry.getKey()) {
695 case "with-defaults":
698 withDefa = entry.getValue().iterator().next();
700 throw new RestconfDocumentedException("With-defaults parameter can be used only once.");
704 LOG.info("Unknown key : {}.", entry.getKey());
708 boolean tagged = false;
710 if ("report-all-tagged".equals(withDefa)) {
714 if ("report-all".equals(withDefa)) {
719 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
720 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
721 NormalizedNode<?, ?> data = null;
722 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
723 if (mountPoint != null) {
724 data = this.broker.readConfigurationData(mountPoint, normalizedII, withDefa);
726 data = this.broker.readConfigurationData(normalizedII, withDefa);
729 throw dataMissing(identifier);
731 return new NormalizedNodeContext(iiWithData, data,
732 QueryParametersParser.parseWriterParameters(uriInfo, tagged));
736 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
737 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
738 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
739 NormalizedNode<?, ?> data = null;
740 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
741 if (mountPoint != null) {
742 data = this.broker.readOperationalData(mountPoint, normalizedII);
744 data = this.broker.readOperationalData(normalizedII);
747 throw dataMissing(identifier);
749 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
752 private static RestconfDocumentedException dataMissing(final String identifier) {
753 LOG.debug("Request could not be completed because the relevant data model content does not exist {}",
755 return new RestconfDocumentedException("Request could not be completed because the relevant data model content "
756 + "does not exist", ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
760 public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload,
761 final UriInfo uriInfo) {
762 boolean insertUsed = false;
763 boolean pointUsed = false;
764 String insert = null;
767 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
768 switch (entry.getKey()) {
772 insert = entry.getValue().iterator().next();
774 throw new RestconfDocumentedException("Insert parameter can be used only once.");
780 point = entry.getValue().iterator().next();
782 throw new RestconfDocumentedException("Point parameter can be used only once.");
786 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
790 if (pointUsed && !insertUsed) {
791 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
793 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
794 throw new RestconfDocumentedException(
795 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
798 Preconditions.checkNotNull(identifier);
800 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
802 validateInput(iiWithData.getSchemaNode(), payload);
803 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
804 validateListKeysEqualityInPayloadAndUri(payload);
806 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
807 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
810 * There is a small window where another write transaction could be
811 * updating the same data simultaneously and we get an
812 * OptimisticLockFailedException. This error is likely transient and The
813 * WriteTransaction#submit API docs state that a retry will likely
814 * succeed. So we'll try again if that scenario occurs. If it fails a
815 * third time then it probably will never succeed so we'll fail in that
818 * By retrying we're attempting to hide the internal implementation of
819 * the data store and how it handles concurrent updates from the
820 * restconf client. The client has instructed us to put the data and we
821 * should make every effort to do so without pushing optimistic lock
822 * failures back to the client and forcing them to handle it via retry
823 * (and having to document the behavior).
825 PutResult result = null;
828 if (mountPoint != null) {
830 result = this.broker.commitMountPointDataPut(mountPoint, normalizedII, payload.getData(), insert,
833 result = this.broker.commitConfigurationDataPut(this.controllerContext.getGlobalSchema(), normalizedII,
834 payload.getData(), insert, point);
838 result.getFutureOfPutData().get();
839 } catch (final InterruptedException e) {
840 LOG.debug("Update failed for {}", identifier, e);
841 throw new RestconfDocumentedException(e.getMessage(), e);
842 } catch (final ExecutionException e) {
843 final TransactionCommitFailedException failure = Throwables.getCauseAs(e,
844 TransactionCommitFailedException.class);
845 if (failure instanceof OptimisticLockFailedException) {
847 LOG.debug("Got OptimisticLockFailedException on last try - failing {}", identifier);
848 throw new RestconfDocumentedException(e.getMessage(), e, failure.getErrorList());
851 LOG.debug("Got OptimisticLockFailedException - trying again {}", identifier);
855 LOG.debug("Update failed for {}", identifier, e);
856 throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), failure);
859 return Response.status(result.getStatus()).build();
863 private static void validateTopLevelNodeName(final NormalizedNodeContext node,
864 final YangInstanceIdentifier identifier) {
866 final String payloadName = node.getData().getNodeType().getLocalName();
869 if (identifier.isEmpty()) {
871 if (!node.getData().getNodeType().equals(NETCONF_BASE_QNAME)) {
872 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
873 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
877 final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
878 if (!payloadName.equals(identifierName)) {
879 throw new RestconfDocumentedException(
880 "Payload name (" + payloadName + ") is different from identifier name (" + identifierName + ")",
881 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
887 * Validates whether keys in {@code payload} are equal to values of keys in
888 * {@code iiWithData} for list schema node.
890 * @throws RestconfDocumentedException
891 * if key values or key count in payload and URI isn't equal
894 private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
895 Preconditions.checkArgument(payload != null);
896 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
897 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
898 final SchemaNode schemaNode = iiWithData.getSchemaNode();
899 final NormalizedNode<?, ?> data = payload.getData();
900 if (schemaNode instanceof ListSchemaNode) {
901 final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
902 if (lastPathArgument instanceof NodeIdentifierWithPredicates && data instanceof MapEntryNode) {
903 final Map<QName, Object> uriKeyValues =
904 ((NodeIdentifierWithPredicates) lastPathArgument).getKeyValues();
905 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
911 public static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final MapEntryNode payload,
912 final List<QName> keyDefinitions) {
914 final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
915 for (final QName keyDefinition : keyDefinitions) {
916 final Object uriKeyValue = mutableCopyUriKeyValues.remove(keyDefinition);
917 // should be caught during parsing URI to InstanceIdentifier
918 RestconfValidationUtils.checkDocumentedError(uriKeyValue != null, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
919 "Missing key " + keyDefinition + " in URI.");
921 final Object dataKeyValue = payload.getIdentifier().getKeyValues().get(keyDefinition);
923 if (!Objects.deepEquals(uriKeyValue, dataKeyValue)) {
924 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName()
925 + "' specified in the URI doesn't match the value '" + dataKeyValue
926 + "' specified in the message body. ";
927 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
933 public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload,
934 final UriInfo uriInfo) {
935 return createConfigurationData(payload, uriInfo);
939 public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
940 if (payload == null) {
941 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
943 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
944 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
945 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
947 boolean insertUsed = false;
948 boolean pointUsed = false;
949 String insert = null;
952 if (uriInfo != null) {
953 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
954 switch (entry.getKey()) {
958 insert = entry.getValue().iterator().next();
960 throw new RestconfDocumentedException("Insert parameter can be used only once.");
966 point = entry.getValue().iterator().next();
968 throw new RestconfDocumentedException("Point parameter can be used only once.");
972 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
977 if (pointUsed && !insertUsed) {
978 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
980 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
981 throw new RestconfDocumentedException(
982 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
985 FluentFuture<? extends CommitInfo> future;
986 if (mountPoint != null) {
987 future = this.broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData(), insert,
990 future = this.broker.commitConfigurationDataPost(this.controllerContext.getGlobalSchema(), normalizedII,
991 payload.getData(), insert, point);
996 } catch (final InterruptedException e) {
997 LOG.info("Error creating data {}", uriInfo != null ? uriInfo.getPath() : "", e);
998 throw new RestconfDocumentedException(e.getMessage(), e);
999 } catch (final ExecutionException e) {
1000 LOG.info("Error creating data {}", uriInfo != null ? uriInfo.getPath() : "", e);
1001 throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), Throwables.getCauseAs(e,
1002 TransactionCommitFailedException.class));
1005 LOG.trace("Successfuly created data.");
1007 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
1008 // FIXME: Provide path to result.
1009 final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
1010 if (location != null) {
1011 responseBuilder.location(location);
1013 return responseBuilder.build();
1016 @SuppressWarnings("checkstyle:IllegalCatch")
1017 private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint,
1018 final YangInstanceIdentifier normalizedII) {
1019 if (uriInfo == null) {
1020 // This is null if invoked internally
1024 final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
1025 uriBuilder.path("config");
1027 uriBuilder.path(this.controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
1028 } catch (final Exception e) {
1029 LOG.info("Location for instance identifier {} was not created", normalizedII, e);
1032 return uriBuilder.build();
1036 public Response deleteConfigurationData(final String identifier) {
1037 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
1038 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
1039 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
1041 final FluentFuture<? extends CommitInfo> future;
1042 if (mountPoint != null) {
1043 future = this.broker.commitConfigurationDataDelete(mountPoint, normalizedII);
1045 future = this.broker.commitConfigurationDataDelete(normalizedII);
1050 } catch (final InterruptedException e) {
1051 throw new RestconfDocumentedException(e.getMessage(), e);
1052 } catch (final ExecutionException e) {
1053 final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
1054 Predicates.instanceOf(ModifiedNodeDoesNotExistException.class)).toJavaUtil();
1055 if (searchedException.isPresent()) {
1056 throw new RestconfDocumentedException("Data specified for delete doesn't exist.", ErrorType.APPLICATION,
1057 ErrorTag.DATA_MISSING, e);
1060 throw RestconfDocumentedException.decodeAndThrow(e.getMessage(), Throwables.getCauseAs(e,
1061 TransactionCommitFailedException.class));
1064 return Response.status(Status.OK).build();
1068 * Subscribes to some path in schema context (stream) to listen on changes
1072 * Additional parameters for subscribing to stream are loaded via rpc input
1075 * <li>datastore - default CONFIGURATION (other values of
1076 * {@link LogicalDatastoreType} enum type)</li>
1077 * <li>scope - default BASE (other values of {@link DataChangeScope})</li>
1081 public NormalizedNodeContext subscribeToStream(final String identifier, final UriInfo uriInfo) {
1082 boolean startTimeUsed = false;
1083 boolean stopTimeUsed = false;
1084 Instant start = Instant.now();
1085 Instant stop = null;
1086 boolean filterUsed = false;
1087 String filter = null;
1088 boolean leafNodesOnlyUsed = false;
1089 boolean leafNodesOnly = false;
1091 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
1092 switch (entry.getKey()) {
1094 if (!startTimeUsed) {
1095 startTimeUsed = true;
1096 start = parseDateFromQueryParam(entry);
1098 throw new RestconfDocumentedException("Start-time parameter can be used only once.");
1102 if (!stopTimeUsed) {
1103 stopTimeUsed = true;
1104 stop = parseDateFromQueryParam(entry);
1106 throw new RestconfDocumentedException("Stop-time parameter can be used only once.");
1112 filter = entry.getValue().iterator().next();
1114 throw new RestconfDocumentedException("Filter parameter can be used only once.");
1117 case "odl-leaf-nodes-only":
1118 if (!leafNodesOnlyUsed) {
1119 leafNodesOnlyUsed = true;
1120 leafNodesOnly = Boolean.parseBoolean(entry.getValue().iterator().next());
1122 throw new RestconfDocumentedException("Odl-leaf-nodes-only parameter can be used only once.");
1126 throw new RestconfDocumentedException("Bad parameter used with notifications: " + entry.getKey());
1129 if (!startTimeUsed && stopTimeUsed) {
1130 throw new RestconfDocumentedException("Stop-time parameter has to be used with start-time parameter.");
1132 URI response = null;
1133 if (identifier.contains(DATA_SUBSCR)) {
1134 response = dataSubs(identifier, uriInfo, start, stop, filter, leafNodesOnly);
1135 } else if (identifier.contains(NOTIFICATION_STREAM)) {
1136 response = notifStream(identifier, uriInfo, start, stop, filter);
1139 if (response != null) {
1140 // prepare node with value of location
1141 final InstanceIdentifierContext<?> iid = prepareIIDSubsStreamOutput();
1142 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> builder =
1143 ImmutableLeafNodeBuilder.create().withValue(response.toString());
1144 builder.withNodeIdentifier(
1145 NodeIdentifier.create(QName.create("subscribe:to:notification", "2016-10-28", "location")));
1147 // prepare new header with location
1148 final Map<String, Object> headers = new HashMap<>();
1149 headers.put("Location", response);
1151 return new NormalizedNodeContext(iid, builder.build(), headers);
1154 final String msg = "Bad type of notification of sal-remote";
1156 throw new RestconfDocumentedException(msg);
1159 private static Instant parseDateFromQueryParam(final Entry<String, List<String>> entry) {
1160 final DateAndTime event = new DateAndTime(entry.getValue().iterator().next());
1161 final String value = event.getValue();
1162 final TemporalAccessor p;
1164 p = FORMATTER.parse(value);
1165 } catch (final DateTimeParseException e) {
1166 throw new RestconfDocumentedException("Cannot parse of value in date: " + value, e);
1168 return Instant.from(p);
1172 * Prepare instance identifier.
1174 * @return {@link InstanceIdentifierContext} of location leaf for
1177 private InstanceIdentifierContext<?> prepareIIDSubsStreamOutput() {
1178 final QName qnameBase = QName.create("subscribe:to:notification", "2016-10-28", "notifi");
1179 final SchemaContext schemaCtx = controllerContext.getGlobalSchema();
1180 final DataSchemaNode location = ((ContainerSchemaNode) schemaCtx
1181 .findModule(qnameBase.getModule()).orElse(null)
1182 .getDataChildByName(qnameBase)).getDataChildByName(QName.create(qnameBase, "location"));
1183 final List<PathArgument> path = new ArrayList<>();
1184 path.add(NodeIdentifier.create(qnameBase));
1185 path.add(NodeIdentifier.create(QName.create(qnameBase, "location")));
1187 return new InstanceIdentifierContext<SchemaNode>(YangInstanceIdentifier.create(path), location, null,
1192 * Register notification listener by stream name.
1199 * stop-time of getting notification
1201 * start-time of getting notification
1203 * indicate which subset of all possible events are of interest
1204 * @return {@link URI} of location
1206 private URI notifStream(final String identifier, final UriInfo uriInfo, final Instant start,
1207 final Instant stop, final String filter) {
1208 final String streamName = Notificator.createStreamNameFromUri(identifier);
1209 if (Strings.isNullOrEmpty(streamName)) {
1210 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1212 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
1213 if (listeners == null || listeners.isEmpty()) {
1214 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1215 ErrorTag.UNKNOWN_ELEMENT);
1218 for (final NotificationListenerAdapter listener : listeners) {
1219 this.broker.registerToListenNotification(listener);
1220 listener.setQueryParams(start, Optional.ofNullable(stop), Optional.ofNullable(filter), false);
1223 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1225 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance(NOTIFICATION_PORT);
1226 final int notificationPort = webSocketServerInstance.getPort();
1229 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme(getWsScheme(uriInfo));
1231 return uriToWebsocketServerBuilder.replacePath(streamName).build();
1234 private static String getWsScheme(final UriInfo uriInfo) {
1235 URI uri = uriInfo.getAbsolutePath();
1239 String subscriptionScheme = uri.getScheme().toLowerCase(Locale.ROOT);
1240 return subscriptionScheme.equals("https") ? "wss" : "ws";
1244 * Register data change listener by stream name.
1251 * start-time of getting notification
1253 * stop-time of getting notification
1255 * indicate which subset of all possible events are of interest
1256 * @return {@link URI} of location
1258 private URI dataSubs(final String identifier, final UriInfo uriInfo, final Instant start, final Instant stop,
1259 final String filter, final boolean leafNodesOnly) {
1260 final String streamName = Notificator.createStreamNameFromUri(identifier);
1261 if (Strings.isNullOrEmpty(streamName)) {
1262 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1265 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1266 if (listener == null) {
1267 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1268 ErrorTag.UNKNOWN_ELEMENT);
1270 listener.setQueryParams(start, Optional.ofNullable(stop), Optional.ofNullable(filter), leafNodesOnly);
1272 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1273 final LogicalDatastoreType datastore =
1274 parserURIEnumParameter(LogicalDatastoreType.class, paramToValues.get(DATASTORE_PARAM_NAME));
1275 if (datastore == null) {
1276 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1277 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1279 final DataChangeScope scope =
1280 parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
1281 if (scope == null) {
1282 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1283 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1286 this.broker.registerToListenDataChanges(datastore, scope, listener);
1288 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1290 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance(NOTIFICATION_PORT);
1291 final int notificationPort = webSocketServerInstance.getPort();
1293 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme(getWsScheme(uriInfo));
1295 return uriToWebsocketServerBuilder.replacePath(streamName).build();
1298 @SuppressWarnings("checkstyle:IllegalCatch")
1300 public PatchStatusContext patchConfigurationData(final String identifier, final PatchContext context,
1301 final UriInfo uriInfo) {
1302 if (context == null) {
1303 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1307 return this.broker.patchConfigurationDataWithinTransaction(context);
1308 } catch (final Exception e) {
1309 LOG.debug("Patch transaction failed", e);
1310 throw new RestconfDocumentedException(e.getMessage(), e);
1314 @SuppressWarnings("checkstyle:IllegalCatch")
1316 public PatchStatusContext patchConfigurationData(final PatchContext context, @Context final UriInfo uriInfo) {
1317 if (context == null) {
1318 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1322 return this.broker.patchConfigurationDataWithinTransaction(context);
1323 } catch (final Exception e) {
1324 LOG.debug("Patch transaction failed", e);
1325 throw new RestconfDocumentedException(e.getMessage(), e);
1330 * Load parameter for subscribing to stream from input composite node.
1334 * @return enum object if its string value is equal to {@code paramName}. In
1337 private static <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1338 final String paramName) {
1339 final Optional<DataContainerChild<? extends PathArgument, ?>> optAugNode = value.getChild(
1340 SAL_REMOTE_AUG_IDENTIFIER);
1341 if (!optAugNode.isPresent()) {
1344 final DataContainerChild<? extends PathArgument, ?> augNode = optAugNode.get();
1345 if (!(augNode instanceof AugmentationNode)) {
1348 final Optional<DataContainerChild<? extends PathArgument, ?>> enumNode = ((AugmentationNode) augNode).getChild(
1349 new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1350 if (!enumNode.isPresent()) {
1353 final Object rawValue = enumNode.get().getValue();
1354 if (!(rawValue instanceof String)) {
1358 return resolveAsEnum(classDescriptor, (String) rawValue);
1362 * Checks whether {@code value} is one of the string representation of
1363 * enumeration {@code classDescriptor}.
1365 * @return enum object if string value of {@code classDescriptor}
1366 * enumeration is equal to {@code value}. Other cases null.
1368 private static <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1369 if (Strings.isNullOrEmpty(value)) {
1372 return resolveAsEnum(classDescriptor, value);
1375 private static <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1376 final T[] enumConstants = classDescriptor.getEnumConstants();
1377 if (enumConstants != null) {
1378 for (final T enm : classDescriptor.getEnumConstants()) {
1379 if (((Enum<?>) enm).name().equals(value)) {
1387 private static Map<String, String> resolveValuesFromUri(final String uri) {
1388 final Map<String, String> result = new HashMap<>();
1389 final String[] tokens = uri.split("/");
1390 for (int i = 1; i < tokens.length; i++) {
1391 final String[] parameterTokens = tokens[i].split("=");
1392 if (parameterTokens.length == 2) {
1393 result.put(parameterTokens[0], parameterTokens[1]);
1399 private MapNode makeModuleMapNode(final Set<Module> modules) {
1400 Preconditions.checkNotNull(modules);
1401 final Module restconfModule = getRestconfModule();
1402 final DataSchemaNode moduleSchemaNode = this.controllerContext
1403 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1404 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1406 final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder =
1407 Builders.mapBuilder((ListSchemaNode) moduleSchemaNode);
1409 for (final Module module : modules) {
1410 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1412 return listModuleBuilder.build();
1415 private MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1416 Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1417 "moduleSchemaNode has to be of type ListSchemaNode");
1418 final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1419 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues =
1420 Builders.mapEntryBuilder(listModuleSchemaNode);
1422 List<DataSchemaNode> instanceDataChildrenByName =
1423 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "name");
1424 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1425 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1427 .withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName()).build());
1429 final QNameModule qNameModule = module.getQNameModule();
1431 instanceDataChildrenByName =
1432 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "revision");
1433 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1434 Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1435 final Optional<Revision> revision = qNameModule.getRevision();
1436 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode)
1437 .withValue(revision.map(Revision::toString).orElse("")).build());
1439 instanceDataChildrenByName =
1440 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "namespace");
1441 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1442 Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1443 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1444 .withValue(qNameModule.getNamespace().toString()).build());
1446 instanceDataChildrenByName =
1447 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "feature");
1448 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1449 Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1450 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder =
1451 Builders.leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1452 for (final FeatureDefinition feature : module.getFeatures()) {
1453 featuresBuilder.withChild(Builders.leafSetEntryBuilder((LeafListSchemaNode) featureSchemaNode)
1454 .withValue(feature.getQName().getLocalName()).build());
1456 moduleNodeValues.withChild(featuresBuilder.build());
1458 return moduleNodeValues.build();
1461 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1462 Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1463 "streamSchemaNode has to be of type ListSchemaNode");
1464 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1465 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues =
1466 Builders.mapEntryBuilder(listStreamSchemaNode);
1468 List<DataSchemaNode> instanceDataChildrenByName =
1469 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "name");
1470 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1471 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1472 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName).build());
1474 instanceDataChildrenByName =
1475 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "description");
1476 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1477 Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1478 streamNodeValues.withChild(
1479 Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue("DESCRIPTION_PLACEHOLDER").build());
1481 instanceDataChildrenByName =
1482 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-support");
1483 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1484 Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1485 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1486 .withValue(Boolean.TRUE).build());
1488 instanceDataChildrenByName =
1489 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-log-creation-time");
1490 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1491 Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1492 streamNodeValues.withChild(
1493 Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode).withValue("").build());
1495 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "events");
1496 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1497 Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1498 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode).build());
1500 return streamNodeValues.build();
1504 * Prepare stream for notification.
1507 * contains list of qnames of notifications
1508 * @return - checked future object
1510 private ListenableFuture<DOMRpcResult> invokeSalRemoteRpcNotifiStrRPC(final NormalizedNodeContext payload) {
1511 final ContainerNode data = (ContainerNode) payload.getData();
1512 LeafSetNode leafSet = null;
1513 String outputType = "XML";
1514 for (final DataContainerChild<? extends PathArgument, ?> dataChild : data.getValue()) {
1515 if (dataChild instanceof LeafSetNode) {
1516 leafSet = (LeafSetNode) dataChild;
1517 } else if (dataChild instanceof AugmentationNode) {
1518 outputType = (String) ((AugmentationNode) dataChild).getValue().iterator().next().getValue();
1522 final Collection<LeafSetEntryNode> entryNodes = leafSet.getValue();
1523 final List<SchemaPath> paths = new ArrayList<>();
1524 String streamName = CREATE_NOTIFICATION_STREAM + "/";
1526 StringBuilder streamNameBuilder = new StringBuilder(streamName);
1527 final Iterator<LeafSetEntryNode> iterator = entryNodes.iterator();
1528 while (iterator.hasNext()) {
1529 final QName valueQName = QName.create((String) iterator.next().getValue());
1530 final Module module = controllerContext.findModuleByNamespace(valueQName.getModule().getNamespace());
1531 Preconditions.checkNotNull(module,
1532 "Module for namespace " + valueQName.getModule().getNamespace() + " does not exist");
1533 NotificationDefinition notifiDef = null;
1534 for (final NotificationDefinition notification : module.getNotifications()) {
1535 if (notification.getQName().equals(valueQName)) {
1536 notifiDef = notification;
1540 final String moduleName = module.getName();
1541 Preconditions.checkNotNull(notifiDef,
1542 "Notification " + valueQName + "doesn't exist in module " + moduleName);
1543 paths.add(notifiDef.getPath());
1544 streamNameBuilder.append(moduleName).append(':').append(valueQName.getLocalName());
1545 if (iterator.hasNext()) {
1546 streamNameBuilder.append(',');
1550 streamName = streamNameBuilder.toString();
1552 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
1553 final QName outputQname = QName.create(rpcQName, "output");
1554 final QName streamNameQname = QName.create(rpcQName, "notification-stream-identifier");
1556 final ContainerNode output =
1557 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
1558 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
1560 if (!Notificator.existNotificationListenerFor(streamName)) {
1561 Notificator.createNotificationListener(paths, streamName, outputType, controllerContext);
1564 return Futures.immediateFuture(new DefaultDOMRpcResult(output));