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.sal.rest.api.Draft02;
62 import org.opendaylight.netconf.sal.rest.api.RestconfService;
63 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
64 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
65 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
66 import org.opendaylight.netconf.sal.streams.websockets.WebSocketServer;
67 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
68 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
69 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
70 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
71 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
72 import org.opendaylight.restconf.common.patch.PatchContext;
73 import org.opendaylight.restconf.common.patch.PatchStatusContext;
74 import org.opendaylight.restconf.common.validation.RestconfValidationUtils;
75 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
76 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
77 import org.opendaylight.yangtools.yang.common.QName;
78 import org.opendaylight.yangtools.yang.common.QNameModule;
79 import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
80 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
81 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
82 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
83 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
84 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
85 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
86 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
87 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
88 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
89 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
90 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
91 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
92 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
93 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
94 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
95 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
96 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
97 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
98 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
99 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
100 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
101 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
102 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
103 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
104 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
105 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
106 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
107 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
108 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
109 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
110 import org.opendaylight.yangtools.yang.model.api.Module;
111 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
112 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
113 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
114 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
115 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
116 import org.opendaylight.yangtools.yang.model.util.SimpleSchemaContext;
117 import org.slf4j.Logger;
118 import org.slf4j.LoggerFactory;
120 public class RestconfImpl implements RestconfService {
122 private static final RestconfImpl INSTANCE = new RestconfImpl();
125 * Notifications are served on port 8181.
127 private static final int NOTIFICATION_PORT = 8181;
129 private static final int CHAR_NOT_FOUND = -1;
131 private static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
133 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
135 private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
137 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
139 private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
141 private static final String DATASTORE_PARAM_NAME = "datastore";
143 private static final String SCOPE_PARAM_NAME = "scope";
145 private static final String OUTPUT_TYPE_PARAM_NAME = "notification-output-type";
147 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
149 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
151 private static final QName NETCONF_BASE_QNAME = QName.create(QNameModule.create(URI.create(NETCONF_BASE), null),
152 NETCONF_BASE_PAYLOAD_NAME).intern();
154 private static final QNameModule SAL_REMOTE_AUGMENT;
158 SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
159 SimpleDateFormatUtil.getRevisionFormat().parse("2014-07-08"));
160 } catch (final ParseException e) {
161 throw new ExceptionInInitializerError(e);
165 private static final AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER =
166 new AugmentationIdentifier(ImmutableSet.of(
167 QName.create(SAL_REMOTE_AUGMENT, "scope"), QName.create(SAL_REMOTE_AUGMENT, "datastore"),
168 QName.create(SAL_REMOTE_AUGMENT, "notification-output-type")));
170 public static final CharSequence DATA_SUBSCR = "data-change-event-subscription";
171 private static final CharSequence CREATE_DATA_SUBSCR = "create-" + DATA_SUBSCR;
173 public static final CharSequence NOTIFICATION_STREAM = "notification-stream";
174 private static final CharSequence CREATE_NOTIFICATION_STREAM = "create-" + NOTIFICATION_STREAM;
176 private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
177 .appendValue(ChronoField.YEAR, 4).appendLiteral('-')
178 .appendValue(ChronoField.MONTH_OF_YEAR, 2).appendLiteral('-')
179 .appendValue(ChronoField.DAY_OF_MONTH, 2).appendLiteral('T')
180 .appendValue(ChronoField.HOUR_OF_DAY, 2).appendLiteral(':')
181 .appendValue(ChronoField.MINUTE_OF_HOUR, 2).appendLiteral(':')
182 .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
183 .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
184 .appendOffset("+HH:MM", "Z").toFormatter();
186 private BrokerFacade broker;
188 private ControllerContext controllerContext;
190 public void setBroker(final BrokerFacade broker) {
191 this.broker = broker;
194 public void setControllerContext(final ControllerContext controllerContext) {
195 this.controllerContext = controllerContext;
198 private RestconfImpl() {
201 public static RestconfImpl getInstance() {
206 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
207 final Set<Module> allModules = this.controllerContext.getAllModules();
208 final MapNode allModuleMap = makeModuleMapNode(allModules);
210 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
212 final Module restconfModule = getRestconfModule();
213 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
214 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
215 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
217 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
218 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
219 moduleContainerBuilder.withChild(allModuleMap);
221 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode, null, schemaContext),
222 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
226 * Valid only for mount point.
229 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
230 Preconditions.checkNotNull(identifier);
231 if (!identifier.contains(ControllerContext.MOUNT)) {
232 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
233 + " URI has to end with " + ControllerContext.MOUNT;
234 LOG.debug(errMsg + " for " + identifier);
235 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
238 final InstanceIdentifierContext<?> mountPointIdentifier =
239 this.controllerContext.toMountPointIdentifier(identifier);
240 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
241 final Set<Module> modules = this.controllerContext.getAllModules(mountPoint);
242 final MapNode mountPointModulesMap = makeModuleMapNode(modules);
244 final Module restconfModule = getRestconfModule();
245 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
246 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
247 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
249 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
250 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
251 moduleContainerBuilder.withChild(mountPointModulesMap);
253 return new NormalizedNodeContext(
254 new InstanceIdentifierContext<>(null, modulesSchemaNode, mountPoint,
255 this.controllerContext.getGlobalSchema()),
256 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
260 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
261 Preconditions.checkNotNull(identifier);
262 final QName moduleNameAndRevision = getModuleNameAndRevision(identifier);
263 Module module = null;
264 DOMMountPoint mountPoint = null;
265 final SchemaContext schemaContext;
266 if (identifier.contains(ControllerContext.MOUNT)) {
267 final InstanceIdentifierContext<?> mountPointIdentifier =
268 this.controllerContext.toMountPointIdentifier(identifier);
269 mountPoint = mountPointIdentifier.getMountPoint();
270 module = this.controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision);
271 schemaContext = mountPoint.getSchemaContext();
273 module = this.controllerContext.findModuleByNameAndRevision(moduleNameAndRevision);
274 schemaContext = this.controllerContext.getGlobalSchema();
277 if (module == null) {
278 final String errMsg = "Module with name '" + moduleNameAndRevision.getLocalName() + "' and revision '"
279 + moduleNameAndRevision.getRevision() + "' was not found.";
281 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
284 final Module restconfModule = getRestconfModule();
285 final Set<Module> modules = Collections.singleton(module);
286 final MapNode moduleMap = makeModuleMapNode(modules);
288 final DataSchemaNode moduleSchemaNode = this.controllerContext
289 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
290 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
292 return new NormalizedNodeContext(
293 new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint, schemaContext), moduleMap,
294 QueryParametersParser.parseWriterParameters(uriInfo));
298 public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
299 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
300 final Set<String> availableStreams = Notificator.getStreamNames();
301 final Module restconfModule = getRestconfModule();
302 final DataSchemaNode streamSchemaNode = this.controllerContext
303 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
304 Preconditions.checkState(streamSchemaNode instanceof ListSchemaNode);
306 final CollectionNodeBuilder<MapEntryNode, MapNode> listStreamsBuilder =
307 Builders.mapBuilder((ListSchemaNode) streamSchemaNode);
309 for (final String streamName : availableStreams) {
310 listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
313 final DataSchemaNode streamsContainerSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
314 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
315 Preconditions.checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
317 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
318 Builders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
319 streamsContainerBuilder.withChild(listStreamsBuilder.build());
321 return new NormalizedNodeContext(
322 new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null, schemaContext),
323 streamsContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
327 public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
328 final Set<Module> allModules = this.controllerContext.getAllModules();
329 return operationsFromModulesToNormalizedContext(allModules, null);
333 public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
334 Set<Module> modules = null;
335 DOMMountPoint mountPoint = null;
336 if (identifier.contains(ControllerContext.MOUNT)) {
337 final InstanceIdentifierContext<?> mountPointIdentifier =
338 this.controllerContext.toMountPointIdentifier(identifier);
339 mountPoint = mountPointIdentifier.getMountPoint();
340 modules = this.controllerContext.getAllModules(mountPoint);
343 final String errMsg =
344 "URI has bad format. If operations behind mount point should be showed, URI has to " + "end with ";
345 LOG.debug(errMsg + ControllerContext.MOUNT + " for " + identifier);
346 throw new RestconfDocumentedException(errMsg + ControllerContext.MOUNT, ErrorType.PROTOCOL,
347 ErrorTag.INVALID_VALUE);
350 return operationsFromModulesToNormalizedContext(modules, mountPoint);
354 * Special case only for GET restconf/operations use (since moment of
355 * pre-Beryllium Yang parser and Yang model API removal). The method is
356 * creating fake schema context with fake module and fake data by use own
357 * implementations of schema nodes and module.
360 * set of modules for get RPCs from every module
362 * mount point, if in use otherwise null
363 * @return {@link NormalizedNodeContext}
365 private static NormalizedNodeContext operationsFromModulesToNormalizedContext(final Set<Module> modules,
366 final DOMMountPoint mountPoint) {
368 final Collection<Module> neededModules = new ArrayList<>(modules.size());
369 final ArrayList<LeafSchemaNode> fakeRpcSchema = new ArrayList<>();
371 for (final Module m : modules) {
372 final Set<RpcDefinition> rpcs = m.getRpcs();
373 if (!rpcs.isEmpty()) {
374 neededModules.add(m);
376 fakeRpcSchema.ensureCapacity(fakeRpcSchema.size() + rpcs.size());
377 rpcs.forEach(rpc -> fakeRpcSchema.add(new FakeLeafSchemaNode(rpc.getQName())));
381 final ContainerSchemaNode fakeCont = new FakeContainerSchemaNode(fakeRpcSchema);
382 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> containerBuilder =
383 Builders.containerBuilder(fakeCont);
385 for (final LeafSchemaNode leaf : fakeRpcSchema) {
386 containerBuilder.withChild(Builders.leafBuilder(leaf).build());
389 final Collection<Module> fakeModules = new ArrayList<>(neededModules.size() + 1);
390 neededModules.forEach(imp -> fakeModules.add(new FakeImportedModule(imp)));
391 fakeModules.add(new FakeRestconfModule(neededModules, fakeCont));
393 final SchemaContext fakeSchemaCtx = SimpleSchemaContext.forModules(ImmutableSet.copyOf(fakeModules));
394 final InstanceIdentifierContext<ContainerSchemaNode> instanceIdentifierContext =
395 new InstanceIdentifierContext<>(null, fakeCont, mountPoint, fakeSchemaCtx);
396 return new NormalizedNodeContext(instanceIdentifierContext, containerBuilder.build());
399 private Module getRestconfModule() {
400 final Module restconfModule = this.controllerContext.getRestconfModule();
401 if (restconfModule == null) {
402 LOG.debug("ietf-restconf module was not found.");
403 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
404 ErrorTag.OPERATION_NOT_SUPPORTED);
407 return restconfModule;
410 private static QName getModuleNameAndRevision(final String identifier) {
411 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
412 String moduleNameAndRevision = "";
413 if (mountIndex >= 0) {
414 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
416 moduleNameAndRevision = identifier;
419 final Splitter splitter = Splitter.on("/").omitEmptyStrings();
420 final Iterable<String> split = splitter.split(moduleNameAndRevision);
421 final List<String> pathArgs = Lists.<String>newArrayList(split);
422 if (pathArgs.size() < 2) {
423 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
424 throw new RestconfDocumentedException(
425 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
426 ErrorTag.INVALID_VALUE);
430 final String moduleName = pathArgs.get(0);
431 final String revision = pathArgs.get(1);
432 return QName.create(null, SimpleDateFormatUtil.getRevisionFormat().parse(revision), moduleName);
433 } catch (final ParseException e) {
434 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
435 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
436 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
441 public Object getRoot() {
446 public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload,
447 final UriInfo uriInfo) {
448 final SchemaPath type = payload.getInstanceIdentifierContext().getSchemaNode().getPath();
449 final URI namespace = payload.getInstanceIdentifierContext().getSchemaNode().getQName().getNamespace();
450 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
451 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
452 final SchemaContext schemaContext;
454 if (mountPoint != null) {
455 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
456 if (!mountRpcServices.isPresent()) {
457 LOG.debug("Error: Rpc service is missing.");
458 throw new RestconfDocumentedException("Rpc service is missing.");
460 schemaContext = mountPoint.getSchemaContext();
461 response = mountRpcServices.get().invokeRpc(type, payload.getData());
463 if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
464 if (identifier.contains(CREATE_DATA_SUBSCR)) {
465 response = invokeSalRemoteRpcSubscribeRPC(payload);
466 } else if (identifier.contains(CREATE_NOTIFICATION_STREAM)) {
467 response = invokeSalRemoteRpcNotifiStrRPC(payload);
469 final String msg = "Not supported operation";
471 throw new RestconfDocumentedException(msg, ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED);
474 response = this.broker.invokeRpc(type, payload.getData());
476 schemaContext = this.controllerContext.getGlobalSchema();
479 final DOMRpcResult result = checkRpcResponse(response);
481 RpcDefinition resultNodeSchema = null;
482 final NormalizedNode<?, ?> resultData = result.getResult();
483 if (result != null && result.getResult() != null) {
484 resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
487 return new NormalizedNodeContext(
488 new InstanceIdentifierContext<>(null, resultNodeSchema, mountPoint, schemaContext),
489 resultData, QueryParametersParser.parseWriterParameters(uriInfo));
493 public NormalizedNodeContext invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
494 if (noPayload != null && !CharMatcher.WHITESPACE.matchesAllOf(noPayload)) {
495 throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
498 String identifierEncoded = null;
499 DOMMountPoint mountPoint = null;
500 final SchemaContext schemaContext;
501 if (identifier.contains(ControllerContext.MOUNT)) {
502 // mounted RPC call - look up mount instance.
503 final InstanceIdentifierContext<?> mountPointId = this.controllerContext.toMountPointIdentifier(identifier);
504 mountPoint = mountPointId.getMountPoint();
505 schemaContext = mountPoint.getSchemaContext();
506 final int startOfRemoteRpcName =
507 identifier.lastIndexOf(ControllerContext.MOUNT) + ControllerContext.MOUNT.length() + 1;
508 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
509 identifierEncoded = remoteRpcName;
511 } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
512 final String slashErrorMsg = String.format(
513 "Identifier %n%s%ncan\'t contain slash "
514 + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.",
516 LOG.debug(slashErrorMsg);
517 throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
519 identifierEncoded = identifier;
520 schemaContext = this.controllerContext.getGlobalSchema();
523 final String identifierDecoded = this.controllerContext.urlPathArgDecode(identifierEncoded);
525 RpcDefinition rpc = null;
526 if (mountPoint == null) {
527 rpc = this.controllerContext.getRpcDefinition(identifierDecoded, null);
529 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
533 LOG.debug("RPC " + identifierDecoded + " does not exist.");
534 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
537 if (!rpc.getInput().getChildNodes().isEmpty()) {
538 LOG.debug("RPC " + rpc + " does not need input value.");
539 // FIXME : find a correct Error from specification
540 throw new IllegalStateException("RPC " + rpc + " does'n need input value!");
543 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
544 if (mountPoint != null) {
545 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
546 if (!mountRpcServices.isPresent()) {
547 throw new RestconfDocumentedException("Rpc service is missing.");
549 response = mountRpcServices.get().invokeRpc(rpc.getPath(), null);
551 response = this.broker.invokeRpc(rpc.getPath(), null);
554 final DOMRpcResult result = checkRpcResponse(response);
556 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpc, mountPoint, schemaContext),
557 result.getResult(), QueryParametersParser.parseWriterParameters(uriInfo));
560 private static DOMRpcResult checkRpcResponse(final CheckedFuture<DOMRpcResult, DOMRpcException> response) {
561 if (response == null) {
565 final DOMRpcResult retValue = response.get();
566 if (retValue.getErrors() == null || retValue.getErrors().isEmpty()) {
569 LOG.debug("RpcError message", retValue.getErrors());
570 throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
571 } catch (final InterruptedException e) {
572 final String errMsg = "The operation was interrupted while executing and did not complete.";
573 LOG.debug("Rpc Interrupt - " + errMsg, e);
574 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
575 } catch (final ExecutionException e) {
576 LOG.debug("Execution RpcError: ", e);
577 Throwable cause = e.getCause();
579 while (cause.getCause() != null) {
580 cause = cause.getCause();
583 if (cause instanceof IllegalArgumentException) {
584 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL,
585 ErrorTag.INVALID_VALUE);
586 } else if (cause instanceof DOMRpcImplementationNotAvailableException) {
587 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.APPLICATION,
588 ErrorTag.OPERATION_NOT_SUPPORTED);
590 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
593 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
596 } catch (final CancellationException e) {
597 final String errMsg = "The operation was cancelled while executing.";
598 LOG.debug("Cancel RpcExecution: " + errMsg, e);
599 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
603 private static void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
604 if (inputSchema != null && payload.getData() == null) {
605 // expected a non null payload
606 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
607 } else if (inputSchema == null && payload.getData() != null) {
608 // did not expect any input
609 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
613 private CheckedFuture<DOMRpcResult, DOMRpcException>
614 invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
615 final ContainerNode value = (ContainerNode) payload.getData();
616 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
617 final Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(new NodeIdentifier(
618 QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(), "path")));
619 final Object pathValue = path.isPresent() ? path.get().getValue() : null;
621 if (!(pathValue instanceof YangInstanceIdentifier)) {
622 final String errMsg = "Instance identifier was not normalized correctly ";
623 LOG.debug(errMsg + rpcQName);
624 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
627 final YangInstanceIdentifier pathIdentifier = (YangInstanceIdentifier) pathValue;
628 String streamName = (String) CREATE_DATA_SUBSCR;
629 NotificationOutputType outputType = null;
630 if (!pathIdentifier.isEmpty()) {
631 final String fullRestconfIdentifier =
632 DATA_SUBSCR + this.controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
634 LogicalDatastoreType datastore =
635 parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
636 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
638 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
639 scope = scope == null ? DEFAULT_SCOPE : scope;
641 outputType = parseEnumTypeParameter(value, NotificationOutputType.class, OUTPUT_TYPE_PARAM_NAME);
642 outputType = outputType == null ? NotificationOutputType.XML : outputType;
644 streamName = Notificator
645 .createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore + "/scope=" + scope);
648 if (Strings.isNullOrEmpty(streamName)) {
649 final String errMsg = "Path is empty or contains value node which is not Container or List build-in type.";
650 LOG.debug(errMsg + pathIdentifier);
651 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
654 final QName outputQname = QName.create(rpcQName, "output");
655 final QName streamNameQname = QName.create(rpcQName, "stream-name");
657 final ContainerNode output =
658 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
659 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
661 if (!Notificator.existListenerFor(streamName)) {
662 Notificator.createListener(pathIdentifier, streamName, outputType);
665 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
667 return Futures.immediateCheckedFuture(defaultDOMRpcResult);
670 private static RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
671 final String[] splittedIdentifier = identifierDecoded.split(":");
672 if (splittedIdentifier.length != 2) {
673 final String errMsg = identifierDecoded + " couldn't be splitted to 2 parts (module:rpc name)";
675 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
677 for (final Module module : schemaContext.getModules()) {
678 if (module.getName().equals(splittedIdentifier[0])) {
679 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
680 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
681 return rpcDefinition;
690 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
691 boolean withDefaUsed = false;
692 String withDefa = null;
694 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
695 switch (entry.getKey()) {
696 case "with-defaults":
699 withDefa = entry.getValue().iterator().next();
701 throw new RestconfDocumentedException("With-defaults parameter can be used only once.");
705 LOG.info("Unknown key : {}.", entry.getKey());
709 boolean tagged = false;
711 if (withDefa.equals("report-all-tagged")) {
715 if (withDefa.equals("report-all")) {
720 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
721 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
722 NormalizedNode<?, ?> data = null;
723 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
724 if (mountPoint != null) {
725 data = this.broker.readConfigurationData(mountPoint, normalizedII, withDefa);
727 data = this.broker.readConfigurationData(normalizedII, withDefa);
730 final String errMsg =
731 "Request could not be completed because the relevant data model content does not exist ";
732 LOG.debug(errMsg + identifier);
733 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
735 return new NormalizedNodeContext(iiWithData, data,
736 QueryParametersParser.parseWriterParameters(uriInfo, tagged));
740 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
741 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
742 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
743 NormalizedNode<?, ?> data = null;
744 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
745 if (mountPoint != null) {
746 data = this.broker.readOperationalData(mountPoint, normalizedII);
748 data = this.broker.readOperationalData(normalizedII);
751 final String errMsg =
752 "Request could not be completed because the relevant data model content does not exist ";
753 LOG.debug(errMsg + identifier);
754 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
756 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
760 public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload,
761 final UriInfo uriInfo) {
762 boolean insertUsed = false;
763 boolean pointUsed = false;
764 String insert = null;
767 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
768 switch (entry.getKey()) {
772 insert = entry.getValue().iterator().next();
774 throw new RestconfDocumentedException("Insert parameter can be used only once.");
780 point = entry.getValue().iterator().next();
782 throw new RestconfDocumentedException("Point parameter can be used only once.");
786 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
790 if (pointUsed && !insertUsed) {
791 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
793 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
794 throw new RestconfDocumentedException(
795 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
798 Preconditions.checkNotNull(identifier);
800 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
802 validateInput(iiWithData.getSchemaNode(), payload);
803 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
804 validateListKeysEqualityInPayloadAndUri(payload);
806 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
807 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
810 * There is a small window where another write transaction could be
811 * updating the same data simultaneously and we get an
812 * OptimisticLockFailedException. This error is likely transient and The
813 * WriteTransaction#submit API docs state that a retry will likely
814 * succeed. So we'll try again if that scenario occurs. If it fails a
815 * third time then it probably will never succeed so we'll fail in that
818 * By retrying we're attempting to hide the internal implementation of
819 * the data store and how it handles concurrent updates from the
820 * restconf client. The client has instructed us to put the data and we
821 * should make every effort to do so without pushing optimistic lock
822 * failures back to the client and forcing them to handle it via retry
823 * (and having to document the behavior).
825 PutResult result = null;
828 if (mountPoint != null) {
830 result = this.broker.commitMountPointDataPut(mountPoint, normalizedII, payload.getData(), insert,
833 result = this.broker.commitConfigurationDataPut(this.controllerContext.getGlobalSchema(), normalizedII,
834 payload.getData(), insert, point);
838 result.getFutureOfPutData().checkedGet();
839 return Response.status(result.getStatus()).build();
840 } catch (final TransactionCommitFailedException e) {
841 if (e instanceof OptimisticLockFailedException) {
843 LOG.debug("Got OptimisticLockFailedException on last try - failing " + identifier);
844 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
847 LOG.debug("Got OptimisticLockFailedException - trying again " + identifier);
849 LOG.debug("Update failed for " + identifier, e);
850 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
856 private static void validateTopLevelNodeName(final NormalizedNodeContext node,
857 final YangInstanceIdentifier identifier) {
859 final String payloadName = node.getData().getNodeType().getLocalName();
862 if (identifier.isEmpty()) {
864 if (!node.getData().getNodeType().equals(NETCONF_BASE_QNAME)) {
865 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
866 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
870 final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
871 if (!payloadName.equals(identifierName)) {
872 throw new RestconfDocumentedException(
873 "Payload name (" + payloadName + ") is different from identifier name (" + identifierName + ")",
874 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
880 * Validates whether keys in {@code payload} are equal to values of keys in
881 * {@code iiWithData} for list schema node.
883 * @throws RestconfDocumentedException
884 * if key values or key count in payload and URI isn't equal
887 private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
888 Preconditions.checkArgument(payload != null);
889 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
890 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
891 final SchemaNode schemaNode = iiWithData.getSchemaNode();
892 final NormalizedNode<?, ?> data = payload.getData();
893 if (schemaNode instanceof ListSchemaNode) {
894 final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
895 if (lastPathArgument instanceof NodeIdentifierWithPredicates && data instanceof MapEntryNode) {
896 final Map<QName, Object> uriKeyValues =
897 ((NodeIdentifierWithPredicates) lastPathArgument).getKeyValues();
898 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
904 public static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final MapEntryNode payload,
905 final List<QName> keyDefinitions) {
907 final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
908 for (final QName keyDefinition : keyDefinitions) {
909 final Object uriKeyValue = mutableCopyUriKeyValues.remove(keyDefinition);
910 // should be caught during parsing URI to InstanceIdentifier
911 RestconfValidationUtils.checkDocumentedError(uriKeyValue != null, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
912 "Missing key " + keyDefinition + " in URI.");
914 final Object dataKeyValue = payload.getIdentifier().getKeyValues().get(keyDefinition);
916 if (!Objects.deepEquals(uriKeyValue, dataKeyValue)) {
917 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName()
918 + "' specified in the URI doesn't match the value '" + dataKeyValue
919 + "' specified in the message body. ";
920 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
926 public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload,
927 final UriInfo uriInfo) {
928 return createConfigurationData(payload, uriInfo);
932 public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
933 if (payload == null) {
934 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
936 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
937 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
938 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
940 boolean insertUsed = false;
941 boolean pointUsed = false;
942 String insert = null;
945 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
946 switch (entry.getKey()) {
950 insert = entry.getValue().iterator().next();
952 throw new RestconfDocumentedException("Insert parameter can be used only once.");
958 point = entry.getValue().iterator().next();
960 throw new RestconfDocumentedException("Point parameter can be used only once.");
964 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
968 if (pointUsed && !insertUsed) {
969 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
971 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
972 throw new RestconfDocumentedException(
973 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
976 CheckedFuture<Void, TransactionCommitFailedException> future;
977 if (mountPoint != null) {
978 future = this.broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData(), insert,
981 future = this.broker.commitConfigurationDataPost(this.controllerContext.getGlobalSchema(), normalizedII,
982 payload.getData(), insert, point);
987 } catch (final RestconfDocumentedException e) {
989 } catch (final TransactionCommitFailedException e) {
990 LOG.info("Error creating data " + (uriInfo != null ? uriInfo.getPath() : ""), e);
991 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
994 LOG.trace("Successfuly created data.");
996 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
997 // FIXME: Provide path to result.
998 final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
999 if (location != null) {
1000 responseBuilder.location(location);
1002 return responseBuilder.build();
1005 // FIXME create RestconfIdetifierHelper and move this method there
1006 private static YangInstanceIdentifier checkConsistencyOfNormalizedNodeContext(final NormalizedNodeContext payload) {
1007 Preconditions.checkArgument(payload != null);
1008 Preconditions.checkArgument(payload.getData() != null);
1009 Preconditions.checkArgument(payload.getData().getNodeType() != null);
1010 Preconditions.checkArgument(payload.getInstanceIdentifierContext() != null);
1011 Preconditions.checkArgument(payload.getInstanceIdentifierContext().getInstanceIdentifier() != null);
1013 final QName payloadNodeQname = payload.getData().getNodeType();
1014 final YangInstanceIdentifier yangIdent = payload.getInstanceIdentifierContext().getInstanceIdentifier();
1015 if (payloadNodeQname.compareTo(yangIdent.getLastPathArgument().getNodeType()) > 0) {
1018 final InstanceIdentifierContext<?> parentContext = payload.getInstanceIdentifierContext();
1019 final SchemaNode parentSchemaNode = parentContext.getSchemaNode();
1020 if (parentSchemaNode instanceof DataNodeContainer) {
1021 final DataNodeContainer cast = (DataNodeContainer) parentSchemaNode;
1022 for (final DataSchemaNode child : cast.getChildNodes()) {
1023 if (payloadNodeQname.compareTo(child.getQName()) == 0) {
1024 return YangInstanceIdentifier.builder(yangIdent).node(child.getQName()).build();
1028 if (parentSchemaNode instanceof RpcDefinition) {
1031 final String errMsg = "Error parsing input: DataSchemaNode has not children ";
1032 LOG.info(errMsg + yangIdent);
1033 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1036 @SuppressWarnings("checkstyle:IllegalCatch")
1037 private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint,
1038 final YangInstanceIdentifier normalizedII) {
1039 if (uriInfo == null) {
1040 // This is null if invoked internally
1044 final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
1045 uriBuilder.path("config");
1047 uriBuilder.path(this.controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
1048 } catch (final Exception e) {
1049 LOG.info("Location for instance identifier" + normalizedII + "wasn't created", e);
1052 return uriBuilder.build();
1056 public Response deleteConfigurationData(final String identifier) {
1057 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
1058 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
1059 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
1061 final CheckedFuture<Void, TransactionCommitFailedException> future;
1062 if (mountPoint != null) {
1063 future = this.broker.commitConfigurationDataDelete(mountPoint, normalizedII);
1065 future = this.broker.commitConfigurationDataDelete(normalizedII);
1069 future.checkedGet();
1070 } catch (final TransactionCommitFailedException e) {
1071 final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
1072 Predicates.instanceOf(ModifiedNodeDoesNotExistException.class));
1073 if (searchedException.isPresent()) {
1074 throw new RestconfDocumentedException("Data specified for delete doesn't exist.", ErrorType.APPLICATION,
1075 ErrorTag.DATA_MISSING);
1078 final String errMsg = "Error while deleting data";
1079 LOG.info(errMsg, e);
1080 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
1083 return Response.status(Status.OK).build();
1087 * Subscribes to some path in schema context (stream) to listen on changes
1091 * Additional parameters for subscribing to stream are loaded via rpc input
1094 * <li>datastore - default CONFIGURATION (other values of
1095 * {@link LogicalDatastoreType} enum type)</li>
1096 * <li>scope - default BASE (other values of {@link DataChangeScope})</li>
1100 public NormalizedNodeContext subscribeToStream(final String identifier, final UriInfo uriInfo) {
1101 boolean startTimeUsed = false;
1102 boolean stopTimeUsed = false;
1103 Instant start = Instant.now();
1104 Instant stop = null;
1105 boolean filterUsed = false;
1106 String filter = null;
1107 boolean leafNodesOnlyUsed = false;
1108 boolean leafNodesOnly = false;
1110 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
1111 switch (entry.getKey()) {
1113 if (!startTimeUsed) {
1114 startTimeUsed = true;
1115 start = parseDateFromQueryParam(entry);
1117 throw new RestconfDocumentedException("Start-time parameter can be used only once.");
1121 if (!stopTimeUsed) {
1122 stopTimeUsed = true;
1123 stop = parseDateFromQueryParam(entry);
1125 throw new RestconfDocumentedException("Stop-time parameter can be used only once.");
1131 filter = entry.getValue().iterator().next();
1133 throw new RestconfDocumentedException("Filter parameter can be used only once.");
1136 case "odl-leaf-nodes-only":
1137 if (!leafNodesOnlyUsed) {
1138 leafNodesOnlyUsed = true;
1139 leafNodesOnly = Boolean.parseBoolean(entry.getValue().iterator().next());
1141 throw new RestconfDocumentedException("Odl-leaf-nodes-only parameter can be used only once.");
1145 throw new RestconfDocumentedException("Bad parameter used with notifications: " + entry.getKey());
1148 if (!startTimeUsed && stopTimeUsed) {
1149 throw new RestconfDocumentedException("Stop-time parameter has to be used with start-time parameter.");
1151 URI response = null;
1152 if (identifier.contains(DATA_SUBSCR)) {
1153 response = dataSubs(identifier, uriInfo, start, stop, filter, leafNodesOnly);
1154 } else if (identifier.contains(NOTIFICATION_STREAM)) {
1155 response = notifStream(identifier, uriInfo, start, stop, filter);
1158 if (response != null) {
1159 // prepare node with value of location
1160 final InstanceIdentifierContext<?> iid = prepareIIDSubsStreamOutput();
1161 final NormalizedNodeAttrBuilder<NodeIdentifier, Object, LeafNode<Object>> builder =
1162 ImmutableLeafNodeBuilder.create().withValue(response.toString());
1163 builder.withNodeIdentifier(
1164 NodeIdentifier.create(QName.create("subscribe:to:notification", "2016-10-28", "location")));
1166 // prepare new header with location
1167 final Map<String, Object> headers = new HashMap<>();
1168 headers.put("Location", response);
1170 return new NormalizedNodeContext(iid, builder.build(), headers);
1173 final String msg = "Bad type of notification of sal-remote";
1175 throw new RestconfDocumentedException(msg);
1178 private static Instant parseDateFromQueryParam(final Entry<String, List<String>> entry) {
1179 final DateAndTime event = new DateAndTime(entry.getValue().iterator().next());
1180 final String value = event.getValue();
1181 final TemporalAccessor p;
1183 p = FORMATTER.parse(value);
1184 } catch (final DateTimeParseException e) {
1185 throw new RestconfDocumentedException("Cannot parse of value in date: " + value, e);
1187 return Instant.from(p);
1191 * Prepare instance identifier.
1193 * @return {@link InstanceIdentifierContext} of location leaf for
1196 private static InstanceIdentifierContext<?> prepareIIDSubsStreamOutput() {
1197 final QName qnameBase = QName.create("subscribe:to:notification", "2016-10-28", "notifi");
1198 final SchemaContext schemaCtx = ControllerContext.getInstance().getGlobalSchema();
1199 final DataSchemaNode location = ((ContainerSchemaNode) schemaCtx
1200 .findModuleByNamespaceAndRevision(qnameBase.getNamespace(), qnameBase.getRevision())
1201 .getDataChildByName(qnameBase)).getDataChildByName(QName.create(qnameBase, "location"));
1202 final List<PathArgument> path = new ArrayList<>();
1203 path.add(NodeIdentifier.create(qnameBase));
1204 path.add(NodeIdentifier.create(QName.create(qnameBase, "location")));
1206 return new InstanceIdentifierContext<SchemaNode>(YangInstanceIdentifier.create(path), location, null,
1211 * Register notification listener by stream name.
1218 * stop-time of getting notification
1220 * start-time of getting notification
1222 * indicate which subset of all possible events are of interest
1223 * @return {@link URI} of location
1225 private URI notifStream(final String identifier, final UriInfo uriInfo, final Instant start,
1226 final Instant stop, final String filter) {
1227 final String streamName = Notificator.createStreamNameFromUri(identifier);
1228 if (Strings.isNullOrEmpty(streamName)) {
1229 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1231 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
1232 if (listeners == null || listeners.isEmpty()) {
1233 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1234 ErrorTag.UNKNOWN_ELEMENT);
1237 for (final NotificationListenerAdapter listener : listeners) {
1238 this.broker.registerToListenNotification(listener);
1239 listener.setQueryParams(start,
1240 java.util.Optional.ofNullable(stop), java.util.Optional.ofNullable(filter), false);
1243 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1244 int notificationPort = NOTIFICATION_PORT;
1246 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
1247 notificationPort = webSocketServerInstance.getPort();
1248 } catch (final NullPointerException e) {
1249 WebSocketServer.createInstance(NOTIFICATION_PORT);
1251 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1252 final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
1254 return uriToWebsocketServer;
1258 * Register data change listener by stream name.
1265 * start-time of getting notification
1267 * stop-time of getting notification
1269 * indicate which subset of all possible events are of interest
1270 * @return {@link URI} of location
1272 private URI dataSubs(final String identifier, final UriInfo uriInfo, final Instant start, final Instant stop,
1273 final String filter, final boolean leafNodesOnly) {
1274 final String streamName = Notificator.createStreamNameFromUri(identifier);
1275 if (Strings.isNullOrEmpty(streamName)) {
1276 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1279 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1280 if (listener == null) {
1281 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1282 ErrorTag.UNKNOWN_ELEMENT);
1284 listener.setQueryParams(start, java.util.Optional.ofNullable(stop),
1285 java.util.Optional.ofNullable(filter), leafNodesOnly);
1287 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1288 final LogicalDatastoreType datastore =
1289 parserURIEnumParameter(LogicalDatastoreType.class, paramToValues.get(DATASTORE_PARAM_NAME));
1290 if (datastore == null) {
1291 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1292 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1294 final DataChangeScope scope =
1295 parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
1296 if (scope == null) {
1297 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1298 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1301 this.broker.registerToListenDataChanges(datastore, scope, listener);
1303 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1304 int notificationPort = NOTIFICATION_PORT;
1306 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
1307 notificationPort = webSocketServerInstance.getPort();
1308 } catch (final NullPointerException e) {
1309 WebSocketServer.createInstance(NOTIFICATION_PORT);
1311 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1312 final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
1314 return uriToWebsocketServer;
1317 @SuppressWarnings("checkstyle:IllegalCatch")
1319 public PatchStatusContext patchConfigurationData(final String identifier, final PatchContext context,
1320 final UriInfo uriInfo) {
1321 if (context == null) {
1322 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1326 return this.broker.patchConfigurationDataWithinTransaction(context);
1327 } catch (final Exception e) {
1328 LOG.debug("Patch transaction failed", e);
1329 throw new RestconfDocumentedException(e.getMessage());
1333 @SuppressWarnings("checkstyle:IllegalCatch")
1335 public PatchStatusContext patchConfigurationData(final PatchContext context, @Context final UriInfo uriInfo) {
1336 if (context == null) {
1337 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1341 return this.broker.patchConfigurationDataWithinTransaction(context);
1342 } catch (final Exception e) {
1343 LOG.debug("Patch transaction failed", e);
1344 throw new RestconfDocumentedException(e.getMessage());
1349 * Load parameter for subscribing to stream from input composite node.
1353 * @return enum object if its string value is equal to {@code paramName}. In
1356 private static <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1357 final String paramName) {
1358 final Optional<DataContainerChild<? extends PathArgument, ?>> augNode =
1359 value.getChild(SAL_REMOTE_AUG_IDENTIFIER);
1360 if (!augNode.isPresent() && !(augNode instanceof AugmentationNode)) {
1363 final Optional<DataContainerChild<? extends PathArgument, ?>> enumNode = ((AugmentationNode) augNode.get())
1364 .getChild(new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1365 if (!enumNode.isPresent()) {
1368 final Object rawValue = enumNode.get().getValue();
1369 if (!(rawValue instanceof String)) {
1373 return resolveAsEnum(classDescriptor, (String) rawValue);
1377 * Checks whether {@code value} is one of the string representation of
1378 * enumeration {@code classDescriptor}.
1380 * @return enum object if string value of {@code classDescriptor}
1381 * enumeration is equal to {@code value}. Other cases null.
1383 private static <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1384 if (Strings.isNullOrEmpty(value)) {
1387 return resolveAsEnum(classDescriptor, value);
1390 private static <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1391 final T[] enumConstants = classDescriptor.getEnumConstants();
1392 if (enumConstants != null) {
1393 for (final T enm : classDescriptor.getEnumConstants()) {
1394 if (((Enum<?>) enm).name().equals(value)) {
1402 private static Map<String, String> resolveValuesFromUri(final String uri) {
1403 final Map<String, String> result = new HashMap<>();
1404 final String[] tokens = uri.split("/");
1405 for (int i = 1; i < tokens.length; i++) {
1406 final String[] parameterTokens = tokens[i].split("=");
1407 if (parameterTokens.length == 2) {
1408 result.put(parameterTokens[0], parameterTokens[1]);
1414 private MapNode makeModuleMapNode(final Set<Module> modules) {
1415 Preconditions.checkNotNull(modules);
1416 final Module restconfModule = getRestconfModule();
1417 final DataSchemaNode moduleSchemaNode = this.controllerContext
1418 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1419 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1421 final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder =
1422 Builders.mapBuilder((ListSchemaNode) moduleSchemaNode);
1424 for (final Module module : modules) {
1425 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1427 return listModuleBuilder.build();
1430 protected MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1431 Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1432 "moduleSchemaNode has to be of type ListSchemaNode");
1433 final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1434 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues =
1435 Builders.mapEntryBuilder(listModuleSchemaNode);
1437 List<DataSchemaNode> instanceDataChildrenByName =
1438 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "name");
1439 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1440 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1442 .withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName()).build());
1444 instanceDataChildrenByName =
1445 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "revision");
1446 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1447 Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1448 final String revision = module.getQNameModule().getFormattedRevision();
1450 .withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode).withValue(revision).build());
1452 instanceDataChildrenByName =
1453 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "namespace");
1454 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1455 Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1456 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1457 .withValue(module.getNamespace().toString()).build());
1459 instanceDataChildrenByName =
1460 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "feature");
1461 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1462 Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1463 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder =
1464 Builders.leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1465 for (final FeatureDefinition feature : module.getFeatures()) {
1466 featuresBuilder.withChild(Builders.leafSetEntryBuilder((LeafListSchemaNode) featureSchemaNode)
1467 .withValue(feature.getQName().getLocalName()).build());
1469 moduleNodeValues.withChild(featuresBuilder.build());
1471 return moduleNodeValues.build();
1474 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1475 Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1476 "streamSchemaNode has to be of type ListSchemaNode");
1477 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1478 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues =
1479 Builders.mapEntryBuilder(listStreamSchemaNode);
1481 List<DataSchemaNode> instanceDataChildrenByName =
1482 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "name");
1483 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1484 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1485 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName).build());
1487 instanceDataChildrenByName =
1488 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "description");
1489 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1490 Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1491 streamNodeValues.withChild(
1492 Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue("DESCRIPTION_PLACEHOLDER").build());
1494 instanceDataChildrenByName =
1495 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-support");
1496 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1497 Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1498 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1499 .withValue(Boolean.valueOf(true)).build());
1501 instanceDataChildrenByName =
1502 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-log-creation-time");
1503 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1504 Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1505 streamNodeValues.withChild(
1506 Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode).withValue("").build());
1508 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "events");
1509 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1510 Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1511 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode).withValue("").build());
1513 return streamNodeValues.build();
1517 * Prepare stream for notification.
1520 * contains list of qnames of notifications
1521 * @return - checked future object
1523 private static CheckedFuture<DOMRpcResult, DOMRpcException> invokeSalRemoteRpcNotifiStrRPC(
1524 final NormalizedNodeContext payload) {
1525 final ContainerNode data = (ContainerNode) payload.getData();
1526 LeafSetNode leafSet = null;
1527 String outputType = "XML";
1528 for (final DataContainerChild<? extends PathArgument, ?> dataChild : data.getValue()) {
1529 if (dataChild instanceof LeafSetNode) {
1530 leafSet = (LeafSetNode) dataChild;
1531 } else if (dataChild instanceof AugmentationNode) {
1532 outputType = (String) ((AugmentationNode) dataChild).getValue().iterator().next().getValue();
1536 final Collection<LeafSetEntryNode> entryNodes = leafSet.getValue();
1537 final List<SchemaPath> paths = new ArrayList<>();
1538 String streamName = CREATE_NOTIFICATION_STREAM + "/";
1540 final Iterator<LeafSetEntryNode> iterator = entryNodes.iterator();
1541 while (iterator.hasNext()) {
1542 final QName valueQName = QName.create((String) iterator.next().getValue());
1543 final Module module =
1544 ControllerContext.getInstance().findModuleByNamespace(valueQName.getModule().getNamespace());
1545 Preconditions.checkNotNull(module,
1546 "Module for namespace " + valueQName.getModule().getNamespace() + " does not exist");
1547 NotificationDefinition notifiDef = null;
1548 for (final NotificationDefinition notification : module.getNotifications()) {
1549 if (notification.getQName().equals(valueQName)) {
1550 notifiDef = notification;
1554 final String moduleName = module.getName();
1555 Preconditions.checkNotNull(notifiDef,
1556 "Notification " + valueQName + "doesn't exist in module " + moduleName);
1557 paths.add(notifiDef.getPath());
1558 streamName = streamName + moduleName + ":" + valueQName.getLocalName();
1559 if (iterator.hasNext()) {
1560 streamName = streamName + ",";
1564 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
1565 final QName outputQname = QName.create(rpcQName, "output");
1566 final QName streamNameQname = QName.create(rpcQName, "notification-stream-identifier");
1568 final ContainerNode output =
1569 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
1570 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
1572 if (!Notificator.existNotificationListenerFor(streamName)) {
1573 Notificator.createNotificationListener(paths, streamName, outputType);
1576 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
1578 return Futures.immediateCheckedFuture(defaultDOMRpcResult);