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.streams.listeners.ListenerAdapter;
65 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
66 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
67 import org.opendaylight.netconf.sal.streams.websockets.WebSocketServer;
68 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
69 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
70 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
71 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
72 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
73 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
74 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
75 import org.opendaylight.yangtools.yang.common.QName;
76 import org.opendaylight.yangtools.yang.common.QNameModule;
77 import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
78 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
79 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
80 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
81 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
82 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
83 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
84 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
85 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
86 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
87 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
88 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
89 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
90 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
91 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
92 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
93 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
94 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
95 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
96 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
97 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
98 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
99 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
100 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
101 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
102 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
103 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
104 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
105 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
106 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
107 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
108 import org.opendaylight.yangtools.yang.model.api.Module;
109 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
110 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
111 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
112 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
113 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
114 import org.opendaylight.yangtools.yang.model.util.SimpleSchemaContext;
115 import org.slf4j.Logger;
116 import org.slf4j.LoggerFactory;
118 public class RestconfImpl implements RestconfService {
120 private static final RestconfImpl INSTANCE = new RestconfImpl();
123 * Notifications are served on port 8181.
125 private static final int NOTIFICATION_PORT = 8181;
127 private static final int CHAR_NOT_FOUND = -1;
129 private static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
131 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
133 private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
135 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
137 private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
139 private static final String DATASTORE_PARAM_NAME = "datastore";
141 private static final String SCOPE_PARAM_NAME = "scope";
143 private static final String OUTPUT_TYPE_PARAM_NAME = "notification-output-type";
145 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
147 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
149 private static final QName NETCONF_BASE_QNAME = QName.create(QNameModule.create(URI.create(NETCONF_BASE), null),
150 NETCONF_BASE_PAYLOAD_NAME).intern();
152 private static final QNameModule SAL_REMOTE_AUGMENT;
156 SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
157 SimpleDateFormatUtil.getRevisionFormat().parse("2014-07-08"));
158 } catch (final ParseException e) {
159 throw new ExceptionInInitializerError(e);
163 private static final AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER =
164 new AugmentationIdentifier(ImmutableSet.of(
165 QName.create(SAL_REMOTE_AUGMENT, "scope"), QName.create(SAL_REMOTE_AUGMENT, "datastore"),
166 QName.create(SAL_REMOTE_AUGMENT, "notification-output-type")));
168 public static final CharSequence DATA_SUBSCR = "data-change-event-subscription";
169 private static final CharSequence CREATE_DATA_SUBSCR = "create-" + DATA_SUBSCR;
171 public static final CharSequence NOTIFICATION_STREAM = "notification-stream";
172 private static final CharSequence CREATE_NOTIFICATION_STREAM = "create-" + NOTIFICATION_STREAM;
174 private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
175 .appendValue(ChronoField.YEAR, 4).appendLiteral('-')
176 .appendValue(ChronoField.MONTH_OF_YEAR, 2).appendLiteral('-')
177 .appendValue(ChronoField.DAY_OF_MONTH, 2).appendLiteral('T')
178 .appendValue(ChronoField.HOUR_OF_DAY, 2).appendLiteral(':')
179 .appendValue(ChronoField.MINUTE_OF_HOUR, 2).appendLiteral(':')
180 .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
181 .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
182 .appendOffset("+HH:MM", "Z").toFormatter();
184 private BrokerFacade broker;
186 private ControllerContext controllerContext;
188 public void setBroker(final BrokerFacade broker) {
189 this.broker = broker;
192 public void setControllerContext(final ControllerContext controllerContext) {
193 this.controllerContext = controllerContext;
196 private RestconfImpl() {
199 public static RestconfImpl getInstance() {
204 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
205 final Set<Module> allModules = this.controllerContext.getAllModules();
206 final MapNode allModuleMap = makeModuleMapNode(allModules);
208 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
210 final Module restconfModule = getRestconfModule();
211 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
212 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
213 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
215 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
216 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
217 moduleContainerBuilder.withChild(allModuleMap);
219 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode, null, schemaContext),
220 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
224 * Valid only for mount point.
227 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
228 Preconditions.checkNotNull(identifier);
229 if (!identifier.contains(ControllerContext.MOUNT)) {
230 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
231 + " URI has to end with " + ControllerContext.MOUNT;
232 LOG.debug(errMsg + " for " + identifier);
233 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
236 final InstanceIdentifierContext<?> mountPointIdentifier =
237 this.controllerContext.toMountPointIdentifier(identifier);
238 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
239 final Set<Module> modules = this.controllerContext.getAllModules(mountPoint);
240 final MapNode mountPointModulesMap = makeModuleMapNode(modules);
242 final Module restconfModule = getRestconfModule();
243 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
244 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
245 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
247 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
248 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
249 moduleContainerBuilder.withChild(mountPointModulesMap);
251 return new NormalizedNodeContext(
252 new InstanceIdentifierContext<>(null, modulesSchemaNode, mountPoint,
253 this.controllerContext.getGlobalSchema()),
254 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
258 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
259 Preconditions.checkNotNull(identifier);
260 final QName moduleNameAndRevision = getModuleNameAndRevision(identifier);
261 Module module = null;
262 DOMMountPoint mountPoint = null;
263 final SchemaContext schemaContext;
264 if (identifier.contains(ControllerContext.MOUNT)) {
265 final InstanceIdentifierContext<?> mountPointIdentifier =
266 this.controllerContext.toMountPointIdentifier(identifier);
267 mountPoint = mountPointIdentifier.getMountPoint();
268 module = this.controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision);
269 schemaContext = mountPoint.getSchemaContext();
271 module = this.controllerContext.findModuleByNameAndRevision(moduleNameAndRevision);
272 schemaContext = this.controllerContext.getGlobalSchema();
275 if (module == null) {
276 final String errMsg = "Module with name '" + moduleNameAndRevision.getLocalName() + "' and revision '"
277 + moduleNameAndRevision.getRevision() + "' was not found.";
279 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
282 final Module restconfModule = getRestconfModule();
283 final Set<Module> modules = Collections.singleton(module);
284 final MapNode moduleMap = makeModuleMapNode(modules);
286 final DataSchemaNode moduleSchemaNode = this.controllerContext
287 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
288 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
290 return new NormalizedNodeContext(
291 new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint, schemaContext), moduleMap,
292 QueryParametersParser.parseWriterParameters(uriInfo));
296 public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
297 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
298 final Set<String> availableStreams = Notificator.getStreamNames();
299 final Module restconfModule = getRestconfModule();
300 final DataSchemaNode streamSchemaNode = this.controllerContext
301 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
302 Preconditions.checkState(streamSchemaNode instanceof ListSchemaNode);
304 final CollectionNodeBuilder<MapEntryNode, MapNode> listStreamsBuilder =
305 Builders.mapBuilder((ListSchemaNode) streamSchemaNode);
307 for (final String streamName : availableStreams) {
308 listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
311 final DataSchemaNode streamsContainerSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
312 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
313 Preconditions.checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
315 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
316 Builders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
317 streamsContainerBuilder.withChild(listStreamsBuilder.build());
319 return new NormalizedNodeContext(
320 new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null, schemaContext),
321 streamsContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
325 public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
326 final Set<Module> allModules = this.controllerContext.getAllModules();
327 return operationsFromModulesToNormalizedContext(allModules, null);
331 public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
332 Set<Module> modules = null;
333 DOMMountPoint mountPoint = null;
334 if (identifier.contains(ControllerContext.MOUNT)) {
335 final InstanceIdentifierContext<?> mountPointIdentifier =
336 this.controllerContext.toMountPointIdentifier(identifier);
337 mountPoint = mountPointIdentifier.getMountPoint();
338 modules = this.controllerContext.getAllModules(mountPoint);
341 final String errMsg =
342 "URI has bad format. If operations behind mount point should be showed, URI has to " + "end with ";
343 LOG.debug(errMsg + ControllerContext.MOUNT + " for " + identifier);
344 throw new RestconfDocumentedException(errMsg + ControllerContext.MOUNT, ErrorType.PROTOCOL,
345 ErrorTag.INVALID_VALUE);
348 return operationsFromModulesToNormalizedContext(modules, mountPoint);
352 * Special case only for GET restconf/operations use (since moment of
353 * pre-Beryllium Yang parser and Yang model API removal). The method is
354 * creating fake schema context with fake module and fake data by use own
355 * implementations of schema nodes and module.
358 * set of modules for get RPCs from every module
360 * mount point, if in use otherwise null
361 * @return {@link NormalizedNodeContext}
363 private static NormalizedNodeContext operationsFromModulesToNormalizedContext(final Set<Module> modules,
364 final DOMMountPoint mountPoint) {
366 final Collection<Module> neededModules = new ArrayList<>(modules.size());
367 final ArrayList<LeafSchemaNode> fakeRpcSchema = new ArrayList<>();
369 for (final Module m : modules) {
370 final Set<RpcDefinition> rpcs = m.getRpcs();
371 if (!rpcs.isEmpty()) {
372 neededModules.add(m);
374 fakeRpcSchema.ensureCapacity(fakeRpcSchema.size() + rpcs.size());
375 rpcs.forEach(rpc -> fakeRpcSchema.add(new FakeLeafSchemaNode(rpc.getQName())));
379 final ContainerSchemaNode fakeCont = new FakeContainerSchemaNode(fakeRpcSchema);
380 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> containerBuilder =
381 Builders.containerBuilder(fakeCont);
383 for (final LeafSchemaNode leaf : fakeRpcSchema) {
384 containerBuilder.withChild(Builders.leafBuilder(leaf).build());
387 final Collection<Module> fakeModules = new ArrayList<>(neededModules.size() + 1);
388 neededModules.forEach(imp -> fakeModules.add(new FakeImportedModule(imp)));
389 fakeModules.add(new FakeRestconfModule(neededModules, fakeCont));
391 final SchemaContext fakeSchemaCtx = SimpleSchemaContext.forModules(ImmutableSet.copyOf(fakeModules));
392 final InstanceIdentifierContext<ContainerSchemaNode> instanceIdentifierContext =
393 new InstanceIdentifierContext<>(null, fakeCont, mountPoint, fakeSchemaCtx);
394 return new NormalizedNodeContext(instanceIdentifierContext, containerBuilder.build());
397 private Module getRestconfModule() {
398 final Module restconfModule = this.controllerContext.getRestconfModule();
399 if (restconfModule == null) {
400 LOG.debug("ietf-restconf module was not found.");
401 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
402 ErrorTag.OPERATION_NOT_SUPPORTED);
405 return restconfModule;
408 private static QName getModuleNameAndRevision(final String identifier) {
409 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
410 String moduleNameAndRevision = "";
411 if (mountIndex >= 0) {
412 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
414 moduleNameAndRevision = identifier;
417 final Splitter splitter = Splitter.on("/").omitEmptyStrings();
418 final Iterable<String> split = splitter.split(moduleNameAndRevision);
419 final List<String> pathArgs = Lists.<String>newArrayList(split);
420 if (pathArgs.size() < 2) {
421 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
422 throw new RestconfDocumentedException(
423 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
424 ErrorTag.INVALID_VALUE);
428 final String moduleName = pathArgs.get(0);
429 final String revision = pathArgs.get(1);
430 return QName.create(null, SimpleDateFormatUtil.getRevisionFormat().parse(revision), moduleName);
431 } catch (final ParseException e) {
432 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
433 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
434 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
439 public Object getRoot() {
444 public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload,
445 final UriInfo uriInfo) {
446 final SchemaPath type = payload.getInstanceIdentifierContext().getSchemaNode().getPath();
447 final URI namespace = payload.getInstanceIdentifierContext().getSchemaNode().getQName().getNamespace();
448 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
449 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
450 final SchemaContext schemaContext;
452 if (mountPoint != null) {
453 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
454 if (!mountRpcServices.isPresent()) {
455 LOG.debug("Error: Rpc service is missing.");
456 throw new RestconfDocumentedException("Rpc service is missing.");
458 schemaContext = mountPoint.getSchemaContext();
459 response = mountRpcServices.get().invokeRpc(type, payload.getData());
461 if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
462 if (identifier.contains(CREATE_DATA_SUBSCR)) {
463 response = invokeSalRemoteRpcSubscribeRPC(payload);
464 } else if (identifier.contains(CREATE_NOTIFICATION_STREAM)) {
465 response = invokeSalRemoteRpcNotifiStrRPC(payload);
467 final String msg = "Not supported operation";
469 throw new RestconfDocumentedException(msg, ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED);
472 response = this.broker.invokeRpc(type, payload.getData());
474 schemaContext = this.controllerContext.getGlobalSchema();
477 final DOMRpcResult result = checkRpcResponse(response);
479 RpcDefinition resultNodeSchema = null;
480 final NormalizedNode<?, ?> resultData = result.getResult();
481 if (result != null && result.getResult() != null) {
482 resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
485 return new NormalizedNodeContext(
486 new InstanceIdentifierContext<>(null, resultNodeSchema, mountPoint, schemaContext),
487 resultData, QueryParametersParser.parseWriterParameters(uriInfo));
491 public NormalizedNodeContext invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
492 if (noPayload != null && !CharMatcher.WHITESPACE.matchesAllOf(noPayload)) {
493 throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
496 String identifierEncoded = null;
497 DOMMountPoint mountPoint = null;
498 final SchemaContext schemaContext;
499 if (identifier.contains(ControllerContext.MOUNT)) {
500 // mounted RPC call - look up mount instance.
501 final InstanceIdentifierContext<?> mountPointId = this.controllerContext.toMountPointIdentifier(identifier);
502 mountPoint = mountPointId.getMountPoint();
503 schemaContext = mountPoint.getSchemaContext();
504 final int startOfRemoteRpcName =
505 identifier.lastIndexOf(ControllerContext.MOUNT) + ControllerContext.MOUNT.length() + 1;
506 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
507 identifierEncoded = remoteRpcName;
509 } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
510 final String slashErrorMsg = String.format(
511 "Identifier %n%s%ncan\'t contain slash "
512 + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.",
514 LOG.debug(slashErrorMsg);
515 throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
517 identifierEncoded = identifier;
518 schemaContext = this.controllerContext.getGlobalSchema();
521 final String identifierDecoded = this.controllerContext.urlPathArgDecode(identifierEncoded);
523 RpcDefinition rpc = null;
524 if (mountPoint == null) {
525 rpc = this.controllerContext.getRpcDefinition(identifierDecoded, null);
527 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
531 LOG.debug("RPC " + identifierDecoded + " does not exist.");
532 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
535 if (!rpc.getInput().getChildNodes().isEmpty()) {
536 LOG.debug("RPC " + rpc + " does not need input value.");
537 // FIXME : find a correct Error from specification
538 throw new IllegalStateException("RPC " + rpc + " does'n need input value!");
541 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
542 if (mountPoint != null) {
543 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
544 if (!mountRpcServices.isPresent()) {
545 throw new RestconfDocumentedException("Rpc service is missing.");
547 response = mountRpcServices.get().invokeRpc(rpc.getPath(), null);
549 response = this.broker.invokeRpc(rpc.getPath(), null);
552 final DOMRpcResult result = checkRpcResponse(response);
554 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpc, mountPoint, schemaContext),
555 result.getResult(), QueryParametersParser.parseWriterParameters(uriInfo));
558 private static DOMRpcResult checkRpcResponse(final CheckedFuture<DOMRpcResult, DOMRpcException> response) {
559 if (response == null) {
563 final DOMRpcResult retValue = response.get();
564 if (retValue.getErrors() == null || retValue.getErrors().isEmpty()) {
567 LOG.debug("RpcError message", retValue.getErrors());
568 throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
569 } catch (final InterruptedException e) {
570 final String errMsg = "The operation was interrupted while executing and did not complete.";
571 LOG.debug("Rpc Interrupt - " + errMsg, e);
572 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
573 } catch (final ExecutionException e) {
574 LOG.debug("Execution RpcError: ", e);
575 Throwable cause = e.getCause();
577 while (cause.getCause() != null) {
578 cause = cause.getCause();
581 if (cause instanceof IllegalArgumentException) {
582 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL,
583 ErrorTag.INVALID_VALUE);
584 } else if (cause instanceof DOMRpcImplementationNotAvailableException) {
585 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.APPLICATION,
586 ErrorTag.OPERATION_NOT_SUPPORTED);
588 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
591 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
594 } catch (final CancellationException e) {
595 final String errMsg = "The operation was cancelled while executing.";
596 LOG.debug("Cancel RpcExecution: " + errMsg, e);
597 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
601 private static void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
602 if (inputSchema != null && payload.getData() == null) {
603 // expected a non null payload
604 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
605 } else if (inputSchema == null && payload.getData() != null) {
606 // did not expect any input
607 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
611 private CheckedFuture<DOMRpcResult, DOMRpcException>
612 invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
613 final ContainerNode value = (ContainerNode) payload.getData();
614 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
615 final Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(new NodeIdentifier(
616 QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(), "path")));
617 final Object pathValue = path.isPresent() ? path.get().getValue() : null;
619 if (!(pathValue instanceof YangInstanceIdentifier)) {
620 final String errMsg = "Instance identifier was not normalized correctly ";
621 LOG.debug(errMsg + rpcQName);
622 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
625 final YangInstanceIdentifier pathIdentifier = (YangInstanceIdentifier) pathValue;
626 String streamName = (String) CREATE_DATA_SUBSCR;
627 NotificationOutputType outputType = null;
628 if (!pathIdentifier.isEmpty()) {
629 final String fullRestconfIdentifier =
630 DATA_SUBSCR + this.controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
632 LogicalDatastoreType datastore =
633 parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
634 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
636 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
637 scope = scope == null ? DEFAULT_SCOPE : scope;
639 outputType = parseEnumTypeParameter(value, NotificationOutputType.class, OUTPUT_TYPE_PARAM_NAME);
640 outputType = outputType == null ? NotificationOutputType.XML : outputType;
642 streamName = Notificator
643 .createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore + "/scope=" + scope);
646 if (Strings.isNullOrEmpty(streamName)) {
647 final String errMsg = "Path is empty or contains value node which is not Container or List build-in type.";
648 LOG.debug(errMsg + pathIdentifier);
649 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
652 final QName outputQname = QName.create(rpcQName, "output");
653 final QName streamNameQname = QName.create(rpcQName, "stream-name");
655 final ContainerNode output =
656 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
657 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
659 if (!Notificator.existListenerFor(streamName)) {
660 Notificator.createListener(pathIdentifier, streamName, outputType);
663 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
665 return Futures.immediateCheckedFuture(defaultDOMRpcResult);
668 private static RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
669 final String[] splittedIdentifier = identifierDecoded.split(":");
670 if (splittedIdentifier.length != 2) {
671 final String errMsg = identifierDecoded + " couldn't be splitted to 2 parts (module:rpc name)";
673 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
675 for (final Module module : schemaContext.getModules()) {
676 if (module.getName().equals(splittedIdentifier[0])) {
677 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
678 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
679 return rpcDefinition;
688 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
689 boolean withDefaUsed = false;
690 String withDefa = null;
692 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
693 switch (entry.getKey()) {
694 case "with-defaults":
697 withDefa = entry.getValue().iterator().next();
699 throw new RestconfDocumentedException("With-defaults parameter can be used only once.");
703 LOG.info("Unknown key : {}.", entry.getKey());
707 boolean tagged = false;
709 if (withDefa.equals("report-all-tagged")) {
713 if (withDefa.equals("report-all")) {
718 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
719 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
720 NormalizedNode<?, ?> data = null;
721 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
722 if (mountPoint != null) {
723 data = this.broker.readConfigurationData(mountPoint, normalizedII, withDefa);
725 data = this.broker.readConfigurationData(normalizedII, withDefa);
728 final String errMsg =
729 "Request could not be completed because the relevant data model content does not exist ";
730 LOG.debug(errMsg + identifier);
731 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
733 return new NormalizedNodeContext(iiWithData, data,
734 QueryParametersParser.parseWriterParameters(uriInfo, tagged));
738 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
739 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
740 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
741 NormalizedNode<?, ?> data = null;
742 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
743 if (mountPoint != null) {
744 data = this.broker.readOperationalData(mountPoint, normalizedII);
746 data = this.broker.readOperationalData(normalizedII);
749 final String errMsg =
750 "Request could not be completed because the relevant data model content does not exist ";
751 LOG.debug(errMsg + identifier);
752 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
754 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
758 public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload,
759 final UriInfo uriInfo) {
760 boolean insertUsed = false;
761 boolean pointUsed = false;
762 String insert = null;
765 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
766 switch (entry.getKey()) {
770 insert = entry.getValue().iterator().next();
772 throw new RestconfDocumentedException("Insert parameter can be used only once.");
778 point = entry.getValue().iterator().next();
780 throw new RestconfDocumentedException("Point parameter can be used only once.");
784 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
788 if (pointUsed && !insertUsed) {
789 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
791 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
792 throw new RestconfDocumentedException(
793 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
796 Preconditions.checkNotNull(identifier);
798 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
800 validateInput(iiWithData.getSchemaNode(), payload);
801 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
802 validateListKeysEqualityInPayloadAndUri(payload);
804 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
805 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
808 * There is a small window where another write transaction could be
809 * updating the same data simultaneously and we get an
810 * OptimisticLockFailedException. This error is likely transient and The
811 * WriteTransaction#submit API docs state that a retry will likely
812 * succeed. So we'll try again if that scenario occurs. If it fails a
813 * third time then it probably will never succeed so we'll fail in that
816 * By retrying we're attempting to hide the internal implementation of
817 * the data store and how it handles concurrent updates from the
818 * restconf client. The client has instructed us to put the data and we
819 * should make every effort to do so without pushing optimistic lock
820 * failures back to the client and forcing them to handle it via retry
821 * (and having to document the behavior).
823 PutResult result = null;
826 if (mountPoint != null) {
828 result = this.broker.commitMountPointDataPut(mountPoint, normalizedII, payload.getData(), insert,
831 result = this.broker.commitConfigurationDataPut(this.controllerContext.getGlobalSchema(), normalizedII,
832 payload.getData(), insert, point);
836 result.getFutureOfPutData().checkedGet();
837 return Response.status(result.getStatus()).build();
838 } catch (final TransactionCommitFailedException e) {
839 if (e instanceof OptimisticLockFailedException) {
841 LOG.debug("Got OptimisticLockFailedException on last try - failing " + identifier);
842 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
845 LOG.debug("Got OptimisticLockFailedException - trying again " + identifier);
847 LOG.debug("Update failed for " + identifier, e);
848 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
854 private static void validateTopLevelNodeName(final NormalizedNodeContext node,
855 final YangInstanceIdentifier identifier) {
857 final String payloadName = node.getData().getNodeType().getLocalName();
860 if (identifier.isEmpty()) {
862 if (!node.getData().getNodeType().equals(NETCONF_BASE_QNAME)) {
863 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
864 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
868 final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
869 if (!payloadName.equals(identifierName)) {
870 throw new RestconfDocumentedException(
871 "Payload name (" + payloadName + ") is different from identifier name (" + identifierName + ")",
872 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
878 * Validates whether keys in {@code payload} are equal to values of keys in
879 * {@code iiWithData} for list schema node.
881 * @throws RestconfDocumentedException
882 * if key values or key count in payload and URI isn't equal
885 private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
886 Preconditions.checkArgument(payload != null);
887 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
888 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
889 final SchemaNode schemaNode = iiWithData.getSchemaNode();
890 final NormalizedNode<?, ?> data = payload.getData();
891 if (schemaNode instanceof ListSchemaNode) {
892 final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
893 if (lastPathArgument instanceof NodeIdentifierWithPredicates && data instanceof MapEntryNode) {
894 final Map<QName, Object> uriKeyValues =
895 ((NodeIdentifierWithPredicates) lastPathArgument).getKeyValues();
896 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
902 public static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final MapEntryNode payload,
903 final List<QName> keyDefinitions) {
905 final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
906 for (final QName keyDefinition : keyDefinitions) {
907 final Object uriKeyValue = mutableCopyUriKeyValues.remove(keyDefinition);
908 // should be caught during parsing URI to InstanceIdentifier
909 RestconfValidationUtils.checkDocumentedError(uriKeyValue != null, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
910 "Missing key " + keyDefinition + " in URI.");
912 final Object dataKeyValue = payload.getIdentifier().getKeyValues().get(keyDefinition);
914 if (!Objects.deepEquals(uriKeyValue, dataKeyValue)) {
915 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName()
916 + "' specified in the URI doesn't match the value '" + dataKeyValue
917 + "' specified in the message body. ";
918 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
924 public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload,
925 final UriInfo uriInfo) {
926 return createConfigurationData(payload, uriInfo);
930 public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
931 if (payload == null) {
932 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
934 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
935 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
936 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
938 boolean insertUsed = false;
939 boolean pointUsed = false;
940 String insert = null;
943 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
944 switch (entry.getKey()) {
948 insert = entry.getValue().iterator().next();
950 throw new RestconfDocumentedException("Insert parameter can be used only once.");
956 point = entry.getValue().iterator().next();
958 throw new RestconfDocumentedException("Point parameter can be used only once.");
962 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
966 if (pointUsed && !insertUsed) {
967 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
969 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
970 throw new RestconfDocumentedException(
971 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
974 CheckedFuture<Void, TransactionCommitFailedException> future;
975 if (mountPoint != null) {
976 future = this.broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData(), insert,
979 future = this.broker.commitConfigurationDataPost(this.controllerContext.getGlobalSchema(), normalizedII,
980 payload.getData(), insert, point);
985 } catch (final RestconfDocumentedException e) {
987 } catch (final TransactionCommitFailedException e) {
988 LOG.info("Error creating data " + (uriInfo != null ? uriInfo.getPath() : ""), e);
989 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
992 LOG.trace("Successfuly created data.");
994 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
995 // FIXME: Provide path to result.
996 final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
997 if (location != null) {
998 responseBuilder.location(location);
1000 return responseBuilder.build();
1003 // FIXME create RestconfIdetifierHelper and move this method there
1004 private static YangInstanceIdentifier checkConsistencyOfNormalizedNodeContext(final NormalizedNodeContext payload) {
1005 Preconditions.checkArgument(payload != null);
1006 Preconditions.checkArgument(payload.getData() != null);
1007 Preconditions.checkArgument(payload.getData().getNodeType() != null);
1008 Preconditions.checkArgument(payload.getInstanceIdentifierContext() != null);
1009 Preconditions.checkArgument(payload.getInstanceIdentifierContext().getInstanceIdentifier() != null);
1011 final QName payloadNodeQname = payload.getData().getNodeType();
1012 final YangInstanceIdentifier yangIdent = payload.getInstanceIdentifierContext().getInstanceIdentifier();
1013 if (payloadNodeQname.compareTo(yangIdent.getLastPathArgument().getNodeType()) > 0) {
1016 final InstanceIdentifierContext<?> parentContext = payload.getInstanceIdentifierContext();
1017 final SchemaNode parentSchemaNode = parentContext.getSchemaNode();
1018 if (parentSchemaNode instanceof DataNodeContainer) {
1019 final DataNodeContainer cast = (DataNodeContainer) parentSchemaNode;
1020 for (final DataSchemaNode child : cast.getChildNodes()) {
1021 if (payloadNodeQname.compareTo(child.getQName()) == 0) {
1022 return YangInstanceIdentifier.builder(yangIdent).node(child.getQName()).build();
1026 if (parentSchemaNode instanceof RpcDefinition) {
1029 final String errMsg = "Error parsing input: DataSchemaNode has not children ";
1030 LOG.info(errMsg + yangIdent);
1031 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1034 @SuppressWarnings("checkstyle:IllegalCatch")
1035 private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint,
1036 final YangInstanceIdentifier normalizedII) {
1037 if (uriInfo == null) {
1038 // This is null if invoked internally
1042 final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
1043 uriBuilder.path("config");
1045 uriBuilder.path(this.controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
1046 } catch (final Exception e) {
1047 LOG.info("Location for instance identifier" + normalizedII + "wasn't created", e);
1050 return uriBuilder.build();
1054 public Response deleteConfigurationData(final String identifier) {
1055 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
1056 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
1057 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
1059 final CheckedFuture<Void, TransactionCommitFailedException> future;
1060 if (mountPoint != null) {
1061 future = this.broker.commitConfigurationDataDelete(mountPoint, normalizedII);
1063 future = this.broker.commitConfigurationDataDelete(normalizedII);
1067 future.checkedGet();
1068 } catch (final TransactionCommitFailedException e) {
1069 final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
1070 Predicates.instanceOf(ModifiedNodeDoesNotExistException.class));
1071 if (searchedException.isPresent()) {
1072 throw new RestconfDocumentedException("Data specified for delete doesn't exist.", ErrorType.APPLICATION,
1073 ErrorTag.DATA_MISSING);
1076 final String errMsg = "Error while deleting data";
1077 LOG.info(errMsg, e);
1078 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
1081 return Response.status(Status.OK).build();
1085 * Subscribes to some path in schema context (stream) to listen on changes
1089 * Additional parameters for subscribing to stream are loaded via rpc input
1092 * <li>datastore - default CONFIGURATION (other values of
1093 * {@link LogicalDatastoreType} enum type)</li>
1094 * <li>scope - default BASE (other values of {@link DataChangeScope})</li>
1098 public NormalizedNodeContext subscribeToStream(final String identifier, final UriInfo uriInfo) {
1099 boolean startTimeUsed = false;
1100 boolean stopTimeUsed = false;
1101 Instant start = Instant.now();
1102 Instant stop = null;
1103 boolean filterUsed = false;
1104 String filter = null;
1105 boolean leafNodesOnlyUsed = false;
1106 boolean leafNodesOnly = false;
1108 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
1109 switch (entry.getKey()) {
1111 if (!startTimeUsed) {
1112 startTimeUsed = true;
1113 start = parseDateFromQueryParam(entry);
1115 throw new RestconfDocumentedException("Start-time parameter can be used only once.");
1119 if (!stopTimeUsed) {
1120 stopTimeUsed = true;
1121 stop = parseDateFromQueryParam(entry);
1123 throw new RestconfDocumentedException("Stop-time parameter can be used only once.");
1129 filter = entry.getValue().iterator().next();
1131 throw new RestconfDocumentedException("Filter parameter can be used only once.");
1134 case "odl-leaf-nodes-only":
1135 if (!leafNodesOnlyUsed) {
1136 leafNodesOnlyUsed = true;
1137 leafNodesOnly = Boolean.parseBoolean(entry.getValue().iterator().next());
1139 throw new RestconfDocumentedException("Odl-leaf-nodes-only parameter can be used only once.");
1143 throw new RestconfDocumentedException("Bad parameter used with notifications: " + entry.getKey());
1146 if (!startTimeUsed && stopTimeUsed) {
1147 throw new RestconfDocumentedException("Stop-time parameter has to be used with start-time parameter.");
1149 URI response = null;
1150 if (identifier.contains(DATA_SUBSCR)) {
1151 response = dataSubs(identifier, uriInfo, start, stop, filter, leafNodesOnly);
1152 } else if (identifier.contains(NOTIFICATION_STREAM)) {
1153 response = notifStream(identifier, uriInfo, start, stop, filter);
1156 if (response != null) {
1157 // prepare node with value of location
1158 final InstanceIdentifierContext<?> iid = prepareIIDSubsStreamOutput();
1159 final NormalizedNodeAttrBuilder<NodeIdentifier, Object, LeafNode<Object>> builder =
1160 ImmutableLeafNodeBuilder.create().withValue(response.toString());
1161 builder.withNodeIdentifier(
1162 NodeIdentifier.create(QName.create("subscribe:to:notification", "2016-10-28", "location")));
1164 // prepare new header with location
1165 final Map<String, Object> headers = new HashMap<>();
1166 headers.put("Location", response);
1168 return new NormalizedNodeContext(iid, builder.build(), headers);
1171 final String msg = "Bad type of notification of sal-remote";
1173 throw new RestconfDocumentedException(msg);
1176 private static Instant parseDateFromQueryParam(final Entry<String, List<String>> entry) {
1177 final DateAndTime event = new DateAndTime(entry.getValue().iterator().next());
1178 final String value = event.getValue();
1179 final TemporalAccessor p;
1181 p = FORMATTER.parse(value);
1182 } catch (final DateTimeParseException e) {
1183 throw new RestconfDocumentedException("Cannot parse of value in date: " + value, e);
1185 return Instant.from(p);
1189 * Prepare instance identifier.
1191 * @return {@link InstanceIdentifierContext} of location leaf for
1194 private static InstanceIdentifierContext<?> prepareIIDSubsStreamOutput() {
1195 final QName qnameBase = QName.create("subscribe:to:notification", "2016-10-28", "notifi");
1196 final SchemaContext schemaCtx = ControllerContext.getInstance().getGlobalSchema();
1197 final DataSchemaNode location = ((ContainerSchemaNode) schemaCtx
1198 .findModuleByNamespaceAndRevision(qnameBase.getNamespace(), qnameBase.getRevision())
1199 .getDataChildByName(qnameBase)).getDataChildByName(QName.create(qnameBase, "location"));
1200 final List<PathArgument> path = new ArrayList<>();
1201 path.add(NodeIdentifier.create(qnameBase));
1202 path.add(NodeIdentifier.create(QName.create(qnameBase, "location")));
1204 return new InstanceIdentifierContext<SchemaNode>(YangInstanceIdentifier.create(path), location, null,
1209 * Register notification listener by stream name.
1216 * stop-time of getting notification
1218 * start-time of getting notification
1220 * indicate which subset of all possible events are of interest
1221 * @return {@link URI} of location
1223 private URI notifStream(final String identifier, final UriInfo uriInfo, final Instant start,
1224 final Instant stop, final String filter) {
1225 final String streamName = Notificator.createStreamNameFromUri(identifier);
1226 if (Strings.isNullOrEmpty(streamName)) {
1227 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1229 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
1230 if (listeners == null || listeners.isEmpty()) {
1231 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1232 ErrorTag.UNKNOWN_ELEMENT);
1235 for (final NotificationListenerAdapter listener : listeners) {
1236 this.broker.registerToListenNotification(listener);
1237 listener.setQueryParams(start,
1238 java.util.Optional.ofNullable(stop), java.util.Optional.ofNullable(filter), false);
1241 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1242 int notificationPort = NOTIFICATION_PORT;
1244 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
1245 notificationPort = webSocketServerInstance.getPort();
1246 } catch (final NullPointerException e) {
1247 WebSocketServer.createInstance(NOTIFICATION_PORT);
1249 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1250 final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
1252 return uriToWebsocketServer;
1256 * Register data change listener by stream name.
1263 * start-time of getting notification
1265 * stop-time of getting notification
1267 * indicate which subset of all possible events are of interest
1268 * @return {@link URI} of location
1270 private URI dataSubs(final String identifier, final UriInfo uriInfo, final Instant start, final Instant stop,
1271 final String filter, final boolean leafNodesOnly) {
1272 final String streamName = Notificator.createStreamNameFromUri(identifier);
1273 if (Strings.isNullOrEmpty(streamName)) {
1274 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1277 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1278 if (listener == null) {
1279 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1280 ErrorTag.UNKNOWN_ELEMENT);
1282 listener.setQueryParams(start, java.util.Optional.ofNullable(stop),
1283 java.util.Optional.ofNullable(filter), leafNodesOnly);
1285 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1286 final LogicalDatastoreType datastore =
1287 parserURIEnumParameter(LogicalDatastoreType.class, paramToValues.get(DATASTORE_PARAM_NAME));
1288 if (datastore == null) {
1289 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1290 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1292 final DataChangeScope scope =
1293 parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
1294 if (scope == null) {
1295 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1296 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1299 this.broker.registerToListenDataChanges(datastore, scope, listener);
1301 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1302 int notificationPort = NOTIFICATION_PORT;
1304 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
1305 notificationPort = webSocketServerInstance.getPort();
1306 } catch (final NullPointerException e) {
1307 WebSocketServer.createInstance(NOTIFICATION_PORT);
1309 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1310 final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
1312 return uriToWebsocketServer;
1315 @SuppressWarnings("checkstyle:IllegalCatch")
1317 public PatchStatusContext patchConfigurationData(final String identifier, final PatchContext context,
1318 final UriInfo uriInfo) {
1319 if (context == null) {
1320 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1324 return this.broker.patchConfigurationDataWithinTransaction(context);
1325 } catch (final Exception e) {
1326 LOG.debug("Patch transaction failed", e);
1327 throw new RestconfDocumentedException(e.getMessage());
1331 @SuppressWarnings("checkstyle:IllegalCatch")
1333 public PatchStatusContext patchConfigurationData(final PatchContext context, @Context final UriInfo uriInfo) {
1334 if (context == null) {
1335 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1339 return this.broker.patchConfigurationDataWithinTransaction(context);
1340 } catch (final Exception e) {
1341 LOG.debug("Patch transaction failed", e);
1342 throw new RestconfDocumentedException(e.getMessage());
1347 * Load parameter for subscribing to stream from input composite node.
1351 * @return enum object if its string value is equal to {@code paramName}. In
1354 private static <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1355 final String paramName) {
1356 final Optional<DataContainerChild<? extends PathArgument, ?>> augNode =
1357 value.getChild(SAL_REMOTE_AUG_IDENTIFIER);
1358 if (!augNode.isPresent() && !(augNode instanceof AugmentationNode)) {
1361 final Optional<DataContainerChild<? extends PathArgument, ?>> enumNode = ((AugmentationNode) augNode.get())
1362 .getChild(new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1363 if (!enumNode.isPresent()) {
1366 final Object rawValue = enumNode.get().getValue();
1367 if (!(rawValue instanceof String)) {
1371 return resolveAsEnum(classDescriptor, (String) rawValue);
1375 * Checks whether {@code value} is one of the string representation of
1376 * enumeration {@code classDescriptor}.
1378 * @return enum object if string value of {@code classDescriptor}
1379 * enumeration is equal to {@code value}. Other cases null.
1381 private static <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1382 if (Strings.isNullOrEmpty(value)) {
1385 return resolveAsEnum(classDescriptor, value);
1388 private static <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1389 final T[] enumConstants = classDescriptor.getEnumConstants();
1390 if (enumConstants != null) {
1391 for (final T enm : classDescriptor.getEnumConstants()) {
1392 if (((Enum<?>) enm).name().equals(value)) {
1400 private static Map<String, String> resolveValuesFromUri(final String uri) {
1401 final Map<String, String> result = new HashMap<>();
1402 final String[] tokens = uri.split("/");
1403 for (int i = 1; i < tokens.length; i++) {
1404 final String[] parameterTokens = tokens[i].split("=");
1405 if (parameterTokens.length == 2) {
1406 result.put(parameterTokens[0], parameterTokens[1]);
1412 private MapNode makeModuleMapNode(final Set<Module> modules) {
1413 Preconditions.checkNotNull(modules);
1414 final Module restconfModule = getRestconfModule();
1415 final DataSchemaNode moduleSchemaNode = this.controllerContext
1416 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1417 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1419 final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder =
1420 Builders.mapBuilder((ListSchemaNode) moduleSchemaNode);
1422 for (final Module module : modules) {
1423 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1425 return listModuleBuilder.build();
1428 protected MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1429 Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1430 "moduleSchemaNode has to be of type ListSchemaNode");
1431 final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1432 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues =
1433 Builders.mapEntryBuilder(listModuleSchemaNode);
1435 List<DataSchemaNode> instanceDataChildrenByName =
1436 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "name");
1437 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1438 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1440 .withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName()).build());
1442 instanceDataChildrenByName =
1443 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "revision");
1444 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1445 Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1446 final String revision = module.getQNameModule().getFormattedRevision();
1448 .withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode).withValue(revision).build());
1450 instanceDataChildrenByName =
1451 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "namespace");
1452 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1453 Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1454 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1455 .withValue(module.getNamespace().toString()).build());
1457 instanceDataChildrenByName =
1458 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "feature");
1459 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1460 Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1461 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder =
1462 Builders.leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1463 for (final FeatureDefinition feature : module.getFeatures()) {
1464 featuresBuilder.withChild(Builders.leafSetEntryBuilder((LeafListSchemaNode) featureSchemaNode)
1465 .withValue(feature.getQName().getLocalName()).build());
1467 moduleNodeValues.withChild(featuresBuilder.build());
1469 return moduleNodeValues.build();
1472 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1473 Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1474 "streamSchemaNode has to be of type ListSchemaNode");
1475 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1476 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues =
1477 Builders.mapEntryBuilder(listStreamSchemaNode);
1479 List<DataSchemaNode> instanceDataChildrenByName =
1480 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "name");
1481 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1482 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1483 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName).build());
1485 instanceDataChildrenByName =
1486 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "description");
1487 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1488 Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1489 streamNodeValues.withChild(
1490 Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue("DESCRIPTION_PLACEHOLDER").build());
1492 instanceDataChildrenByName =
1493 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-support");
1494 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1495 Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1496 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1497 .withValue(Boolean.valueOf(true)).build());
1499 instanceDataChildrenByName =
1500 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-log-creation-time");
1501 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1502 Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1503 streamNodeValues.withChild(
1504 Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode).withValue("").build());
1506 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "events");
1507 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1508 Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1509 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode).withValue("").build());
1511 return streamNodeValues.build();
1515 * Prepare stream for notification.
1518 * contains list of qnames of notifications
1519 * @return - checked future object
1521 private static CheckedFuture<DOMRpcResult, DOMRpcException> invokeSalRemoteRpcNotifiStrRPC(
1522 final NormalizedNodeContext payload) {
1523 final ContainerNode data = (ContainerNode) payload.getData();
1524 LeafSetNode leafSet = null;
1525 String outputType = "XML";
1526 for (final DataContainerChild<? extends PathArgument, ?> dataChild : data.getValue()) {
1527 if (dataChild instanceof LeafSetNode) {
1528 leafSet = (LeafSetNode) dataChild;
1529 } else if (dataChild instanceof AugmentationNode) {
1530 outputType = (String) ((AugmentationNode) dataChild).getValue().iterator().next().getValue();
1534 final Collection<LeafSetEntryNode> entryNodes = leafSet.getValue();
1535 final List<SchemaPath> paths = new ArrayList<>();
1536 String streamName = CREATE_NOTIFICATION_STREAM + "/";
1538 final Iterator<LeafSetEntryNode> iterator = entryNodes.iterator();
1539 while (iterator.hasNext()) {
1540 final QName valueQName = QName.create((String) iterator.next().getValue());
1541 final Module module =
1542 ControllerContext.getInstance().findModuleByNamespace(valueQName.getModule().getNamespace());
1543 Preconditions.checkNotNull(module,
1544 "Module for namespace " + valueQName.getModule().getNamespace() + " does not exist");
1545 NotificationDefinition notifiDef = null;
1546 for (final NotificationDefinition notification : module.getNotifications()) {
1547 if (notification.getQName().equals(valueQName)) {
1548 notifiDef = notification;
1552 final String moduleName = module.getName();
1553 Preconditions.checkNotNull(notifiDef,
1554 "Notification " + valueQName + "doesn't exist in module " + moduleName);
1555 paths.add(notifiDef.getPath());
1556 streamName = streamName + moduleName + ":" + valueQName.getLocalName();
1557 if (iterator.hasNext()) {
1558 streamName = streamName + ",";
1562 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
1563 final QName outputQname = QName.create(rpcQName, "output");
1564 final QName streamNameQname = QName.create(rpcQName, "notification-stream-identifier");
1566 final ContainerNode output =
1567 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
1568 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
1570 if (!Notificator.existNotificationListenerFor(streamName)) {
1571 Notificator.createNotificationListener(paths, streamName, outputType);
1574 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
1576 return Futures.immediateCheckedFuture(defaultDOMRpcResult);