2 * Copyright (c) 2014 - 2016 Brocade Communication Systems, Inc., Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.netconf.sal.restconf.impl;
11 import com.google.common.annotations.VisibleForTesting;
12 import com.google.common.base.CharMatcher;
13 import com.google.common.base.Optional;
14 import com.google.common.base.Preconditions;
15 import com.google.common.base.Predicates;
16 import com.google.common.base.Splitter;
17 import com.google.common.base.Strings;
18 import com.google.common.base.Throwables;
19 import com.google.common.collect.ImmutableSet;
20 import com.google.common.collect.Iterables;
21 import com.google.common.collect.Maps;
22 import com.google.common.util.concurrent.CheckedFuture;
23 import com.google.common.util.concurrent.Futures;
25 import java.time.Instant;
26 import java.time.format.DateTimeFormatter;
27 import java.time.format.DateTimeFormatterBuilder;
28 import java.time.format.DateTimeParseException;
29 import java.time.temporal.ChronoField;
30 import java.time.temporal.TemporalAccessor;
31 import java.util.AbstractMap.SimpleImmutableEntry;
32 import java.util.ArrayList;
33 import java.util.Collection;
34 import java.util.Collections;
35 import java.util.HashMap;
36 import java.util.Iterator;
37 import java.util.List;
39 import java.util.Map.Entry;
40 import java.util.Objects;
42 import java.util.concurrent.CancellationException;
43 import java.util.concurrent.ExecutionException;
44 import javax.ws.rs.core.Context;
45 import javax.ws.rs.core.Response;
46 import javax.ws.rs.core.Response.ResponseBuilder;
47 import javax.ws.rs.core.Response.Status;
48 import javax.ws.rs.core.UriBuilder;
49 import javax.ws.rs.core.UriInfo;
50 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
51 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
52 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
53 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
54 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
55 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
56 import org.opendaylight.controller.md.sal.dom.api.DOMRpcImplementationNotAvailableException;
57 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
58 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
59 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
60 import org.opendaylight.netconf.sal.rest.api.Draft02;
61 import org.opendaylight.netconf.sal.rest.api.RestconfService;
62 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
63 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
64 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
65 import org.opendaylight.netconf.sal.streams.websockets.WebSocketServer;
66 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
67 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
68 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
69 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
70 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
71 import org.opendaylight.restconf.common.patch.PatchContext;
72 import org.opendaylight.restconf.common.patch.PatchStatusContext;
73 import org.opendaylight.restconf.common.validation.RestconfValidationUtils;
74 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
75 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
76 import org.opendaylight.yangtools.yang.common.QName;
77 import org.opendaylight.yangtools.yang.common.QNameModule;
78 import org.opendaylight.yangtools.yang.common.Revision;
79 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
80 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
81 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
82 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
83 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
84 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
85 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
86 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
87 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
88 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
89 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
90 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
91 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
92 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
93 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
94 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
95 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
96 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
97 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
98 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
99 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
100 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
101 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
102 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
103 import org.opendaylight.yangtools.yang.model.api.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 final 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)),
150 NETCONF_BASE_PAYLOAD_NAME).intern();
152 private static final QNameModule SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
153 Revision.of("2014-07-08"));
155 private static final AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER =
156 new AugmentationIdentifier(ImmutableSet.of(
157 QName.create(SAL_REMOTE_AUGMENT, "scope"), QName.create(SAL_REMOTE_AUGMENT, "datastore"),
158 QName.create(SAL_REMOTE_AUGMENT, "notification-output-type")));
160 public static final CharSequence DATA_SUBSCR = "data-change-event-subscription";
161 private static final CharSequence CREATE_DATA_SUBSCR = "create-" + DATA_SUBSCR;
163 public static final CharSequence NOTIFICATION_STREAM = "notification-stream";
164 private static final CharSequence CREATE_NOTIFICATION_STREAM = "create-" + NOTIFICATION_STREAM;
166 private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
167 .appendValue(ChronoField.YEAR, 4).appendLiteral('-')
168 .appendValue(ChronoField.MONTH_OF_YEAR, 2).appendLiteral('-')
169 .appendValue(ChronoField.DAY_OF_MONTH, 2).appendLiteral('T')
170 .appendValue(ChronoField.HOUR_OF_DAY, 2).appendLiteral(':')
171 .appendValue(ChronoField.MINUTE_OF_HOUR, 2).appendLiteral(':')
172 .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
173 .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
174 .appendOffset("+HH:MM", "Z").toFormatter();
176 private BrokerFacade broker;
178 private ControllerContext controllerContext;
180 public void setBroker(final BrokerFacade broker) {
181 this.broker = broker;
184 public void setControllerContext(final ControllerContext controllerContext) {
185 this.controllerContext = controllerContext;
188 private RestconfImpl() {
191 public static RestconfImpl getInstance() {
196 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
197 final Set<Module> allModules = this.controllerContext.getAllModules();
198 final MapNode allModuleMap = makeModuleMapNode(allModules);
200 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
202 final Module restconfModule = getRestconfModule();
203 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
204 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
205 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
207 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
208 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
209 moduleContainerBuilder.withChild(allModuleMap);
211 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode, null, schemaContext),
212 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
216 * Valid only for mount point.
219 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
220 Preconditions.checkNotNull(identifier);
221 if (!identifier.contains(ControllerContext.MOUNT)) {
222 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
223 + " URI has to end with " + ControllerContext.MOUNT;
224 LOG.debug(errMsg + " for " + identifier);
225 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
228 final InstanceIdentifierContext<?> mountPointIdentifier =
229 this.controllerContext.toMountPointIdentifier(identifier);
230 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
231 final Set<Module> modules = this.controllerContext.getAllModules(mountPoint);
232 final MapNode mountPointModulesMap = makeModuleMapNode(modules);
234 final Module restconfModule = getRestconfModule();
235 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
236 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
237 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
239 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
240 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
241 moduleContainerBuilder.withChild(mountPointModulesMap);
243 return new NormalizedNodeContext(
244 new InstanceIdentifierContext<>(null, modulesSchemaNode, mountPoint,
245 this.controllerContext.getGlobalSchema()),
246 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
250 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
251 Preconditions.checkNotNull(identifier);
252 final Entry<String, Revision> nameRev = getModuleNameAndRevision(identifier);
253 Module module = null;
254 DOMMountPoint mountPoint = null;
255 final SchemaContext schemaContext;
256 if (identifier.contains(ControllerContext.MOUNT)) {
257 final InstanceIdentifierContext<?> mountPointIdentifier =
258 this.controllerContext.toMountPointIdentifier(identifier);
259 mountPoint = mountPointIdentifier.getMountPoint();
260 module = this.controllerContext.findModuleByNameAndRevision(mountPoint, nameRev.getKey(),
262 schemaContext = mountPoint.getSchemaContext();
264 module = this.controllerContext.findModuleByNameAndRevision(nameRev.getKey(), nameRev.getValue());
265 schemaContext = this.controllerContext.getGlobalSchema();
268 if (module == null) {
269 final String errMsg = "Module with name '" + nameRev.getKey() + "' and revision '"
270 + nameRev.getValue() + "' was not found.";
272 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
275 final Module restconfModule = getRestconfModule();
276 final Set<Module> modules = Collections.singleton(module);
277 final MapNode moduleMap = makeModuleMapNode(modules);
279 final DataSchemaNode moduleSchemaNode = this.controllerContext
280 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
281 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
283 return new NormalizedNodeContext(
284 new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint, schemaContext), moduleMap,
285 QueryParametersParser.parseWriterParameters(uriInfo));
289 public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
290 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
291 final Set<String> availableStreams = Notificator.getStreamNames();
292 final Module restconfModule = getRestconfModule();
293 final DataSchemaNode streamSchemaNode = this.controllerContext
294 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
295 Preconditions.checkState(streamSchemaNode instanceof ListSchemaNode);
297 final CollectionNodeBuilder<MapEntryNode, MapNode> listStreamsBuilder =
298 Builders.mapBuilder((ListSchemaNode) streamSchemaNode);
300 for (final String streamName : availableStreams) {
301 listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
304 final DataSchemaNode streamsContainerSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
305 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
306 Preconditions.checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
308 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
309 Builders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
310 streamsContainerBuilder.withChild(listStreamsBuilder.build());
312 return new NormalizedNodeContext(
313 new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null, schemaContext),
314 streamsContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
318 public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
319 final Set<Module> allModules = this.controllerContext.getAllModules();
320 return operationsFromModulesToNormalizedContext(allModules, null);
324 public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
325 Set<Module> modules = null;
326 DOMMountPoint mountPoint = null;
327 if (identifier.contains(ControllerContext.MOUNT)) {
328 final InstanceIdentifierContext<?> mountPointIdentifier =
329 this.controllerContext.toMountPointIdentifier(identifier);
330 mountPoint = mountPointIdentifier.getMountPoint();
331 modules = this.controllerContext.getAllModules(mountPoint);
334 final String errMsg =
335 "URI has bad format. If operations behind mount point should be showed, URI has to " + "end with ";
336 LOG.debug(errMsg + ControllerContext.MOUNT + " for " + identifier);
337 throw new RestconfDocumentedException(errMsg + ControllerContext.MOUNT, ErrorType.PROTOCOL,
338 ErrorTag.INVALID_VALUE);
341 return operationsFromModulesToNormalizedContext(modules, mountPoint);
345 * Special case only for GET restconf/operations use (since moment of
346 * pre-Beryllium Yang parser and Yang model API removal). The method is
347 * creating fake schema context with fake module and fake data by use own
348 * implementations of schema nodes and module.
351 * set of modules for get RPCs from every module
353 * mount point, if in use otherwise null
354 * @return {@link NormalizedNodeContext}
356 private static NormalizedNodeContext operationsFromModulesToNormalizedContext(final Set<Module> modules,
357 final DOMMountPoint mountPoint) {
359 final Collection<Module> neededModules = new ArrayList<>(modules.size());
360 final ArrayList<LeafSchemaNode> fakeRpcSchema = new ArrayList<>();
362 for (final Module m : modules) {
363 final Set<RpcDefinition> rpcs = m.getRpcs();
364 if (!rpcs.isEmpty()) {
365 neededModules.add(m);
367 fakeRpcSchema.ensureCapacity(fakeRpcSchema.size() + rpcs.size());
368 rpcs.forEach(rpc -> fakeRpcSchema.add(new FakeLeafSchemaNode(rpc.getQName())));
372 final ContainerSchemaNode fakeCont = new FakeContainerSchemaNode(fakeRpcSchema);
373 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> containerBuilder =
374 Builders.containerBuilder(fakeCont);
376 for (final LeafSchemaNode leaf : fakeRpcSchema) {
377 containerBuilder.withChild(Builders.leafBuilder(leaf).build());
380 final Collection<Module> fakeModules = new ArrayList<>(neededModules.size() + 1);
381 neededModules.forEach(imp -> fakeModules.add(new FakeImportedModule(imp)));
382 fakeModules.add(new FakeRestconfModule(neededModules, fakeCont));
384 final SchemaContext fakeSchemaCtx = SimpleSchemaContext.forModules(ImmutableSet.copyOf(fakeModules));
385 final InstanceIdentifierContext<ContainerSchemaNode> instanceIdentifierContext =
386 new InstanceIdentifierContext<>(null, fakeCont, mountPoint, fakeSchemaCtx);
387 return new NormalizedNodeContext(instanceIdentifierContext, containerBuilder.build());
390 private Module getRestconfModule() {
391 final Module restconfModule = this.controllerContext.getRestconfModule();
392 if (restconfModule == null) {
393 LOG.debug("ietf-restconf module was not found.");
394 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
395 ErrorTag.OPERATION_NOT_SUPPORTED);
398 return restconfModule;
401 private static Entry<String, Revision> getModuleNameAndRevision(final String identifier) {
402 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
403 String moduleNameAndRevision = "";
404 if (mountIndex >= 0) {
405 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
407 moduleNameAndRevision = identifier;
410 final Splitter splitter = Splitter.on('/').omitEmptyStrings();
411 final List<String> pathArgs = splitter.splitToList(moduleNameAndRevision);
412 if (pathArgs.size() < 2) {
413 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
414 throw new RestconfDocumentedException(
415 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
416 ErrorTag.INVALID_VALUE);
420 return new SimpleImmutableEntry<>(pathArgs.get(0), Revision.of(pathArgs.get(1)));
421 } catch (final DateTimeParseException e) {
422 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
423 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
424 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
429 public Object getRoot() {
434 public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload,
435 final UriInfo uriInfo) {
436 final SchemaPath type = payload.getInstanceIdentifierContext().getSchemaNode().getPath();
437 final URI namespace = payload.getInstanceIdentifierContext().getSchemaNode().getQName().getNamespace();
438 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
439 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
440 final SchemaContext schemaContext;
442 if (mountPoint != null) {
443 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
444 if (!mountRpcServices.isPresent()) {
445 LOG.debug("Error: Rpc service is missing.");
446 throw new RestconfDocumentedException("Rpc service is missing.");
448 schemaContext = mountPoint.getSchemaContext();
449 response = mountRpcServices.get().invokeRpc(type, payload.getData());
451 if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
452 if (identifier.contains(CREATE_DATA_SUBSCR)) {
453 response = invokeSalRemoteRpcSubscribeRPC(payload);
454 } else if (identifier.contains(CREATE_NOTIFICATION_STREAM)) {
455 response = invokeSalRemoteRpcNotifiStrRPC(payload);
457 final String msg = "Not supported operation";
459 throw new RestconfDocumentedException(msg, ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED);
462 response = this.broker.invokeRpc(type, payload.getData());
464 schemaContext = this.controllerContext.getGlobalSchema();
467 final DOMRpcResult result = checkRpcResponse(response);
469 RpcDefinition resultNodeSchema = null;
470 final NormalizedNode<?, ?> resultData;
471 if (result != null && result.getResult() != null) {
472 resultData = result.getResult();
473 resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
478 return new NormalizedNodeContext(
479 new InstanceIdentifierContext<>(null, resultNodeSchema, mountPoint, schemaContext),
480 resultData, QueryParametersParser.parseWriterParameters(uriInfo));
484 public NormalizedNodeContext invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
485 if (noPayload != null && !CharMatcher.WHITESPACE.matchesAllOf(noPayload)) {
486 throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
489 String identifierEncoded = null;
490 DOMMountPoint mountPoint = null;
491 final SchemaContext schemaContext;
492 if (identifier.contains(ControllerContext.MOUNT)) {
493 // mounted RPC call - look up mount instance.
494 final InstanceIdentifierContext<?> mountPointId = this.controllerContext.toMountPointIdentifier(identifier);
495 mountPoint = mountPointId.getMountPoint();
496 schemaContext = mountPoint.getSchemaContext();
497 final int startOfRemoteRpcName =
498 identifier.lastIndexOf(ControllerContext.MOUNT) + ControllerContext.MOUNT.length() + 1;
499 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
500 identifierEncoded = remoteRpcName;
502 } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
503 final String slashErrorMsg = String.format(
504 "Identifier %n%s%ncan\'t contain slash "
505 + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.",
507 LOG.debug(slashErrorMsg);
508 throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
510 identifierEncoded = identifier;
511 schemaContext = this.controllerContext.getGlobalSchema();
514 final String identifierDecoded = this.controllerContext.urlPathArgDecode(identifierEncoded);
516 RpcDefinition rpc = null;
517 if (mountPoint == null) {
518 rpc = this.controllerContext.getRpcDefinition(identifierDecoded);
520 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
524 LOG.debug("RPC " + identifierDecoded + " does not exist.");
525 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
528 if (!rpc.getInput().getChildNodes().isEmpty()) {
529 LOG.debug("RPC " + rpc + " does not need input value.");
530 throw new RestconfDocumentedException("RPC " + rpc + " does not take any input value.",
531 ErrorType.RPC, ErrorTag.INVALID_VALUE);
534 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
535 if (mountPoint != null) {
536 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
537 if (!mountRpcServices.isPresent()) {
538 throw new RestconfDocumentedException("Rpc service is missing.");
540 response = mountRpcServices.get().invokeRpc(rpc.getPath(), null);
542 response = this.broker.invokeRpc(rpc.getPath(), null);
545 final DOMRpcResult result = checkRpcResponse(response);
547 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpc, mountPoint, schemaContext),
548 result.getResult(), QueryParametersParser.parseWriterParameters(uriInfo));
551 @SuppressWarnings("checkstyle:avoidHidingCauseException")
552 private static DOMRpcResult checkRpcResponse(final CheckedFuture<DOMRpcResult, DOMRpcException> response) {
553 if (response == null) {
557 final DOMRpcResult retValue = response.get();
558 if (retValue.getErrors().isEmpty()) {
561 LOG.debug("RpcError message", retValue.getErrors());
562 throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
563 } catch (final InterruptedException e) {
564 final String errMsg = "The operation was interrupted while executing and did not complete.";
565 LOG.debug("Rpc Interrupt - " + errMsg, e);
566 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION, e);
567 } catch (final ExecutionException e) {
568 LOG.debug("Execution RpcError: ", e);
569 Throwable cause = e.getCause();
571 while (cause.getCause() != null) {
572 cause = cause.getCause();
575 if (cause instanceof IllegalArgumentException) {
576 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL,
577 ErrorTag.INVALID_VALUE);
578 } else if (cause instanceof DOMRpcImplementationNotAvailableException) {
579 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.APPLICATION,
580 ErrorTag.OPERATION_NOT_SUPPORTED);
582 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
585 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
588 } catch (final CancellationException e) {
589 final String errMsg = "The operation was cancelled while executing.";
590 LOG.debug("Cancel RpcExecution: " + errMsg, e);
591 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
595 private static void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
596 if (inputSchema != null && payload.getData() == null) {
597 // expected a non null payload
598 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
599 } else if (inputSchema == null && payload.getData() != null) {
600 // did not expect any input
601 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
605 private CheckedFuture<DOMRpcResult, DOMRpcException>
606 invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
607 final ContainerNode value = (ContainerNode) payload.getData();
608 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
609 final java.util.Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(
610 new NodeIdentifier(QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(),
612 final Object pathValue = path.isPresent() ? path.get().getValue() : null;
614 if (!(pathValue instanceof YangInstanceIdentifier)) {
615 final String errMsg = "Instance identifier was not normalized correctly ";
616 LOG.debug(errMsg + rpcQName);
617 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
620 final YangInstanceIdentifier pathIdentifier = (YangInstanceIdentifier) pathValue;
621 String streamName = (String) CREATE_DATA_SUBSCR;
622 NotificationOutputType outputType = null;
623 if (!pathIdentifier.isEmpty()) {
624 final String fullRestconfIdentifier =
625 DATA_SUBSCR + this.controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
627 LogicalDatastoreType datastore =
628 parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
629 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
631 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
632 scope = scope == null ? DEFAULT_SCOPE : scope;
634 outputType = parseEnumTypeParameter(value, NotificationOutputType.class, OUTPUT_TYPE_PARAM_NAME);
635 outputType = outputType == null ? NotificationOutputType.XML : outputType;
637 streamName = Notificator
638 .createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore + "/scope=" + scope);
641 if (Strings.isNullOrEmpty(streamName)) {
642 final String errMsg = "Path is empty or contains value node which is not Container or List build-in type.";
643 LOG.debug(errMsg + pathIdentifier);
644 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
647 final QName outputQname = QName.create(rpcQName, "output");
648 final QName streamNameQname = QName.create(rpcQName, "stream-name");
650 final ContainerNode output =
651 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
652 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
654 if (!Notificator.existListenerFor(streamName)) {
655 Notificator.createListener(pathIdentifier, streamName, outputType);
658 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
660 return Futures.immediateCheckedFuture(defaultDOMRpcResult);
663 private static RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
664 final String[] splittedIdentifier = identifierDecoded.split(":");
665 if (splittedIdentifier.length != 2) {
666 final String errMsg = identifierDecoded + " couldn't be splitted to 2 parts (module:rpc name)";
668 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
670 for (final Module module : schemaContext.getModules()) {
671 if (module.getName().equals(splittedIdentifier[0])) {
672 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
673 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
674 return rpcDefinition;
683 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
684 boolean withDefaUsed = false;
685 String withDefa = null;
687 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
688 switch (entry.getKey()) {
689 case "with-defaults":
692 withDefa = entry.getValue().iterator().next();
694 throw new RestconfDocumentedException("With-defaults parameter can be used only once.");
698 LOG.info("Unknown key : {}.", entry.getKey());
702 boolean tagged = false;
704 if ("report-all-tagged".equals(withDefa)) {
708 if ("report-all".equals(withDefa)) {
713 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
714 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
715 NormalizedNode<?, ?> data = null;
716 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
717 if (mountPoint != null) {
718 data = this.broker.readConfigurationData(mountPoint, normalizedII, withDefa);
720 data = this.broker.readConfigurationData(normalizedII, withDefa);
723 final String errMsg =
724 "Request could not be completed because the relevant data model content does not exist ";
725 LOG.debug(errMsg + identifier);
726 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
728 return new NormalizedNodeContext(iiWithData, data,
729 QueryParametersParser.parseWriterParameters(uriInfo, tagged));
733 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
734 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
735 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
736 NormalizedNode<?, ?> data = null;
737 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
738 if (mountPoint != null) {
739 data = this.broker.readOperationalData(mountPoint, normalizedII);
741 data = this.broker.readOperationalData(normalizedII);
744 final String errMsg =
745 "Request could not be completed because the relevant data model content does not exist ";
746 LOG.debug(errMsg + identifier);
747 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
749 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
753 public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload,
754 final UriInfo uriInfo) {
755 boolean insertUsed = false;
756 boolean pointUsed = false;
757 String insert = null;
760 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
761 switch (entry.getKey()) {
765 insert = entry.getValue().iterator().next();
767 throw new RestconfDocumentedException("Insert parameter can be used only once.");
773 point = entry.getValue().iterator().next();
775 throw new RestconfDocumentedException("Point parameter can be used only once.");
779 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
783 if (pointUsed && !insertUsed) {
784 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
786 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
787 throw new RestconfDocumentedException(
788 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
791 Preconditions.checkNotNull(identifier);
793 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
795 validateInput(iiWithData.getSchemaNode(), payload);
796 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
797 validateListKeysEqualityInPayloadAndUri(payload);
799 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
800 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
803 * There is a small window where another write transaction could be
804 * updating the same data simultaneously and we get an
805 * OptimisticLockFailedException. This error is likely transient and The
806 * WriteTransaction#submit API docs state that a retry will likely
807 * succeed. So we'll try again if that scenario occurs. If it fails a
808 * third time then it probably will never succeed so we'll fail in that
811 * By retrying we're attempting to hide the internal implementation of
812 * the data store and how it handles concurrent updates from the
813 * restconf client. The client has instructed us to put the data and we
814 * should make every effort to do so without pushing optimistic lock
815 * failures back to the client and forcing them to handle it via retry
816 * (and having to document the behavior).
818 PutResult result = null;
821 if (mountPoint != null) {
823 result = this.broker.commitMountPointDataPut(mountPoint, normalizedII, payload.getData(), insert,
826 result = this.broker.commitConfigurationDataPut(this.controllerContext.getGlobalSchema(), normalizedII,
827 payload.getData(), insert, point);
831 result.getFutureOfPutData().checkedGet();
832 return Response.status(result.getStatus()).build();
833 } catch (final TransactionCommitFailedException e) {
834 if (e instanceof OptimisticLockFailedException) {
836 LOG.debug("Got OptimisticLockFailedException on last try - failing " + identifier);
837 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
840 LOG.debug("Got OptimisticLockFailedException - trying again " + identifier);
842 LOG.debug("Update failed for " + identifier, e);
843 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
849 private static void validateTopLevelNodeName(final NormalizedNodeContext node,
850 final YangInstanceIdentifier identifier) {
852 final String payloadName = node.getData().getNodeType().getLocalName();
855 if (identifier.isEmpty()) {
857 if (!node.getData().getNodeType().equals(NETCONF_BASE_QNAME)) {
858 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
859 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
863 final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
864 if (!payloadName.equals(identifierName)) {
865 throw new RestconfDocumentedException(
866 "Payload name (" + payloadName + ") is different from identifier name (" + identifierName + ")",
867 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
873 * Validates whether keys in {@code payload} are equal to values of keys in
874 * {@code iiWithData} for list schema node.
876 * @throws RestconfDocumentedException
877 * if key values or key count in payload and URI isn't equal
880 private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
881 Preconditions.checkArgument(payload != null);
882 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
883 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
884 final SchemaNode schemaNode = iiWithData.getSchemaNode();
885 final NormalizedNode<?, ?> data = payload.getData();
886 if (schemaNode instanceof ListSchemaNode) {
887 final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
888 if (lastPathArgument instanceof NodeIdentifierWithPredicates && data instanceof MapEntryNode) {
889 final Map<QName, Object> uriKeyValues =
890 ((NodeIdentifierWithPredicates) lastPathArgument).getKeyValues();
891 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
897 public static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final MapEntryNode payload,
898 final List<QName> keyDefinitions) {
900 final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
901 for (final QName keyDefinition : keyDefinitions) {
902 final Object uriKeyValue = mutableCopyUriKeyValues.remove(keyDefinition);
903 // should be caught during parsing URI to InstanceIdentifier
904 RestconfValidationUtils.checkDocumentedError(uriKeyValue != null, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
905 "Missing key " + keyDefinition + " in URI.");
907 final Object dataKeyValue = payload.getIdentifier().getKeyValues().get(keyDefinition);
909 if (!Objects.deepEquals(uriKeyValue, dataKeyValue)) {
910 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName()
911 + "' specified in the URI doesn't match the value '" + dataKeyValue
912 + "' specified in the message body. ";
913 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
919 public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload,
920 final UriInfo uriInfo) {
921 return createConfigurationData(payload, uriInfo);
925 public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
926 if (payload == null) {
927 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
929 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
930 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
931 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
933 boolean insertUsed = false;
934 boolean pointUsed = false;
935 String insert = null;
938 if (uriInfo != null) {
939 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
940 switch (entry.getKey()) {
944 insert = entry.getValue().iterator().next();
946 throw new RestconfDocumentedException("Insert parameter can be used only once.");
952 point = entry.getValue().iterator().next();
954 throw new RestconfDocumentedException("Point parameter can be used only once.");
958 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
963 if (pointUsed && !insertUsed) {
964 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
966 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
967 throw new RestconfDocumentedException(
968 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
971 CheckedFuture<Void, TransactionCommitFailedException> future;
972 if (mountPoint != null) {
973 future = this.broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData(), insert,
976 future = this.broker.commitConfigurationDataPost(this.controllerContext.getGlobalSchema(), normalizedII,
977 payload.getData(), insert, point);
982 } catch (final RestconfDocumentedException e) {
984 } catch (final TransactionCommitFailedException e) {
985 LOG.info("Error creating data " + (uriInfo != null ? uriInfo.getPath() : ""), e);
986 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
989 LOG.trace("Successfuly created data.");
991 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
992 // FIXME: Provide path to result.
993 final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
994 if (location != null) {
995 responseBuilder.location(location);
997 return responseBuilder.build();
1000 @SuppressWarnings("checkstyle:IllegalCatch")
1001 private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint,
1002 final YangInstanceIdentifier normalizedII) {
1003 if (uriInfo == null) {
1004 // This is null if invoked internally
1008 final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
1009 uriBuilder.path("config");
1011 uriBuilder.path(this.controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
1012 } catch (final Exception e) {
1013 LOG.info("Location for instance identifier" + normalizedII + "wasn't created", e);
1016 return uriBuilder.build();
1020 public Response deleteConfigurationData(final String identifier) {
1021 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
1022 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
1023 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
1025 final CheckedFuture<Void, TransactionCommitFailedException> future;
1026 if (mountPoint != null) {
1027 future = this.broker.commitConfigurationDataDelete(mountPoint, normalizedII);
1029 future = this.broker.commitConfigurationDataDelete(normalizedII);
1033 future.checkedGet();
1034 } catch (final TransactionCommitFailedException e) {
1035 final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
1036 Predicates.instanceOf(ModifiedNodeDoesNotExistException.class));
1037 if (searchedException.isPresent()) {
1038 throw new RestconfDocumentedException("Data specified for delete doesn't exist.",
1039 ErrorType.APPLICATION, ErrorTag.DATA_MISSING, e);
1042 final String errMsg = "Error while deleting data";
1043 LOG.info(errMsg, e);
1044 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
1047 return Response.status(Status.OK).build();
1051 * Subscribes to some path in schema context (stream) to listen on changes
1055 * Additional parameters for subscribing to stream are loaded via rpc input
1058 * <li>datastore - default CONFIGURATION (other values of
1059 * {@link LogicalDatastoreType} enum type)</li>
1060 * <li>scope - default BASE (other values of {@link DataChangeScope})</li>
1064 public NormalizedNodeContext subscribeToStream(final String identifier, final UriInfo uriInfo) {
1065 boolean startTimeUsed = false;
1066 boolean stopTimeUsed = false;
1067 Instant start = Instant.now();
1068 Instant stop = null;
1069 boolean filterUsed = false;
1070 String filter = null;
1071 boolean leafNodesOnlyUsed = false;
1072 boolean leafNodesOnly = false;
1074 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
1075 switch (entry.getKey()) {
1077 if (!startTimeUsed) {
1078 startTimeUsed = true;
1079 start = parseDateFromQueryParam(entry);
1081 throw new RestconfDocumentedException("Start-time parameter can be used only once.");
1085 if (!stopTimeUsed) {
1086 stopTimeUsed = true;
1087 stop = parseDateFromQueryParam(entry);
1089 throw new RestconfDocumentedException("Stop-time parameter can be used only once.");
1095 filter = entry.getValue().iterator().next();
1097 throw new RestconfDocumentedException("Filter parameter can be used only once.");
1100 case "odl-leaf-nodes-only":
1101 if (!leafNodesOnlyUsed) {
1102 leafNodesOnlyUsed = true;
1103 leafNodesOnly = Boolean.parseBoolean(entry.getValue().iterator().next());
1105 throw new RestconfDocumentedException("Odl-leaf-nodes-only parameter can be used only once.");
1109 throw new RestconfDocumentedException("Bad parameter used with notifications: " + entry.getKey());
1112 if (!startTimeUsed && stopTimeUsed) {
1113 throw new RestconfDocumentedException("Stop-time parameter has to be used with start-time parameter.");
1115 URI response = null;
1116 if (identifier.contains(DATA_SUBSCR)) {
1117 response = dataSubs(identifier, uriInfo, start, stop, filter, leafNodesOnly);
1118 } else if (identifier.contains(NOTIFICATION_STREAM)) {
1119 response = notifStream(identifier, uriInfo, start, stop, filter);
1122 if (response != null) {
1123 // prepare node with value of location
1124 final InstanceIdentifierContext<?> iid = prepareIIDSubsStreamOutput();
1125 final NormalizedNodeAttrBuilder<NodeIdentifier, Object, LeafNode<Object>> builder =
1126 ImmutableLeafNodeBuilder.create().withValue(response.toString());
1127 builder.withNodeIdentifier(
1128 NodeIdentifier.create(QName.create("subscribe:to:notification", "2016-10-28", "location")));
1130 // prepare new header with location
1131 final Map<String, Object> headers = new HashMap<>();
1132 headers.put("Location", response);
1134 return new NormalizedNodeContext(iid, builder.build(), headers);
1137 final String msg = "Bad type of notification of sal-remote";
1139 throw new RestconfDocumentedException(msg);
1142 private static Instant parseDateFromQueryParam(final Entry<String, List<String>> entry) {
1143 final DateAndTime event = new DateAndTime(entry.getValue().iterator().next());
1144 final String value = event.getValue();
1145 final TemporalAccessor p;
1147 p = FORMATTER.parse(value);
1148 } catch (final DateTimeParseException e) {
1149 throw new RestconfDocumentedException("Cannot parse of value in date: " + value, e);
1151 return Instant.from(p);
1155 * Prepare instance identifier.
1157 * @return {@link InstanceIdentifierContext} of location leaf for
1160 private static InstanceIdentifierContext<?> prepareIIDSubsStreamOutput() {
1161 final QName qnameBase = QName.create("subscribe:to:notification", "2016-10-28", "notifi");
1162 final SchemaContext schemaCtx = ControllerContext.getInstance().getGlobalSchema();
1163 final DataSchemaNode location = ((ContainerSchemaNode) schemaCtx
1164 .findModule(qnameBase.getModule()).orElse(null)
1165 .getDataChildByName(qnameBase)).getDataChildByName(QName.create(qnameBase, "location"));
1166 final List<PathArgument> path = new ArrayList<>();
1167 path.add(NodeIdentifier.create(qnameBase));
1168 path.add(NodeIdentifier.create(QName.create(qnameBase, "location")));
1170 return new InstanceIdentifierContext<SchemaNode>(YangInstanceIdentifier.create(path), location, null,
1175 * Register notification listener by stream name.
1182 * stop-time of getting notification
1184 * start-time of getting notification
1186 * indicate which subset of all possible events are of interest
1187 * @return {@link URI} of location
1189 private URI notifStream(final String identifier, final UriInfo uriInfo, final Instant start,
1190 final Instant stop, final String filter) {
1191 final String streamName = Notificator.createStreamNameFromUri(identifier);
1192 if (Strings.isNullOrEmpty(streamName)) {
1193 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1195 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
1196 if (listeners == null || listeners.isEmpty()) {
1197 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1198 ErrorTag.UNKNOWN_ELEMENT);
1201 for (final NotificationListenerAdapter listener : listeners) {
1202 this.broker.registerToListenNotification(listener);
1203 listener.setQueryParams(start,
1204 java.util.Optional.ofNullable(stop), java.util.Optional.ofNullable(filter), false);
1207 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1209 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance(NOTIFICATION_PORT);
1210 final int notificationPort = webSocketServerInstance.getPort();
1212 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1214 return uriToWebsocketServerBuilder.replacePath(streamName).build();
1218 * Register data change listener by stream name.
1225 * start-time of getting notification
1227 * stop-time of getting notification
1229 * indicate which subset of all possible events are of interest
1230 * @return {@link URI} of location
1232 private URI dataSubs(final String identifier, final UriInfo uriInfo, final Instant start, final Instant stop,
1233 final String filter, final boolean leafNodesOnly) {
1234 final String streamName = Notificator.createStreamNameFromUri(identifier);
1235 if (Strings.isNullOrEmpty(streamName)) {
1236 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1239 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1240 if (listener == null) {
1241 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1242 ErrorTag.UNKNOWN_ELEMENT);
1244 listener.setQueryParams(start, java.util.Optional.ofNullable(stop),
1245 java.util.Optional.ofNullable(filter), leafNodesOnly);
1247 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1248 final LogicalDatastoreType datastore =
1249 parserURIEnumParameter(LogicalDatastoreType.class, paramToValues.get(DATASTORE_PARAM_NAME));
1250 if (datastore == null) {
1251 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1252 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1254 final DataChangeScope scope =
1255 parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
1256 if (scope == null) {
1257 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1258 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1261 this.broker.registerToListenDataChanges(datastore, scope, listener);
1263 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1265 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance(NOTIFICATION_PORT);
1266 final int notificationPort = webSocketServerInstance.getPort();
1268 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1270 return uriToWebsocketServerBuilder.replacePath(streamName).build();
1273 @SuppressWarnings("checkstyle:IllegalCatch")
1275 public PatchStatusContext patchConfigurationData(final String identifier, final PatchContext context,
1276 final UriInfo uriInfo) {
1277 if (context == null) {
1278 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1282 return this.broker.patchConfigurationDataWithinTransaction(context);
1283 } catch (final Exception e) {
1284 LOG.debug("Patch transaction failed", e);
1285 throw new RestconfDocumentedException(e.getMessage(), e);
1289 @SuppressWarnings("checkstyle:IllegalCatch")
1291 public PatchStatusContext patchConfigurationData(final PatchContext context, @Context final UriInfo uriInfo) {
1292 if (context == null) {
1293 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1297 return this.broker.patchConfigurationDataWithinTransaction(context);
1298 } catch (final Exception e) {
1299 LOG.debug("Patch transaction failed", e);
1300 throw new RestconfDocumentedException(e.getMessage(), e);
1305 * Load parameter for subscribing to stream from input composite node.
1309 * @return enum object if its string value is equal to {@code paramName}. In
1312 private static <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1313 final String paramName) {
1314 final java.util.Optional<DataContainerChild<? extends PathArgument, ?>> optAugNode = value.getChild(
1315 SAL_REMOTE_AUG_IDENTIFIER);
1316 if (!optAugNode.isPresent()) {
1319 final DataContainerChild<? extends PathArgument, ?> augNode = optAugNode.get();
1320 if (!(augNode instanceof AugmentationNode)) {
1323 final java.util.Optional<DataContainerChild<? extends PathArgument, ?>> enumNode = ((AugmentationNode) augNode)
1324 .getChild(new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1325 if (!enumNode.isPresent()) {
1328 final Object rawValue = enumNode.get().getValue();
1329 if (!(rawValue instanceof String)) {
1333 return resolveAsEnum(classDescriptor, (String) rawValue);
1337 * Checks whether {@code value} is one of the string representation of
1338 * enumeration {@code classDescriptor}.
1340 * @return enum object if string value of {@code classDescriptor}
1341 * enumeration is equal to {@code value}. Other cases null.
1343 private static <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1344 if (Strings.isNullOrEmpty(value)) {
1347 return resolveAsEnum(classDescriptor, value);
1350 private static <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1351 final T[] enumConstants = classDescriptor.getEnumConstants();
1352 if (enumConstants != null) {
1353 for (final T enm : classDescriptor.getEnumConstants()) {
1354 if (((Enum<?>) enm).name().equals(value)) {
1362 private static Map<String, String> resolveValuesFromUri(final String uri) {
1363 final Map<String, String> result = new HashMap<>();
1364 final String[] tokens = uri.split("/");
1365 for (int i = 1; i < tokens.length; i++) {
1366 final String[] parameterTokens = tokens[i].split("=");
1367 if (parameterTokens.length == 2) {
1368 result.put(parameterTokens[0], parameterTokens[1]);
1374 private MapNode makeModuleMapNode(final Set<Module> modules) {
1375 Preconditions.checkNotNull(modules);
1376 final Module restconfModule = getRestconfModule();
1377 final DataSchemaNode moduleSchemaNode = this.controllerContext
1378 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1379 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1381 final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder =
1382 Builders.mapBuilder((ListSchemaNode) moduleSchemaNode);
1384 for (final Module module : modules) {
1385 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1387 return listModuleBuilder.build();
1390 protected MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1391 Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1392 "moduleSchemaNode has to be of type ListSchemaNode");
1393 final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1394 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues =
1395 Builders.mapEntryBuilder(listModuleSchemaNode);
1397 List<DataSchemaNode> instanceDataChildrenByName =
1398 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "name");
1399 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1400 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1402 .withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName()).build());
1404 instanceDataChildrenByName =
1405 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "revision");
1406 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1407 Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1408 final java.util.Optional<Revision> revision = module.getQNameModule().getRevision();
1409 if (revision.isPresent()) {
1410 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode)
1411 .withValue(revision.get().toString()).build());
1414 instanceDataChildrenByName =
1415 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "namespace");
1416 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1417 Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1418 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1419 .withValue(module.getNamespace().toString()).build());
1421 instanceDataChildrenByName =
1422 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "feature");
1423 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1424 Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1425 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder =
1426 Builders.leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1427 for (final FeatureDefinition feature : module.getFeatures()) {
1428 featuresBuilder.withChild(Builders.leafSetEntryBuilder((LeafListSchemaNode) featureSchemaNode)
1429 .withValue(feature.getQName().getLocalName()).build());
1431 moduleNodeValues.withChild(featuresBuilder.build());
1433 return moduleNodeValues.build();
1436 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1437 Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1438 "streamSchemaNode has to be of type ListSchemaNode");
1439 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1440 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues =
1441 Builders.mapEntryBuilder(listStreamSchemaNode);
1443 List<DataSchemaNode> instanceDataChildrenByName =
1444 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "name");
1445 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1446 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1447 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName).build());
1449 instanceDataChildrenByName =
1450 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "description");
1451 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1452 Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1453 streamNodeValues.withChild(
1454 Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue("DESCRIPTION_PLACEHOLDER").build());
1456 instanceDataChildrenByName =
1457 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-support");
1458 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1459 Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1460 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1461 .withValue(Boolean.valueOf(true)).build());
1463 instanceDataChildrenByName =
1464 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-log-creation-time");
1465 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1466 Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1467 streamNodeValues.withChild(
1468 Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode).withValue("").build());
1470 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "events");
1471 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1472 Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1473 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode).build());
1475 return streamNodeValues.build();
1479 * Prepare stream for notification.
1482 * contains list of qnames of notifications
1483 * @return - checked future object
1485 private static CheckedFuture<DOMRpcResult, DOMRpcException> invokeSalRemoteRpcNotifiStrRPC(
1486 final NormalizedNodeContext payload) {
1487 final ContainerNode data = (ContainerNode) payload.getData();
1488 LeafSetNode leafSet = null;
1489 String outputType = "XML";
1490 for (final DataContainerChild<? extends PathArgument, ?> dataChild : data.getValue()) {
1491 if (dataChild instanceof LeafSetNode) {
1492 leafSet = (LeafSetNode) dataChild;
1493 } else if (dataChild instanceof AugmentationNode) {
1494 outputType = (String) ((AugmentationNode) dataChild).getValue().iterator().next().getValue();
1498 final Collection<LeafSetEntryNode> entryNodes = leafSet.getValue();
1499 final List<SchemaPath> paths = new ArrayList<>();
1500 String streamName = CREATE_NOTIFICATION_STREAM + "/";
1502 StringBuilder streamNameBuilder = new StringBuilder(streamName);
1503 final Iterator<LeafSetEntryNode> iterator = entryNodes.iterator();
1504 while (iterator.hasNext()) {
1505 final QName valueQName = QName.create((String) iterator.next().getValue());
1506 final Module module =
1507 ControllerContext.getInstance().findModuleByNamespace(valueQName.getModule().getNamespace());
1508 Preconditions.checkNotNull(module,
1509 "Module for namespace " + valueQName.getModule().getNamespace() + " does not exist");
1510 NotificationDefinition notifiDef = null;
1511 for (final NotificationDefinition notification : module.getNotifications()) {
1512 if (notification.getQName().equals(valueQName)) {
1513 notifiDef = notification;
1517 final String moduleName = module.getName();
1518 Preconditions.checkNotNull(notifiDef,
1519 "Notification " + valueQName + "doesn't exist in module " + moduleName);
1520 paths.add(notifiDef.getPath());
1521 streamNameBuilder.append(moduleName).append(':').append(valueQName.getLocalName());
1522 if (iterator.hasNext()) {
1523 streamNameBuilder.append(',');
1527 streamName = streamNameBuilder.toString();
1529 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
1530 final QName outputQname = QName.create(rpcQName, "output");
1531 final QName streamNameQname = QName.create(rpcQName, "notification-stream-identifier");
1533 final ContainerNode output =
1534 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
1535 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
1537 if (!Notificator.existNotificationListenerFor(streamName)) {
1538 Notificator.createNotificationListener(paths, streamName, outputType);
1541 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
1543 return Futures.immediateCheckedFuture(defaultDOMRpcResult);