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.Splitter;
15 import com.google.common.base.Strings;
16 import com.google.common.collect.Iterables;
17 import com.google.common.collect.Lists;
18 import com.google.common.collect.Maps;
19 import com.google.common.collect.Sets;
20 import com.google.common.util.concurrent.CheckedFuture;
21 import com.google.common.util.concurrent.FutureCallback;
22 import com.google.common.util.concurrent.Futures;
24 import java.net.URISyntaxException;
25 import java.text.ParseException;
26 import java.text.SimpleDateFormat;
27 import java.util.ArrayList;
28 import java.util.Collection;
29 import java.util.Collections;
30 import java.util.Date;
31 import java.util.HashMap;
32 import java.util.HashSet;
33 import java.util.Iterator;
34 import java.util.List;
37 import java.util.concurrent.CancellationException;
38 import java.util.concurrent.CountDownLatch;
39 import java.util.concurrent.ExecutionException;
40 import javax.ws.rs.core.Context;
41 import javax.ws.rs.core.Response;
42 import javax.ws.rs.core.Response.ResponseBuilder;
43 import javax.ws.rs.core.Response.Status;
44 import javax.ws.rs.core.UriBuilder;
45 import javax.ws.rs.core.UriInfo;
46 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
47 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
48 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
49 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
50 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
51 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
52 import org.opendaylight.controller.md.sal.dom.api.DOMRpcImplementationNotAvailableException;
53 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
54 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
55 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
56 import org.opendaylight.netconf.md.sal.rest.common.RestconfValidationUtils;
57 import org.opendaylight.netconf.sal.rest.api.Draft02;
58 import org.opendaylight.netconf.sal.rest.api.RestconfService;
59 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
60 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
61 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
62 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
63 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
64 import org.opendaylight.netconf.sal.streams.websockets.WebSocketServer;
65 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
66 import org.opendaylight.yangtools.yang.common.QName;
67 import org.opendaylight.yangtools.yang.common.QNameModule;
68 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
69 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
70 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
71 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
72 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
73 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
74 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
75 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
76 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
77 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
78 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
79 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
80 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
81 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
82 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
83 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
84 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
85 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
86 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
87 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
88 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
89 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
90 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
91 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
92 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
93 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
94 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
95 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
96 import org.opendaylight.yangtools.yang.model.api.Module;
97 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
98 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
99 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
100 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
101 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
102 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.EffectiveSchemaContext;
103 import org.slf4j.Logger;
104 import org.slf4j.LoggerFactory;
106 public class RestconfImpl implements RestconfService {
108 private static final RestconfImpl INSTANCE = new RestconfImpl();
111 * Notifications are served on port 8181.
113 private static final int NOTIFICATION_PORT = 8181;
115 private static final int CHAR_NOT_FOUND = -1;
117 private static final SimpleDateFormat REVISION_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
119 private static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
121 private BrokerFacade broker;
123 private ControllerContext controllerContext;
125 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
127 private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
129 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
131 private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
133 private static final String DATASTORE_PARAM_NAME = "datastore";
135 private static final String SCOPE_PARAM_NAME = "scope";
137 private static final String OUTPUT_TYPE_PARAM_NAME = "notification-output-type";
139 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
141 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
143 private static final QName NETCONF_BASE_QNAME;
145 private static final QNameModule SAL_REMOTE_AUGMENT;
147 private static final YangInstanceIdentifier.AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER;
149 public static final CharSequence DATA_SUBSCR = "data-change-event-subscription";
150 private static final CharSequence CREATE_DATA_SUBSCR = "create-" + DATA_SUBSCR;
152 public static final CharSequence NOTIFICATION_STREAM = "notification-stream";
153 private static final CharSequence CREATE_NOTIFICATION_STREAM = "create-" + NOTIFICATION_STREAM;
157 final Date eventSubscriptionAugRevision = new SimpleDateFormat("yyyy-MM-dd").parse("2014-07-08");
158 NETCONF_BASE_QNAME = QName.create(QNameModule.create(new URI(NETCONF_BASE), null),
159 NETCONF_BASE_PAYLOAD_NAME);
160 SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
161 eventSubscriptionAugRevision);
162 SAL_REMOTE_AUG_IDENTIFIER = new YangInstanceIdentifier.AugmentationIdentifier(Sets.newHashSet(
163 QName.create(SAL_REMOTE_AUGMENT, "scope"),
164 QName.create(SAL_REMOTE_AUGMENT, "datastore"),
165 QName.create(SAL_REMOTE_AUGMENT, "notification-output-type")));
166 } catch (final ParseException e) {
167 final String errMsg = "It wasn't possible to convert revision date of sal-remote-augment to date";
169 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
170 } catch (final URISyntaxException e) {
171 final String errMsg = "It wasn't possible to create instance of URI class with "+NETCONF_BASE+" URI";
172 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
176 public void setBroker(final BrokerFacade broker) {
177 this.broker = broker;
180 public void setControllerContext(final ControllerContext controllerContext) {
181 this.controllerContext = controllerContext;
184 private RestconfImpl() {
187 public static RestconfImpl getInstance() {
192 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
193 final Set<Module> allModules = this.controllerContext.getAllModules();
194 final MapNode allModuleMap = makeModuleMapNode(allModules);
196 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
198 final Module restconfModule = getRestconfModule();
199 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
200 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
201 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
203 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
204 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
205 moduleContainerBuilder.withChild(allModuleMap);
207 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode,
208 null, schemaContext), moduleContainerBuilder.build(),
209 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 = this.controllerContext
226 .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(new InstanceIdentifierContext<>(null, modulesSchemaNode,
241 mountPoint, this.controllerContext.getGlobalSchema()), moduleContainerBuilder.build(),
242 QueryParametersParser.parseWriterParameters(uriInfo));
246 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
247 Preconditions.checkNotNull(identifier);
248 final QName moduleNameAndRevision = getModuleNameAndRevision(identifier);
249 Module module = null;
250 DOMMountPoint mountPoint = null;
251 final SchemaContext schemaContext;
252 if (identifier.contains(ControllerContext.MOUNT)) {
253 final InstanceIdentifierContext<?> mountPointIdentifier = this.controllerContext
254 .toMountPointIdentifier(identifier);
255 mountPoint = mountPointIdentifier.getMountPoint();
256 module = this.controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision);
257 schemaContext = mountPoint.getSchemaContext();
259 module = this.controllerContext.findModuleByNameAndRevision(moduleNameAndRevision);
260 schemaContext = this.controllerContext.getGlobalSchema();
263 if (module == null) {
264 final String errMsg = "Module with name '" + moduleNameAndRevision.getLocalName()
265 + "' and revision '" + moduleNameAndRevision.getRevision() + "' was not found.";
267 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
270 final Module restconfModule = getRestconfModule();
271 final Set<Module> modules = Collections.singleton(module);
272 final MapNode moduleMap = makeModuleMapNode(modules);
274 final DataSchemaNode moduleSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
275 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
276 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
278 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint,
279 schemaContext), moduleMap, QueryParametersParser.parseWriterParameters(uriInfo));
283 public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
284 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
285 final Set<String> availableStreams = Notificator.getStreamNames();
286 final Module restconfModule = getRestconfModule();
287 final DataSchemaNode streamSchemaNode = this.controllerContext
288 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
289 Preconditions.checkState(streamSchemaNode instanceof ListSchemaNode);
291 final CollectionNodeBuilder<MapEntryNode, MapNode> listStreamsBuilder = Builders
292 .mapBuilder((ListSchemaNode) streamSchemaNode);
294 for (final String streamName : availableStreams) {
295 listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
298 final DataSchemaNode streamsContainerSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
299 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
300 Preconditions.checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
302 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
303 Builders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
304 streamsContainerBuilder.withChild(listStreamsBuilder.build());
307 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null,
308 schemaContext), streamsContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
312 public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
313 final Set<Module> allModules = this.controllerContext.getAllModules();
314 return operationsFromModulesToNormalizedContext(allModules, null);
318 public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
319 Set<Module> modules = null;
320 DOMMountPoint mountPoint = null;
321 if (identifier.contains(ControllerContext.MOUNT)) {
322 final InstanceIdentifierContext<?> mountPointIdentifier = this.controllerContext
323 .toMountPointIdentifier(identifier);
324 mountPoint = mountPointIdentifier.getMountPoint();
325 modules = this.controllerContext.getAllModules(mountPoint);
328 final String errMsg = "URI has bad format. If operations behind mount point should be showed, URI has to "
330 LOG.debug(errMsg + ControllerContext.MOUNT + " for " + identifier);
331 throw new RestconfDocumentedException(errMsg + ControllerContext.MOUNT, ErrorType.PROTOCOL,
332 ErrorTag.INVALID_VALUE);
335 return operationsFromModulesToNormalizedContext(modules, mountPoint);
339 * Special case only for GET restconf/operations use (since moment of pre-Beryllium
340 * Yang parser and Yang model API removal). The method is creating fake
341 * schema context with fake module and fake data by use own implementations
342 * of schema nodes and module.
345 * - set of modules for get RPCs from every module
347 * - mount point, if in use otherwise null
348 * @return {@link NormalizedNodeContext}
350 private NormalizedNodeContext operationsFromModulesToNormalizedContext(final Set<Module> modules,
351 final DOMMountPoint mountPoint) {
353 final ContainerSchemaNodeImpl fakeCont = new ContainerSchemaNodeImpl();
354 final List<LeafNode<Object>> listRpcNodes = new ArrayList<>();
355 for (final Module m : modules) {
356 for (final RpcDefinition rpc : m.getRpcs()) {
358 final LeafSchemaNode fakeLeaf = new LeafSchemaNodeImpl(fakeCont.getPath(),
359 QName.create(ModuleImpl.moduleQName, m.getName() + ":" + rpc.getQName().getLocalName()));
360 fakeCont.addNodeChild(fakeLeaf);
361 listRpcNodes.add(Builders.leafBuilder(fakeLeaf).build());
364 final ContainerSchemaNode fakeContSchNode = fakeCont;
365 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> containerBuilder = Builders
366 .containerBuilder(fakeContSchNode);
368 for (final LeafNode<Object> rpcNode : listRpcNodes) {
369 containerBuilder.withChild(rpcNode);
372 final Module fakeModule = new ModuleImpl(fakeContSchNode);
374 final Set<Module> fakeModules = new HashSet<>();
375 fakeModules.add(fakeModule);
376 final SchemaContext fakeSchemaCtx = EffectiveSchemaContext.resolveSchemaContext(fakeModules);
377 final InstanceIdentifierContext<ContainerSchemaNode> instanceIdentifierContext =
378 new InstanceIdentifierContext<>(null, fakeContSchNode, mountPoint, fakeSchemaCtx);
379 return new NormalizedNodeContext(instanceIdentifierContext, containerBuilder.build());
382 private Module getRestconfModule() {
383 final Module restconfModule = this.controllerContext.getRestconfModule();
384 if (restconfModule == null) {
385 LOG.debug("ietf-restconf module was not found.");
386 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
387 ErrorTag.OPERATION_NOT_SUPPORTED);
390 return restconfModule;
393 private static QName getModuleNameAndRevision(final String identifier) {
394 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
395 String moduleNameAndRevision = "";
396 if (mountIndex >= 0) {
397 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
399 moduleNameAndRevision = identifier;
402 final Splitter splitter = Splitter.on("/").omitEmptyStrings();
403 final Iterable<String> split = splitter.split(moduleNameAndRevision);
404 final List<String> pathArgs = Lists.<String> newArrayList(split);
405 if (pathArgs.size() < 2) {
406 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
407 throw new RestconfDocumentedException(
408 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
409 ErrorTag.INVALID_VALUE);
413 final String moduleName = pathArgs.get(0);
414 final String revision = pathArgs.get(1);
415 final Date moduleRevision = REVISION_FORMAT.parse(revision);
416 return QName.create(null, moduleRevision, moduleName);
417 } catch (final ParseException e) {
418 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
419 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
420 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
425 public Object getRoot() {
430 public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload,
431 final UriInfo uriInfo) {
432 final SchemaPath type = payload.getInstanceIdentifierContext().getSchemaNode().getPath();
433 final URI namespace = payload.getInstanceIdentifierContext().getSchemaNode().getQName().getNamespace();
434 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
435 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
436 final SchemaContext schemaContext;
437 if (mountPoint != null) {
438 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
439 if ( ! mountRpcServices.isPresent()) {
440 LOG.debug("Error: Rpc service is missing.");
441 throw new RestconfDocumentedException("Rpc service is missing.");
443 schemaContext = mountPoint.getSchemaContext();
444 response = mountRpcServices.get().invokeRpc(type, payload.getData());
446 if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
447 if (identifier.contains(CREATE_DATA_SUBSCR)) {
448 response = invokeSalRemoteRpcSubscribeRPC(payload);
449 } else if (identifier.contains(CREATE_NOTIFICATION_STREAM)) {
450 response = invokeSalRemoteRpcNotifiStrRPC(payload);
452 final String msg = "Not supported operation";
454 throw new RestconfDocumentedException(msg, ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED);
457 response = this.broker.invokeRpc(type, payload.getData());
459 schemaContext = this.controllerContext.getGlobalSchema();
462 final DOMRpcResult result = checkRpcResponse(response);
464 RpcDefinition resultNodeSchema = null;
465 final NormalizedNode<?, ?> resultData = result.getResult();
466 if ((result != null) && (result.getResult() != null)) {
467 resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
470 return new NormalizedNodeContext(new InstanceIdentifierContext<RpcDefinition>(null,
471 resultNodeSchema, mountPoint, schemaContext), resultData,
472 QueryParametersParser.parseWriterParameters(uriInfo));
475 private static DOMRpcResult checkRpcResponse(final CheckedFuture<DOMRpcResult, DOMRpcException> response) {
476 if (response == null) {
480 final DOMRpcResult retValue = response.get();
481 if ((retValue.getErrors() == null) || retValue.getErrors().isEmpty()) {
484 LOG.debug("RpcError message", retValue.getErrors());
485 throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
486 } catch (final InterruptedException e) {
487 final String errMsg = "The operation was interrupted while executing and did not complete.";
488 LOG.debug("Rpc Interrupt - " + errMsg, e);
489 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
490 } catch (final ExecutionException e) {
491 LOG.debug("Execution RpcError: ", e);
492 Throwable cause = e.getCause();
494 while (cause.getCause() != null) {
495 cause = cause.getCause();
498 if (cause instanceof IllegalArgumentException) {
499 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL,
500 ErrorTag.INVALID_VALUE);
501 } else if (cause instanceof DOMRpcImplementationNotAvailableException) {
502 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.APPLICATION,
503 ErrorTag.OPERATION_NOT_SUPPORTED);
505 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
508 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
511 } catch (final CancellationException e) {
512 final String errMsg = "The operation was cancelled while executing.";
513 LOG.debug("Cancel RpcExecution: " + errMsg, e);
514 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
518 private static void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
519 if ((inputSchema != null) && (payload.getData() == null)) {
520 // expected a non null payload
521 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
522 } else if ((inputSchema == null) && (payload.getData() != null)) {
523 // did not expect any input
524 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
528 private CheckedFuture<DOMRpcResult, DOMRpcException>
529 invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
530 final ContainerNode value = (ContainerNode) payload.getData();
531 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
532 final Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(new NodeIdentifier(
533 QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(), "path")));
534 final Object pathValue = path.isPresent() ? path.get().getValue() : null;
536 if (!(pathValue instanceof YangInstanceIdentifier)) {
537 final String errMsg = "Instance identifier was not normalized correctly ";
538 LOG.debug(errMsg + rpcQName);
539 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
542 final YangInstanceIdentifier pathIdentifier = ((YangInstanceIdentifier) pathValue);
543 String streamName = (String) CREATE_DATA_SUBSCR;
544 NotificationOutputType outputType = null;
545 if (!pathIdentifier.isEmpty()) {
546 final String fullRestconfIdentifier = DATA_SUBSCR
547 + this.controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
549 LogicalDatastoreType datastore =
550 parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
551 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
553 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
554 scope = scope == null ? DEFAULT_SCOPE : scope;
556 outputType = parseEnumTypeParameter(value, NotificationOutputType.class,
557 OUTPUT_TYPE_PARAM_NAME);
558 outputType = outputType == null ? NotificationOutputType.XML : outputType;
560 streamName = Notificator.createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore
561 + "/scope=" + scope);
564 if (Strings.isNullOrEmpty(streamName)) {
565 final String errMsg = "Path is empty or contains value node which is not Container or List build-in type.";
566 LOG.debug(errMsg + pathIdentifier);
567 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
570 final QName outputQname = QName.create(rpcQName, "output");
571 final QName streamNameQname = QName.create(rpcQName, "stream-name");
573 final ContainerNode output =
574 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
575 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
577 if (!Notificator.existListenerFor(streamName)) {
578 Notificator.createListener(pathIdentifier, streamName, outputType);
581 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
583 return Futures.immediateCheckedFuture(defaultDOMRpcResult);
587 public NormalizedNodeContext invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
588 if ((noPayload != null) && !CharMatcher.WHITESPACE.matchesAllOf(noPayload)) {
589 throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
592 String identifierEncoded = null;
593 DOMMountPoint mountPoint = null;
594 final SchemaContext schemaContext;
595 if (identifier.contains(ControllerContext.MOUNT)) {
596 // mounted RPC call - look up mount instance.
597 final InstanceIdentifierContext<?> mountPointId = this.controllerContext.toMountPointIdentifier(identifier);
598 mountPoint = mountPointId.getMountPoint();
599 schemaContext = mountPoint.getSchemaContext();
600 final int startOfRemoteRpcName = identifier.lastIndexOf(ControllerContext.MOUNT)
601 + ControllerContext.MOUNT.length() + 1;
602 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
603 identifierEncoded = remoteRpcName;
605 } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
606 final String slashErrorMsg = String.format("Identifier %n%s%ncan\'t contain slash "
607 + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.", identifier);
608 LOG.debug(slashErrorMsg);
609 throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
611 identifierEncoded = identifier;
612 schemaContext = this.controllerContext.getGlobalSchema();
615 final String identifierDecoded = this.controllerContext.urlPathArgDecode(identifierEncoded);
617 RpcDefinition rpc = null;
618 if (mountPoint == null) {
619 rpc = this.controllerContext.getRpcDefinition(identifierDecoded, null);
621 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
625 LOG.debug("RPC " + identifierDecoded + " does not exist.");
626 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
629 if (rpc.getInput() != null) {
630 LOG.debug("RPC " + rpc + " does not need input value.");
631 // FIXME : find a correct Error from specification
632 throw new IllegalStateException("RPC " + rpc + " does'n need input value!");
635 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
636 if (mountPoint != null) {
637 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
638 if ( ! mountRpcServices.isPresent()) {
639 throw new RestconfDocumentedException("Rpc service is missing.");
641 response = mountRpcServices.get().invokeRpc(rpc.getPath(), null);
643 response = this.broker.invokeRpc(rpc.getPath(), null);
646 final DOMRpcResult result = checkRpcResponse(response);
648 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpc, mountPoint, schemaContext),
649 result.getResult(), QueryParametersParser.parseWriterParameters(uriInfo));
652 private static RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
653 final String[] splittedIdentifier = identifierDecoded.split(":");
654 if (splittedIdentifier.length != 2) {
655 final String errMsg = identifierDecoded + " couldn't be splitted to 2 parts (module:rpc name)";
657 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
659 for (final Module module : schemaContext.getModules()) {
660 if (module.getName().equals(splittedIdentifier[0])) {
661 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
662 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
663 return rpcDefinition;
672 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
673 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
674 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
675 NormalizedNode<?, ?> data = null;
676 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
677 if (mountPoint != null) {
678 data = this.broker.readConfigurationData(mountPoint, normalizedII);
680 data = this.broker.readConfigurationData(normalizedII);
683 final String errMsg = "Request could not be completed because the relevant data model content does not exist ";
684 LOG.debug(errMsg + identifier);
685 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
687 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
691 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
692 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
693 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
694 NormalizedNode<?, ?> data = null;
695 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
696 if (mountPoint != null) {
697 data = this.broker.readOperationalData(mountPoint, normalizedII);
699 data = this.broker.readOperationalData(normalizedII);
702 final String errMsg = "Request could not be completed because the relevant data model content does not exist ";
703 LOG.debug(errMsg + identifier);
704 throw new RestconfDocumentedException(errMsg , ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
706 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
710 public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload) {
711 Preconditions.checkNotNull(identifier);
712 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
714 validateInput(iiWithData.getSchemaNode(), payload);
715 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
716 validateListKeysEqualityInPayloadAndUri(payload);
718 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
719 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
722 * There is a small window where another write transaction could be updating the same data
723 * simultaneously and we get an OptimisticLockFailedException. This error is likely
724 * transient and The WriteTransaction#submit API docs state that a retry will likely
725 * succeed. So we'll try again if that scenario occurs. If it fails a third time then it
726 * probably will never succeed so we'll fail in that case.
728 * By retrying we're attempting to hide the internal implementation of the data store and
729 * how it handles concurrent updates from the restconf client. The client has instructed us
730 * to put the data and we should make every effort to do so without pushing optimistic lock
731 * failures back to the client and forcing them to handle it via retry (and having to
732 * document the behavior).
734 PutResult result = null;
735 final TryOfPutData tryPutData = new TryOfPutData();
737 if (mountPoint != null) {
739 result = this.broker.commitMountPointDataPut(mountPoint, normalizedII, payload.getData());
741 result = this.broker.commitConfigurationDataPut(this.controllerContext.getGlobalSchema(), normalizedII,
744 final CountDownLatch waiter = new CountDownLatch(1);
745 Futures.addCallback(result.getFutureOfPutData(), new FutureCallback<Void>() {
748 public void onSuccess(final Void result) {
749 handlingLoggerPut(null, tryPutData, identifier);
754 public void onFailure(final Throwable t) {
756 handlingLoggerPut(t, tryPutData, identifier);
762 } catch (final Exception e) {
763 final String msg = "Problem while waiting for response";
765 throw new RestconfDocumentedException(msg, e);
768 if(tryPutData.isDone()){
771 throw new RestconfDocumentedException("Problem while PUT operations");
775 return Response.status(result.getStatus()).build();
778 protected void handlingLoggerPut(final Throwable t, final TryOfPutData tryPutData, final String identifier) {
780 if (t instanceof OptimisticLockFailedException) {
781 if (tryPutData.countGet() <= 0) {
782 LOG.debug("Got OptimisticLockFailedException on last try - failing " + identifier);
783 throw new RestconfDocumentedException(t.getMessage(), t);
785 LOG.debug("Got OptimisticLockFailedException - trying again " + identifier);
786 tryPutData.countDown();
788 LOG.debug("Update ConfigDataStore fail " + identifier, t);
789 throw new RestconfDocumentedException(t.getMessage(), t);
792 LOG.trace("PUT Successful " + identifier);
797 private static void validateTopLevelNodeName(final NormalizedNodeContext node,
798 final YangInstanceIdentifier identifier) {
800 final String payloadName = node.getData().getNodeType().getLocalName();
803 if (identifier.isEmpty()) {
805 if (!node.getData().getNodeType().equals(NETCONF_BASE_QNAME)) {
806 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
807 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
811 final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
812 if (!payloadName.equals(identifierName)) {
813 throw new RestconfDocumentedException("Payload name (" + payloadName
814 + ") is different from identifier name (" + identifierName + ")", ErrorType.PROTOCOL,
815 ErrorTag.MALFORMED_MESSAGE);
821 * Validates whether keys in {@code payload} are equal to values of keys in {@code iiWithData} for list schema node
823 * @throws RestconfDocumentedException
824 * if key values or key count in payload and URI isn't equal
827 private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
828 Preconditions.checkArgument(payload != null);
829 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
830 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
831 final SchemaNode schemaNode = iiWithData.getSchemaNode();
832 final NormalizedNode<?, ?> data = payload.getData();
833 if (schemaNode instanceof ListSchemaNode) {
834 final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
835 if ((lastPathArgument instanceof NodeIdentifierWithPredicates) && (data instanceof MapEntryNode)) {
836 final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument).getKeyValues();
837 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
842 private static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues,
843 final MapEntryNode payload, final List<QName> keyDefinitions) {
845 final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
846 for (final QName keyDefinition : keyDefinitions) {
847 final Object uriKeyValue = mutableCopyUriKeyValues.remove(keyDefinition);
848 // should be caught during parsing URI to InstanceIdentifier
849 RestconfValidationUtils.checkDocumentedError(uriKeyValue != null, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
850 "Missing key " + keyDefinition + " in URI.");
852 final Object dataKeyValue = payload.getIdentifier().getKeyValues().get(keyDefinition);
854 if ( ! uriKeyValue.equals(dataKeyValue)) {
855 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName() +
856 "' specified in the URI doesn't match the value '" + dataKeyValue
857 + "' specified in the message body. ";
858 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
864 public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload,
865 final UriInfo uriInfo) {
866 return createConfigurationData(payload, uriInfo);
869 // FIXME create RestconfIdetifierHelper and move this method there
870 private static YangInstanceIdentifier checkConsistencyOfNormalizedNodeContext(final NormalizedNodeContext payload) {
871 Preconditions.checkArgument(payload != null);
872 Preconditions.checkArgument(payload.getData() != null);
873 Preconditions.checkArgument(payload.getData().getNodeType() != null);
874 Preconditions.checkArgument(payload.getInstanceIdentifierContext() != null);
875 Preconditions.checkArgument(payload.getInstanceIdentifierContext().getInstanceIdentifier() != null);
877 final QName payloadNodeQname = payload.getData().getNodeType();
878 final YangInstanceIdentifier yangIdent = payload.getInstanceIdentifierContext().getInstanceIdentifier();
879 if (payloadNodeQname.compareTo(yangIdent.getLastPathArgument().getNodeType()) > 0) {
882 final InstanceIdentifierContext<?> parentContext = payload.getInstanceIdentifierContext();
883 final SchemaNode parentSchemaNode = parentContext.getSchemaNode();
884 if(parentSchemaNode instanceof DataNodeContainer) {
885 final DataNodeContainer cast = (DataNodeContainer) parentSchemaNode;
886 for (final DataSchemaNode child : cast.getChildNodes()) {
887 if (payloadNodeQname.compareTo(child.getQName()) == 0) {
888 return YangInstanceIdentifier.builder(yangIdent).node(child.getQName()).build();
892 if (parentSchemaNode instanceof RpcDefinition) {
895 final String errMsg = "Error parsing input: DataSchemaNode has not children ";
896 LOG.info(errMsg + yangIdent);
897 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
901 public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
902 if (payload == null) {
903 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
906 // FIXME: move this to parsing stage (we can have augmentation nodes here which do not have namespace)
907 // final URI payloadNS = payload.getData().getNodeType().getNamespace();
908 // if (payloadNS == null) {
909 // throw new RestconfDocumentedException(
910 // "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
911 // ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
914 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
915 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
916 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
918 CheckedFuture<Void, TransactionCommitFailedException> future;
919 if (mountPoint != null) {
920 future = this.broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData());
922 future = this.broker.commitConfigurationDataPost(this.controllerContext.getGlobalSchema(), normalizedII,
926 final CountDownLatch waiter = new CountDownLatch(1);
927 Futures.addCallback(future, new FutureCallback<Void>() {
930 public void onSuccess(final Void result) {
931 handlerLoggerPost(null, uriInfo);
936 public void onFailure(final Throwable t) {
938 handlerLoggerPost(t, uriInfo);
944 } catch (final Exception e) {
945 final String msg = "Problem while waiting for response";
947 throw new RestconfDocumentedException(msg, e);
950 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
951 // FIXME: Provide path to result.
952 final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
953 if (location != null) {
954 responseBuilder.location(location);
956 return responseBuilder.build();
959 protected void handlerLoggerPost(final Throwable t, final UriInfo uriInfo) {
961 final String errMsg = "Error creating data ";
962 LOG.warn(errMsg + (uriInfo != null ? uriInfo.getPath() : ""), t);
963 throw new RestconfDocumentedException(errMsg, t);
965 LOG.trace("Successfuly create data.");
969 private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint,
970 final YangInstanceIdentifier normalizedII) {
971 if(uriInfo == null) {
972 // This is null if invoked internally
976 final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
977 uriBuilder.path("config");
979 uriBuilder.path(this.controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
980 } catch (final Exception e) {
981 LOG.info("Location for instance identifier" + normalizedII + "wasn't created", e);
984 return uriBuilder.build();
988 public Response deleteConfigurationData(final String identifier) {
989 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
990 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
991 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
993 final CheckedFuture<Void, TransactionCommitFailedException> future;
994 if (mountPoint != null) {
995 future = this.broker.commitConfigurationDataDelete(mountPoint, normalizedII);
997 future = this.broker.commitConfigurationDataDelete(normalizedII);
1000 final CountDownLatch waiter = new CountDownLatch(1);
1001 Futures.addCallback(future, new FutureCallback<Void>() {
1004 public void onSuccess(final Void result) {
1005 handlerLoggerDelete(null);
1010 public void onFailure(final Throwable t) {
1012 handlerLoggerDelete(t);
1019 } catch (final Exception e) {
1020 final String msg = "Problem while waiting for response";
1022 throw new RestconfDocumentedException(msg, e);
1025 return Response.status(Status.OK).build();
1028 protected void handlerLoggerDelete(final Throwable t) {
1030 final String errMsg = "Error while deleting data";
1031 LOG.info(errMsg, t);
1032 throw new RestconfDocumentedException(errMsg, t);
1034 LOG.trace("Successfuly delete data.");
1039 * Subscribes to some path in schema context (stream) to listen on changes on this stream.
1041 * Additional parameters for subscribing to stream are loaded via rpc input parameters:
1043 * <li>datastore - default CONFIGURATION (other values of {@link LogicalDatastoreType} enum type)</li>
1044 * <li>scope - default BASE (other values of {@link DataChangeScope})</li>
1048 public NormalizedNodeContext subscribeToStream(final String identifier, final UriInfo uriInfo) {
1049 URI response = null;
1050 if (identifier.contains(DATA_SUBSCR)) {
1051 response = dataSubs(identifier, uriInfo);
1052 } else if (identifier.contains(NOTIFICATION_STREAM)) {
1053 response = notifStream(identifier, uriInfo);
1056 if(response != null){
1057 // prepare node with value of location
1058 final InstanceIdentifierContext<?> iid = prepareIIDSubsStreamOutput();
1059 final NormalizedNodeAttrBuilder<NodeIdentifier, Object, LeafNode<Object>> builder = ImmutableLeafNodeBuilder
1060 .create().withValue(response.toString());
1061 builder.withNodeIdentifier(
1062 NodeIdentifier.create(QName.create("subscribe:to:notification", "2016-10-28", "location")));
1064 // prepare new header with location
1065 final Map<String, Object> headers = new HashMap<>();
1066 headers.put("Location", response);
1068 return new NormalizedNodeContext(iid, builder.build(), headers);
1071 final String msg = "Bad type of notification of sal-remote";
1073 throw new RestconfDocumentedException(msg);
1077 * @return {@link InstanceIdentifierContext} of location leaf for
1080 private InstanceIdentifierContext<?> prepareIIDSubsStreamOutput() {
1081 final QName qnameBase = QName.create("subscribe:to:notification", "2016-10-28", "notifi");
1082 final SchemaContext schemaCtx = ControllerContext.getInstance().getGlobalSchema();
1083 final DataSchemaNode location = ((ContainerSchemaNode) schemaCtx
1084 .findModuleByNamespaceAndRevision(qnameBase.getNamespace(), qnameBase.getRevision())
1085 .getDataChildByName(qnameBase)).getDataChildByName(QName.create(qnameBase, "location"));
1086 final List<PathArgument> path = new ArrayList<>();
1087 path.add(NodeIdentifier.create(qnameBase));
1088 path.add(NodeIdentifier.create(QName.create(qnameBase, "location")));
1090 return new InstanceIdentifierContext<SchemaNode>(YangInstanceIdentifier.create(path), location, null,
1095 * Register notification listener by stream name
1101 * @return {@link Response}
1103 private URI notifStream(final String identifier, final UriInfo uriInfo) {
1104 final String streamName = Notificator.createStreamNameFromUri(identifier);
1105 if (Strings.isNullOrEmpty(streamName)) {
1106 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1108 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
1109 if ((listeners == null) || listeners.isEmpty()) {
1110 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1111 ErrorTag.UNKNOWN_ELEMENT);
1114 for (final NotificationListenerAdapter listener : listeners) {
1115 this.broker.registerToListenNotification(listener);
1118 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1119 int notificationPort = NOTIFICATION_PORT;
1121 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
1122 notificationPort = webSocketServerInstance.getPort();
1123 } catch (final NullPointerException e) {
1124 WebSocketServer.createInstance(NOTIFICATION_PORT);
1126 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1127 final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
1129 return uriToWebsocketServer;
1133 * Register data change listener by stream name
1139 * @return {@link Response}
1141 private URI dataSubs(final String identifier, final UriInfo uriInfo) {
1142 final String streamName = Notificator.createStreamNameFromUri(identifier);
1143 if (Strings.isNullOrEmpty(streamName)) {
1144 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1147 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1148 if (listener == null) {
1149 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
1152 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1153 final LogicalDatastoreType datastore = parserURIEnumParameter(LogicalDatastoreType.class,
1154 paramToValues.get(DATASTORE_PARAM_NAME));
1155 if (datastore == null) {
1156 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1157 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1159 final DataChangeScope scope = parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
1160 if (scope == null) {
1161 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1162 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1165 this.broker.registerToListenDataChanges(datastore, scope, listener);
1167 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1168 int notificationPort = NOTIFICATION_PORT;
1170 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
1171 notificationPort = webSocketServerInstance.getPort();
1172 } catch (final NullPointerException e) {
1173 WebSocketServer.createInstance(NOTIFICATION_PORT);
1175 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1176 final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
1178 return uriToWebsocketServer;
1182 public PATCHStatusContext patchConfigurationData(final String identifier, final PATCHContext context,
1183 final UriInfo uriInfo) {
1184 if (context == null) {
1185 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1189 return this.broker.patchConfigurationDataWithinTransaction(context);
1190 } catch (final Exception e) {
1191 LOG.debug("Patch transaction failed", e);
1192 throw new RestconfDocumentedException(e.getMessage());
1197 public PATCHStatusContext patchConfigurationData(final PATCHContext context, @Context final UriInfo uriInfo) {
1198 if (context == null) {
1199 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1203 return this.broker.patchConfigurationDataWithinTransaction(context);
1204 } catch (final Exception e) {
1205 LOG.debug("Patch transaction failed", e);
1206 throw new RestconfDocumentedException(e.getMessage());
1211 * Load parameter for subscribing to stream from input composite node
1215 * @return enum object if its string value is equal to {@code paramName}. In other cases null.
1217 private static <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1218 final String paramName) {
1219 final Optional<DataContainerChild<? extends PathArgument, ?>> augNode = value.getChild(SAL_REMOTE_AUG_IDENTIFIER);
1220 if (!augNode.isPresent() && !(augNode instanceof AugmentationNode)) {
1223 final Optional<DataContainerChild<? extends PathArgument, ?>> enumNode =
1224 ((AugmentationNode) augNode.get())
1225 .getChild(new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1226 if (!enumNode.isPresent()) {
1229 final Object rawValue = enumNode.get().getValue();
1230 if (!(rawValue instanceof String)) {
1234 return resolveAsEnum(classDescriptor, (String) rawValue);
1238 * Checks whether {@code value} is one of the string representation of enumeration {@code classDescriptor}
1240 * @return enum object if string value of {@code classDescriptor} enumeration is equal to {@code value}. Other cases
1243 private static <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1244 if (Strings.isNullOrEmpty(value)) {
1247 return resolveAsEnum(classDescriptor, value);
1250 private static <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1251 final T[] enumConstants = classDescriptor.getEnumConstants();
1252 if (enumConstants != null) {
1253 for (final T enm : classDescriptor.getEnumConstants()) {
1254 if (((Enum<?>) enm).name().equals(value)) {
1262 private static Map<String, String> resolveValuesFromUri(final String uri) {
1263 final Map<String, String> result = new HashMap<>();
1264 final String[] tokens = uri.split("/");
1265 for (int i = 1; i < tokens.length; i++) {
1266 final String[] parameterTokens = tokens[i].split("=");
1267 if (parameterTokens.length == 2) {
1268 result.put(parameterTokens[0], parameterTokens[1]);
1274 private MapNode makeModuleMapNode(final Set<Module> modules) {
1275 Preconditions.checkNotNull(modules);
1276 final Module restconfModule = getRestconfModule();
1277 final DataSchemaNode moduleSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
1278 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1279 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1281 final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder = Builders
1282 .mapBuilder((ListSchemaNode) moduleSchemaNode);
1284 for (final Module module : modules) {
1285 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1287 return listModuleBuilder.build();
1290 protected MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1291 Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1292 "moduleSchemaNode has to be of type ListSchemaNode");
1293 final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1294 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues = Builders
1295 .mapEntryBuilder(listModuleSchemaNode);
1297 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1298 (listModuleSchemaNode), "name");
1299 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1300 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1301 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName())
1304 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1305 (listModuleSchemaNode), "revision");
1306 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1307 Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1308 final String revision = REVISION_FORMAT.format(module.getRevision());
1309 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode).withValue(revision)
1312 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1313 (listModuleSchemaNode), "namespace");
1314 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1315 Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1316 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1317 .withValue(module.getNamespace().toString()).build());
1319 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1320 (listModuleSchemaNode), "feature");
1321 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1322 Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1323 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder = Builders
1324 .leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1325 for (final FeatureDefinition feature : module.getFeatures()) {
1326 featuresBuilder.withChild(Builders.leafSetEntryBuilder(((LeafListSchemaNode) featureSchemaNode))
1327 .withValue(feature.getQName().getLocalName()).build());
1329 moduleNodeValues.withChild(featuresBuilder.build());
1331 return moduleNodeValues.build();
1334 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1335 Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1336 "streamSchemaNode has to be of type ListSchemaNode");
1337 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1338 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues = Builders
1339 .mapEntryBuilder(listStreamSchemaNode);
1341 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1342 (listStreamSchemaNode), "name");
1343 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1344 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1345 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName)
1348 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1349 (listStreamSchemaNode), "description");
1350 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1351 Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1352 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode)
1353 .withValue("DESCRIPTION_PLACEHOLDER").build());
1355 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1356 (listStreamSchemaNode), "replay-support");
1357 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1358 Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1359 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1360 .withValue(Boolean.valueOf(true)).build());
1362 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1363 (listStreamSchemaNode), "replay-log-creation-time");
1364 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1365 Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1366 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode)
1367 .withValue("").build());
1369 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1370 (listStreamSchemaNode), "events");
1371 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1372 Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1373 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode)
1374 .withValue("").build());
1376 return streamNodeValues.build();
1380 * Prepare stream for notification
1383 * - contains list of qnames of notifications
1384 * @return - checked future object
1386 private CheckedFuture<DOMRpcResult, DOMRpcException> invokeSalRemoteRpcNotifiStrRPC(
1387 final NormalizedNodeContext payload) {
1388 final ContainerNode data = (ContainerNode) payload.getData();
1389 LeafSetNode leafSet = null;
1390 String outputType = "XML";
1391 for (final DataContainerChild<? extends PathArgument, ?> dataChild : data.getValue()) {
1392 if (dataChild instanceof LeafSetNode) {
1393 leafSet = (LeafSetNode) dataChild;
1394 } else if (dataChild instanceof AugmentationNode) {
1395 outputType = (String) (((AugmentationNode) dataChild).getValue()).iterator().next().getValue();
1399 final Collection<LeafSetEntryNode> entryNodes = leafSet.getValue();
1400 final List<SchemaPath> paths = new ArrayList<>();
1401 String streamName = CREATE_NOTIFICATION_STREAM + "/";
1403 final Iterator<LeafSetEntryNode> iterator = entryNodes.iterator();
1404 while (iterator.hasNext()) {
1405 final QName valueQName = QName.create((String) iterator.next().getValue());
1406 final Module module = ControllerContext.getInstance()
1407 .findModuleByNamespace(valueQName.getModule().getNamespace());
1408 Preconditions.checkNotNull(module, "Module for namespace " + valueQName.getModule().getNamespace()
1409 + " does not exist");
1410 NotificationDefinition notifiDef = null;
1411 for (final NotificationDefinition notification : module.getNotifications()) {
1412 if (notification.getQName().equals(valueQName)) {
1413 notifiDef = notification;
1417 final String moduleName = module.getName();
1418 Preconditions.checkNotNull(notifiDef,
1419 "Notification " + valueQName + "doesn't exist in module " + moduleName);
1420 paths.add(notifiDef.getPath());
1421 streamName = streamName + moduleName + ":" + valueQName.getLocalName();
1422 if (iterator.hasNext()) {
1423 streamName = streamName + ",";
1427 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
1428 final QName outputQname = QName.create(rpcQName, "output");
1429 final QName streamNameQname = QName.create(rpcQName, "notification-stream-identifier");
1431 final ContainerNode output = ImmutableContainerNodeBuilder.create()
1432 .withNodeIdentifier(new NodeIdentifier(outputQname))
1433 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
1435 if (!Notificator.existNotificationListenerFor(streamName)) {
1436 Notificator.createNotificationListener(paths, streamName, outputType);
1439 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
1441 return Futures.immediateCheckedFuture(defaultDOMRpcResult);
1444 private class TryOfPutData {
1446 boolean done = false;