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.Lists;
22 import com.google.common.collect.Maps;
23 import com.google.common.util.concurrent.CheckedFuture;
24 import com.google.common.util.concurrent.Futures;
26 import java.text.ParseException;
27 import java.time.Instant;
28 import java.time.format.DateTimeFormatter;
29 import java.time.format.DateTimeFormatterBuilder;
30 import java.time.format.DateTimeParseException;
31 import java.time.temporal.ChronoField;
32 import java.time.temporal.TemporalAccessor;
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;
40 import java.util.Map.Entry;
41 import java.util.Objects;
43 import java.util.concurrent.CancellationException;
44 import java.util.concurrent.ExecutionException;
45 import javax.ws.rs.core.Context;
46 import javax.ws.rs.core.Response;
47 import javax.ws.rs.core.Response.ResponseBuilder;
48 import javax.ws.rs.core.Response.Status;
49 import javax.ws.rs.core.UriBuilder;
50 import javax.ws.rs.core.UriInfo;
51 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
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.DOMRpcException;
57 import org.opendaylight.controller.md.sal.dom.api.DOMRpcImplementationNotAvailableException;
58 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
59 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
60 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
61 import org.opendaylight.netconf.md.sal.rest.common.RestconfValidationUtils;
62 import org.opendaylight.netconf.sal.rest.api.Draft02;
63 import org.opendaylight.netconf.sal.rest.api.RestconfService;
64 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
65 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
66 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
67 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
68 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
69 import org.opendaylight.netconf.sal.streams.websockets.WebSocketServer;
70 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
71 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
72 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
73 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
74 import org.opendaylight.yangtools.yang.common.QName;
75 import org.opendaylight.yangtools.yang.common.QNameModule;
76 import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
77 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
78 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
79 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
80 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
81 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
82 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
83 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
84 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
85 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
86 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
87 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
88 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
89 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
90 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
91 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
92 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
93 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
94 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
95 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
96 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
97 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
98 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
99 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
100 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
101 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
102 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
103 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
104 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
105 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
106 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
107 import org.opendaylight.yangtools.yang.model.api.Module;
108 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
109 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
110 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
111 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
112 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
113 import org.opendaylight.yangtools.yang.model.util.SimpleSchemaContext;
114 import org.slf4j.Logger;
115 import org.slf4j.LoggerFactory;
117 public class RestconfImpl implements RestconfService {
119 private static final RestconfImpl INSTANCE = new RestconfImpl();
122 * Notifications are served on port 8181.
124 private static final int NOTIFICATION_PORT = 8181;
126 private static final int CHAR_NOT_FOUND = -1;
128 private static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
130 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
132 private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
134 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
136 private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
138 private static final String DATASTORE_PARAM_NAME = "datastore";
140 private static final String SCOPE_PARAM_NAME = "scope";
142 private static final String OUTPUT_TYPE_PARAM_NAME = "notification-output-type";
144 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
146 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
148 private static final QName NETCONF_BASE_QNAME = QName.create(QNameModule.create(URI.create(NETCONF_BASE), null),
149 NETCONF_BASE_PAYLOAD_NAME).intern();
151 private static final QNameModule SAL_REMOTE_AUGMENT;
155 SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
156 SimpleDateFormatUtil.getRevisionFormat().parse("2014-07-08"));
157 } catch (final ParseException e) {
158 throw new ExceptionInInitializerError(e);
162 private static final AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER =
163 new AugmentationIdentifier(ImmutableSet.of(
164 QName.create(SAL_REMOTE_AUGMENT, "scope"), QName.create(SAL_REMOTE_AUGMENT, "datastore"),
165 QName.create(SAL_REMOTE_AUGMENT, "notification-output-type")));
167 public static final CharSequence DATA_SUBSCR = "data-change-event-subscription";
168 private static final CharSequence CREATE_DATA_SUBSCR = "create-" + DATA_SUBSCR;
170 public static final CharSequence NOTIFICATION_STREAM = "notification-stream";
171 private static final CharSequence CREATE_NOTIFICATION_STREAM = "create-" + NOTIFICATION_STREAM;
173 private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
174 .appendValue(ChronoField.YEAR, 4).appendLiteral('-')
175 .appendValue(ChronoField.MONTH_OF_YEAR, 2).appendLiteral('-')
176 .appendValue(ChronoField.DAY_OF_MONTH, 2).appendLiteral('T')
177 .appendValue(ChronoField.HOUR_OF_DAY, 2).appendLiteral(':')
178 .appendValue(ChronoField.MINUTE_OF_HOUR, 2).appendLiteral(':')
179 .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
180 .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
181 .appendOffset("+HH:MM", "Z").toFormatter();
183 private BrokerFacade broker;
185 private ControllerContext controllerContext;
187 public void setBroker(final BrokerFacade broker) {
188 this.broker = broker;
191 public void setControllerContext(final ControllerContext controllerContext) {
192 this.controllerContext = controllerContext;
195 private RestconfImpl() {
198 public static RestconfImpl getInstance() {
203 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
204 final Set<Module> allModules = this.controllerContext.getAllModules();
205 final MapNode allModuleMap = makeModuleMapNode(allModules);
207 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
209 final Module restconfModule = getRestconfModule();
210 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
211 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
212 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
214 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
215 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
216 moduleContainerBuilder.withChild(allModuleMap);
218 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode, null, schemaContext),
219 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
223 * Valid only for mount point.
226 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
227 Preconditions.checkNotNull(identifier);
228 if (!identifier.contains(ControllerContext.MOUNT)) {
229 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
230 + " URI has to end with " + ControllerContext.MOUNT;
231 LOG.debug(errMsg + " for " + identifier);
232 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
235 final InstanceIdentifierContext<?> mountPointIdentifier =
236 this.controllerContext.toMountPointIdentifier(identifier);
237 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
238 final Set<Module> modules = this.controllerContext.getAllModules(mountPoint);
239 final MapNode mountPointModulesMap = makeModuleMapNode(modules);
241 final Module restconfModule = getRestconfModule();
242 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
243 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
244 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
246 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
247 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
248 moduleContainerBuilder.withChild(mountPointModulesMap);
250 return new NormalizedNodeContext(
251 new InstanceIdentifierContext<>(null, modulesSchemaNode, mountPoint,
252 this.controllerContext.getGlobalSchema()),
253 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
257 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
258 Preconditions.checkNotNull(identifier);
259 final QName moduleNameAndRevision = getModuleNameAndRevision(identifier);
260 Module module = null;
261 DOMMountPoint mountPoint = null;
262 final SchemaContext schemaContext;
263 if (identifier.contains(ControllerContext.MOUNT)) {
264 final InstanceIdentifierContext<?> mountPointIdentifier =
265 this.controllerContext.toMountPointIdentifier(identifier);
266 mountPoint = mountPointIdentifier.getMountPoint();
267 module = this.controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision);
268 schemaContext = mountPoint.getSchemaContext();
270 module = this.controllerContext.findModuleByNameAndRevision(moduleNameAndRevision);
271 schemaContext = this.controllerContext.getGlobalSchema();
274 if (module == null) {
275 final String errMsg = "Module with name '" + moduleNameAndRevision.getLocalName() + "' and revision '"
276 + moduleNameAndRevision.getRevision() + "' was not found.";
278 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
281 final Module restconfModule = getRestconfModule();
282 final Set<Module> modules = Collections.singleton(module);
283 final MapNode moduleMap = makeModuleMapNode(modules);
285 final DataSchemaNode moduleSchemaNode = this.controllerContext
286 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
287 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
289 return new NormalizedNodeContext(
290 new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint, schemaContext), moduleMap,
291 QueryParametersParser.parseWriterParameters(uriInfo));
295 public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
296 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
297 final Set<String> availableStreams = Notificator.getStreamNames();
298 final Module restconfModule = getRestconfModule();
299 final DataSchemaNode streamSchemaNode = this.controllerContext
300 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
301 Preconditions.checkState(streamSchemaNode instanceof ListSchemaNode);
303 final CollectionNodeBuilder<MapEntryNode, MapNode> listStreamsBuilder =
304 Builders.mapBuilder((ListSchemaNode) streamSchemaNode);
306 for (final String streamName : availableStreams) {
307 listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
310 final DataSchemaNode streamsContainerSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
311 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
312 Preconditions.checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
314 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
315 Builders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
316 streamsContainerBuilder.withChild(listStreamsBuilder.build());
318 return new NormalizedNodeContext(
319 new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null, schemaContext),
320 streamsContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
324 public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
325 final Set<Module> allModules = this.controllerContext.getAllModules();
326 return operationsFromModulesToNormalizedContext(allModules, null);
330 public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
331 Set<Module> modules = null;
332 DOMMountPoint mountPoint = null;
333 if (identifier.contains(ControllerContext.MOUNT)) {
334 final InstanceIdentifierContext<?> mountPointIdentifier =
335 this.controllerContext.toMountPointIdentifier(identifier);
336 mountPoint = mountPointIdentifier.getMountPoint();
337 modules = this.controllerContext.getAllModules(mountPoint);
340 final String errMsg =
341 "URI has bad format. If operations behind mount point should be showed, URI has to " + "end with ";
342 LOG.debug(errMsg + ControllerContext.MOUNT + " for " + identifier);
343 throw new RestconfDocumentedException(errMsg + ControllerContext.MOUNT, ErrorType.PROTOCOL,
344 ErrorTag.INVALID_VALUE);
347 return operationsFromModulesToNormalizedContext(modules, mountPoint);
351 * Special case only for GET restconf/operations use (since moment of
352 * pre-Beryllium Yang parser and Yang model API removal). The method is
353 * creating fake schema context with fake module and fake data by use own
354 * implementations of schema nodes and module.
357 * set of modules for get RPCs from every module
359 * mount point, if in use otherwise null
360 * @return {@link NormalizedNodeContext}
362 private static NormalizedNodeContext operationsFromModulesToNormalizedContext(final Set<Module> modules,
363 final DOMMountPoint mountPoint) {
365 final Collection<Module> neededModules = new ArrayList<>(modules.size());
366 final ArrayList<LeafSchemaNode> fakeRpcSchema = new ArrayList<>();
368 for (final Module m : modules) {
369 final Set<RpcDefinition> rpcs = m.getRpcs();
370 if (!rpcs.isEmpty()) {
371 neededModules.add(m);
373 fakeRpcSchema.ensureCapacity(fakeRpcSchema.size() + rpcs.size());
374 rpcs.forEach(rpc -> fakeRpcSchema.add(new FakeLeafSchemaNode(rpc.getQName())));
378 final ContainerSchemaNode fakeCont = new FakeContainerSchemaNode(fakeRpcSchema);
379 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> containerBuilder =
380 Builders.containerBuilder(fakeCont);
382 for (final LeafSchemaNode leaf : fakeRpcSchema) {
383 containerBuilder.withChild(Builders.leafBuilder(leaf).build());
386 final Collection<Module> fakeModules = new ArrayList<>(neededModules.size() + 1);
387 neededModules.forEach(imp -> fakeModules.add(new FakeImportedModule(imp)));
388 fakeModules.add(new FakeRestconfModule(neededModules, fakeCont));
390 final SchemaContext fakeSchemaCtx = SimpleSchemaContext.forModules(ImmutableSet.copyOf(fakeModules));
391 final InstanceIdentifierContext<ContainerSchemaNode> instanceIdentifierContext =
392 new InstanceIdentifierContext<>(null, fakeCont, mountPoint, fakeSchemaCtx);
393 return new NormalizedNodeContext(instanceIdentifierContext, containerBuilder.build());
396 private Module getRestconfModule() {
397 final Module restconfModule = this.controllerContext.getRestconfModule();
398 if (restconfModule == null) {
399 LOG.debug("ietf-restconf module was not found.");
400 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
401 ErrorTag.OPERATION_NOT_SUPPORTED);
404 return restconfModule;
407 private static QName getModuleNameAndRevision(final String identifier) {
408 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
409 String moduleNameAndRevision = "";
410 if (mountIndex >= 0) {
411 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
413 moduleNameAndRevision = identifier;
416 final Splitter splitter = Splitter.on("/").omitEmptyStrings();
417 final Iterable<String> split = splitter.split(moduleNameAndRevision);
418 final List<String> pathArgs = Lists.<String>newArrayList(split);
419 if (pathArgs.size() < 2) {
420 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
421 throw new RestconfDocumentedException(
422 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
423 ErrorTag.INVALID_VALUE);
427 final String moduleName = pathArgs.get(0);
428 final String revision = pathArgs.get(1);
429 return QName.create(null, SimpleDateFormatUtil.getRevisionFormat().parse(revision), moduleName);
430 } catch (final ParseException e) {
431 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
432 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
433 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
438 public Object getRoot() {
443 public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload,
444 final UriInfo uriInfo) {
445 final SchemaPath type = payload.getInstanceIdentifierContext().getSchemaNode().getPath();
446 final URI namespace = payload.getInstanceIdentifierContext().getSchemaNode().getQName().getNamespace();
447 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
448 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
449 final SchemaContext schemaContext;
451 if (mountPoint != null) {
452 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
453 if (!mountRpcServices.isPresent()) {
454 LOG.debug("Error: Rpc service is missing.");
455 throw new RestconfDocumentedException("Rpc service is missing.");
457 schemaContext = mountPoint.getSchemaContext();
458 response = mountRpcServices.get().invokeRpc(type, payload.getData());
460 if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
461 if (identifier.contains(CREATE_DATA_SUBSCR)) {
462 response = invokeSalRemoteRpcSubscribeRPC(payload);
463 } else if (identifier.contains(CREATE_NOTIFICATION_STREAM)) {
464 response = invokeSalRemoteRpcNotifiStrRPC(payload);
466 final String msg = "Not supported operation";
468 throw new RestconfDocumentedException(msg, ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED);
471 response = this.broker.invokeRpc(type, payload.getData());
473 schemaContext = this.controllerContext.getGlobalSchema();
476 final DOMRpcResult result = checkRpcResponse(response);
478 RpcDefinition resultNodeSchema = null;
479 final NormalizedNode<?, ?> resultData = result.getResult();
480 if (result != null && result.getResult() != null) {
481 resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
484 return new NormalizedNodeContext(
485 new InstanceIdentifierContext<>(null, resultNodeSchema, mountPoint, schemaContext),
486 resultData, QueryParametersParser.parseWriterParameters(uriInfo));
490 public NormalizedNodeContext invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
491 if (noPayload != null && !CharMatcher.WHITESPACE.matchesAllOf(noPayload)) {
492 throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
495 String identifierEncoded = null;
496 DOMMountPoint mountPoint = null;
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 final String slashErrorMsg = String.format(
510 "Identifier %n%s%ncan\'t contain slash "
511 + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.",
513 LOG.debug(slashErrorMsg);
514 throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
516 identifierEncoded = identifier;
517 schemaContext = this.controllerContext.getGlobalSchema();
520 final String identifierDecoded = this.controllerContext.urlPathArgDecode(identifierEncoded);
522 RpcDefinition rpc = null;
523 if (mountPoint == null) {
524 rpc = this.controllerContext.getRpcDefinition(identifierDecoded, null);
526 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
530 LOG.debug("RPC " + identifierDecoded + " does not exist.");
531 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
534 if (!rpc.getInput().getChildNodes().isEmpty()) {
535 LOG.debug("RPC " + rpc + " does not need input value.");
536 // FIXME : find a correct Error from specification
537 throw new IllegalStateException("RPC " + rpc + " does'n need input value!");
540 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
541 if (mountPoint != null) {
542 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
543 if (!mountRpcServices.isPresent()) {
544 throw new RestconfDocumentedException("Rpc service is missing.");
546 response = mountRpcServices.get().invokeRpc(rpc.getPath(), null);
548 response = this.broker.invokeRpc(rpc.getPath(), null);
551 final DOMRpcResult result = checkRpcResponse(response);
553 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpc, mountPoint, schemaContext),
554 result.getResult(), QueryParametersParser.parseWriterParameters(uriInfo));
557 private static DOMRpcResult checkRpcResponse(final CheckedFuture<DOMRpcResult, DOMRpcException> response) {
558 if (response == null) {
562 final DOMRpcResult retValue = response.get();
563 if (retValue.getErrors() == null || retValue.getErrors().isEmpty()) {
566 LOG.debug("RpcError message", retValue.getErrors());
567 throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
568 } catch (final InterruptedException e) {
569 final String errMsg = "The operation was interrupted while executing and did not complete.";
570 LOG.debug("Rpc Interrupt - " + errMsg, e);
571 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
572 } catch (final ExecutionException e) {
573 LOG.debug("Execution RpcError: ", e);
574 Throwable cause = e.getCause();
576 while (cause.getCause() != null) {
577 cause = cause.getCause();
580 if (cause instanceof IllegalArgumentException) {
581 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL,
582 ErrorTag.INVALID_VALUE);
583 } else if (cause instanceof DOMRpcImplementationNotAvailableException) {
584 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.APPLICATION,
585 ErrorTag.OPERATION_NOT_SUPPORTED);
587 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
590 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
593 } catch (final CancellationException e) {
594 final String errMsg = "The operation was cancelled while executing.";
595 LOG.debug("Cancel RpcExecution: " + errMsg, e);
596 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
600 private static void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
601 if (inputSchema != null && payload.getData() == null) {
602 // expected a non null payload
603 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
604 } else if (inputSchema == null && payload.getData() != null) {
605 // did not expect any input
606 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
610 private CheckedFuture<DOMRpcResult, DOMRpcException>
611 invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
612 final ContainerNode value = (ContainerNode) payload.getData();
613 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
614 final Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(new NodeIdentifier(
615 QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(), "path")));
616 final Object pathValue = path.isPresent() ? path.get().getValue() : null;
618 if (!(pathValue instanceof YangInstanceIdentifier)) {
619 final String errMsg = "Instance identifier was not normalized correctly ";
620 LOG.debug(errMsg + rpcQName);
621 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
624 final YangInstanceIdentifier pathIdentifier = (YangInstanceIdentifier) pathValue;
625 String streamName = (String) CREATE_DATA_SUBSCR;
626 NotificationOutputType outputType = null;
627 if (!pathIdentifier.isEmpty()) {
628 final String fullRestconfIdentifier =
629 DATA_SUBSCR + this.controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
631 LogicalDatastoreType datastore =
632 parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
633 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
635 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
636 scope = scope == null ? DEFAULT_SCOPE : scope;
638 outputType = parseEnumTypeParameter(value, NotificationOutputType.class, OUTPUT_TYPE_PARAM_NAME);
639 outputType = outputType == null ? NotificationOutputType.XML : outputType;
641 streamName = Notificator
642 .createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore + "/scope=" + scope);
645 if (Strings.isNullOrEmpty(streamName)) {
646 final String errMsg = "Path is empty or contains value node which is not Container or List build-in type.";
647 LOG.debug(errMsg + pathIdentifier);
648 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
651 final QName outputQname = QName.create(rpcQName, "output");
652 final QName streamNameQname = QName.create(rpcQName, "stream-name");
654 final ContainerNode output =
655 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
656 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
658 if (!Notificator.existListenerFor(streamName)) {
659 Notificator.createListener(pathIdentifier, streamName, outputType);
662 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
664 return Futures.immediateCheckedFuture(defaultDOMRpcResult);
667 private static RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
668 final String[] splittedIdentifier = identifierDecoded.split(":");
669 if (splittedIdentifier.length != 2) {
670 final String errMsg = identifierDecoded + " couldn't be splitted to 2 parts (module:rpc name)";
672 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
674 for (final Module module : schemaContext.getModules()) {
675 if (module.getName().equals(splittedIdentifier[0])) {
676 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
677 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
678 return rpcDefinition;
687 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
688 boolean withDefaUsed = false;
689 String withDefa = null;
691 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
692 switch (entry.getKey()) {
693 case "with-defaults":
696 withDefa = entry.getValue().iterator().next();
698 throw new RestconfDocumentedException("With-defaults parameter can be used only once.");
702 LOG.info("Unknown key : {}.", entry.getKey());
706 boolean tagged = false;
708 if (withDefa.equals("report-all-tagged")) {
712 if (withDefa.equals("report-all")) {
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.readConfigurationData(mountPoint, normalizedII, withDefa);
724 data = this.broker.readConfigurationData(normalizedII, withDefa);
727 final String errMsg =
728 "Request could not be completed because the relevant data model content does not exist ";
729 LOG.debug(errMsg + identifier);
730 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
732 return new NormalizedNodeContext(iiWithData, data,
733 QueryParametersParser.parseWriterParameters(uriInfo, tagged));
737 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
738 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
739 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
740 NormalizedNode<?, ?> data = null;
741 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
742 if (mountPoint != null) {
743 data = this.broker.readOperationalData(mountPoint, normalizedII);
745 data = this.broker.readOperationalData(normalizedII);
748 final String errMsg =
749 "Request could not be completed because the relevant data model content does not exist ";
750 LOG.debug(errMsg + identifier);
751 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
753 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
757 public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload,
758 final UriInfo uriInfo) {
759 boolean insertUsed = false;
760 boolean pointUsed = false;
761 String insert = null;
764 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
765 switch (entry.getKey()) {
769 insert = entry.getValue().iterator().next();
771 throw new RestconfDocumentedException("Insert parameter can be used only once.");
777 point = entry.getValue().iterator().next();
779 throw new RestconfDocumentedException("Point parameter can be used only once.");
783 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
787 if (pointUsed && !insertUsed) {
788 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
790 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
791 throw new RestconfDocumentedException(
792 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
795 Preconditions.checkNotNull(identifier);
797 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
799 validateInput(iiWithData.getSchemaNode(), payload);
800 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
801 validateListKeysEqualityInPayloadAndUri(payload);
803 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
804 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
807 * There is a small window where another write transaction could be
808 * updating the same data simultaneously and we get an
809 * OptimisticLockFailedException. This error is likely transient and The
810 * WriteTransaction#submit API docs state that a retry will likely
811 * succeed. So we'll try again if that scenario occurs. If it fails a
812 * third time then it probably will never succeed so we'll fail in that
815 * By retrying we're attempting to hide the internal implementation of
816 * the data store and how it handles concurrent updates from the
817 * restconf client. The client has instructed us to put the data and we
818 * should make every effort to do so without pushing optimistic lock
819 * failures back to the client and forcing them to handle it via retry
820 * (and having to document the behavior).
822 PutResult result = null;
825 if (mountPoint != null) {
827 result = this.broker.commitMountPointDataPut(mountPoint, normalizedII, payload.getData(), insert,
830 result = this.broker.commitConfigurationDataPut(this.controllerContext.getGlobalSchema(), normalizedII,
831 payload.getData(), insert, point);
835 result.getFutureOfPutData().checkedGet();
836 return Response.status(result.getStatus()).build();
837 } catch (final TransactionCommitFailedException e) {
838 if (e instanceof OptimisticLockFailedException) {
840 LOG.debug("Got OptimisticLockFailedException on last try - failing " + identifier);
841 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
844 LOG.debug("Got OptimisticLockFailedException - trying again " + identifier);
846 LOG.debug("Update failed for " + identifier, e);
847 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
853 private static void validateTopLevelNodeName(final NormalizedNodeContext node,
854 final YangInstanceIdentifier identifier) {
856 final String payloadName = node.getData().getNodeType().getLocalName();
859 if (identifier.isEmpty()) {
861 if (!node.getData().getNodeType().equals(NETCONF_BASE_QNAME)) {
862 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
863 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
867 final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
868 if (!payloadName.equals(identifierName)) {
869 throw new RestconfDocumentedException(
870 "Payload name (" + payloadName + ") is different from identifier name (" + identifierName + ")",
871 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
877 * Validates whether keys in {@code payload} are equal to values of keys in
878 * {@code iiWithData} for list schema node.
880 * @throws RestconfDocumentedException
881 * if key values or key count in payload and URI isn't equal
884 private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
885 Preconditions.checkArgument(payload != null);
886 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
887 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
888 final SchemaNode schemaNode = iiWithData.getSchemaNode();
889 final NormalizedNode<?, ?> data = payload.getData();
890 if (schemaNode instanceof ListSchemaNode) {
891 final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
892 if (lastPathArgument instanceof NodeIdentifierWithPredicates && data instanceof MapEntryNode) {
893 final Map<QName, Object> uriKeyValues =
894 ((NodeIdentifierWithPredicates) lastPathArgument).getKeyValues();
895 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
901 public static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final MapEntryNode payload,
902 final List<QName> keyDefinitions) {
904 final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
905 for (final QName keyDefinition : keyDefinitions) {
906 final Object uriKeyValue = mutableCopyUriKeyValues.remove(keyDefinition);
907 // should be caught during parsing URI to InstanceIdentifier
908 RestconfValidationUtils.checkDocumentedError(uriKeyValue != null, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
909 "Missing key " + keyDefinition + " in URI.");
911 final Object dataKeyValue = payload.getIdentifier().getKeyValues().get(keyDefinition);
913 if (!Objects.deepEquals(uriKeyValue, dataKeyValue)) {
914 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName()
915 + "' specified in the URI doesn't match the value '" + dataKeyValue
916 + "' specified in the message body. ";
917 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
923 public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload,
924 final UriInfo uriInfo) {
925 return createConfigurationData(payload, uriInfo);
929 public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
930 if (payload == null) {
931 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
933 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
934 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
935 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
937 boolean insertUsed = false;
938 boolean pointUsed = false;
939 String insert = null;
942 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
943 switch (entry.getKey()) {
947 insert = entry.getValue().iterator().next();
949 throw new RestconfDocumentedException("Insert parameter can be used only once.");
955 point = entry.getValue().iterator().next();
957 throw new RestconfDocumentedException("Point parameter can be used only once.");
961 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
965 if (pointUsed && !insertUsed) {
966 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
968 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
969 throw new RestconfDocumentedException(
970 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
973 CheckedFuture<Void, TransactionCommitFailedException> future;
974 if (mountPoint != null) {
975 future = this.broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData(), insert,
978 future = this.broker.commitConfigurationDataPost(this.controllerContext.getGlobalSchema(), normalizedII,
979 payload.getData(), insert, point);
984 } catch (final RestconfDocumentedException e) {
986 } catch (final TransactionCommitFailedException e) {
987 LOG.info("Error creating data " + (uriInfo != null ? uriInfo.getPath() : ""), e);
988 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
991 LOG.trace("Successfuly created data.");
993 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
994 // FIXME: Provide path to result.
995 final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
996 if (location != null) {
997 responseBuilder.location(location);
999 return responseBuilder.build();
1002 // FIXME create RestconfIdetifierHelper and move this method there
1003 private static YangInstanceIdentifier checkConsistencyOfNormalizedNodeContext(final NormalizedNodeContext payload) {
1004 Preconditions.checkArgument(payload != null);
1005 Preconditions.checkArgument(payload.getData() != null);
1006 Preconditions.checkArgument(payload.getData().getNodeType() != null);
1007 Preconditions.checkArgument(payload.getInstanceIdentifierContext() != null);
1008 Preconditions.checkArgument(payload.getInstanceIdentifierContext().getInstanceIdentifier() != null);
1010 final QName payloadNodeQname = payload.getData().getNodeType();
1011 final YangInstanceIdentifier yangIdent = payload.getInstanceIdentifierContext().getInstanceIdentifier();
1012 if (payloadNodeQname.compareTo(yangIdent.getLastPathArgument().getNodeType()) > 0) {
1015 final InstanceIdentifierContext<?> parentContext = payload.getInstanceIdentifierContext();
1016 final SchemaNode parentSchemaNode = parentContext.getSchemaNode();
1017 if (parentSchemaNode instanceof DataNodeContainer) {
1018 final DataNodeContainer cast = (DataNodeContainer) parentSchemaNode;
1019 for (final DataSchemaNode child : cast.getChildNodes()) {
1020 if (payloadNodeQname.compareTo(child.getQName()) == 0) {
1021 return YangInstanceIdentifier.builder(yangIdent).node(child.getQName()).build();
1025 if (parentSchemaNode instanceof RpcDefinition) {
1028 final String errMsg = "Error parsing input: DataSchemaNode has not children ";
1029 LOG.info(errMsg + yangIdent);
1030 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1033 @SuppressWarnings("checkstyle:IllegalCatch")
1034 private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint,
1035 final YangInstanceIdentifier normalizedII) {
1036 if (uriInfo == null) {
1037 // This is null if invoked internally
1041 final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
1042 uriBuilder.path("config");
1044 uriBuilder.path(this.controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
1045 } catch (final Exception e) {
1046 LOG.info("Location for instance identifier" + normalizedII + "wasn't created", e);
1049 return uriBuilder.build();
1053 public Response deleteConfigurationData(final String identifier) {
1054 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
1055 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
1056 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
1058 final CheckedFuture<Void, TransactionCommitFailedException> future;
1059 if (mountPoint != null) {
1060 future = this.broker.commitConfigurationDataDelete(mountPoint, normalizedII);
1062 future = this.broker.commitConfigurationDataDelete(normalizedII);
1066 future.checkedGet();
1067 } catch (final TransactionCommitFailedException e) {
1068 final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
1069 Predicates.instanceOf(ModifiedNodeDoesNotExistException.class));
1070 if (searchedException.isPresent()) {
1071 throw new RestconfDocumentedException("Data specified for delete doesn't exist.", ErrorType.APPLICATION,
1072 ErrorTag.DATA_MISSING);
1075 final String errMsg = "Error while deleting data";
1076 LOG.info(errMsg, e);
1077 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
1080 return Response.status(Status.OK).build();
1084 * Subscribes to some path in schema context (stream) to listen on changes
1088 * Additional parameters for subscribing to stream are loaded via rpc input
1091 * <li>datastore - default CONFIGURATION (other values of
1092 * {@link LogicalDatastoreType} enum type)</li>
1093 * <li>scope - default BASE (other values of {@link DataChangeScope})</li>
1097 public NormalizedNodeContext subscribeToStream(final String identifier, final UriInfo uriInfo) {
1098 boolean startTimeUsed = false;
1099 boolean stopTimeUsed = false;
1100 Instant start = Instant.now();
1101 Instant stop = null;
1102 boolean filterUsed = false;
1103 String filter = null;
1104 boolean leafNodesOnlyUsed = false;
1105 boolean leafNodesOnly = false;
1107 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
1108 switch (entry.getKey()) {
1110 if (!startTimeUsed) {
1111 startTimeUsed = true;
1112 start = parseDateFromQueryParam(entry);
1114 throw new RestconfDocumentedException("Start-time parameter can be used only once.");
1118 if (!stopTimeUsed) {
1119 stopTimeUsed = true;
1120 stop = parseDateFromQueryParam(entry);
1122 throw new RestconfDocumentedException("Stop-time parameter can be used only once.");
1128 filter = entry.getValue().iterator().next();
1130 throw new RestconfDocumentedException("Filter parameter can be used only once.");
1133 case "odl-leaf-nodes-only":
1134 if (!leafNodesOnlyUsed) {
1135 leafNodesOnlyUsed = true;
1136 leafNodesOnly = Boolean.parseBoolean(entry.getValue().iterator().next());
1138 throw new RestconfDocumentedException("Odl-leaf-nodes-only parameter can be used only once.");
1142 throw new RestconfDocumentedException("Bad parameter used with notifications: " + entry.getKey());
1145 if (!startTimeUsed && stopTimeUsed) {
1146 throw new RestconfDocumentedException("Stop-time parameter has to be used with start-time parameter.");
1148 URI response = null;
1149 if (identifier.contains(DATA_SUBSCR)) {
1150 response = dataSubs(identifier, uriInfo, start, stop, filter, leafNodesOnly);
1151 } else if (identifier.contains(NOTIFICATION_STREAM)) {
1152 response = notifStream(identifier, uriInfo, start, stop, filter);
1155 if (response != null) {
1156 // prepare node with value of location
1157 final InstanceIdentifierContext<?> iid = prepareIIDSubsStreamOutput();
1158 final NormalizedNodeAttrBuilder<NodeIdentifier, Object, LeafNode<Object>> builder =
1159 ImmutableLeafNodeBuilder.create().withValue(response.toString());
1160 builder.withNodeIdentifier(
1161 NodeIdentifier.create(QName.create("subscribe:to:notification", "2016-10-28", "location")));
1163 // prepare new header with location
1164 final Map<String, Object> headers = new HashMap<>();
1165 headers.put("Location", response);
1167 return new NormalizedNodeContext(iid, builder.build(), headers);
1170 final String msg = "Bad type of notification of sal-remote";
1172 throw new RestconfDocumentedException(msg);
1175 private static Instant parseDateFromQueryParam(final Entry<String, List<String>> entry) {
1176 final DateAndTime event = new DateAndTime(entry.getValue().iterator().next());
1177 final String value = event.getValue();
1178 final TemporalAccessor p;
1180 p = FORMATTER.parse(value);
1181 } catch (final DateTimeParseException e) {
1182 throw new RestconfDocumentedException("Cannot parse of value in date: " + value, e);
1184 return Instant.from(p);
1188 * Prepare instance identifier.
1190 * @return {@link InstanceIdentifierContext} of location leaf for
1193 private static InstanceIdentifierContext<?> prepareIIDSubsStreamOutput() {
1194 final QName qnameBase = QName.create("subscribe:to:notification", "2016-10-28", "notifi");
1195 final SchemaContext schemaCtx = ControllerContext.getInstance().getGlobalSchema();
1196 final DataSchemaNode location = ((ContainerSchemaNode) schemaCtx
1197 .findModuleByNamespaceAndRevision(qnameBase.getNamespace(), qnameBase.getRevision())
1198 .getDataChildByName(qnameBase)).getDataChildByName(QName.create(qnameBase, "location"));
1199 final List<PathArgument> path = new ArrayList<>();
1200 path.add(NodeIdentifier.create(qnameBase));
1201 path.add(NodeIdentifier.create(QName.create(qnameBase, "location")));
1203 return new InstanceIdentifierContext<SchemaNode>(YangInstanceIdentifier.create(path), location, null,
1208 * Register notification listener by stream name.
1215 * stop-time of getting notification
1217 * start-time of getting notification
1219 * indicate which subset of all possible events are of interest
1220 * @return {@link URI} of location
1222 private URI notifStream(final String identifier, final UriInfo uriInfo, final Instant start,
1223 final Instant stop, final String filter) {
1224 final String streamName = Notificator.createStreamNameFromUri(identifier);
1225 if (Strings.isNullOrEmpty(streamName)) {
1226 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1228 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
1229 if (listeners == null || listeners.isEmpty()) {
1230 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1231 ErrorTag.UNKNOWN_ELEMENT);
1234 for (final NotificationListenerAdapter listener : listeners) {
1235 this.broker.registerToListenNotification(listener);
1236 listener.setQueryParams(start,
1237 java.util.Optional.ofNullable(stop), java.util.Optional.ofNullable(filter), false);
1240 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1241 int notificationPort = NOTIFICATION_PORT;
1243 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
1244 notificationPort = webSocketServerInstance.getPort();
1245 } catch (final NullPointerException e) {
1246 WebSocketServer.createInstance(NOTIFICATION_PORT);
1248 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1249 final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
1251 return uriToWebsocketServer;
1255 * Register data change listener by stream name.
1262 * start-time of getting notification
1264 * stop-time of getting notification
1266 * indicate which subset of all possible events are of interest
1267 * @return {@link URI} of location
1269 private URI dataSubs(final String identifier, final UriInfo uriInfo, final Instant start, final Instant stop,
1270 final String filter, final boolean leafNodesOnly) {
1271 final String streamName = Notificator.createStreamNameFromUri(identifier);
1272 if (Strings.isNullOrEmpty(streamName)) {
1273 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1276 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1277 if (listener == null) {
1278 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1279 ErrorTag.UNKNOWN_ELEMENT);
1281 listener.setQueryParams(start, java.util.Optional.ofNullable(stop),
1282 java.util.Optional.ofNullable(filter), leafNodesOnly);
1284 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1285 final LogicalDatastoreType datastore =
1286 parserURIEnumParameter(LogicalDatastoreType.class, paramToValues.get(DATASTORE_PARAM_NAME));
1287 if (datastore == null) {
1288 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1289 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1291 final DataChangeScope scope =
1292 parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
1293 if (scope == null) {
1294 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1295 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1298 this.broker.registerToListenDataChanges(datastore, scope, listener);
1300 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1301 int notificationPort = NOTIFICATION_PORT;
1303 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
1304 notificationPort = webSocketServerInstance.getPort();
1305 } catch (final NullPointerException e) {
1306 WebSocketServer.createInstance(NOTIFICATION_PORT);
1308 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1309 final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
1311 return uriToWebsocketServer;
1314 @SuppressWarnings("checkstyle:IllegalCatch")
1316 public PatchStatusContext patchConfigurationData(final String identifier, final PatchContext context,
1317 final UriInfo uriInfo) {
1318 if (context == null) {
1319 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1323 return this.broker.patchConfigurationDataWithinTransaction(context);
1324 } catch (final Exception e) {
1325 LOG.debug("Patch transaction failed", e);
1326 throw new RestconfDocumentedException(e.getMessage());
1330 @SuppressWarnings("checkstyle:IllegalCatch")
1332 public PatchStatusContext patchConfigurationData(final PatchContext context, @Context final UriInfo uriInfo) {
1333 if (context == null) {
1334 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1338 return this.broker.patchConfigurationDataWithinTransaction(context);
1339 } catch (final Exception e) {
1340 LOG.debug("Patch transaction failed", e);
1341 throw new RestconfDocumentedException(e.getMessage());
1346 * Load parameter for subscribing to stream from input composite node.
1350 * @return enum object if its string value is equal to {@code paramName}. In
1353 private static <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1354 final String paramName) {
1355 final Optional<DataContainerChild<? extends PathArgument, ?>> augNode =
1356 value.getChild(SAL_REMOTE_AUG_IDENTIFIER);
1357 if (!augNode.isPresent() && !(augNode instanceof AugmentationNode)) {
1360 final Optional<DataContainerChild<? extends PathArgument, ?>> enumNode = ((AugmentationNode) augNode.get())
1361 .getChild(new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1362 if (!enumNode.isPresent()) {
1365 final Object rawValue = enumNode.get().getValue();
1366 if (!(rawValue instanceof String)) {
1370 return resolveAsEnum(classDescriptor, (String) rawValue);
1374 * Checks whether {@code value} is one of the string representation of
1375 * enumeration {@code classDescriptor}.
1377 * @return enum object if string value of {@code classDescriptor}
1378 * enumeration is equal to {@code value}. Other cases null.
1380 private static <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1381 if (Strings.isNullOrEmpty(value)) {
1384 return resolveAsEnum(classDescriptor, value);
1387 private static <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1388 final T[] enumConstants = classDescriptor.getEnumConstants();
1389 if (enumConstants != null) {
1390 for (final T enm : classDescriptor.getEnumConstants()) {
1391 if (((Enum<?>) enm).name().equals(value)) {
1399 private static Map<String, String> resolveValuesFromUri(final String uri) {
1400 final Map<String, String> result = new HashMap<>();
1401 final String[] tokens = uri.split("/");
1402 for (int i = 1; i < tokens.length; i++) {
1403 final String[] parameterTokens = tokens[i].split("=");
1404 if (parameterTokens.length == 2) {
1405 result.put(parameterTokens[0], parameterTokens[1]);
1411 private MapNode makeModuleMapNode(final Set<Module> modules) {
1412 Preconditions.checkNotNull(modules);
1413 final Module restconfModule = getRestconfModule();
1414 final DataSchemaNode moduleSchemaNode = this.controllerContext
1415 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1416 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1418 final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder =
1419 Builders.mapBuilder((ListSchemaNode) moduleSchemaNode);
1421 for (final Module module : modules) {
1422 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1424 return listModuleBuilder.build();
1427 protected MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1428 Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1429 "moduleSchemaNode has to be of type ListSchemaNode");
1430 final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1431 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues =
1432 Builders.mapEntryBuilder(listModuleSchemaNode);
1434 List<DataSchemaNode> instanceDataChildrenByName =
1435 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "name");
1436 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1437 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1439 .withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName()).build());
1441 instanceDataChildrenByName =
1442 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "revision");
1443 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1444 Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1445 final String revision = module.getQNameModule().getFormattedRevision();
1447 .withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode).withValue(revision).build());
1449 instanceDataChildrenByName =
1450 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "namespace");
1451 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1452 Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1453 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1454 .withValue(module.getNamespace().toString()).build());
1456 instanceDataChildrenByName =
1457 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "feature");
1458 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1459 Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1460 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder =
1461 Builders.leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1462 for (final FeatureDefinition feature : module.getFeatures()) {
1463 featuresBuilder.withChild(Builders.leafSetEntryBuilder((LeafListSchemaNode) featureSchemaNode)
1464 .withValue(feature.getQName().getLocalName()).build());
1466 moduleNodeValues.withChild(featuresBuilder.build());
1468 return moduleNodeValues.build();
1471 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1472 Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1473 "streamSchemaNode has to be of type ListSchemaNode");
1474 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1475 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues =
1476 Builders.mapEntryBuilder(listStreamSchemaNode);
1478 List<DataSchemaNode> instanceDataChildrenByName =
1479 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "name");
1480 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1481 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1482 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName).build());
1484 instanceDataChildrenByName =
1485 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "description");
1486 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1487 Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1488 streamNodeValues.withChild(
1489 Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue("DESCRIPTION_PLACEHOLDER").build());
1491 instanceDataChildrenByName =
1492 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-support");
1493 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1494 Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1495 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1496 .withValue(Boolean.valueOf(true)).build());
1498 instanceDataChildrenByName =
1499 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-log-creation-time");
1500 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1501 Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1502 streamNodeValues.withChild(
1503 Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode).withValue("").build());
1505 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "events");
1506 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1507 Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1508 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode).withValue("").build());
1510 return streamNodeValues.build();
1514 * Prepare stream for notification.
1517 * contains list of qnames of notifications
1518 * @return - checked future object
1520 private static CheckedFuture<DOMRpcResult, DOMRpcException> invokeSalRemoteRpcNotifiStrRPC(
1521 final NormalizedNodeContext payload) {
1522 final ContainerNode data = (ContainerNode) payload.getData();
1523 LeafSetNode leafSet = null;
1524 String outputType = "XML";
1525 for (final DataContainerChild<? extends PathArgument, ?> dataChild : data.getValue()) {
1526 if (dataChild instanceof LeafSetNode) {
1527 leafSet = (LeafSetNode) dataChild;
1528 } else if (dataChild instanceof AugmentationNode) {
1529 outputType = (String) ((AugmentationNode) dataChild).getValue().iterator().next().getValue();
1533 final Collection<LeafSetEntryNode> entryNodes = leafSet.getValue();
1534 final List<SchemaPath> paths = new ArrayList<>();
1535 String streamName = CREATE_NOTIFICATION_STREAM + "/";
1537 final Iterator<LeafSetEntryNode> iterator = entryNodes.iterator();
1538 while (iterator.hasNext()) {
1539 final QName valueQName = QName.create((String) iterator.next().getValue());
1540 final Module module =
1541 ControllerContext.getInstance().findModuleByNamespace(valueQName.getModule().getNamespace());
1542 Preconditions.checkNotNull(module,
1543 "Module for namespace " + valueQName.getModule().getNamespace() + " does not exist");
1544 NotificationDefinition notifiDef = null;
1545 for (final NotificationDefinition notification : module.getNotifications()) {
1546 if (notification.getQName().equals(valueQName)) {
1547 notifiDef = notification;
1551 final String moduleName = module.getName();
1552 Preconditions.checkNotNull(notifiDef,
1553 "Notification " + valueQName + "doesn't exist in module " + moduleName);
1554 paths.add(notifiDef.getPath());
1555 streamName = streamName + moduleName + ":" + valueQName.getLocalName();
1556 if (iterator.hasNext()) {
1557 streamName = streamName + ",";
1561 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
1562 final QName outputQname = QName.create(rpcQName, "output");
1563 final QName streamNameQname = QName.create(rpcQName, "notification-stream-identifier");
1565 final ContainerNode output =
1566 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
1567 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
1569 if (!Notificator.existNotificationListenerFor(streamName)) {
1570 Notificator.createNotificationListener(paths, streamName, outputType);
1573 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
1575 return Futures.immediateCheckedFuture(defaultDOMRpcResult);