2 * Copyright (c) 2014, 2015 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.base.CharMatcher;
12 import com.google.common.base.Optional;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Predicates;
15 import com.google.common.base.Splitter;
16 import com.google.common.base.Strings;
17 import com.google.common.base.Throwables;
18 import com.google.common.collect.ImmutableSet;
19 import com.google.common.collect.Iterables;
20 import com.google.common.collect.Lists;
21 import com.google.common.collect.Maps;
22 import com.google.common.collect.Sets;
23 import com.google.common.util.concurrent.CheckedFuture;
24 import com.google.common.util.concurrent.Futures;
26 import java.net.URISyntaxException;
27 import java.text.DateFormat;
28 import java.text.ParseException;
29 import java.text.SimpleDateFormat;
30 import java.util.ArrayList;
31 import java.util.Collection;
32 import java.util.Collections;
33 import java.util.Date;
34 import java.util.HashMap;
35 import java.util.Iterator;
36 import java.util.List;
38 import java.util.Map.Entry;
40 import java.util.concurrent.CancellationException;
41 import java.util.concurrent.ExecutionException;
42 import javax.ws.rs.core.Context;
43 import javax.ws.rs.core.Response;
44 import javax.ws.rs.core.Response.ResponseBuilder;
45 import javax.ws.rs.core.Response.Status;
46 import javax.ws.rs.core.UriBuilder;
47 import javax.ws.rs.core.UriInfo;
48 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
49 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
50 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
51 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
52 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
53 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
54 import org.opendaylight.controller.md.sal.dom.api.DOMRpcImplementationNotAvailableException;
55 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
56 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
57 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
58 import org.opendaylight.netconf.md.sal.rest.common.RestconfValidationUtils;
59 import org.opendaylight.netconf.sal.rest.api.Draft02;
60 import org.opendaylight.netconf.sal.rest.api.RestconfService;
61 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
62 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
63 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
64 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
65 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
66 import org.opendaylight.netconf.sal.streams.websockets.WebSocketServer;
67 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
68 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
69 import org.opendaylight.yangtools.yang.common.QName;
70 import org.opendaylight.yangtools.yang.common.QNameModule;
71 import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
72 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
73 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
74 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
75 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
76 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
77 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
78 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
79 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
80 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
81 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
82 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
83 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
84 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
85 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
86 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
87 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
88 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
89 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
90 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
91 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
92 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
93 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
94 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
95 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
96 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
97 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
98 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
99 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
100 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
101 import org.opendaylight.yangtools.yang.model.api.Module;
102 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
103 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
104 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
105 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
106 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
107 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.EffectiveSchemaContext;
108 import org.slf4j.Logger;
109 import org.slf4j.LoggerFactory;
111 public class RestconfImpl implements RestconfService {
113 private static final RestconfImpl INSTANCE = new RestconfImpl();
116 * Notifications are served on port 8181.
118 private static final int NOTIFICATION_PORT = 8181;
120 private static final int CHAR_NOT_FOUND = -1;
122 private static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
124 private BrokerFacade broker;
126 private ControllerContext controllerContext;
128 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
130 private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
132 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
134 private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
136 private static final String DATASTORE_PARAM_NAME = "datastore";
138 private static final String SCOPE_PARAM_NAME = "scope";
140 private static final String OUTPUT_TYPE_PARAM_NAME = "notification-output-type";
142 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
144 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
146 private static final QName NETCONF_BASE_QNAME;
148 private static final QNameModule SAL_REMOTE_AUGMENT;
150 private static final YangInstanceIdentifier.AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER;
152 public static final CharSequence DATA_SUBSCR = "data-change-event-subscription";
153 private static final CharSequence CREATE_DATA_SUBSCR = "create-" + DATA_SUBSCR;
155 public static final CharSequence NOTIFICATION_STREAM = "notification-stream";
156 private static final CharSequence CREATE_NOTIFICATION_STREAM = "create-" + NOTIFICATION_STREAM;
160 final Date eventSubscriptionAugRevision = SimpleDateFormatUtil.getRevisionFormat().parse("2014-07-08");
162 QName.create(QNameModule.create(new URI(NETCONF_BASE), null), NETCONF_BASE_PAYLOAD_NAME);
163 SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT, eventSubscriptionAugRevision);
164 SAL_REMOTE_AUG_IDENTIFIER = new YangInstanceIdentifier.AugmentationIdentifier(Sets.newHashSet(
165 QName.create(SAL_REMOTE_AUGMENT, "scope"), QName.create(SAL_REMOTE_AUGMENT, "datastore"),
166 QName.create(SAL_REMOTE_AUGMENT, "notification-output-type")));
167 } catch (final ParseException e) {
168 final String errMsg = "It wasn't possible to convert revision date of sal-remote-augment to date";
170 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
171 } catch (final URISyntaxException e) {
172 final String errMsg = "It wasn't possible to create instance of URI class with " + NETCONF_BASE + " URI";
173 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
177 public void setBroker(final BrokerFacade broker) {
178 this.broker = broker;
181 public void setControllerContext(final ControllerContext controllerContext) {
182 this.controllerContext = controllerContext;
185 private RestconfImpl() {
188 public static RestconfImpl getInstance() {
193 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
194 final Set<Module> allModules = this.controllerContext.getAllModules();
195 final MapNode allModuleMap = makeModuleMapNode(allModules);
197 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
199 final Module restconfModule = getRestconfModule();
200 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
201 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
202 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
204 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
205 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
206 moduleContainerBuilder.withChild(allModuleMap);
208 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode, null, schemaContext),
209 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
213 * Valid only for mount point
216 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
217 Preconditions.checkNotNull(identifier);
218 if (!identifier.contains(ControllerContext.MOUNT)) {
219 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
220 + " URI has to end with " + ControllerContext.MOUNT;
221 LOG.debug(errMsg + " for " + identifier);
222 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
225 final InstanceIdentifierContext<?> mountPointIdentifier =
226 this.controllerContext.toMountPointIdentifier(identifier);
227 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
228 final Set<Module> modules = this.controllerContext.getAllModules(mountPoint);
229 final MapNode mountPointModulesMap = makeModuleMapNode(modules);
231 final Module restconfModule = getRestconfModule();
232 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
233 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
234 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
236 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
237 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
238 moduleContainerBuilder.withChild(mountPointModulesMap);
240 return new NormalizedNodeContext(
241 new InstanceIdentifierContext<>(null, modulesSchemaNode, mountPoint,
242 this.controllerContext.getGlobalSchema()),
243 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
247 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
248 Preconditions.checkNotNull(identifier);
249 final QName moduleNameAndRevision = getModuleNameAndRevision(identifier);
250 Module module = null;
251 DOMMountPoint mountPoint = null;
252 final SchemaContext schemaContext;
253 if (identifier.contains(ControllerContext.MOUNT)) {
254 final InstanceIdentifierContext<?> mountPointIdentifier =
255 this.controllerContext.toMountPointIdentifier(identifier);
256 mountPoint = mountPointIdentifier.getMountPoint();
257 module = this.controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision);
258 schemaContext = mountPoint.getSchemaContext();
260 module = this.controllerContext.findModuleByNameAndRevision(moduleNameAndRevision);
261 schemaContext = this.controllerContext.getGlobalSchema();
264 if (module == null) {
265 final String errMsg = "Module with name '" + moduleNameAndRevision.getLocalName() + "' and revision '"
266 + moduleNameAndRevision.getRevision() + "' was not found.";
268 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
271 final Module restconfModule = getRestconfModule();
272 final Set<Module> modules = Collections.singleton(module);
273 final MapNode moduleMap = makeModuleMapNode(modules);
275 final DataSchemaNode moduleSchemaNode = this.controllerContext
276 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
277 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
279 return new NormalizedNodeContext(
280 new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint, schemaContext), moduleMap,
281 QueryParametersParser.parseWriterParameters(uriInfo));
285 public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
286 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
287 final Set<String> availableStreams = Notificator.getStreamNames();
288 final Module restconfModule = getRestconfModule();
289 final DataSchemaNode streamSchemaNode = this.controllerContext
290 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
291 Preconditions.checkState(streamSchemaNode instanceof ListSchemaNode);
293 final CollectionNodeBuilder<MapEntryNode, MapNode> listStreamsBuilder =
294 Builders.mapBuilder((ListSchemaNode) streamSchemaNode);
296 for (final String streamName : availableStreams) {
297 listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
300 final DataSchemaNode streamsContainerSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
301 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
302 Preconditions.checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
304 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
305 Builders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
306 streamsContainerBuilder.withChild(listStreamsBuilder.build());
308 return new NormalizedNodeContext(
309 new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null, schemaContext),
310 streamsContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
314 public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
315 final Set<Module> allModules = this.controllerContext.getAllModules();
316 return operationsFromModulesToNormalizedContext(allModules, null);
320 public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
321 Set<Module> modules = null;
322 DOMMountPoint mountPoint = null;
323 if (identifier.contains(ControllerContext.MOUNT)) {
324 final InstanceIdentifierContext<?> mountPointIdentifier =
325 this.controllerContext.toMountPointIdentifier(identifier);
326 mountPoint = mountPointIdentifier.getMountPoint();
327 modules = this.controllerContext.getAllModules(mountPoint);
330 final String errMsg =
331 "URI has bad format. If operations behind mount point should be showed, URI has to " + "end with ";
332 LOG.debug(errMsg + ControllerContext.MOUNT + " for " + identifier);
333 throw new RestconfDocumentedException(errMsg + ControllerContext.MOUNT, ErrorType.PROTOCOL,
334 ErrorTag.INVALID_VALUE);
337 return operationsFromModulesToNormalizedContext(modules, mountPoint);
341 * Special case only for GET restconf/operations use (since moment of
342 * pre-Beryllium Yang parser and Yang model API removal). The method is
343 * creating fake schema context with fake module and fake data by use own
344 * implementations of schema nodes and module.
347 * - set of modules for get RPCs from every module
349 * - mount point, if in use otherwise null
350 * @return {@link NormalizedNodeContext}
352 private static NormalizedNodeContext operationsFromModulesToNormalizedContext(final Set<Module> modules,
353 final DOMMountPoint mountPoint) {
355 final Collection<Module> neededModules = new ArrayList<>(modules.size());
356 final ArrayList<LeafSchemaNode> fakeRpcSchema = new ArrayList<>();
358 for (final Module m : modules) {
359 final Set<RpcDefinition> rpcs = m.getRpcs();
360 if (!rpcs.isEmpty()) {
361 neededModules.add(m);
363 fakeRpcSchema.ensureCapacity(fakeRpcSchema.size() + rpcs.size());
364 rpcs.forEach(rpc -> fakeRpcSchema.add(new FakeLeafSchemaNode(rpc.getQName())));
368 final ContainerSchemaNode fakeCont = new FakeContainerSchemaNode(fakeRpcSchema);
369 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> containerBuilder =
370 Builders.containerBuilder(fakeCont);
372 for (final LeafSchemaNode leaf : fakeRpcSchema) {
373 containerBuilder.withChild(Builders.leafBuilder(leaf).build());
376 final Collection<Module> fakeModules = new ArrayList<>(neededModules.size() + 1);
377 neededModules.forEach(imp -> fakeModules.add(new FakeImportedModule(imp)));
378 fakeModules.add(new FakeRestconfModule(neededModules, fakeCont));
380 final SchemaContext fakeSchemaCtx =
381 EffectiveSchemaContext.resolveSchemaContext(ImmutableSet.copyOf(fakeModules));
382 final InstanceIdentifierContext<ContainerSchemaNode> instanceIdentifierContext =
383 new InstanceIdentifierContext<>(null, fakeCont, mountPoint, fakeSchemaCtx);
384 return new NormalizedNodeContext(instanceIdentifierContext, containerBuilder.build());
387 private Module getRestconfModule() {
388 final Module restconfModule = this.controllerContext.getRestconfModule();
389 if (restconfModule == null) {
390 LOG.debug("ietf-restconf module was not found.");
391 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
392 ErrorTag.OPERATION_NOT_SUPPORTED);
395 return restconfModule;
398 private static QName getModuleNameAndRevision(final String identifier) {
399 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
400 String moduleNameAndRevision = "";
401 if (mountIndex >= 0) {
402 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
404 moduleNameAndRevision = identifier;
407 final Splitter splitter = Splitter.on("/").omitEmptyStrings();
408 final Iterable<String> split = splitter.split(moduleNameAndRevision);
409 final List<String> pathArgs = Lists.<String> newArrayList(split);
410 if (pathArgs.size() < 2) {
411 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
412 throw new RestconfDocumentedException(
413 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
414 ErrorTag.INVALID_VALUE);
418 final String moduleName = pathArgs.get(0);
419 final String revision = pathArgs.get(1);
420 final Date moduleRevision = SimpleDateFormatUtil.getRevisionFormat().parse(revision);
421 return QName.create(null, moduleRevision, moduleName);
422 } catch (final ParseException e) {
423 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
424 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
425 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
430 public Object getRoot() {
435 public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload,
436 final UriInfo uriInfo) {
437 final SchemaPath type = payload.getInstanceIdentifierContext().getSchemaNode().getPath();
438 final URI namespace = payload.getInstanceIdentifierContext().getSchemaNode().getQName().getNamespace();
439 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
440 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
441 final SchemaContext schemaContext;
443 if (mountPoint != null) {
444 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
445 if (!mountRpcServices.isPresent()) {
446 LOG.debug("Error: Rpc service is missing.");
447 throw new RestconfDocumentedException("Rpc service is missing.");
449 schemaContext = mountPoint.getSchemaContext();
450 response = mountRpcServices.get().invokeRpc(type, payload.getData());
452 if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
453 if (identifier.contains(CREATE_DATA_SUBSCR)) {
454 response = invokeSalRemoteRpcSubscribeRPC(payload);
455 } else if (identifier.contains(CREATE_NOTIFICATION_STREAM)) {
456 response = invokeSalRemoteRpcNotifiStrRPC(payload);
458 final String msg = "Not supported operation";
460 throw new RestconfDocumentedException(msg, ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED);
463 response = this.broker.invokeRpc(type, payload.getData());
465 schemaContext = this.controllerContext.getGlobalSchema();
468 final DOMRpcResult result = checkRpcResponse(response);
470 RpcDefinition resultNodeSchema = null;
471 final NormalizedNode<?, ?> resultData = result.getResult();
472 if (result != null && result.getResult() != null) {
473 resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
476 return new NormalizedNodeContext(
477 new InstanceIdentifierContext<>(null, resultNodeSchema, mountPoint, schemaContext),
478 resultData, QueryParametersParser.parseWriterParameters(uriInfo));
481 private static DOMRpcResult checkRpcResponse(final CheckedFuture<DOMRpcResult, DOMRpcException> response) {
482 if (response == null) {
486 final DOMRpcResult retValue = response.get();
487 if (retValue.getErrors() == null || retValue.getErrors().isEmpty()) {
490 LOG.debug("RpcError message", retValue.getErrors());
491 throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
492 } catch (final InterruptedException e) {
493 final String errMsg = "The operation was interrupted while executing and did not complete.";
494 LOG.debug("Rpc Interrupt - " + errMsg, e);
495 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
496 } catch (final ExecutionException e) {
497 LOG.debug("Execution RpcError: ", e);
498 Throwable cause = e.getCause();
500 while (cause.getCause() != null) {
501 cause = cause.getCause();
504 if (cause instanceof IllegalArgumentException) {
505 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL,
506 ErrorTag.INVALID_VALUE);
507 } else if (cause instanceof DOMRpcImplementationNotAvailableException) {
508 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.APPLICATION,
509 ErrorTag.OPERATION_NOT_SUPPORTED);
511 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
514 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
517 } catch (final CancellationException e) {
518 final String errMsg = "The operation was cancelled while executing.";
519 LOG.debug("Cancel RpcExecution: " + errMsg, e);
520 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
524 private static void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
525 if (inputSchema != null && payload.getData() == null) {
526 // expected a non null payload
527 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
528 } else if (inputSchema == null && payload.getData() != null) {
529 // did not expect any input
530 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
534 private CheckedFuture<DOMRpcResult, DOMRpcException>
535 invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
536 final ContainerNode value = (ContainerNode) payload.getData();
537 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
538 final Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(new NodeIdentifier(
539 QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(), "path")));
540 final Object pathValue = path.isPresent() ? path.get().getValue() : null;
542 if (!(pathValue instanceof YangInstanceIdentifier)) {
543 final String errMsg = "Instance identifier was not normalized correctly ";
544 LOG.debug(errMsg + rpcQName);
545 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
548 final YangInstanceIdentifier pathIdentifier = (YangInstanceIdentifier) pathValue;
549 String streamName = (String) CREATE_DATA_SUBSCR;
550 NotificationOutputType outputType = null;
551 if (!pathIdentifier.isEmpty()) {
552 final String fullRestconfIdentifier =
553 DATA_SUBSCR + this.controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
555 LogicalDatastoreType datastore =
556 parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
557 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
559 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
560 scope = scope == null ? DEFAULT_SCOPE : scope;
562 outputType = parseEnumTypeParameter(value, NotificationOutputType.class, OUTPUT_TYPE_PARAM_NAME);
563 outputType = outputType == null ? NotificationOutputType.XML : outputType;
565 streamName = Notificator
566 .createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore + "/scope=" + scope);
569 if (Strings.isNullOrEmpty(streamName)) {
570 final String errMsg = "Path is empty or contains value node which is not Container or List build-in type.";
571 LOG.debug(errMsg + pathIdentifier);
572 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
575 final QName outputQname = QName.create(rpcQName, "output");
576 final QName streamNameQname = QName.create(rpcQName, "stream-name");
578 final ContainerNode output =
579 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
580 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
582 if (!Notificator.existListenerFor(streamName)) {
583 Notificator.createListener(pathIdentifier, streamName, outputType);
586 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
588 return Futures.immediateCheckedFuture(defaultDOMRpcResult);
592 public NormalizedNodeContext invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
593 if (noPayload != null && !CharMatcher.WHITESPACE.matchesAllOf(noPayload)) {
594 throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
597 String identifierEncoded = null;
598 DOMMountPoint mountPoint = null;
599 final SchemaContext schemaContext;
600 if (identifier.contains(ControllerContext.MOUNT)) {
601 // mounted RPC call - look up mount instance.
602 final InstanceIdentifierContext<?> mountPointId = this.controllerContext.toMountPointIdentifier(identifier);
603 mountPoint = mountPointId.getMountPoint();
604 schemaContext = mountPoint.getSchemaContext();
605 final int startOfRemoteRpcName =
606 identifier.lastIndexOf(ControllerContext.MOUNT) + ControllerContext.MOUNT.length() + 1;
607 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
608 identifierEncoded = remoteRpcName;
610 } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
611 final String slashErrorMsg = String.format(
612 "Identifier %n%s%ncan\'t contain slash "
613 + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.",
615 LOG.debug(slashErrorMsg);
616 throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
618 identifierEncoded = identifier;
619 schemaContext = this.controllerContext.getGlobalSchema();
622 final String identifierDecoded = this.controllerContext.urlPathArgDecode(identifierEncoded);
624 RpcDefinition rpc = null;
625 if (mountPoint == null) {
626 rpc = this.controllerContext.getRpcDefinition(identifierDecoded, null);
628 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
632 LOG.debug("RPC " + identifierDecoded + " does not exist.");
633 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
636 if (!rpc.getInput().getChildNodes().isEmpty()) {
637 LOG.debug("RPC " + rpc + " does not need input value.");
638 // FIXME : find a correct Error from specification
639 throw new IllegalStateException("RPC " + rpc + " does'n need input value!");
642 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
643 if (mountPoint != null) {
644 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
645 if (!mountRpcServices.isPresent()) {
646 throw new RestconfDocumentedException("Rpc service is missing.");
648 response = mountRpcServices.get().invokeRpc(rpc.getPath(), null);
650 response = this.broker.invokeRpc(rpc.getPath(), null);
653 final DOMRpcResult result = checkRpcResponse(response);
655 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpc, mountPoint, schemaContext),
656 result.getResult(), QueryParametersParser.parseWriterParameters(uriInfo));
659 private static RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
660 final String[] splittedIdentifier = identifierDecoded.split(":");
661 if (splittedIdentifier.length != 2) {
662 final String errMsg = identifierDecoded + " couldn't be splitted to 2 parts (module:rpc name)";
664 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
666 for (final Module module : schemaContext.getModules()) {
667 if (module.getName().equals(splittedIdentifier[0])) {
668 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
669 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
670 return rpcDefinition;
679 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
680 boolean withDefa_used = false;
681 String withDefa = null;
683 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
684 switch (entry.getKey()) {
685 case "with-defaults":
686 if (!withDefa_used) {
687 withDefa_used = true;
688 withDefa = entry.getValue().iterator().next();
690 throw new RestconfDocumentedException("With-defaults parameter can be used only once.");
695 boolean tagged = false;
697 if (withDefa.equals("report-all-tagged")) {
701 if (withDefa.equals("report-all")) {
706 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
707 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
708 NormalizedNode<?, ?> data = null;
709 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
710 if (mountPoint != null) {
711 data = this.broker.readConfigurationData(mountPoint, normalizedII, withDefa);
713 data = this.broker.readConfigurationData(normalizedII, withDefa);
716 final String errMsg =
717 "Request could not be completed because the relevant data model content does not exist ";
718 LOG.debug(errMsg + identifier);
719 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
721 return new NormalizedNodeContext(iiWithData, data,
722 QueryParametersParser.parseWriterParameters(uriInfo, tagged));
726 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
727 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
728 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
729 NormalizedNode<?, ?> data = null;
730 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
731 if (mountPoint != null) {
732 data = this.broker.readOperationalData(mountPoint, normalizedII);
734 data = this.broker.readOperationalData(normalizedII);
737 final String errMsg =
738 "Request could not be completed because the relevant data model content does not exist ";
739 LOG.debug(errMsg + identifier);
740 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
742 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
746 public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload,
747 final UriInfo uriInfo) {
748 boolean insertUsed = false;
749 boolean pointUsed = false;
750 String insert = null;
753 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
754 switch (entry.getKey()) {
758 insert = entry.getValue().iterator().next();
760 throw new RestconfDocumentedException("Insert parameter can be used only once.");
766 point = entry.getValue().iterator().next();
768 throw new RestconfDocumentedException("Point parameter can be used only once.");
772 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
776 if (pointUsed && !insertUsed) {
777 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
779 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
780 throw new RestconfDocumentedException(
781 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
784 Preconditions.checkNotNull(identifier);
786 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
788 validateInput(iiWithData.getSchemaNode(), payload);
789 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
790 validateListKeysEqualityInPayloadAndUri(payload);
792 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
793 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
796 * There is a small window where another write transaction could be
797 * updating the same data simultaneously and we get an
798 * OptimisticLockFailedException. This error is likely transient and The
799 * WriteTransaction#submit API docs state that a retry will likely
800 * succeed. So we'll try again if that scenario occurs. If it fails a
801 * third time then it probably will never succeed so we'll fail in that
804 * By retrying we're attempting to hide the internal implementation of
805 * the data store and how it handles concurrent updates from the
806 * restconf client. The client has instructed us to put the data and we
807 * should make every effort to do so without pushing optimistic lock
808 * failures back to the client and forcing them to handle it via retry
809 * (and having to document the behavior).
811 PutResult result = null;
814 if (mountPoint != null) {
816 result = this.broker.commitMountPointDataPut(mountPoint, normalizedII, payload.getData(), insert,
819 result = this.broker.commitConfigurationDataPut(this.controllerContext.getGlobalSchema(), normalizedII,
820 payload.getData(), insert, point);
824 result.getFutureOfPutData().checkedGet();
825 return Response.status(result.getStatus()).build();
826 } catch (TransactionCommitFailedException e) {
827 if (e instanceof OptimisticLockFailedException) {
829 LOG.debug("Got OptimisticLockFailedException on last try - failing " + identifier);
830 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
833 LOG.debug("Got OptimisticLockFailedException - trying again " + identifier);
835 LOG.debug("Update failed for " + identifier, e);
836 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
842 private static void validateTopLevelNodeName(final NormalizedNodeContext node,
843 final YangInstanceIdentifier identifier) {
845 final String payloadName = node.getData().getNodeType().getLocalName();
848 if (identifier.isEmpty()) {
850 if (!node.getData().getNodeType().equals(NETCONF_BASE_QNAME)) {
851 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
852 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
856 final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
857 if (!payloadName.equals(identifierName)) {
858 throw new RestconfDocumentedException(
859 "Payload name (" + payloadName + ") is different from identifier name (" + identifierName + ")",
860 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
866 * Validates whether keys in {@code payload} are equal to values of keys in
867 * {@code iiWithData} for list schema node
869 * @throws RestconfDocumentedException
870 * if key values or key count in payload and URI isn't equal
873 private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
874 Preconditions.checkArgument(payload != null);
875 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
876 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
877 final SchemaNode schemaNode = iiWithData.getSchemaNode();
878 final NormalizedNode<?, ?> data = payload.getData();
879 if (schemaNode instanceof ListSchemaNode) {
880 final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
881 if (lastPathArgument instanceof NodeIdentifierWithPredicates && data instanceof MapEntryNode) {
882 final Map<QName, Object> uriKeyValues =
883 ((NodeIdentifierWithPredicates) lastPathArgument).getKeyValues();
884 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
889 private static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final MapEntryNode payload,
890 final List<QName> keyDefinitions) {
892 final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
893 for (final QName keyDefinition : keyDefinitions) {
894 final Object uriKeyValue = mutableCopyUriKeyValues.remove(keyDefinition);
895 // should be caught during parsing URI to InstanceIdentifier
896 RestconfValidationUtils.checkDocumentedError(uriKeyValue != null, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
897 "Missing key " + keyDefinition + " in URI.");
899 final Object dataKeyValue = payload.getIdentifier().getKeyValues().get(keyDefinition);
901 if (!uriKeyValue.equals(dataKeyValue)) {
902 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName()
903 + "' specified in the URI doesn't match the value '" + dataKeyValue
904 + "' specified in the message body. ";
905 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
911 public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload,
912 final UriInfo uriInfo) {
913 return createConfigurationData(payload, uriInfo);
916 // FIXME create RestconfIdetifierHelper and move this method there
917 private static YangInstanceIdentifier checkConsistencyOfNormalizedNodeContext(final NormalizedNodeContext payload) {
918 Preconditions.checkArgument(payload != null);
919 Preconditions.checkArgument(payload.getData() != null);
920 Preconditions.checkArgument(payload.getData().getNodeType() != null);
921 Preconditions.checkArgument(payload.getInstanceIdentifierContext() != null);
922 Preconditions.checkArgument(payload.getInstanceIdentifierContext().getInstanceIdentifier() != null);
924 final QName payloadNodeQname = payload.getData().getNodeType();
925 final YangInstanceIdentifier yangIdent = payload.getInstanceIdentifierContext().getInstanceIdentifier();
926 if (payloadNodeQname.compareTo(yangIdent.getLastPathArgument().getNodeType()) > 0) {
929 final InstanceIdentifierContext<?> parentContext = payload.getInstanceIdentifierContext();
930 final SchemaNode parentSchemaNode = parentContext.getSchemaNode();
931 if (parentSchemaNode instanceof DataNodeContainer) {
932 final DataNodeContainer cast = (DataNodeContainer) parentSchemaNode;
933 for (final DataSchemaNode child : cast.getChildNodes()) {
934 if (payloadNodeQname.compareTo(child.getQName()) == 0) {
935 return YangInstanceIdentifier.builder(yangIdent).node(child.getQName()).build();
939 if (parentSchemaNode instanceof RpcDefinition) {
942 final String errMsg = "Error parsing input: DataSchemaNode has not children ";
943 LOG.info(errMsg + yangIdent);
944 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
948 public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
949 if (payload == null) {
950 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
952 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
953 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
954 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
956 boolean insertUsed = false;
957 boolean pointUsed = false;
958 String insert = null;
961 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
962 switch (entry.getKey()) {
966 insert = entry.getValue().iterator().next();
968 throw new RestconfDocumentedException("Insert parameter can be used only once.");
974 point = entry.getValue().iterator().next();
976 throw new RestconfDocumentedException("Point parameter can be used only once.");
980 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
984 if (pointUsed && !insertUsed) {
985 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
987 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
988 throw new RestconfDocumentedException(
989 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
992 CheckedFuture<Void, TransactionCommitFailedException> future;
993 if (mountPoint != null) {
994 future = this.broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData(), insert,
997 future = this.broker.commitConfigurationDataPost(this.controllerContext.getGlobalSchema(), normalizedII,
998 payload.getData(), insert, point);
1002 future.checkedGet();
1003 } catch (final RestconfDocumentedException e) {
1005 } catch (TransactionCommitFailedException e) {
1006 LOG.info("Error creating data " + (uriInfo != null ? uriInfo.getPath() : ""), e);
1007 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
1010 LOG.trace("Successfuly created data.");
1012 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
1013 // FIXME: Provide path to result.
1014 final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
1015 if (location != null) {
1016 responseBuilder.location(location);
1018 return responseBuilder.build();
1021 private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint,
1022 final YangInstanceIdentifier normalizedII) {
1023 if (uriInfo == null) {
1024 // This is null if invoked internally
1028 final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
1029 uriBuilder.path("config");
1031 uriBuilder.path(this.controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
1032 } catch (final Exception e) {
1033 LOG.info("Location for instance identifier" + normalizedII + "wasn't created", e);
1036 return uriBuilder.build();
1040 public Response deleteConfigurationData(final String identifier) {
1041 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
1042 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
1043 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
1045 final CheckedFuture<Void, TransactionCommitFailedException> future;
1046 if (mountPoint != null) {
1047 future = this.broker.commitConfigurationDataDelete(mountPoint, normalizedII);
1049 future = this.broker.commitConfigurationDataDelete(normalizedII);
1053 future.checkedGet();
1054 } catch (TransactionCommitFailedException e) {
1055 final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
1056 Predicates.instanceOf(ModifiedNodeDoesNotExistException.class));
1057 if (searchedException.isPresent()) {
1058 throw new RestconfDocumentedException("Data specified for delete doesn't exist.", ErrorType.APPLICATION,
1059 ErrorTag.DATA_MISSING);
1062 final String errMsg = "Error while deleting data";
1063 LOG.info(errMsg, e);
1064 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
1067 return Response.status(Status.OK).build();
1071 * Subscribes to some path in schema context (stream) to listen on changes
1074 * Additional parameters for subscribing to stream are loaded via rpc input
1077 * <li>datastore - default CONFIGURATION (other values of
1078 * {@link LogicalDatastoreType} enum type)</li>
1079 * <li>scope - default BASE (other values of {@link DataChangeScope})</li>
1083 public NormalizedNodeContext subscribeToStream(final String identifier, final UriInfo uriInfo) {
1084 boolean startTime_used = false;
1085 boolean stopTime_used = false;
1086 boolean filter_used = false;
1089 String filter = null;
1091 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
1092 switch (entry.getKey()) {
1094 if (!startTime_used) {
1095 startTime_used = true;
1096 start = parseDateFromQueryParam(entry);
1098 throw new RestconfDocumentedException("Start-time parameter can be used only once.");
1102 if (!stopTime_used) {
1103 stopTime_used = true;
1104 stop = parseDateFromQueryParam(entry);
1106 throw new RestconfDocumentedException("Stop-time parameter can be used only once.");
1112 filter = entry.getValue().iterator().next();
1114 throw new RestconfDocumentedException("Filter parameter can be used only once.");
1118 throw new RestconfDocumentedException("Bad parameter used with notifications: " + entry.getKey());
1121 if (!startTime_used && stopTime_used) {
1122 throw new RestconfDocumentedException("Stop-time parameter has to be used with start-time parameter.");
1124 URI response = null;
1125 if (identifier.contains(DATA_SUBSCR)) {
1126 response = dataSubs(identifier, uriInfo, start, stop, filter);
1127 } else if (identifier.contains(NOTIFICATION_STREAM)) {
1128 response = notifStream(identifier, uriInfo, start, stop, filter);
1131 if (response != null) {
1132 // prepare node with value of location
1133 final InstanceIdentifierContext<?> iid = prepareIIDSubsStreamOutput();
1134 final NormalizedNodeAttrBuilder<NodeIdentifier, Object, LeafNode<Object>> builder =
1135 ImmutableLeafNodeBuilder.create().withValue(response.toString());
1136 builder.withNodeIdentifier(
1137 NodeIdentifier.create(QName.create("subscribe:to:notification", "2016-10-28", "location")));
1139 // prepare new header with location
1140 final Map<String, Object> headers = new HashMap<>();
1141 headers.put("Location", response);
1143 return new NormalizedNodeContext(iid, builder.build(), headers);
1146 final String msg = "Bad type of notification of sal-remote";
1148 throw new RestconfDocumentedException(msg);
1151 private static Date parseDateFromQueryParam(final Entry<String, List<String>> entry) {
1152 final DateAndTime event = new DateAndTime(entry.getValue().iterator().next());
1153 String numOf_ms = "";
1154 final String value = event.getValue();
1155 if (value.contains(".")) {
1156 numOf_ms = numOf_ms + ".";
1157 final int lastChar = value.contains("Z") ? value.indexOf("Z") : value.contains("+") ? value.indexOf("+")
1158 : value.contains("-") ? value.indexOf("-") : value.length();
1159 for (int i = 0; i < lastChar - value.indexOf(".") - 1; i++) {
1160 numOf_ms = numOf_ms + "S";
1164 if (!value.contains("Z")) {
1165 zone = zone + "XXX";
1167 final DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss" + numOf_ms + zone);
1170 return dateFormatter.parse(value.contains("Z") ? value.replace('T', ' ').substring(0, value.indexOf("Z"))
1171 : value.replace('T', ' '));
1172 } catch (final ParseException e) {
1173 throw new RestconfDocumentedException("Cannot parse of value in date: " + value + e);
1178 * @return {@link InstanceIdentifierContext} of location leaf for
1181 private static InstanceIdentifierContext<?> prepareIIDSubsStreamOutput() {
1182 final QName qnameBase = QName.create("subscribe:to:notification", "2016-10-28", "notifi");
1183 final SchemaContext schemaCtx = ControllerContext.getInstance().getGlobalSchema();
1184 final DataSchemaNode location = ((ContainerSchemaNode) schemaCtx
1185 .findModuleByNamespaceAndRevision(qnameBase.getNamespace(), qnameBase.getRevision())
1186 .getDataChildByName(qnameBase)).getDataChildByName(QName.create(qnameBase, "location"));
1187 final List<PathArgument> path = new ArrayList<>();
1188 path.add(NodeIdentifier.create(qnameBase));
1189 path.add(NodeIdentifier.create(QName.create(qnameBase, "location")));
1191 return new InstanceIdentifierContext<SchemaNode>(YangInstanceIdentifier.create(path), location, null,
1196 * Register notification listener by stream name
1203 * - stop-time of getting notification
1205 * - start-time of getting notification
1207 * - indicate wh ich subset of allpossible events are of interest
1208 * @return {@link URI} of location
1210 private URI notifStream(final String identifier, final UriInfo uriInfo, final Date start, final Date stop,
1211 final String filter) {
1212 final String streamName = Notificator.createStreamNameFromUri(identifier);
1213 if (Strings.isNullOrEmpty(streamName)) {
1214 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1216 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
1217 if (listeners == null || listeners.isEmpty()) {
1218 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1219 ErrorTag.UNKNOWN_ELEMENT);
1222 for (final NotificationListenerAdapter listener : listeners) {
1223 this.broker.registerToListenNotification(listener);
1224 listener.setQueryParams(start, stop, filter);
1227 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1228 int notificationPort = NOTIFICATION_PORT;
1230 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
1231 notificationPort = webSocketServerInstance.getPort();
1232 } catch (final NullPointerException e) {
1233 WebSocketServer.createInstance(NOTIFICATION_PORT);
1235 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1236 final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
1238 return uriToWebsocketServer;
1242 * Register data change listener by stream name
1249 * - start-time of getting notification
1251 * - stop-time of getting notification
1253 * - indicate which subset of all possible events are of interest
1254 * @return {@link URI} of location
1256 private URI dataSubs(final String identifier, final UriInfo uriInfo, final Date start, final Date stop,
1257 final String filter) {
1258 final String streamName = Notificator.createStreamNameFromUri(identifier);
1259 if (Strings.isNullOrEmpty(streamName)) {
1260 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1263 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1264 if (listener == null) {
1265 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1266 ErrorTag.UNKNOWN_ELEMENT);
1268 listener.setQueryParams(start, stop, filter);
1270 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1271 final LogicalDatastoreType datastore =
1272 parserURIEnumParameter(LogicalDatastoreType.class, paramToValues.get(DATASTORE_PARAM_NAME));
1273 if (datastore == null) {
1274 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1275 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1277 final DataChangeScope scope =
1278 parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
1279 if (scope == null) {
1280 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1281 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1284 this.broker.registerToListenDataChanges(datastore, scope, listener);
1286 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1287 int notificationPort = NOTIFICATION_PORT;
1289 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
1290 notificationPort = webSocketServerInstance.getPort();
1291 } catch (final NullPointerException e) {
1292 WebSocketServer.createInstance(NOTIFICATION_PORT);
1294 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1295 final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
1297 return uriToWebsocketServer;
1301 public PATCHStatusContext patchConfigurationData(final String identifier, final PATCHContext context,
1302 final UriInfo uriInfo) {
1303 if (context == null) {
1304 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1308 return this.broker.patchConfigurationDataWithinTransaction(context);
1309 } catch (final Exception e) {
1310 LOG.debug("Patch transaction failed", e);
1311 throw new RestconfDocumentedException(e.getMessage());
1316 public PATCHStatusContext patchConfigurationData(final PATCHContext context, @Context final UriInfo uriInfo) {
1317 if (context == null) {
1318 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1322 return this.broker.patchConfigurationDataWithinTransaction(context);
1323 } catch (final Exception e) {
1324 LOG.debug("Patch transaction failed", e);
1325 throw new RestconfDocumentedException(e.getMessage());
1330 * Load parameter for subscribing to stream from input composite node
1334 * @return enum object if its string value is equal to {@code paramName}. In
1337 private static <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1338 final String paramName) {
1339 final Optional<DataContainerChild<? extends PathArgument, ?>> augNode =
1340 value.getChild(SAL_REMOTE_AUG_IDENTIFIER);
1341 if (!augNode.isPresent() && !(augNode instanceof AugmentationNode)) {
1344 final Optional<DataContainerChild<? extends PathArgument, ?>> enumNode = ((AugmentationNode) augNode.get())
1345 .getChild(new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1346 if (!enumNode.isPresent()) {
1349 final Object rawValue = enumNode.get().getValue();
1350 if (!(rawValue instanceof String)) {
1354 return resolveAsEnum(classDescriptor, (String) rawValue);
1358 * Checks whether {@code value} is one of the string representation of
1359 * enumeration {@code classDescriptor}
1361 * @return enum object if string value of {@code classDescriptor}
1362 * enumeration is equal to {@code value}. Other cases null.
1364 private static <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1365 if (Strings.isNullOrEmpty(value)) {
1368 return resolveAsEnum(classDescriptor, value);
1371 private static <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1372 final T[] enumConstants = classDescriptor.getEnumConstants();
1373 if (enumConstants != null) {
1374 for (final T enm : classDescriptor.getEnumConstants()) {
1375 if (((Enum<?>) enm).name().equals(value)) {
1383 private static Map<String, String> resolveValuesFromUri(final String uri) {
1384 final Map<String, String> result = new HashMap<>();
1385 final String[] tokens = uri.split("/");
1386 for (int i = 1; i < tokens.length; i++) {
1387 final String[] parameterTokens = tokens[i].split("=");
1388 if (parameterTokens.length == 2) {
1389 result.put(parameterTokens[0], parameterTokens[1]);
1395 private MapNode makeModuleMapNode(final Set<Module> modules) {
1396 Preconditions.checkNotNull(modules);
1397 final Module restconfModule = getRestconfModule();
1398 final DataSchemaNode moduleSchemaNode = this.controllerContext
1399 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1400 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1402 final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder =
1403 Builders.mapBuilder((ListSchemaNode) moduleSchemaNode);
1405 for (final Module module : modules) {
1406 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1408 return listModuleBuilder.build();
1411 protected MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1412 Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1413 "moduleSchemaNode has to be of type ListSchemaNode");
1414 final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1415 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues =
1416 Builders.mapEntryBuilder(listModuleSchemaNode);
1418 List<DataSchemaNode> instanceDataChildrenByName =
1419 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "name");
1420 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1421 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1423 .withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName()).build());
1425 instanceDataChildrenByName =
1426 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "revision");
1427 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1428 Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1429 final String revision = module.getQNameModule().getFormattedRevision();
1431 .withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode).withValue(revision).build());
1433 instanceDataChildrenByName =
1434 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "namespace");
1435 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1436 Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1437 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1438 .withValue(module.getNamespace().toString()).build());
1440 instanceDataChildrenByName =
1441 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "feature");
1442 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1443 Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1444 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder =
1445 Builders.leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1446 for (final FeatureDefinition feature : module.getFeatures()) {
1447 featuresBuilder.withChild(Builders.leafSetEntryBuilder((LeafListSchemaNode) featureSchemaNode)
1448 .withValue(feature.getQName().getLocalName()).build());
1450 moduleNodeValues.withChild(featuresBuilder.build());
1452 return moduleNodeValues.build();
1455 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1456 Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1457 "streamSchemaNode has to be of type ListSchemaNode");
1458 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1459 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues =
1460 Builders.mapEntryBuilder(listStreamSchemaNode);
1462 List<DataSchemaNode> instanceDataChildrenByName =
1463 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "name");
1464 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1465 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1466 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName).build());
1468 instanceDataChildrenByName =
1469 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "description");
1470 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1471 Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1472 streamNodeValues.withChild(
1473 Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue("DESCRIPTION_PLACEHOLDER").build());
1475 instanceDataChildrenByName =
1476 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-support");
1477 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1478 Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1479 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1480 .withValue(Boolean.valueOf(true)).build());
1482 instanceDataChildrenByName =
1483 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-log-creation-time");
1484 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1485 Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1486 streamNodeValues.withChild(
1487 Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode).withValue("").build());
1489 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "events");
1490 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1491 Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1492 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode).withValue("").build());
1494 return streamNodeValues.build();
1498 * Prepare stream for notification
1501 * - contains list of qnames of notifications
1502 * @return - checked future object
1504 private static CheckedFuture<DOMRpcResult, DOMRpcException> invokeSalRemoteRpcNotifiStrRPC(
1505 final NormalizedNodeContext payload) {
1506 final ContainerNode data = (ContainerNode) payload.getData();
1507 LeafSetNode leafSet = null;
1508 String outputType = "XML";
1509 for (final DataContainerChild<? extends PathArgument, ?> dataChild : data.getValue()) {
1510 if (dataChild instanceof LeafSetNode) {
1511 leafSet = (LeafSetNode) dataChild;
1512 } else if (dataChild instanceof AugmentationNode) {
1513 outputType = (String) ((AugmentationNode) dataChild).getValue().iterator().next().getValue();
1517 final Collection<LeafSetEntryNode> entryNodes = leafSet.getValue();
1518 final List<SchemaPath> paths = new ArrayList<>();
1519 String streamName = CREATE_NOTIFICATION_STREAM + "/";
1521 final Iterator<LeafSetEntryNode> iterator = entryNodes.iterator();
1522 while (iterator.hasNext()) {
1523 final QName valueQName = QName.create((String) iterator.next().getValue());
1524 final Module module =
1525 ControllerContext.getInstance().findModuleByNamespace(valueQName.getModule().getNamespace());
1526 Preconditions.checkNotNull(module,
1527 "Module for namespace " + valueQName.getModule().getNamespace() + " does not exist");
1528 NotificationDefinition notifiDef = null;
1529 for (final NotificationDefinition notification : module.getNotifications()) {
1530 if (notification.getQName().equals(valueQName)) {
1531 notifiDef = notification;
1535 final String moduleName = module.getName();
1536 Preconditions.checkNotNull(notifiDef,
1537 "Notification " + valueQName + "doesn't exist in module " + moduleName);
1538 paths.add(notifiDef.getPath());
1539 streamName = streamName + moduleName + ":" + valueQName.getLocalName();
1540 if (iterator.hasNext()) {
1541 streamName = streamName + ",";
1545 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
1546 final QName outputQname = QName.create(rpcQName, "output");
1547 final QName streamNameQname = QName.create(rpcQName, "notification-stream-identifier");
1549 final ContainerNode output =
1550 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
1551 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
1553 if (!Notificator.existNotificationListenerFor(streamName)) {
1554 Notificator.createNotificationListener(paths, streamName, outputType);
1557 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
1559 return Futures.immediateCheckedFuture(defaultDOMRpcResult);