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.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
71 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
72 import org.opendaylight.yangtools.yang.common.QName;
73 import org.opendaylight.yangtools.yang.common.QNameModule;
74 import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
75 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
76 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
77 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
78 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
79 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
80 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
81 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
82 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
83 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
84 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
85 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
86 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
87 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
88 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
89 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
90 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
91 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
92 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
93 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
94 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
95 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
96 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
97 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
98 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
99 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
100 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
101 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
102 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
103 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
104 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
105 import org.opendaylight.yangtools.yang.model.api.Module;
106 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
107 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
108 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
109 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
110 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
111 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.EffectiveSchemaContext;
112 import org.slf4j.Logger;
113 import org.slf4j.LoggerFactory;
115 public class RestconfImpl implements RestconfService {
117 private static final RestconfImpl INSTANCE = new RestconfImpl();
120 * Notifications are served on port 8181.
122 private static final int NOTIFICATION_PORT = 8181;
124 private static final int CHAR_NOT_FOUND = -1;
126 private static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
128 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
130 private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
132 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
134 private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
136 private static final String DATASTORE_PARAM_NAME = "datastore";
138 private static final String SCOPE_PARAM_NAME = "scope";
140 private static final String OUTPUT_TYPE_PARAM_NAME = "notification-output-type";
142 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
144 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
146 private static final QName NETCONF_BASE_QNAME = QName.create(QNameModule.create(URI.create(NETCONF_BASE), null),
147 NETCONF_BASE_PAYLOAD_NAME).intern();
149 private static final QNameModule SAL_REMOTE_AUGMENT;
152 SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
153 SimpleDateFormatUtil.getRevisionFormat().parse("2014-07-08"));
154 } catch (final ParseException e) {
155 throw new ExceptionInInitializerError(e);
159 private static final AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER =
160 new AugmentationIdentifier(ImmutableSet.of(
161 QName.create(SAL_REMOTE_AUGMENT, "scope"), QName.create(SAL_REMOTE_AUGMENT, "datastore"),
162 QName.create(SAL_REMOTE_AUGMENT, "notification-output-type")));
164 public static final CharSequence DATA_SUBSCR = "data-change-event-subscription";
165 private static final CharSequence CREATE_DATA_SUBSCR = "create-" + DATA_SUBSCR;
167 public static final CharSequence NOTIFICATION_STREAM = "notification-stream";
168 private static final CharSequence CREATE_NOTIFICATION_STREAM = "create-" + NOTIFICATION_STREAM;
170 private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
171 .appendValue(ChronoField.YEAR, 4).appendLiteral('-')
172 .appendValue(ChronoField.MONTH_OF_YEAR, 2).appendLiteral('-')
173 .appendValue(ChronoField.DAY_OF_MONTH, 2).appendLiteral('T')
174 .appendValue(ChronoField.HOUR_OF_DAY, 2).appendLiteral(':')
175 .appendValue(ChronoField.MINUTE_OF_HOUR, 2).appendLiteral(':')
176 .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
177 .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
178 .appendOffset("+HH:MM", "Z").toFormatter();
180 private BrokerFacade broker;
182 private ControllerContext controllerContext;
184 public void setBroker(final BrokerFacade broker) {
185 this.broker = broker;
188 public void setControllerContext(final ControllerContext controllerContext) {
189 this.controllerContext = controllerContext;
192 private RestconfImpl() {
195 public static RestconfImpl getInstance() {
200 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
201 final Set<Module> allModules = this.controllerContext.getAllModules();
202 final MapNode allModuleMap = makeModuleMapNode(allModules);
204 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
206 final Module restconfModule = getRestconfModule();
207 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
208 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
209 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
211 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
212 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
213 moduleContainerBuilder.withChild(allModuleMap);
215 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode, null, schemaContext),
216 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
220 * Valid only for mount point
223 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
224 Preconditions.checkNotNull(identifier);
225 if (!identifier.contains(ControllerContext.MOUNT)) {
226 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
227 + " URI has to end with " + ControllerContext.MOUNT;
228 LOG.debug(errMsg + " for " + identifier);
229 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
232 final InstanceIdentifierContext<?> mountPointIdentifier =
233 this.controllerContext.toMountPointIdentifier(identifier);
234 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
235 final Set<Module> modules = this.controllerContext.getAllModules(mountPoint);
236 final MapNode mountPointModulesMap = makeModuleMapNode(modules);
238 final Module restconfModule = getRestconfModule();
239 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
240 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
241 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
243 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
244 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
245 moduleContainerBuilder.withChild(mountPointModulesMap);
247 return new NormalizedNodeContext(
248 new InstanceIdentifierContext<>(null, modulesSchemaNode, mountPoint,
249 this.controllerContext.getGlobalSchema()),
250 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
254 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
255 Preconditions.checkNotNull(identifier);
256 final QName moduleNameAndRevision = getModuleNameAndRevision(identifier);
257 Module module = null;
258 DOMMountPoint mountPoint = null;
259 final SchemaContext schemaContext;
260 if (identifier.contains(ControllerContext.MOUNT)) {
261 final InstanceIdentifierContext<?> mountPointIdentifier =
262 this.controllerContext.toMountPointIdentifier(identifier);
263 mountPoint = mountPointIdentifier.getMountPoint();
264 module = this.controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision);
265 schemaContext = mountPoint.getSchemaContext();
267 module = this.controllerContext.findModuleByNameAndRevision(moduleNameAndRevision);
268 schemaContext = this.controllerContext.getGlobalSchema();
271 if (module == null) {
272 final String errMsg = "Module with name '" + moduleNameAndRevision.getLocalName() + "' and revision '"
273 + moduleNameAndRevision.getRevision() + "' was not found.";
275 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
278 final Module restconfModule = getRestconfModule();
279 final Set<Module> modules = Collections.singleton(module);
280 final MapNode moduleMap = makeModuleMapNode(modules);
282 final DataSchemaNode moduleSchemaNode = this.controllerContext
283 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
284 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
286 return new NormalizedNodeContext(
287 new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint, schemaContext), moduleMap,
288 QueryParametersParser.parseWriterParameters(uriInfo));
292 public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
293 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
294 final Set<String> availableStreams = Notificator.getStreamNames();
295 final Module restconfModule = getRestconfModule();
296 final DataSchemaNode streamSchemaNode = this.controllerContext
297 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
298 Preconditions.checkState(streamSchemaNode instanceof ListSchemaNode);
300 final CollectionNodeBuilder<MapEntryNode, MapNode> listStreamsBuilder =
301 Builders.mapBuilder((ListSchemaNode) streamSchemaNode);
303 for (final String streamName : availableStreams) {
304 listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
307 final DataSchemaNode streamsContainerSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
308 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
309 Preconditions.checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
311 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
312 Builders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
313 streamsContainerBuilder.withChild(listStreamsBuilder.build());
315 return new NormalizedNodeContext(
316 new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null, schemaContext),
317 streamsContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
321 public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
322 final Set<Module> allModules = this.controllerContext.getAllModules();
323 return operationsFromModulesToNormalizedContext(allModules, null);
327 public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
328 Set<Module> modules = null;
329 DOMMountPoint mountPoint = null;
330 if (identifier.contains(ControllerContext.MOUNT)) {
331 final InstanceIdentifierContext<?> mountPointIdentifier =
332 this.controllerContext.toMountPointIdentifier(identifier);
333 mountPoint = mountPointIdentifier.getMountPoint();
334 modules = this.controllerContext.getAllModules(mountPoint);
337 final String errMsg =
338 "URI has bad format. If operations behind mount point should be showed, URI has to " + "end with ";
339 LOG.debug(errMsg + ControllerContext.MOUNT + " for " + identifier);
340 throw new RestconfDocumentedException(errMsg + ControllerContext.MOUNT, ErrorType.PROTOCOL,
341 ErrorTag.INVALID_VALUE);
344 return operationsFromModulesToNormalizedContext(modules, mountPoint);
348 * Special case only for GET restconf/operations use (since moment of
349 * pre-Beryllium Yang parser and Yang model API removal). The method is
350 * creating fake schema context with fake module and fake data by use own
351 * implementations of schema nodes and module.
354 * - set of modules for get RPCs from every module
356 * - mount point, if in use otherwise null
357 * @return {@link NormalizedNodeContext}
359 private static NormalizedNodeContext operationsFromModulesToNormalizedContext(final Set<Module> modules,
360 final DOMMountPoint mountPoint) {
362 final Collection<Module> neededModules = new ArrayList<>(modules.size());
363 final ArrayList<LeafSchemaNode> fakeRpcSchema = new ArrayList<>();
365 for (final Module m : modules) {
366 final Set<RpcDefinition> rpcs = m.getRpcs();
367 if (!rpcs.isEmpty()) {
368 neededModules.add(m);
370 fakeRpcSchema.ensureCapacity(fakeRpcSchema.size() + rpcs.size());
371 rpcs.forEach(rpc -> fakeRpcSchema.add(new FakeLeafSchemaNode(rpc.getQName())));
375 final ContainerSchemaNode fakeCont = new FakeContainerSchemaNode(fakeRpcSchema);
376 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> containerBuilder =
377 Builders.containerBuilder(fakeCont);
379 for (final LeafSchemaNode leaf : fakeRpcSchema) {
380 containerBuilder.withChild(Builders.leafBuilder(leaf).build());
383 final Collection<Module> fakeModules = new ArrayList<>(neededModules.size() + 1);
384 neededModules.forEach(imp -> fakeModules.add(new FakeImportedModule(imp)));
385 fakeModules.add(new FakeRestconfModule(neededModules, fakeCont));
387 final SchemaContext fakeSchemaCtx =
388 EffectiveSchemaContext.resolveSchemaContext(ImmutableSet.copyOf(fakeModules));
389 final InstanceIdentifierContext<ContainerSchemaNode> instanceIdentifierContext =
390 new InstanceIdentifierContext<>(null, fakeCont, mountPoint, fakeSchemaCtx);
391 return new NormalizedNodeContext(instanceIdentifierContext, containerBuilder.build());
394 private Module getRestconfModule() {
395 final Module restconfModule = this.controllerContext.getRestconfModule();
396 if (restconfModule == null) {
397 LOG.debug("ietf-restconf module was not found.");
398 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
399 ErrorTag.OPERATION_NOT_SUPPORTED);
402 return restconfModule;
405 private static QName getModuleNameAndRevision(final String identifier) {
406 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
407 String moduleNameAndRevision = "";
408 if (mountIndex >= 0) {
409 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
411 moduleNameAndRevision = identifier;
414 final Splitter splitter = Splitter.on("/").omitEmptyStrings();
415 final Iterable<String> split = splitter.split(moduleNameAndRevision);
416 final List<String> pathArgs = Lists.<String> newArrayList(split);
417 if (pathArgs.size() < 2) {
418 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
419 throw new RestconfDocumentedException(
420 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
421 ErrorTag.INVALID_VALUE);
425 final String moduleName = pathArgs.get(0);
426 final String revision = pathArgs.get(1);
427 return QName.create(null, SimpleDateFormatUtil.getRevisionFormat().parse(revision), moduleName);
428 } catch (final ParseException e) {
429 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
430 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
431 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
436 public Object getRoot() {
441 public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload,
442 final UriInfo uriInfo) {
443 final SchemaPath type = payload.getInstanceIdentifierContext().getSchemaNode().getPath();
444 final URI namespace = payload.getInstanceIdentifierContext().getSchemaNode().getQName().getNamespace();
445 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
446 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
447 final SchemaContext schemaContext;
449 if (mountPoint != null) {
450 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
451 if (!mountRpcServices.isPresent()) {
452 LOG.debug("Error: Rpc service is missing.");
453 throw new RestconfDocumentedException("Rpc service is missing.");
455 schemaContext = mountPoint.getSchemaContext();
456 response = mountRpcServices.get().invokeRpc(type, payload.getData());
458 if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
459 if (identifier.contains(CREATE_DATA_SUBSCR)) {
460 response = invokeSalRemoteRpcSubscribeRPC(payload);
461 } else if (identifier.contains(CREATE_NOTIFICATION_STREAM)) {
462 response = invokeSalRemoteRpcNotifiStrRPC(payload);
464 final String msg = "Not supported operation";
466 throw new RestconfDocumentedException(msg, ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED);
469 response = this.broker.invokeRpc(type, payload.getData());
471 schemaContext = this.controllerContext.getGlobalSchema();
474 final DOMRpcResult result = checkRpcResponse(response);
476 RpcDefinition resultNodeSchema = null;
477 final NormalizedNode<?, ?> resultData = result.getResult();
478 if (result != null && result.getResult() != null) {
479 resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
482 return new NormalizedNodeContext(
483 new InstanceIdentifierContext<>(null, resultNodeSchema, mountPoint, schemaContext),
484 resultData, QueryParametersParser.parseWriterParameters(uriInfo));
487 private static DOMRpcResult checkRpcResponse(final CheckedFuture<DOMRpcResult, DOMRpcException> response) {
488 if (response == null) {
492 final DOMRpcResult retValue = response.get();
493 if (retValue.getErrors() == null || retValue.getErrors().isEmpty()) {
496 LOG.debug("RpcError message", retValue.getErrors());
497 throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
498 } catch (final InterruptedException e) {
499 final String errMsg = "The operation was interrupted while executing and did not complete.";
500 LOG.debug("Rpc Interrupt - " + errMsg, e);
501 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
502 } catch (final ExecutionException e) {
503 LOG.debug("Execution RpcError: ", e);
504 Throwable cause = e.getCause();
506 while (cause.getCause() != null) {
507 cause = cause.getCause();
510 if (cause instanceof IllegalArgumentException) {
511 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL,
512 ErrorTag.INVALID_VALUE);
513 } else if (cause instanceof DOMRpcImplementationNotAvailableException) {
514 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.APPLICATION,
515 ErrorTag.OPERATION_NOT_SUPPORTED);
517 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
520 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
523 } catch (final CancellationException e) {
524 final String errMsg = "The operation was cancelled while executing.";
525 LOG.debug("Cancel RpcExecution: " + errMsg, e);
526 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
530 private static void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
531 if (inputSchema != null && payload.getData() == null) {
532 // expected a non null payload
533 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
534 } else if (inputSchema == null && payload.getData() != null) {
535 // did not expect any input
536 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
540 private CheckedFuture<DOMRpcResult, DOMRpcException>
541 invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
542 final ContainerNode value = (ContainerNode) payload.getData();
543 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
544 final Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(new NodeIdentifier(
545 QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(), "path")));
546 final Object pathValue = path.isPresent() ? path.get().getValue() : null;
548 if (!(pathValue instanceof YangInstanceIdentifier)) {
549 final String errMsg = "Instance identifier was not normalized correctly ";
550 LOG.debug(errMsg + rpcQName);
551 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
554 final YangInstanceIdentifier pathIdentifier = (YangInstanceIdentifier) pathValue;
555 String streamName = (String) CREATE_DATA_SUBSCR;
556 NotificationOutputType outputType = null;
557 if (!pathIdentifier.isEmpty()) {
558 final String fullRestconfIdentifier =
559 DATA_SUBSCR + this.controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
561 LogicalDatastoreType datastore =
562 parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
563 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
565 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
566 scope = scope == null ? DEFAULT_SCOPE : scope;
568 outputType = parseEnumTypeParameter(value, NotificationOutputType.class, OUTPUT_TYPE_PARAM_NAME);
569 outputType = outputType == null ? NotificationOutputType.XML : outputType;
571 streamName = Notificator
572 .createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore + "/scope=" + scope);
575 if (Strings.isNullOrEmpty(streamName)) {
576 final String errMsg = "Path is empty or contains value node which is not Container or List build-in type.";
577 LOG.debug(errMsg + pathIdentifier);
578 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
581 final QName outputQname = QName.create(rpcQName, "output");
582 final QName streamNameQname = QName.create(rpcQName, "stream-name");
584 final ContainerNode output =
585 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
586 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
588 if (!Notificator.existListenerFor(streamName)) {
589 Notificator.createListener(pathIdentifier, streamName, outputType);
592 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
594 return Futures.immediateCheckedFuture(defaultDOMRpcResult);
598 public NormalizedNodeContext invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
599 if (noPayload != null && !CharMatcher.WHITESPACE.matchesAllOf(noPayload)) {
600 throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
603 String identifierEncoded = null;
604 DOMMountPoint mountPoint = null;
605 final SchemaContext schemaContext;
606 if (identifier.contains(ControllerContext.MOUNT)) {
607 // mounted RPC call - look up mount instance.
608 final InstanceIdentifierContext<?> mountPointId = this.controllerContext.toMountPointIdentifier(identifier);
609 mountPoint = mountPointId.getMountPoint();
610 schemaContext = mountPoint.getSchemaContext();
611 final int startOfRemoteRpcName =
612 identifier.lastIndexOf(ControllerContext.MOUNT) + ControllerContext.MOUNT.length() + 1;
613 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
614 identifierEncoded = remoteRpcName;
616 } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
617 final String slashErrorMsg = String.format(
618 "Identifier %n%s%ncan\'t contain slash "
619 + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.",
621 LOG.debug(slashErrorMsg);
622 throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
624 identifierEncoded = identifier;
625 schemaContext = this.controllerContext.getGlobalSchema();
628 final String identifierDecoded = this.controllerContext.urlPathArgDecode(identifierEncoded);
630 RpcDefinition rpc = null;
631 if (mountPoint == null) {
632 rpc = this.controllerContext.getRpcDefinition(identifierDecoded, null);
634 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
638 LOG.debug("RPC " + identifierDecoded + " does not exist.");
639 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
642 if (!rpc.getInput().getChildNodes().isEmpty()) {
643 LOG.debug("RPC " + rpc + " does not need input value.");
644 // FIXME : find a correct Error from specification
645 throw new IllegalStateException("RPC " + rpc + " does'n need input value!");
648 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
649 if (mountPoint != null) {
650 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
651 if (!mountRpcServices.isPresent()) {
652 throw new RestconfDocumentedException("Rpc service is missing.");
654 response = mountRpcServices.get().invokeRpc(rpc.getPath(), null);
656 response = this.broker.invokeRpc(rpc.getPath(), null);
659 final DOMRpcResult result = checkRpcResponse(response);
661 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpc, mountPoint, schemaContext),
662 result.getResult(), QueryParametersParser.parseWriterParameters(uriInfo));
665 private static RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
666 final String[] splittedIdentifier = identifierDecoded.split(":");
667 if (splittedIdentifier.length != 2) {
668 final String errMsg = identifierDecoded + " couldn't be splitted to 2 parts (module:rpc name)";
670 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
672 for (final Module module : schemaContext.getModules()) {
673 if (module.getName().equals(splittedIdentifier[0])) {
674 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
675 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
676 return rpcDefinition;
685 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
686 boolean withDefa_used = false;
687 String withDefa = null;
689 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
690 switch (entry.getKey()) {
691 case "with-defaults":
692 if (!withDefa_used) {
693 withDefa_used = true;
694 withDefa = entry.getValue().iterator().next();
696 throw new RestconfDocumentedException("With-defaults parameter can be used only once.");
701 boolean tagged = false;
703 if (withDefa.equals("report-all-tagged")) {
707 if (withDefa.equals("report-all")) {
712 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
713 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
714 NormalizedNode<?, ?> data = null;
715 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
716 if (mountPoint != null) {
717 data = this.broker.readConfigurationData(mountPoint, normalizedII, withDefa);
719 data = this.broker.readConfigurationData(normalizedII, withDefa);
722 final String errMsg =
723 "Request could not be completed because the relevant data model content does not exist ";
724 LOG.debug(errMsg + identifier);
725 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
727 return new NormalizedNodeContext(iiWithData, data,
728 QueryParametersParser.parseWriterParameters(uriInfo, tagged));
732 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
733 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
734 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
735 NormalizedNode<?, ?> data = null;
736 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
737 if (mountPoint != null) {
738 data = this.broker.readOperationalData(mountPoint, normalizedII);
740 data = this.broker.readOperationalData(normalizedII);
743 final String errMsg =
744 "Request could not be completed because the relevant data model content does not exist ";
745 LOG.debug(errMsg + identifier);
746 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
748 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
752 public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload,
753 final UriInfo uriInfo) {
754 boolean insertUsed = false;
755 boolean pointUsed = false;
756 String insert = null;
759 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
760 switch (entry.getKey()) {
764 insert = entry.getValue().iterator().next();
766 throw new RestconfDocumentedException("Insert parameter can be used only once.");
772 point = entry.getValue().iterator().next();
774 throw new RestconfDocumentedException("Point parameter can be used only once.");
778 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
782 if (pointUsed && !insertUsed) {
783 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
785 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
786 throw new RestconfDocumentedException(
787 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
790 Preconditions.checkNotNull(identifier);
792 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
794 validateInput(iiWithData.getSchemaNode(), payload);
795 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
796 validateListKeysEqualityInPayloadAndUri(payload);
798 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
799 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
802 * There is a small window where another write transaction could be
803 * updating the same data simultaneously and we get an
804 * OptimisticLockFailedException. This error is likely transient and The
805 * WriteTransaction#submit API docs state that a retry will likely
806 * succeed. So we'll try again if that scenario occurs. If it fails a
807 * third time then it probably will never succeed so we'll fail in that
810 * By retrying we're attempting to hide the internal implementation of
811 * the data store and how it handles concurrent updates from the
812 * restconf client. The client has instructed us to put the data and we
813 * should make every effort to do so without pushing optimistic lock
814 * failures back to the client and forcing them to handle it via retry
815 * (and having to document the behavior).
817 PutResult result = null;
820 if (mountPoint != null) {
822 result = this.broker.commitMountPointDataPut(mountPoint, normalizedII, payload.getData(), insert,
825 result = this.broker.commitConfigurationDataPut(this.controllerContext.getGlobalSchema(), normalizedII,
826 payload.getData(), insert, point);
830 result.getFutureOfPutData().checkedGet();
831 return Response.status(result.getStatus()).build();
832 } catch (final TransactionCommitFailedException e) {
833 if (e instanceof OptimisticLockFailedException) {
835 LOG.debug("Got OptimisticLockFailedException on last try - failing " + identifier);
836 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
839 LOG.debug("Got OptimisticLockFailedException - trying again " + identifier);
841 LOG.debug("Update failed for " + identifier, e);
842 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
848 private static void validateTopLevelNodeName(final NormalizedNodeContext node,
849 final YangInstanceIdentifier identifier) {
851 final String payloadName = node.getData().getNodeType().getLocalName();
854 if (identifier.isEmpty()) {
856 if (!node.getData().getNodeType().equals(NETCONF_BASE_QNAME)) {
857 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
858 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
862 final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
863 if (!payloadName.equals(identifierName)) {
864 throw new RestconfDocumentedException(
865 "Payload name (" + payloadName + ") is different from identifier name (" + identifierName + ")",
866 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
872 * Validates whether keys in {@code payload} are equal to values of keys in
873 * {@code iiWithData} for list schema node
875 * @throws RestconfDocumentedException
876 * if key values or key count in payload and URI isn't equal
879 private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
880 Preconditions.checkArgument(payload != null);
881 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
882 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
883 final SchemaNode schemaNode = iiWithData.getSchemaNode();
884 final NormalizedNode<?, ?> data = payload.getData();
885 if (schemaNode instanceof ListSchemaNode) {
886 final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
887 if (lastPathArgument instanceof NodeIdentifierWithPredicates && data instanceof MapEntryNode) {
888 final Map<QName, Object> uriKeyValues =
889 ((NodeIdentifierWithPredicates) lastPathArgument).getKeyValues();
890 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
896 public static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final MapEntryNode payload,
897 final List<QName> keyDefinitions) {
899 final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
900 for (final QName keyDefinition : keyDefinitions) {
901 final Object uriKeyValue = mutableCopyUriKeyValues.remove(keyDefinition);
902 // should be caught during parsing URI to InstanceIdentifier
903 RestconfValidationUtils.checkDocumentedError(uriKeyValue != null, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
904 "Missing key " + keyDefinition + " in URI.");
906 final Object dataKeyValue = payload.getIdentifier().getKeyValues().get(keyDefinition);
908 if (!Objects.deepEquals(uriKeyValue, dataKeyValue)) {
909 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName()
910 + "' specified in the URI doesn't match the value '" + dataKeyValue
911 + "' specified in the message body. ";
912 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
918 public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload,
919 final UriInfo uriInfo) {
920 return createConfigurationData(payload, uriInfo);
923 // FIXME create RestconfIdetifierHelper and move this method there
924 private static YangInstanceIdentifier checkConsistencyOfNormalizedNodeContext(final NormalizedNodeContext payload) {
925 Preconditions.checkArgument(payload != null);
926 Preconditions.checkArgument(payload.getData() != null);
927 Preconditions.checkArgument(payload.getData().getNodeType() != null);
928 Preconditions.checkArgument(payload.getInstanceIdentifierContext() != null);
929 Preconditions.checkArgument(payload.getInstanceIdentifierContext().getInstanceIdentifier() != null);
931 final QName payloadNodeQname = payload.getData().getNodeType();
932 final YangInstanceIdentifier yangIdent = payload.getInstanceIdentifierContext().getInstanceIdentifier();
933 if (payloadNodeQname.compareTo(yangIdent.getLastPathArgument().getNodeType()) > 0) {
936 final InstanceIdentifierContext<?> parentContext = payload.getInstanceIdentifierContext();
937 final SchemaNode parentSchemaNode = parentContext.getSchemaNode();
938 if (parentSchemaNode instanceof DataNodeContainer) {
939 final DataNodeContainer cast = (DataNodeContainer) parentSchemaNode;
940 for (final DataSchemaNode child : cast.getChildNodes()) {
941 if (payloadNodeQname.compareTo(child.getQName()) == 0) {
942 return YangInstanceIdentifier.builder(yangIdent).node(child.getQName()).build();
946 if (parentSchemaNode instanceof RpcDefinition) {
949 final String errMsg = "Error parsing input: DataSchemaNode has not children ";
950 LOG.info(errMsg + yangIdent);
951 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
955 public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
956 if (payload == null) {
957 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
959 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
960 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
961 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
963 boolean insertUsed = false;
964 boolean pointUsed = false;
965 String insert = null;
968 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
969 switch (entry.getKey()) {
973 insert = entry.getValue().iterator().next();
975 throw new RestconfDocumentedException("Insert parameter can be used only once.");
981 point = entry.getValue().iterator().next();
983 throw new RestconfDocumentedException("Point parameter can be used only once.");
987 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
991 if (pointUsed && !insertUsed) {
992 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
994 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
995 throw new RestconfDocumentedException(
996 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
999 CheckedFuture<Void, TransactionCommitFailedException> future;
1000 if (mountPoint != null) {
1001 future = this.broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData(), insert,
1004 future = this.broker.commitConfigurationDataPost(this.controllerContext.getGlobalSchema(), normalizedII,
1005 payload.getData(), insert, point);
1009 future.checkedGet();
1010 } catch (final RestconfDocumentedException e) {
1012 } catch (final TransactionCommitFailedException e) {
1013 LOG.info("Error creating data " + (uriInfo != null ? uriInfo.getPath() : ""), e);
1014 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
1017 LOG.trace("Successfuly created data.");
1019 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
1020 // FIXME: Provide path to result.
1021 final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
1022 if (location != null) {
1023 responseBuilder.location(location);
1025 return responseBuilder.build();
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.", ErrorType.APPLICATION,
1066 ErrorTag.DATA_MISSING);
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
1081 * Additional parameters for subscribing to stream are loaded via rpc input
1084 * <li>datastore - default CONFIGURATION (other values of
1085 * {@link LogicalDatastoreType} enum type)</li>
1086 * <li>scope - default BASE (other values of {@link DataChangeScope})</li>
1090 public NormalizedNodeContext subscribeToStream(final String identifier, final UriInfo uriInfo) {
1091 boolean startTime_used = false;
1092 boolean stopTime_used = false;
1093 Instant start = Instant.now();
1094 Instant stop = null;
1095 boolean filter_used = false;
1096 String filter = null;
1097 boolean leafNodesOnly_used = false;
1098 boolean leafNodesOnly = false;
1100 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
1101 switch (entry.getKey()) {
1103 if (!startTime_used) {
1104 startTime_used = true;
1105 start = parseDateFromQueryParam(entry);
1107 throw new RestconfDocumentedException("Start-time parameter can be used only once.");
1111 if (!stopTime_used) {
1112 stopTime_used = true;
1113 stop = parseDateFromQueryParam(entry);
1115 throw new RestconfDocumentedException("Stop-time parameter can be used only once.");
1121 filter = entry.getValue().iterator().next();
1123 throw new RestconfDocumentedException("Filter parameter can be used only once.");
1126 case "odl-leaf-nodes-only":
1127 if (!leafNodesOnly_used) {
1128 leafNodesOnly_used = true;
1129 leafNodesOnly = Boolean.parseBoolean(entry.getValue().iterator().next());
1131 throw new RestconfDocumentedException("Odl-leaf-nodes-only parameter can be used only once.");
1135 throw new RestconfDocumentedException("Bad parameter used with notifications: " + entry.getKey());
1138 if (!startTime_used && stopTime_used) {
1139 throw new RestconfDocumentedException("Stop-time parameter has to be used with start-time parameter.");
1141 URI response = null;
1142 if (identifier.contains(DATA_SUBSCR)) {
1143 response = dataSubs(identifier, uriInfo, start, stop, filter, leafNodesOnly);
1144 } else if (identifier.contains(NOTIFICATION_STREAM)) {
1145 response = notifStream(identifier, uriInfo, start, stop, filter);
1148 if (response != null) {
1149 // prepare node with value of location
1150 final InstanceIdentifierContext<?> iid = prepareIIDSubsStreamOutput();
1151 final NormalizedNodeAttrBuilder<NodeIdentifier, Object, LeafNode<Object>> builder =
1152 ImmutableLeafNodeBuilder.create().withValue(response.toString());
1153 builder.withNodeIdentifier(
1154 NodeIdentifier.create(QName.create("subscribe:to:notification", "2016-10-28", "location")));
1156 // prepare new header with location
1157 final Map<String, Object> headers = new HashMap<>();
1158 headers.put("Location", response);
1160 return new NormalizedNodeContext(iid, builder.build(), headers);
1163 final String msg = "Bad type of notification of sal-remote";
1165 throw new RestconfDocumentedException(msg);
1168 private static Instant parseDateFromQueryParam(final Entry<String, List<String>> entry) {
1169 final DateAndTime event = new DateAndTime(entry.getValue().iterator().next());
1170 final String value = event.getValue();
1171 final TemporalAccessor p;
1173 p = FORMATTER.parse(value);
1174 } catch (final DateTimeParseException e) {
1175 throw new RestconfDocumentedException("Cannot parse of value in date: " + value, e);
1177 return Instant.from(p);
1181 * @return {@link InstanceIdentifierContext} of location leaf for
1184 private static InstanceIdentifierContext<?> prepareIIDSubsStreamOutput() {
1185 final QName qnameBase = QName.create("subscribe:to:notification", "2016-10-28", "notifi");
1186 final SchemaContext schemaCtx = ControllerContext.getInstance().getGlobalSchema();
1187 final DataSchemaNode location = ((ContainerSchemaNode) schemaCtx
1188 .findModuleByNamespaceAndRevision(qnameBase.getNamespace(), qnameBase.getRevision())
1189 .getDataChildByName(qnameBase)).getDataChildByName(QName.create(qnameBase, "location"));
1190 final List<PathArgument> path = new ArrayList<>();
1191 path.add(NodeIdentifier.create(qnameBase));
1192 path.add(NodeIdentifier.create(QName.create(qnameBase, "location")));
1194 return new InstanceIdentifierContext<SchemaNode>(YangInstanceIdentifier.create(path), location, null,
1199 * Register notification listener by stream name
1206 * - stop-time of getting notification
1208 * - start-time of getting notification
1210 * - indicate which subset of all possible events are of interest
1211 * @return {@link URI} of location
1213 private URI notifStream(final String identifier, final UriInfo uriInfo, final Instant start,
1214 final Instant stop, final String filter) {
1215 final String streamName = Notificator.createStreamNameFromUri(identifier);
1216 if (Strings.isNullOrEmpty(streamName)) {
1217 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1219 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
1220 if (listeners == null || listeners.isEmpty()) {
1221 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1222 ErrorTag.UNKNOWN_ELEMENT);
1225 for (final NotificationListenerAdapter listener : listeners) {
1226 this.broker.registerToListenNotification(listener);
1227 listener.setQueryParams(start, java.util.Optional.ofNullable(stop), java.util.Optional.ofNullable(filter), false);
1230 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1231 int notificationPort = NOTIFICATION_PORT;
1233 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
1234 notificationPort = webSocketServerInstance.getPort();
1235 } catch (final NullPointerException e) {
1236 WebSocketServer.createInstance(NOTIFICATION_PORT);
1238 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1239 final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
1241 return uriToWebsocketServer;
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), java.util.Optional.ofNullable(filter), leafNodesOnly);
1273 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1274 final LogicalDatastoreType datastore =
1275 parserURIEnumParameter(LogicalDatastoreType.class, paramToValues.get(DATASTORE_PARAM_NAME));
1276 if (datastore == null) {
1277 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1278 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1280 final DataChangeScope scope =
1281 parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
1282 if (scope == null) {
1283 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1284 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1287 this.broker.registerToListenDataChanges(datastore, scope, listener);
1289 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1290 int notificationPort = NOTIFICATION_PORT;
1292 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
1293 notificationPort = webSocketServerInstance.getPort();
1294 } catch (final NullPointerException e) {
1295 WebSocketServer.createInstance(NOTIFICATION_PORT);
1297 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1298 final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
1300 return uriToWebsocketServer;
1304 public PATCHStatusContext patchConfigurationData(final String identifier, final PATCHContext context,
1305 final UriInfo uriInfo) {
1306 if (context == null) {
1307 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1311 return this.broker.patchConfigurationDataWithinTransaction(context);
1312 } catch (final Exception e) {
1313 LOG.debug("Patch transaction failed", e);
1314 throw new RestconfDocumentedException(e.getMessage());
1319 public PATCHStatusContext patchConfigurationData(final PATCHContext context, @Context final UriInfo uriInfo) {
1320 if (context == null) {
1321 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1325 return this.broker.patchConfigurationDataWithinTransaction(context);
1326 } catch (final Exception e) {
1327 LOG.debug("Patch transaction failed", e);
1328 throw new RestconfDocumentedException(e.getMessage());
1333 * Load parameter for subscribing to stream from input composite node
1337 * @return enum object if its string value is equal to {@code paramName}. In
1340 private static <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1341 final String paramName) {
1342 final Optional<DataContainerChild<? extends PathArgument, ?>> augNode =
1343 value.getChild(SAL_REMOTE_AUG_IDENTIFIER);
1344 if (!augNode.isPresent() && !(augNode instanceof AugmentationNode)) {
1347 final Optional<DataContainerChild<? extends PathArgument, ?>> enumNode = ((AugmentationNode) augNode.get())
1348 .getChild(new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1349 if (!enumNode.isPresent()) {
1352 final Object rawValue = enumNode.get().getValue();
1353 if (!(rawValue instanceof String)) {
1357 return resolveAsEnum(classDescriptor, (String) rawValue);
1361 * Checks whether {@code value} is one of the string representation of
1362 * enumeration {@code classDescriptor}
1364 * @return enum object if string value of {@code classDescriptor}
1365 * enumeration is equal to {@code value}. Other cases null.
1367 private static <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1368 if (Strings.isNullOrEmpty(value)) {
1371 return resolveAsEnum(classDescriptor, value);
1374 private static <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1375 final T[] enumConstants = classDescriptor.getEnumConstants();
1376 if (enumConstants != null) {
1377 for (final T enm : classDescriptor.getEnumConstants()) {
1378 if (((Enum<?>) enm).name().equals(value)) {
1386 private static Map<String, String> resolveValuesFromUri(final String uri) {
1387 final Map<String, String> result = new HashMap<>();
1388 final String[] tokens = uri.split("/");
1389 for (int i = 1; i < tokens.length; i++) {
1390 final String[] parameterTokens = tokens[i].split("=");
1391 if (parameterTokens.length == 2) {
1392 result.put(parameterTokens[0], parameterTokens[1]);
1398 private MapNode makeModuleMapNode(final Set<Module> modules) {
1399 Preconditions.checkNotNull(modules);
1400 final Module restconfModule = getRestconfModule();
1401 final DataSchemaNode moduleSchemaNode = this.controllerContext
1402 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1403 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1405 final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder =
1406 Builders.mapBuilder((ListSchemaNode) moduleSchemaNode);
1408 for (final Module module : modules) {
1409 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1411 return listModuleBuilder.build();
1414 protected MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1415 Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1416 "moduleSchemaNode has to be of type ListSchemaNode");
1417 final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1418 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues =
1419 Builders.mapEntryBuilder(listModuleSchemaNode);
1421 List<DataSchemaNode> instanceDataChildrenByName =
1422 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "name");
1423 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1424 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1426 .withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName()).build());
1428 instanceDataChildrenByName =
1429 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "revision");
1430 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1431 Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1432 final String revision = module.getQNameModule().getFormattedRevision();
1434 .withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode).withValue(revision).build());
1436 instanceDataChildrenByName =
1437 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "namespace");
1438 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1439 Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1440 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1441 .withValue(module.getNamespace().toString()).build());
1443 instanceDataChildrenByName =
1444 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "feature");
1445 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1446 Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1447 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder =
1448 Builders.leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1449 for (final FeatureDefinition feature : module.getFeatures()) {
1450 featuresBuilder.withChild(Builders.leafSetEntryBuilder((LeafListSchemaNode) featureSchemaNode)
1451 .withValue(feature.getQName().getLocalName()).build());
1453 moduleNodeValues.withChild(featuresBuilder.build());
1455 return moduleNodeValues.build();
1458 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1459 Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1460 "streamSchemaNode has to be of type ListSchemaNode");
1461 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1462 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues =
1463 Builders.mapEntryBuilder(listStreamSchemaNode);
1465 List<DataSchemaNode> instanceDataChildrenByName =
1466 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "name");
1467 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1468 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1469 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName).build());
1471 instanceDataChildrenByName =
1472 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "description");
1473 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1474 Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1475 streamNodeValues.withChild(
1476 Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue("DESCRIPTION_PLACEHOLDER").build());
1478 instanceDataChildrenByName =
1479 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-support");
1480 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1481 Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1482 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1483 .withValue(Boolean.valueOf(true)).build());
1485 instanceDataChildrenByName =
1486 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-log-creation-time");
1487 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1488 Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1489 streamNodeValues.withChild(
1490 Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode).withValue("").build());
1492 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "events");
1493 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1494 Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1495 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode).withValue("").build());
1497 return streamNodeValues.build();
1501 * Prepare stream for notification
1504 * - contains list of qnames of notifications
1505 * @return - checked future object
1507 private static CheckedFuture<DOMRpcResult, DOMRpcException> invokeSalRemoteRpcNotifiStrRPC(
1508 final NormalizedNodeContext payload) {
1509 final ContainerNode data = (ContainerNode) payload.getData();
1510 LeafSetNode leafSet = null;
1511 String outputType = "XML";
1512 for (final DataContainerChild<? extends PathArgument, ?> dataChild : data.getValue()) {
1513 if (dataChild instanceof LeafSetNode) {
1514 leafSet = (LeafSetNode) dataChild;
1515 } else if (dataChild instanceof AugmentationNode) {
1516 outputType = (String) ((AugmentationNode) dataChild).getValue().iterator().next().getValue();
1520 final Collection<LeafSetEntryNode> entryNodes = leafSet.getValue();
1521 final List<SchemaPath> paths = new ArrayList<>();
1522 String streamName = CREATE_NOTIFICATION_STREAM + "/";
1524 final Iterator<LeafSetEntryNode> iterator = entryNodes.iterator();
1525 while (iterator.hasNext()) {
1526 final QName valueQName = QName.create((String) iterator.next().getValue());
1527 final Module module =
1528 ControllerContext.getInstance().findModuleByNamespace(valueQName.getModule().getNamespace());
1529 Preconditions.checkNotNull(module,
1530 "Module for namespace " + valueQName.getModule().getNamespace() + " does not exist");
1531 NotificationDefinition notifiDef = null;
1532 for (final NotificationDefinition notification : module.getNotifications()) {
1533 if (notification.getQName().equals(valueQName)) {
1534 notifiDef = notification;
1538 final String moduleName = module.getName();
1539 Preconditions.checkNotNull(notifiDef,
1540 "Notification " + valueQName + "doesn't exist in module " + moduleName);
1541 paths.add(notifiDef.getPath());
1542 streamName = streamName + moduleName + ":" + valueQName.getLocalName();
1543 if (iterator.hasNext()) {
1544 streamName = streamName + ",";
1548 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
1549 final QName outputQname = QName.create(rpcQName, "output");
1550 final QName streamNameQname = QName.create(rpcQName, "notification-stream-identifier");
1552 final ContainerNode output =
1553 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
1554 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
1556 if (!Notificator.existNotificationListenerFor(streamName)) {
1557 Notificator.createNotificationListener(paths, streamName, outputType);
1560 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
1562 return Futures.immediateCheckedFuture(defaultDOMRpcResult);