2 * Copyright (c) 2014 - 2016 Brocade Communication Systems, Inc., Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.netconf.sal.restconf.impl;
11 import com.google.common.annotations.VisibleForTesting;
12 import com.google.common.base.CharMatcher;
13 import com.google.common.base.Optional;
14 import com.google.common.base.Preconditions;
15 import com.google.common.base.Predicates;
16 import com.google.common.base.Splitter;
17 import com.google.common.base.Strings;
18 import com.google.common.base.Throwables;
19 import com.google.common.collect.ImmutableSet;
20 import com.google.common.collect.Iterables;
21 import com.google.common.collect.Maps;
22 import com.google.common.util.concurrent.CheckedFuture;
23 import com.google.common.util.concurrent.Futures;
25 import java.time.Instant;
26 import java.time.format.DateTimeFormatter;
27 import java.time.format.DateTimeFormatterBuilder;
28 import java.time.format.DateTimeParseException;
29 import java.time.temporal.ChronoField;
30 import java.time.temporal.TemporalAccessor;
31 import java.util.AbstractMap.SimpleImmutableEntry;
32 import java.util.ArrayList;
33 import java.util.Collection;
34 import java.util.Collections;
35 import java.util.HashMap;
36 import java.util.Iterator;
37 import java.util.List;
39 import java.util.Map.Entry;
40 import java.util.Objects;
42 import java.util.concurrent.CancellationException;
43 import java.util.concurrent.ExecutionException;
44 import javax.ws.rs.core.Context;
45 import javax.ws.rs.core.Response;
46 import javax.ws.rs.core.Response.ResponseBuilder;
47 import javax.ws.rs.core.Response.Status;
48 import javax.ws.rs.core.UriBuilder;
49 import javax.ws.rs.core.UriInfo;
50 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
51 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
52 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
53 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
54 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
55 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
56 import org.opendaylight.controller.md.sal.dom.api.DOMRpcImplementationNotAvailableException;
57 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
58 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
59 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
60 import org.opendaylight.netconf.sal.rest.api.Draft02;
61 import org.opendaylight.netconf.sal.rest.api.RestconfService;
62 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
63 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
64 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
65 import org.opendaylight.netconf.sal.streams.websockets.WebSocketServer;
66 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
67 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
68 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
69 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
70 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
71 import org.opendaylight.restconf.common.patch.PatchContext;
72 import org.opendaylight.restconf.common.patch.PatchStatusContext;
73 import org.opendaylight.restconf.common.validation.RestconfValidationUtils;
74 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
75 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
76 import org.opendaylight.yangtools.yang.common.QName;
77 import org.opendaylight.yangtools.yang.common.QNameModule;
78 import org.opendaylight.yangtools.yang.common.Revision;
79 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
80 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
81 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
82 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
83 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
84 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
85 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
86 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
87 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
88 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
89 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
90 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
91 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
92 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
93 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
94 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
95 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
96 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
97 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
98 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
99 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
100 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
101 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
102 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
103 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
104 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
105 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
106 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
107 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
108 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
109 import org.opendaylight.yangtools.yang.model.api.Module;
110 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
111 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
112 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
113 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
114 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
115 import org.opendaylight.yangtools.yang.model.util.SimpleSchemaContext;
116 import org.slf4j.Logger;
117 import org.slf4j.LoggerFactory;
119 public final class RestconfImpl implements RestconfService {
121 private static final RestconfImpl INSTANCE = new RestconfImpl();
124 * Notifications are served on port 8181.
126 private static final int NOTIFICATION_PORT = 8181;
128 private static final int CHAR_NOT_FOUND = -1;
130 private static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
132 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
134 private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
136 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
138 private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
140 private static final String DATASTORE_PARAM_NAME = "datastore";
142 private static final String SCOPE_PARAM_NAME = "scope";
144 private static final String OUTPUT_TYPE_PARAM_NAME = "notification-output-type";
146 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
148 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
150 private static final QName NETCONF_BASE_QNAME = QName.create(QNameModule.create(URI.create(NETCONF_BASE)),
151 NETCONF_BASE_PAYLOAD_NAME).intern();
153 private static final QNameModule SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
154 Revision.of("2014-07-08"));
156 private static final AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER =
157 new AugmentationIdentifier(ImmutableSet.of(
158 QName.create(SAL_REMOTE_AUGMENT, "scope"), QName.create(SAL_REMOTE_AUGMENT, "datastore"),
159 QName.create(SAL_REMOTE_AUGMENT, "notification-output-type")));
161 public static final CharSequence DATA_SUBSCR = "data-change-event-subscription";
162 private static final CharSequence CREATE_DATA_SUBSCR = "create-" + DATA_SUBSCR;
164 public static final CharSequence NOTIFICATION_STREAM = "notification-stream";
165 private static final CharSequence CREATE_NOTIFICATION_STREAM = "create-" + NOTIFICATION_STREAM;
167 private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
168 .appendValue(ChronoField.YEAR, 4).appendLiteral('-')
169 .appendValue(ChronoField.MONTH_OF_YEAR, 2).appendLiteral('-')
170 .appendValue(ChronoField.DAY_OF_MONTH, 2).appendLiteral('T')
171 .appendValue(ChronoField.HOUR_OF_DAY, 2).appendLiteral(':')
172 .appendValue(ChronoField.MINUTE_OF_HOUR, 2).appendLiteral(':')
173 .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
174 .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
175 .appendOffset("+HH:MM", "Z").toFormatter();
177 private BrokerFacade broker;
179 private ControllerContext controllerContext;
181 public void setBroker(final BrokerFacade broker) {
182 this.broker = broker;
185 public void setControllerContext(final ControllerContext controllerContext) {
186 this.controllerContext = controllerContext;
189 private RestconfImpl() {
192 public static RestconfImpl getInstance() {
197 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
198 final Set<Module> allModules = this.controllerContext.getAllModules();
199 final MapNode allModuleMap = makeModuleMapNode(allModules);
201 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
203 final Module restconfModule = getRestconfModule();
204 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
205 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
206 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
208 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
209 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
210 moduleContainerBuilder.withChild(allModuleMap);
212 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode, null, schemaContext),
213 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
217 * Valid only for mount point.
220 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
221 Preconditions.checkNotNull(identifier);
222 if (!identifier.contains(ControllerContext.MOUNT)) {
223 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
224 + " URI has to end with " + ControllerContext.MOUNT;
225 LOG.debug(errMsg + " for " + identifier);
226 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
229 final InstanceIdentifierContext<?> mountPointIdentifier =
230 this.controllerContext.toMountPointIdentifier(identifier);
231 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
232 final Set<Module> modules = this.controllerContext.getAllModules(mountPoint);
233 final MapNode mountPointModulesMap = makeModuleMapNode(modules);
235 final Module restconfModule = getRestconfModule();
236 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
237 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
238 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
240 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
241 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
242 moduleContainerBuilder.withChild(mountPointModulesMap);
244 return new NormalizedNodeContext(
245 new InstanceIdentifierContext<>(null, modulesSchemaNode, mountPoint,
246 this.controllerContext.getGlobalSchema()),
247 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
251 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
252 Preconditions.checkNotNull(identifier);
253 final Entry<String, Revision> nameRev = getModuleNameAndRevision(identifier);
254 Module module = null;
255 DOMMountPoint mountPoint = null;
256 final SchemaContext schemaContext;
257 if (identifier.contains(ControllerContext.MOUNT)) {
258 final InstanceIdentifierContext<?> mountPointIdentifier =
259 this.controllerContext.toMountPointIdentifier(identifier);
260 mountPoint = mountPointIdentifier.getMountPoint();
261 module = this.controllerContext.findModuleByNameAndRevision(mountPoint, nameRev.getKey(),
263 schemaContext = mountPoint.getSchemaContext();
265 module = this.controllerContext.findModuleByNameAndRevision(nameRev.getKey(), nameRev.getValue());
266 schemaContext = this.controllerContext.getGlobalSchema();
269 if (module == null) {
270 final String errMsg = "Module with name '" + nameRev.getKey() + "' and revision '"
271 + nameRev.getValue() + "' was not found.";
273 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
276 final Module restconfModule = getRestconfModule();
277 final Set<Module> modules = Collections.singleton(module);
278 final MapNode moduleMap = makeModuleMapNode(modules);
280 final DataSchemaNode moduleSchemaNode = this.controllerContext
281 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
282 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
284 return new NormalizedNodeContext(
285 new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint, schemaContext), moduleMap,
286 QueryParametersParser.parseWriterParameters(uriInfo));
290 public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
291 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
292 final Set<String> availableStreams = Notificator.getStreamNames();
293 final Module restconfModule = getRestconfModule();
294 final DataSchemaNode streamSchemaNode = this.controllerContext
295 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
296 Preconditions.checkState(streamSchemaNode instanceof ListSchemaNode);
298 final CollectionNodeBuilder<MapEntryNode, MapNode> listStreamsBuilder =
299 Builders.mapBuilder((ListSchemaNode) streamSchemaNode);
301 for (final String streamName : availableStreams) {
302 listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
305 final DataSchemaNode streamsContainerSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
306 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
307 Preconditions.checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
309 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
310 Builders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
311 streamsContainerBuilder.withChild(listStreamsBuilder.build());
313 return new NormalizedNodeContext(
314 new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null, schemaContext),
315 streamsContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
319 public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
320 final Set<Module> allModules = this.controllerContext.getAllModules();
321 return operationsFromModulesToNormalizedContext(allModules, null);
325 public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
326 Set<Module> modules = null;
327 DOMMountPoint mountPoint = null;
328 if (identifier.contains(ControllerContext.MOUNT)) {
329 final InstanceIdentifierContext<?> mountPointIdentifier =
330 this.controllerContext.toMountPointIdentifier(identifier);
331 mountPoint = mountPointIdentifier.getMountPoint();
332 modules = this.controllerContext.getAllModules(mountPoint);
335 final String errMsg =
336 "URI has bad format. If operations behind mount point should be showed, URI has to " + "end with ";
337 LOG.debug(errMsg + ControllerContext.MOUNT + " for " + identifier);
338 throw new RestconfDocumentedException(errMsg + ControllerContext.MOUNT, ErrorType.PROTOCOL,
339 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 DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> containerBuilder =
375 Builders.containerBuilder(fakeCont);
377 for (final LeafSchemaNode leaf : fakeRpcSchema) {
378 containerBuilder.withChild(Builders.leafBuilder(leaf).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 final SchemaPath type = payload.getInstanceIdentifierContext().getSchemaNode().getPath();
438 final URI namespace = payload.getInstanceIdentifierContext().getSchemaNode().getQName().getNamespace();
439 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
440 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
441 final SchemaContext schemaContext;
443 if (mountPoint != null) {
444 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
445 if (!mountRpcServices.isPresent()) {
446 LOG.debug("Error: Rpc service is missing.");
447 throw new RestconfDocumentedException("Rpc service is missing.");
449 schemaContext = mountPoint.getSchemaContext();
450 response = mountRpcServices.get().invokeRpc(type, payload.getData());
452 if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
453 if (identifier.contains(CREATE_DATA_SUBSCR)) {
454 response = invokeSalRemoteRpcSubscribeRPC(payload);
455 } else if (identifier.contains(CREATE_NOTIFICATION_STREAM)) {
456 response = invokeSalRemoteRpcNotifiStrRPC(payload);
458 final String msg = "Not supported operation";
460 throw new RestconfDocumentedException(msg, ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED);
463 response = this.broker.invokeRpc(type, payload.getData());
465 schemaContext = this.controllerContext.getGlobalSchema();
468 final DOMRpcResult result = checkRpcResponse(response);
470 RpcDefinition resultNodeSchema = null;
471 final NormalizedNode<?, ?> resultData = result.getResult();
472 if (result != null && result.getResult() != null) {
473 resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
476 return new NormalizedNodeContext(
477 new InstanceIdentifierContext<>(null, resultNodeSchema, mountPoint, schemaContext),
478 resultData, QueryParametersParser.parseWriterParameters(uriInfo));
482 public NormalizedNodeContext invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
483 if (noPayload != null && !CharMatcher.WHITESPACE.matchesAllOf(noPayload)) {
484 throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
487 String identifierEncoded = null;
488 DOMMountPoint mountPoint = null;
489 final SchemaContext schemaContext;
490 if (identifier.contains(ControllerContext.MOUNT)) {
491 // mounted RPC call - look up mount instance.
492 final InstanceIdentifierContext<?> mountPointId = this.controllerContext.toMountPointIdentifier(identifier);
493 mountPoint = mountPointId.getMountPoint();
494 schemaContext = mountPoint.getSchemaContext();
495 final int startOfRemoteRpcName =
496 identifier.lastIndexOf(ControllerContext.MOUNT) + ControllerContext.MOUNT.length() + 1;
497 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
498 identifierEncoded = remoteRpcName;
500 } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
501 final String slashErrorMsg = String.format(
502 "Identifier %n%s%ncan\'t contain slash "
503 + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.",
505 LOG.debug(slashErrorMsg);
506 throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
508 identifierEncoded = identifier;
509 schemaContext = this.controllerContext.getGlobalSchema();
512 final String identifierDecoded = this.controllerContext.urlPathArgDecode(identifierEncoded);
514 RpcDefinition rpc = null;
515 if (mountPoint == null) {
516 rpc = this.controllerContext.getRpcDefinition(identifierDecoded);
518 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
522 LOG.debug("RPC " + identifierDecoded + " does not exist.");
523 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
526 if (!rpc.getInput().getChildNodes().isEmpty()) {
527 LOG.debug("RPC " + rpc + " does not need input value.");
528 // FIXME : find a correct Error from specification
529 throw new IllegalStateException("RPC " + rpc + " does'n need input value!");
532 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
533 if (mountPoint != null) {
534 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
535 if (!mountRpcServices.isPresent()) {
536 throw new RestconfDocumentedException("Rpc service is missing.");
538 response = mountRpcServices.get().invokeRpc(rpc.getPath(), null);
540 response = this.broker.invokeRpc(rpc.getPath(), null);
543 final DOMRpcResult result = checkRpcResponse(response);
545 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpc, mountPoint, schemaContext),
546 result.getResult(), QueryParametersParser.parseWriterParameters(uriInfo));
549 @SuppressWarnings("checkstyle:avoidHidingCauseException")
550 private static DOMRpcResult checkRpcResponse(final CheckedFuture<DOMRpcResult, DOMRpcException> response) {
551 if (response == null) {
555 final DOMRpcResult retValue = response.get();
556 if (retValue.getErrors() == null || retValue.getErrors().isEmpty()) {
559 LOG.debug("RpcError message", retValue.getErrors());
560 throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
561 } catch (final InterruptedException e) {
562 final String errMsg = "The operation was interrupted while executing and did not complete.";
563 LOG.debug("Rpc Interrupt - " + errMsg, e);
564 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION, e);
565 } catch (final ExecutionException e) {
566 LOG.debug("Execution RpcError: ", e);
567 Throwable cause = e.getCause();
569 while (cause.getCause() != null) {
570 cause = cause.getCause();
573 if (cause instanceof IllegalArgumentException) {
574 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL,
575 ErrorTag.INVALID_VALUE);
576 } else if (cause instanceof DOMRpcImplementationNotAvailableException) {
577 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.APPLICATION,
578 ErrorTag.OPERATION_NOT_SUPPORTED);
580 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
583 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
586 } catch (final CancellationException e) {
587 final String errMsg = "The operation was cancelled while executing.";
588 LOG.debug("Cancel RpcExecution: " + errMsg, e);
589 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
593 private static void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
594 if (inputSchema != null && payload.getData() == null) {
595 // expected a non null payload
596 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
597 } else if (inputSchema == null && payload.getData() != null) {
598 // did not expect any input
599 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
603 private CheckedFuture<DOMRpcResult, DOMRpcException>
604 invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
605 final ContainerNode value = (ContainerNode) payload.getData();
606 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
607 final java.util.Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(
608 new NodeIdentifier(QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(),
610 final Object pathValue = path.isPresent() ? path.get().getValue() : null;
612 if (!(pathValue instanceof YangInstanceIdentifier)) {
613 final String errMsg = "Instance identifier was not normalized correctly ";
614 LOG.debug(errMsg + rpcQName);
615 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
618 final YangInstanceIdentifier pathIdentifier = (YangInstanceIdentifier) pathValue;
619 String streamName = (String) CREATE_DATA_SUBSCR;
620 NotificationOutputType outputType = null;
621 if (!pathIdentifier.isEmpty()) {
622 final String fullRestconfIdentifier =
623 DATA_SUBSCR + this.controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
625 LogicalDatastoreType datastore =
626 parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
627 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
629 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
630 scope = scope == null ? DEFAULT_SCOPE : scope;
632 outputType = parseEnumTypeParameter(value, NotificationOutputType.class, OUTPUT_TYPE_PARAM_NAME);
633 outputType = outputType == null ? NotificationOutputType.XML : outputType;
635 streamName = Notificator
636 .createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore + "/scope=" + scope);
639 if (Strings.isNullOrEmpty(streamName)) {
640 final String errMsg = "Path is empty or contains value node which is not Container or List build-in type.";
641 LOG.debug(errMsg + pathIdentifier);
642 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
645 final QName outputQname = QName.create(rpcQName, "output");
646 final QName streamNameQname = QName.create(rpcQName, "stream-name");
648 final ContainerNode output =
649 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
650 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
652 if (!Notificator.existListenerFor(streamName)) {
653 Notificator.createListener(pathIdentifier, streamName, outputType);
656 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
658 return Futures.immediateCheckedFuture(defaultDOMRpcResult);
661 private static RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
662 final String[] splittedIdentifier = identifierDecoded.split(":");
663 if (splittedIdentifier.length != 2) {
664 final String errMsg = identifierDecoded + " couldn't be splitted to 2 parts (module:rpc name)";
666 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
668 for (final Module module : schemaContext.getModules()) {
669 if (module.getName().equals(splittedIdentifier[0])) {
670 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
671 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
672 return rpcDefinition;
681 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
682 boolean withDefaUsed = false;
683 String withDefa = null;
685 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
686 switch (entry.getKey()) {
687 case "with-defaults":
690 withDefa = entry.getValue().iterator().next();
692 throw new RestconfDocumentedException("With-defaults parameter can be used only once.");
696 LOG.info("Unknown key : {}.", entry.getKey());
700 boolean tagged = false;
702 if (withDefa.equals("report-all-tagged")) {
706 if (withDefa.equals("report-all")) {
711 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
712 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
713 NormalizedNode<?, ?> data = null;
714 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
715 if (mountPoint != null) {
716 data = this.broker.readConfigurationData(mountPoint, normalizedII, withDefa);
718 data = this.broker.readConfigurationData(normalizedII, withDefa);
721 final String errMsg =
722 "Request could not be completed because the relevant data model content does not exist ";
723 LOG.debug(errMsg + identifier);
724 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
726 return new NormalizedNodeContext(iiWithData, data,
727 QueryParametersParser.parseWriterParameters(uriInfo, tagged));
731 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
732 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
733 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
734 NormalizedNode<?, ?> data = null;
735 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
736 if (mountPoint != null) {
737 data = this.broker.readOperationalData(mountPoint, normalizedII);
739 data = this.broker.readOperationalData(normalizedII);
742 final String errMsg =
743 "Request could not be completed because the relevant data model content does not exist ";
744 LOG.debug(errMsg + identifier);
745 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
747 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
751 public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload,
752 final UriInfo uriInfo) {
753 boolean insertUsed = false;
754 boolean pointUsed = false;
755 String insert = null;
758 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
759 switch (entry.getKey()) {
763 insert = entry.getValue().iterator().next();
765 throw new RestconfDocumentedException("Insert parameter can be used only once.");
771 point = entry.getValue().iterator().next();
773 throw new RestconfDocumentedException("Point parameter can be used only once.");
777 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
781 if (pointUsed && !insertUsed) {
782 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
784 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
785 throw new RestconfDocumentedException(
786 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
789 Preconditions.checkNotNull(identifier);
791 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
793 validateInput(iiWithData.getSchemaNode(), payload);
794 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
795 validateListKeysEqualityInPayloadAndUri(payload);
797 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
798 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
801 * There is a small window where another write transaction could be
802 * updating the same data simultaneously and we get an
803 * OptimisticLockFailedException. This error is likely transient and The
804 * WriteTransaction#submit API docs state that a retry will likely
805 * succeed. So we'll try again if that scenario occurs. If it fails a
806 * third time then it probably will never succeed so we'll fail in that
809 * By retrying we're attempting to hide the internal implementation of
810 * the data store and how it handles concurrent updates from the
811 * restconf client. The client has instructed us to put the data and we
812 * should make every effort to do so without pushing optimistic lock
813 * failures back to the client and forcing them to handle it via retry
814 * (and having to document the behavior).
816 PutResult result = null;
819 if (mountPoint != null) {
821 result = this.broker.commitMountPointDataPut(mountPoint, normalizedII, payload.getData(), insert,
824 result = this.broker.commitConfigurationDataPut(this.controllerContext.getGlobalSchema(), normalizedII,
825 payload.getData(), insert, point);
829 result.getFutureOfPutData().checkedGet();
830 return Response.status(result.getStatus()).build();
831 } catch (final TransactionCommitFailedException e) {
832 if (e instanceof OptimisticLockFailedException) {
834 LOG.debug("Got OptimisticLockFailedException on last try - failing " + identifier);
835 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
838 LOG.debug("Got OptimisticLockFailedException - trying again " + identifier);
840 LOG.debug("Update failed for " + identifier, e);
841 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
847 private static void validateTopLevelNodeName(final NormalizedNodeContext node,
848 final YangInstanceIdentifier identifier) {
850 final String payloadName = node.getData().getNodeType().getLocalName();
853 if (identifier.isEmpty()) {
855 if (!node.getData().getNodeType().equals(NETCONF_BASE_QNAME)) {
856 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
857 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
861 final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
862 if (!payloadName.equals(identifierName)) {
863 throw new RestconfDocumentedException(
864 "Payload name (" + payloadName + ") is different from identifier name (" + identifierName + ")",
865 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
871 * Validates whether keys in {@code payload} are equal to values of keys in
872 * {@code iiWithData} for list schema node.
874 * @throws RestconfDocumentedException
875 * if key values or key count in payload and URI isn't equal
878 private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
879 Preconditions.checkArgument(payload != null);
880 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
881 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
882 final SchemaNode schemaNode = iiWithData.getSchemaNode();
883 final NormalizedNode<?, ?> data = payload.getData();
884 if (schemaNode instanceof ListSchemaNode) {
885 final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
886 if (lastPathArgument instanceof NodeIdentifierWithPredicates && data instanceof MapEntryNode) {
887 final Map<QName, Object> uriKeyValues =
888 ((NodeIdentifierWithPredicates) lastPathArgument).getKeyValues();
889 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
895 public static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final MapEntryNode payload,
896 final List<QName> keyDefinitions) {
898 final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
899 for (final QName keyDefinition : keyDefinitions) {
900 final Object uriKeyValue = mutableCopyUriKeyValues.remove(keyDefinition);
901 // should be caught during parsing URI to InstanceIdentifier
902 RestconfValidationUtils.checkDocumentedError(uriKeyValue != null, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
903 "Missing key " + keyDefinition + " in URI.");
905 final Object dataKeyValue = payload.getIdentifier().getKeyValues().get(keyDefinition);
907 if (!Objects.deepEquals(uriKeyValue, dataKeyValue)) {
908 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName()
909 + "' specified in the URI doesn't match the value '" + dataKeyValue
910 + "' specified in the message body. ";
911 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
917 public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload,
918 final UriInfo uriInfo) {
919 return createConfigurationData(payload, uriInfo);
923 public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
924 if (payload == null) {
925 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
927 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
928 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
929 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
931 boolean insertUsed = false;
932 boolean pointUsed = false;
933 String insert = null;
936 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
937 switch (entry.getKey()) {
941 insert = entry.getValue().iterator().next();
943 throw new RestconfDocumentedException("Insert parameter can be used only once.");
949 point = entry.getValue().iterator().next();
951 throw new RestconfDocumentedException("Point parameter can be used only once.");
955 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
959 if (pointUsed && !insertUsed) {
960 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
962 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
963 throw new RestconfDocumentedException(
964 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
967 CheckedFuture<Void, TransactionCommitFailedException> future;
968 if (mountPoint != null) {
969 future = this.broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData(), insert,
972 future = this.broker.commitConfigurationDataPost(this.controllerContext.getGlobalSchema(), normalizedII,
973 payload.getData(), insert, point);
978 } catch (final RestconfDocumentedException e) {
980 } catch (final TransactionCommitFailedException e) {
981 LOG.info("Error creating data " + (uriInfo != null ? uriInfo.getPath() : ""), e);
982 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
985 LOG.trace("Successfuly created data.");
987 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
988 // FIXME: Provide path to result.
989 final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
990 if (location != null) {
991 responseBuilder.location(location);
993 return responseBuilder.build();
996 // FIXME create RestconfIdetifierHelper and move this method there
997 private static YangInstanceIdentifier checkConsistencyOfNormalizedNodeContext(final NormalizedNodeContext payload) {
998 Preconditions.checkArgument(payload != null);
999 Preconditions.checkArgument(payload.getData() != null);
1000 Preconditions.checkArgument(payload.getData().getNodeType() != null);
1001 Preconditions.checkArgument(payload.getInstanceIdentifierContext() != null);
1002 Preconditions.checkArgument(payload.getInstanceIdentifierContext().getInstanceIdentifier() != null);
1004 final QName payloadNodeQname = payload.getData().getNodeType();
1005 final YangInstanceIdentifier yangIdent = payload.getInstanceIdentifierContext().getInstanceIdentifier();
1006 if (payloadNodeQname.compareTo(yangIdent.getLastPathArgument().getNodeType()) > 0) {
1009 final InstanceIdentifierContext<?> parentContext = payload.getInstanceIdentifierContext();
1010 final SchemaNode parentSchemaNode = parentContext.getSchemaNode();
1011 if (parentSchemaNode instanceof DataNodeContainer) {
1012 final DataNodeContainer cast = (DataNodeContainer) parentSchemaNode;
1013 for (final DataSchemaNode child : cast.getChildNodes()) {
1014 if (payloadNodeQname.compareTo(child.getQName()) == 0) {
1015 return YangInstanceIdentifier.builder(yangIdent).node(child.getQName()).build();
1019 if (parentSchemaNode instanceof RpcDefinition) {
1022 final String errMsg = "Error parsing input: DataSchemaNode has not children ";
1023 LOG.info(errMsg + yangIdent);
1024 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1027 @SuppressWarnings("checkstyle:IllegalCatch")
1028 private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint,
1029 final YangInstanceIdentifier normalizedII) {
1030 if (uriInfo == null) {
1031 // This is null if invoked internally
1035 final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
1036 uriBuilder.path("config");
1038 uriBuilder.path(this.controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
1039 } catch (final Exception e) {
1040 LOG.info("Location for instance identifier" + normalizedII + "wasn't created", e);
1043 return uriBuilder.build();
1047 public Response deleteConfigurationData(final String identifier) {
1048 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
1049 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
1050 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
1052 final CheckedFuture<Void, TransactionCommitFailedException> future;
1053 if (mountPoint != null) {
1054 future = this.broker.commitConfigurationDataDelete(mountPoint, normalizedII);
1056 future = this.broker.commitConfigurationDataDelete(normalizedII);
1060 future.checkedGet();
1061 } catch (final TransactionCommitFailedException e) {
1062 final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
1063 Predicates.instanceOf(ModifiedNodeDoesNotExistException.class));
1064 if (searchedException.isPresent()) {
1065 throw new RestconfDocumentedException("Data specified for delete doesn't exist.",
1066 ErrorType.APPLICATION, ErrorTag.DATA_MISSING, e);
1069 final String errMsg = "Error while deleting data";
1070 LOG.info(errMsg, e);
1071 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
1074 return Response.status(Status.OK).build();
1078 * Subscribes to some path in schema context (stream) to listen on changes
1082 * Additional parameters for subscribing to stream are loaded via rpc input
1085 * <li>datastore - default CONFIGURATION (other values of
1086 * {@link LogicalDatastoreType} enum type)</li>
1087 * <li>scope - default BASE (other values of {@link DataChangeScope})</li>
1091 public NormalizedNodeContext subscribeToStream(final String identifier, final UriInfo uriInfo) {
1092 boolean startTimeUsed = false;
1093 boolean stopTimeUsed = false;
1094 Instant start = Instant.now();
1095 Instant stop = null;
1096 boolean filterUsed = false;
1097 String filter = null;
1098 boolean leafNodesOnlyUsed = false;
1099 boolean leafNodesOnly = false;
1101 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
1102 switch (entry.getKey()) {
1104 if (!startTimeUsed) {
1105 startTimeUsed = true;
1106 start = parseDateFromQueryParam(entry);
1108 throw new RestconfDocumentedException("Start-time parameter can be used only once.");
1112 if (!stopTimeUsed) {
1113 stopTimeUsed = true;
1114 stop = parseDateFromQueryParam(entry);
1116 throw new RestconfDocumentedException("Stop-time parameter can be used only once.");
1122 filter = entry.getValue().iterator().next();
1124 throw new RestconfDocumentedException("Filter parameter can be used only once.");
1127 case "odl-leaf-nodes-only":
1128 if (!leafNodesOnlyUsed) {
1129 leafNodesOnlyUsed = true;
1130 leafNodesOnly = Boolean.parseBoolean(entry.getValue().iterator().next());
1132 throw new RestconfDocumentedException("Odl-leaf-nodes-only parameter can be used only once.");
1136 throw new RestconfDocumentedException("Bad parameter used with notifications: " + entry.getKey());
1139 if (!startTimeUsed && stopTimeUsed) {
1140 throw new RestconfDocumentedException("Stop-time parameter has to be used with start-time parameter.");
1142 URI response = null;
1143 if (identifier.contains(DATA_SUBSCR)) {
1144 response = dataSubs(identifier, uriInfo, start, stop, filter, leafNodesOnly);
1145 } else if (identifier.contains(NOTIFICATION_STREAM)) {
1146 response = notifStream(identifier, uriInfo, start, stop, filter);
1149 if (response != null) {
1150 // prepare node with value of location
1151 final InstanceIdentifierContext<?> iid = prepareIIDSubsStreamOutput();
1152 final NormalizedNodeAttrBuilder<NodeIdentifier, Object, LeafNode<Object>> builder =
1153 ImmutableLeafNodeBuilder.create().withValue(response.toString());
1154 builder.withNodeIdentifier(
1155 NodeIdentifier.create(QName.create("subscribe:to:notification", "2016-10-28", "location")));
1157 // prepare new header with location
1158 final Map<String, Object> headers = new HashMap<>();
1159 headers.put("Location", response);
1161 return new NormalizedNodeContext(iid, builder.build(), headers);
1164 final String msg = "Bad type of notification of sal-remote";
1166 throw new RestconfDocumentedException(msg);
1169 private static Instant parseDateFromQueryParam(final Entry<String, List<String>> entry) {
1170 final DateAndTime event = new DateAndTime(entry.getValue().iterator().next());
1171 final String value = event.getValue();
1172 final TemporalAccessor p;
1174 p = FORMATTER.parse(value);
1175 } catch (final DateTimeParseException e) {
1176 throw new RestconfDocumentedException("Cannot parse of value in date: " + value, e);
1178 return Instant.from(p);
1182 * Prepare instance identifier.
1184 * @return {@link InstanceIdentifierContext} of location leaf for
1187 private static InstanceIdentifierContext<?> prepareIIDSubsStreamOutput() {
1188 final QName qnameBase = QName.create("subscribe:to:notification", "2016-10-28", "notifi");
1189 final SchemaContext schemaCtx = ControllerContext.getInstance().getGlobalSchema();
1190 final DataSchemaNode location = ((ContainerSchemaNode) schemaCtx
1191 .findModule(qnameBase.getModule()).orElse(null)
1192 .getDataChildByName(qnameBase)).getDataChildByName(QName.create(qnameBase, "location"));
1193 final List<PathArgument> path = new ArrayList<>();
1194 path.add(NodeIdentifier.create(qnameBase));
1195 path.add(NodeIdentifier.create(QName.create(qnameBase, "location")));
1197 return new InstanceIdentifierContext<SchemaNode>(YangInstanceIdentifier.create(path), location, null,
1202 * Register notification listener by stream name.
1209 * stop-time of getting notification
1211 * start-time of getting notification
1213 * indicate which subset of all possible events are of interest
1214 * @return {@link URI} of location
1216 private URI notifStream(final String identifier, final UriInfo uriInfo, final Instant start,
1217 final Instant stop, final String filter) {
1218 final String streamName = Notificator.createStreamNameFromUri(identifier);
1219 if (Strings.isNullOrEmpty(streamName)) {
1220 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1222 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
1223 if (listeners == null || listeners.isEmpty()) {
1224 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1225 ErrorTag.UNKNOWN_ELEMENT);
1228 for (final NotificationListenerAdapter listener : listeners) {
1229 this.broker.registerToListenNotification(listener);
1230 listener.setQueryParams(start,
1231 java.util.Optional.ofNullable(stop), java.util.Optional.ofNullable(filter), false);
1234 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1236 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance(NOTIFICATION_PORT);
1237 final int notificationPort = webSocketServerInstance.getPort();
1239 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1241 return uriToWebsocketServerBuilder.replacePath(streamName).build();
1245 * Register data change listener by stream name.
1252 * start-time of getting notification
1254 * stop-time of getting notification
1256 * indicate which subset of all possible events are of interest
1257 * @return {@link URI} of location
1259 private URI dataSubs(final String identifier, final UriInfo uriInfo, final Instant start, final Instant stop,
1260 final String filter, final boolean leafNodesOnly) {
1261 final String streamName = Notificator.createStreamNameFromUri(identifier);
1262 if (Strings.isNullOrEmpty(streamName)) {
1263 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1266 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1267 if (listener == null) {
1268 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1269 ErrorTag.UNKNOWN_ELEMENT);
1271 listener.setQueryParams(start, java.util.Optional.ofNullable(stop),
1272 java.util.Optional.ofNullable(filter), leafNodesOnly);
1274 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1275 final LogicalDatastoreType datastore =
1276 parserURIEnumParameter(LogicalDatastoreType.class, paramToValues.get(DATASTORE_PARAM_NAME));
1277 if (datastore == null) {
1278 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1279 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1281 final DataChangeScope scope =
1282 parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
1283 if (scope == null) {
1284 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1285 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1288 this.broker.registerToListenDataChanges(datastore, scope, listener);
1290 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1292 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance(NOTIFICATION_PORT);
1293 final int notificationPort = webSocketServerInstance.getPort();
1295 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1297 return uriToWebsocketServerBuilder.replacePath(streamName).build();
1300 @SuppressWarnings("checkstyle:IllegalCatch")
1302 public PatchStatusContext patchConfigurationData(final String identifier, final PatchContext context,
1303 final UriInfo uriInfo) {
1304 if (context == null) {
1305 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1309 return this.broker.patchConfigurationDataWithinTransaction(context);
1310 } catch (final Exception e) {
1311 LOG.debug("Patch transaction failed", e);
1312 throw new RestconfDocumentedException(e.getMessage(), e);
1316 @SuppressWarnings("checkstyle:IllegalCatch")
1318 public PatchStatusContext patchConfigurationData(final PatchContext context, @Context final UriInfo uriInfo) {
1319 if (context == null) {
1320 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1324 return this.broker.patchConfigurationDataWithinTransaction(context);
1325 } catch (final Exception e) {
1326 LOG.debug("Patch transaction failed", e);
1327 throw new RestconfDocumentedException(e.getMessage(), e);
1332 * Load parameter for subscribing to stream from input composite node.
1336 * @return enum object if its string value is equal to {@code paramName}. In
1339 private static <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1340 final String paramName) {
1341 final java.util.Optional<DataContainerChild<? extends PathArgument, ?>> optAugNode = value.getChild(
1342 SAL_REMOTE_AUG_IDENTIFIER);
1343 if (!optAugNode.isPresent()) {
1346 final DataContainerChild<? extends PathArgument, ?> augNode = optAugNode.get();
1347 if (!(augNode instanceof AugmentationNode)) {
1350 final java.util.Optional<DataContainerChild<? extends PathArgument, ?>> enumNode = ((AugmentationNode) augNode)
1351 .getChild(new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1352 if (!enumNode.isPresent()) {
1355 final Object rawValue = enumNode.get().getValue();
1356 if (!(rawValue instanceof String)) {
1360 return resolveAsEnum(classDescriptor, (String) rawValue);
1364 * Checks whether {@code value} is one of the string representation of
1365 * enumeration {@code classDescriptor}.
1367 * @return enum object if string value of {@code classDescriptor}
1368 * enumeration is equal to {@code value}. Other cases null.
1370 private static <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1371 if (Strings.isNullOrEmpty(value)) {
1374 return resolveAsEnum(classDescriptor, value);
1377 private static <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1378 final T[] enumConstants = classDescriptor.getEnumConstants();
1379 if (enumConstants != null) {
1380 for (final T enm : classDescriptor.getEnumConstants()) {
1381 if (((Enum<?>) enm).name().equals(value)) {
1389 private static Map<String, String> resolveValuesFromUri(final String uri) {
1390 final Map<String, String> result = new HashMap<>();
1391 final String[] tokens = uri.split("/");
1392 for (int i = 1; i < tokens.length; i++) {
1393 final String[] parameterTokens = tokens[i].split("=");
1394 if (parameterTokens.length == 2) {
1395 result.put(parameterTokens[0], parameterTokens[1]);
1401 private MapNode makeModuleMapNode(final Set<Module> modules) {
1402 Preconditions.checkNotNull(modules);
1403 final Module restconfModule = getRestconfModule();
1404 final DataSchemaNode moduleSchemaNode = this.controllerContext
1405 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1406 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1408 final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder =
1409 Builders.mapBuilder((ListSchemaNode) moduleSchemaNode);
1411 for (final Module module : modules) {
1412 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1414 return listModuleBuilder.build();
1417 protected MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1418 Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1419 "moduleSchemaNode has to be of type ListSchemaNode");
1420 final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1421 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues =
1422 Builders.mapEntryBuilder(listModuleSchemaNode);
1424 List<DataSchemaNode> instanceDataChildrenByName =
1425 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "name");
1426 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1427 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1429 .withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName()).build());
1431 instanceDataChildrenByName =
1432 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "revision");
1433 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1434 Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1435 final java.util.Optional<Revision> revision = module.getQNameModule().getRevision();
1436 if (revision.isPresent()) {
1437 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode)
1438 .withValue(revision.get().toString()).build());
1441 instanceDataChildrenByName =
1442 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "namespace");
1443 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1444 Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1445 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1446 .withValue(module.getNamespace().toString()).build());
1448 instanceDataChildrenByName =
1449 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "feature");
1450 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1451 Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1452 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder =
1453 Builders.leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1454 for (final FeatureDefinition feature : module.getFeatures()) {
1455 featuresBuilder.withChild(Builders.leafSetEntryBuilder((LeafListSchemaNode) featureSchemaNode)
1456 .withValue(feature.getQName().getLocalName()).build());
1458 moduleNodeValues.withChild(featuresBuilder.build());
1460 return moduleNodeValues.build();
1463 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1464 Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1465 "streamSchemaNode has to be of type ListSchemaNode");
1466 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1467 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues =
1468 Builders.mapEntryBuilder(listStreamSchemaNode);
1470 List<DataSchemaNode> instanceDataChildrenByName =
1471 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "name");
1472 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1473 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1474 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName).build());
1476 instanceDataChildrenByName =
1477 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "description");
1478 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1479 Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1480 streamNodeValues.withChild(
1481 Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue("DESCRIPTION_PLACEHOLDER").build());
1483 instanceDataChildrenByName =
1484 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-support");
1485 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1486 Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1487 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1488 .withValue(Boolean.valueOf(true)).build());
1490 instanceDataChildrenByName =
1491 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-log-creation-time");
1492 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1493 Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1494 streamNodeValues.withChild(
1495 Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode).withValue("").build());
1497 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "events");
1498 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1499 Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1500 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode).build());
1502 return streamNodeValues.build();
1506 * Prepare stream for notification.
1509 * contains list of qnames of notifications
1510 * @return - checked future object
1512 private static CheckedFuture<DOMRpcResult, DOMRpcException> invokeSalRemoteRpcNotifiStrRPC(
1513 final NormalizedNodeContext payload) {
1514 final ContainerNode data = (ContainerNode) payload.getData();
1515 LeafSetNode leafSet = null;
1516 String outputType = "XML";
1517 for (final DataContainerChild<? extends PathArgument, ?> dataChild : data.getValue()) {
1518 if (dataChild instanceof LeafSetNode) {
1519 leafSet = (LeafSetNode) dataChild;
1520 } else if (dataChild instanceof AugmentationNode) {
1521 outputType = (String) ((AugmentationNode) dataChild).getValue().iterator().next().getValue();
1525 final Collection<LeafSetEntryNode> entryNodes = leafSet.getValue();
1526 final List<SchemaPath> paths = new ArrayList<>();
1527 String streamName = CREATE_NOTIFICATION_STREAM + "/";
1529 final Iterator<LeafSetEntryNode> iterator = entryNodes.iterator();
1530 while (iterator.hasNext()) {
1531 final QName valueQName = QName.create((String) iterator.next().getValue());
1532 final Module module =
1533 ControllerContext.getInstance().findModuleByNamespace(valueQName.getModule().getNamespace());
1534 Preconditions.checkNotNull(module,
1535 "Module for namespace " + valueQName.getModule().getNamespace() + " does not exist");
1536 NotificationDefinition notifiDef = null;
1537 for (final NotificationDefinition notification : module.getNotifications()) {
1538 if (notification.getQName().equals(valueQName)) {
1539 notifiDef = notification;
1543 final String moduleName = module.getName();
1544 Preconditions.checkNotNull(notifiDef,
1545 "Notification " + valueQName + "doesn't exist in module " + moduleName);
1546 paths.add(notifiDef.getPath());
1547 streamName = streamName + moduleName + ":" + valueQName.getLocalName();
1548 if (iterator.hasNext()) {
1549 streamName = streamName + ",";
1553 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
1554 final QName outputQname = QName.create(rpcQName, "output");
1555 final QName streamNameQname = QName.create(rpcQName, "notification-stream-identifier");
1557 final ContainerNode output =
1558 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
1559 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
1561 if (!Notificator.existNotificationListenerFor(streamName)) {
1562 Notificator.createNotificationListener(paths, streamName, outputType);
1565 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
1567 return Futures.immediateCheckedFuture(defaultDOMRpcResult);