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.Iterables;
19 import com.google.common.collect.Lists;
20 import com.google.common.collect.Maps;
21 import com.google.common.collect.Sets;
22 import com.google.common.util.concurrent.CheckedFuture;
23 import com.google.common.util.concurrent.FutureCallback;
24 import com.google.common.util.concurrent.Futures;
25 import java.math.BigInteger;
27 import java.net.URISyntaxException;
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;
39 import java.util.concurrent.CancellationException;
40 import java.util.concurrent.CountDownLatch;
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.yangtools.yang.common.QName;
68 import org.opendaylight.yangtools.yang.common.QNameModule;
69 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
70 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
71 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
72 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
73 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
74 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
75 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
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.api.schema.tree.ModifiedNodeDoesNotExistException;
82 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
83 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
84 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
85 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
86 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
87 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
88 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
90 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
91 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
92 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
93 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
94 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
95 import org.opendaylight.yangtools.yang.model.api.Module;
96 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
97 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
98 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
99 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
100 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
101 import org.slf4j.Logger;
102 import org.slf4j.LoggerFactory;
104 public class RestconfImpl implements RestconfService {
106 private static final RestconfImpl INSTANCE = new RestconfImpl();
109 * Notifications are served on port 8181.
111 private static final int NOTIFICATION_PORT = 8181;
113 private static final int CHAR_NOT_FOUND = -1;
115 private static final SimpleDateFormat REVISION_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
117 private static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
119 private BrokerFacade broker;
121 private ControllerContext controllerContext;
123 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
125 private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
127 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
129 private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
131 private static final String DATASTORE_PARAM_NAME = "datastore";
133 private static final String SCOPE_PARAM_NAME = "scope";
135 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
137 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
139 private static final QName NETCONF_BASE_QNAME;
141 private static final QNameModule SAL_REMOTE_AUGMENT;
143 private static final YangInstanceIdentifier.AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER;
145 public static final CharSequence DATA_SUBSCR = "data-change-event-subscription";
146 private static final CharSequence CREATE_DATA_SUBSCR = "create-" + DATA_SUBSCR;
148 public static final CharSequence NOTIFICATION_STREAM = "notification-stream";
149 private static final CharSequence CREATE_NOTIFICATION_STREAM = "create-" + NOTIFICATION_STREAM;
153 final Date eventSubscriptionAugRevision = new SimpleDateFormat("yyyy-MM-dd").parse("2014-07-08");
154 NETCONF_BASE_QNAME = QName.create(QNameModule.create(new URI(NETCONF_BASE), null), NETCONF_BASE_PAYLOAD_NAME );
155 SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
156 eventSubscriptionAugRevision);
157 SAL_REMOTE_AUG_IDENTIFIER = new YangInstanceIdentifier.AugmentationIdentifier(Sets.newHashSet(QName.create(SAL_REMOTE_AUGMENT, "scope"),
158 QName.create(SAL_REMOTE_AUGMENT, "datastore")));
159 } catch (final ParseException e) {
160 final String errMsg = "It wasn't possible to convert revision date of sal-remote-augment to date";
162 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
163 } catch (final URISyntaxException e) {
164 final String errMsg = "It wasn't possible to create instance of URI class with "+NETCONF_BASE+" URI";
165 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
169 public void setBroker(final BrokerFacade broker) {
170 this.broker = broker;
173 public void setControllerContext(final ControllerContext controllerContext) {
174 this.controllerContext = controllerContext;
177 private RestconfImpl() {
180 public static RestconfImpl getInstance() {
185 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
186 final Set<Module> allModules = this.controllerContext.getAllModules();
187 final MapNode allModuleMap = makeModuleMapNode(allModules);
189 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
191 final Module restconfModule = getRestconfModule();
192 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
193 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
194 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
196 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
197 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
198 moduleContainerBuilder.withChild(allModuleMap);
200 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode,
201 null, schemaContext), moduleContainerBuilder.build(),
202 QueryParametersParser.parseWriterParameters(uriInfo));
206 * Valid only for mount point
209 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
210 Preconditions.checkNotNull(identifier);
211 if ( ! identifier.contains(ControllerContext.MOUNT)) {
212 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
213 + " URI has to end with " + ControllerContext.MOUNT;
214 LOG.debug(errMsg + " for " + identifier);
215 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
218 final InstanceIdentifierContext<?> mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier);
219 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
220 final Set<Module> modules = this.controllerContext.getAllModules(mountPoint);
221 final MapNode mountPointModulesMap = makeModuleMapNode(modules);
223 final Module restconfModule = getRestconfModule();
224 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
225 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
226 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
228 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
229 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
230 moduleContainerBuilder.withChild(mountPointModulesMap);
232 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode,
233 mountPoint, this.controllerContext.getGlobalSchema()), moduleContainerBuilder.build(),
234 QueryParametersParser.parseWriterParameters(uriInfo));
238 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
239 Preconditions.checkNotNull(identifier);
240 final QName moduleNameAndRevision = getModuleNameAndRevision(identifier);
241 Module module = null;
242 DOMMountPoint mountPoint = null;
243 final SchemaContext schemaContext;
244 if (identifier.contains(ControllerContext.MOUNT)) {
245 final InstanceIdentifierContext<?> mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier);
246 mountPoint = mountPointIdentifier.getMountPoint();
247 module = this.controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision);
248 schemaContext = mountPoint.getSchemaContext();
250 module = this.controllerContext.findModuleByNameAndRevision(moduleNameAndRevision);
251 schemaContext = this.controllerContext.getGlobalSchema();
254 if (module == null) {
255 final String errMsg = "Module with name '" + moduleNameAndRevision.getLocalName()
256 + "' and revision '" + moduleNameAndRevision.getRevision() + "' was not found.";
258 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
261 final Module restconfModule = getRestconfModule();
262 final Set<Module> modules = Collections.singleton(module);
263 final MapNode moduleMap = makeModuleMapNode(modules);
265 final DataSchemaNode moduleSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
266 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
267 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
269 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint,
270 schemaContext), moduleMap, QueryParametersParser.parseWriterParameters(uriInfo));
274 public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
275 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
276 final Set<String> availableStreams = Notificator.getStreamNames();
277 final Module restconfModule = getRestconfModule();
278 final DataSchemaNode streamSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
279 Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
280 Preconditions.checkState(streamSchemaNode instanceof ListSchemaNode);
282 final CollectionNodeBuilder<MapEntryNode, MapNode> listStreamsBuilder = Builders
283 .mapBuilder((ListSchemaNode) streamSchemaNode);
285 for (final String streamName : availableStreams) {
286 listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
289 final DataSchemaNode streamsContainerSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
290 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
291 Preconditions.checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
293 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
294 Builders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
295 streamsContainerBuilder.withChild(listStreamsBuilder.build());
298 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null,
299 schemaContext), streamsContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
303 public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
304 final Set<Module> allModules = this.controllerContext.getAllModules();
305 return operationsFromModulesToNormalizedContext(allModules, null);
309 public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
310 Set<Module> modules = null;
311 DOMMountPoint mountPoint = null;
312 if (identifier.contains(ControllerContext.MOUNT)) {
313 final InstanceIdentifierContext<?> mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier);
314 mountPoint = mountPointIdentifier.getMountPoint();
315 modules = this.controllerContext.getAllModules(mountPoint);
318 final String errMsg = "URI has bad format. If operations behind mount point should be showed, URI has to end with ";
319 LOG.debug(errMsg + ControllerContext.MOUNT + " for " + identifier);
320 throw new RestconfDocumentedException(errMsg + ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
323 return operationsFromModulesToNormalizedContext(modules, mountPoint);
326 private NormalizedNodeContext operationsFromModulesToNormalizedContext(final Set<Module> modules,
327 final DOMMountPoint mountPoint) {
328 throw new UnsupportedOperationException();
331 private Module getRestconfModule() {
332 final Module restconfModule = this.controllerContext.getRestconfModule();
333 if (restconfModule == null) {
334 LOG.debug("ietf-restconf module was not found.");
335 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
336 ErrorTag.OPERATION_NOT_SUPPORTED);
339 return restconfModule;
342 private static QName getModuleNameAndRevision(final String identifier) {
343 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
344 String moduleNameAndRevision = "";
345 if (mountIndex >= 0) {
346 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
348 moduleNameAndRevision = identifier;
351 final Splitter splitter = Splitter.on("/").omitEmptyStrings();
352 final Iterable<String> split = splitter.split(moduleNameAndRevision);
353 final List<String> pathArgs = Lists.<String> newArrayList(split);
354 if (pathArgs.size() < 2) {
355 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
356 throw new RestconfDocumentedException(
357 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
358 ErrorTag.INVALID_VALUE);
362 final String moduleName = pathArgs.get(0);
363 final String revision = pathArgs.get(1);
364 final Date moduleRevision = REVISION_FORMAT.parse(revision);
365 return QName.create(null, moduleRevision, moduleName);
366 } catch (final ParseException e) {
367 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
368 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
369 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
374 public Object getRoot() {
379 public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
380 final SchemaPath type = payload.getInstanceIdentifierContext().getSchemaNode().getPath();
381 final URI namespace = payload.getInstanceIdentifierContext().getSchemaNode().getQName().getNamespace();
382 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
383 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
384 final SchemaContext schemaContext;
385 if (mountPoint != null) {
386 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
387 if ( ! mountRpcServices.isPresent()) {
388 LOG.debug("Error: Rpc service is missing.");
389 throw new RestconfDocumentedException("Rpc service is missing.");
391 schemaContext = mountPoint.getSchemaContext();
392 response = mountRpcServices.get().invokeRpc(type, payload.getData());
394 if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
395 if (identifier.contains(CREATE_DATA_SUBSCR)) {
396 response = invokeSalRemoteRpcSubscribeRPC(payload);
397 } else if (identifier.contains(CREATE_NOTIFICATION_STREAM)) {
398 response = invokeSalRemoteRpcNotifiStrRPC(payload);
400 final String msg = "Not supported operation";
402 throw new RestconfDocumentedException(msg, ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED);
405 response = this.broker.invokeRpc(type, payload.getData());
407 schemaContext = this.controllerContext.getGlobalSchema();
410 final DOMRpcResult result = checkRpcResponse(response);
412 RpcDefinition resultNodeSchema = null;
413 final NormalizedNode<?, ?> resultData = result.getResult();
414 if ((result != null) && (result.getResult() != null)) {
415 resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
418 return new NormalizedNodeContext(new InstanceIdentifierContext<RpcDefinition>(null,
419 resultNodeSchema, mountPoint, schemaContext), resultData,
420 QueryParametersParser.parseWriterParameters(uriInfo));
423 private static DOMRpcResult checkRpcResponse(final CheckedFuture<DOMRpcResult, DOMRpcException> response) {
424 if (response == null) {
428 final DOMRpcResult retValue = response.get();
429 if ((retValue.getErrors() == null) || retValue.getErrors().isEmpty()) {
432 LOG.debug("RpcError message", retValue.getErrors());
433 throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
434 } catch (final InterruptedException e) {
435 final String errMsg = "The operation was interrupted while executing and did not complete.";
436 LOG.debug("Rpc Interrupt - " + errMsg, e);
437 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
438 } catch (final ExecutionException e) {
439 LOG.debug("Execution RpcError: ", e);
440 Throwable cause = e.getCause();
442 while (cause.getCause() != null) {
443 cause = cause.getCause();
446 if (cause instanceof IllegalArgumentException) {
447 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL,
448 ErrorTag.INVALID_VALUE);
449 } else if (cause instanceof DOMRpcImplementationNotAvailableException) {
450 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
452 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",cause);
454 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",e);
456 } catch (final CancellationException e) {
457 final String errMsg = "The operation was cancelled while executing.";
458 LOG.debug("Cancel RpcExecution: " + errMsg, e);
459 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
463 private static void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
464 if ((inputSchema != null) && (payload.getData() == null)) {
465 // expected a non null payload
466 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
467 } else if ((inputSchema == null) && (payload.getData() != null)) {
468 // did not expect any input
469 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
473 // TODO: Validate "mandatory" and "config" values here??? Or should those be
475 // validate in a more central location inside MD-SAL core.
479 private CheckedFuture<DOMRpcResult, DOMRpcException> invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
480 final ContainerNode value = (ContainerNode) payload.getData();
481 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
482 final Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(new NodeIdentifier(
483 QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(), "path")));
484 final Object pathValue = path.isPresent() ? path.get().getValue() : null;
486 if (!(pathValue instanceof YangInstanceIdentifier)) {
487 final String errMsg = "Instance identifier was not normalized correctly ";
488 LOG.debug(errMsg + rpcQName);
489 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
492 final YangInstanceIdentifier pathIdentifier = ((YangInstanceIdentifier) pathValue);
493 String streamName = (String) CREATE_DATA_SUBSCR;
494 if (!pathIdentifier.isEmpty()) {
495 final String fullRestconfIdentifier = DATA_SUBSCR
496 + this.controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
498 LogicalDatastoreType datastore = parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
499 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
501 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
502 scope = scope == null ? DEFAULT_SCOPE : scope;
504 streamName = Notificator.createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore
505 + "/scope=" + scope);
508 if (Strings.isNullOrEmpty(streamName)) {
509 final String errMsg = "Path is empty or contains value node which is not Container or List build-in type.";
510 LOG.debug(errMsg + pathIdentifier);
511 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
514 final QName outputQname = QName.create(rpcQName, "output");
515 final QName streamNameQname = QName.create(rpcQName, "stream-name");
517 final ContainerNode output = ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
518 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
520 if (!Notificator.existListenerFor(streamName)) {
521 Notificator.createListener(pathIdentifier, streamName);
524 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
526 return Futures.immediateCheckedFuture(defaultDOMRpcResult);
530 public NormalizedNodeContext invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
531 if ((noPayload != null) && !CharMatcher.WHITESPACE.matchesAllOf(noPayload)) {
532 throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
535 String identifierEncoded = null;
536 DOMMountPoint mountPoint = null;
537 final SchemaContext schemaContext;
538 if (identifier.contains(ControllerContext.MOUNT)) {
539 // mounted RPC call - look up mount instance.
540 final InstanceIdentifierContext<?> mountPointId = this.controllerContext.toMountPointIdentifier(identifier);
541 mountPoint = mountPointId.getMountPoint();
542 schemaContext = mountPoint.getSchemaContext();
543 final int startOfRemoteRpcName = identifier.lastIndexOf(ControllerContext.MOUNT)
544 + ControllerContext.MOUNT.length() + 1;
545 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
546 identifierEncoded = remoteRpcName;
548 } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
549 final String slashErrorMsg = String.format("Identifier %n%s%ncan\'t contain slash "
550 + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.", identifier);
551 LOG.debug(slashErrorMsg);
552 throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
554 identifierEncoded = identifier;
555 schemaContext = this.controllerContext.getGlobalSchema();
558 final String identifierDecoded = this.controllerContext.urlPathArgDecode(identifierEncoded);
560 RpcDefinition rpc = null;
561 if (mountPoint == null) {
562 rpc = this.controllerContext.getRpcDefinition(identifierDecoded, null);
564 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
568 LOG.debug("RPC " + identifierDecoded + " does not exist.");
569 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
572 if (rpc.getInput() != null) {
573 LOG.debug("RPC " + rpc + " does not need input value.");
574 // FIXME : find a correct Error from specification
575 throw new IllegalStateException("RPC " + rpc + " does'n need input value!");
578 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
579 if (mountPoint != null) {
580 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
581 if ( ! mountRpcServices.isPresent()) {
582 throw new RestconfDocumentedException("Rpc service is missing.");
584 response = mountRpcServices.get().invokeRpc(rpc.getPath(), null);
586 response = this.broker.invokeRpc(rpc.getPath(), null);
589 final DOMRpcResult result = checkRpcResponse(response);
591 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpc, mountPoint, schemaContext),
592 result.getResult(), QueryParametersParser.parseWriterParameters(uriInfo));
595 private static RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
596 final String[] splittedIdentifier = identifierDecoded.split(":");
597 if (splittedIdentifier.length != 2) {
598 final String errMsg = identifierDecoded + " couldn't be splitted to 2 parts (module:rpc name)";
600 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
602 for (final Module module : schemaContext.getModules()) {
603 if (module.getName().equals(splittedIdentifier[0])) {
604 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
605 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
606 return rpcDefinition;
615 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
616 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
617 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
618 NormalizedNode<?, ?> data = null;
619 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
620 if (mountPoint != null) {
621 data = this.broker.readConfigurationData(mountPoint, normalizedII);
623 data = this.broker.readConfigurationData(normalizedII);
626 final String errMsg = "Request could not be completed because the relevant data model content does not exist ";
627 LOG.debug(errMsg + identifier);
628 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
630 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
634 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
635 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
636 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
637 NormalizedNode<?, ?> data = null;
638 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
639 if (mountPoint != null) {
640 data = this.broker.readOperationalData(mountPoint, normalizedII);
642 data = this.broker.readOperationalData(normalizedII);
645 final String errMsg = "Request could not be completed because the relevant data model content does not exist ";
646 LOG.debug(errMsg + identifier);
647 throw new RestconfDocumentedException(errMsg , ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
649 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
653 public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload) {
654 Preconditions.checkNotNull(identifier);
655 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
657 validateInput(iiWithData.getSchemaNode(), payload);
658 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
659 validateListKeysEqualityInPayloadAndUri(payload);
661 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
662 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
665 * There is a small window where another write transaction could be updating the same data
666 * simultaneously and we get an OptimisticLockFailedException. This error is likely
667 * transient and The WriteTransaction#submit API docs state that a retry will likely
668 * succeed. So we'll try again if that scenario occurs. If it fails a third time then it
669 * probably will never succeed so we'll fail in that case.
671 * By retrying we're attempting to hide the internal implementation of the data store and
672 * how it handles concurrent updates from the restconf client. The client has instructed us
673 * to put the data and we should make every effort to do so without pushing optimistic lock
674 * failures back to the client and forcing them to handle it via retry (and having to
675 * document the behavior).
677 PutResult result = null;
678 final TryOfPutData tryPutData = new TryOfPutData();
680 if (mountPoint != null) {
682 result = this.broker.commitMountPointDataPut(mountPoint, normalizedII, payload.getData());
684 result = this.broker.commitConfigurationDataPut(this.controllerContext.getGlobalSchema(), normalizedII,
687 final CountDownLatch waiter = new CountDownLatch(1);
688 Futures.addCallback(result.getFutureOfPutData(), new FutureCallback<Void>() {
691 public void onSuccess(final Void result) {
692 handlingLoggerPut(null, tryPutData, identifier);
697 public void onFailure(final Throwable t) {
699 handlingLoggerPut(t, tryPutData, identifier);
705 } catch (final InterruptedException e) {
706 final String msg = "Problem while waiting for response";
708 throw new RestconfDocumentedException(msg, e);
711 if(tryPutData.isDone()){
714 throw new RestconfDocumentedException("Problem while PUT operations");
718 return Response.status(result.getStatus()).build();
721 protected void handlingLoggerPut(final Throwable t, final TryOfPutData tryPutData, final String identifier) {
723 if (t instanceof OptimisticLockFailedException) {
724 if (tryPutData.countGet() <= 0) {
725 LOG.debug("Got OptimisticLockFailedException on last try - failing " + identifier);
726 throw new RestconfDocumentedException(t.getMessage(), t);
728 LOG.debug("Got OptimisticLockFailedException - trying again " + identifier);
729 tryPutData.countDown();
731 LOG.debug("Update ConfigDataStore fail " + identifier, t);
732 throw new RestconfDocumentedException(t.getMessage(), t);
735 LOG.trace("PUT Successful " + identifier);
740 private static void validateTopLevelNodeName(final NormalizedNodeContext node,
741 final YangInstanceIdentifier identifier) {
743 final String payloadName = node.getData().getNodeType().getLocalName();
746 if (identifier.isEmpty()) {
748 if (!node.getData().getNodeType().equals(NETCONF_BASE_QNAME)) {
749 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
750 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
754 final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
755 if (!payloadName.equals(identifierName)) {
756 throw new RestconfDocumentedException("Payload name (" + payloadName
757 + ") is different from identifier name (" + identifierName + ")", ErrorType.PROTOCOL,
758 ErrorTag.MALFORMED_MESSAGE);
764 * Validates whether keys in {@code payload} are equal to values of keys in {@code iiWithData} for list schema node
766 * @throws RestconfDocumentedException
767 * if key values or key count in payload and URI isn't equal
770 private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
771 Preconditions.checkArgument(payload != null);
772 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
773 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
774 final SchemaNode schemaNode = iiWithData.getSchemaNode();
775 final NormalizedNode<?, ?> data = payload.getData();
776 if (schemaNode instanceof ListSchemaNode) {
777 final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
778 if ((lastPathArgument instanceof NodeIdentifierWithPredicates) && (data instanceof MapEntryNode)) {
779 final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument).getKeyValues();
780 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
785 private static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues,
786 final MapEntryNode payload, final List<QName> keyDefinitions) {
788 final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
789 for (final QName keyDefinition : keyDefinitions) {
790 final Object uriKeyValue = mutableCopyUriKeyValues.remove(keyDefinition);
791 // should be caught during parsing URI to InstanceIdentifier
792 RestconfValidationUtils.checkDocumentedError(uriKeyValue != null, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
793 "Missing key " + keyDefinition + " in URI.");
795 final Object dataKeyValue = payload.getIdentifier().getKeyValues().get(keyDefinition);
797 if ( ! uriKeyValue.equals(dataKeyValue)) {
798 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName() +
799 "' specified in the URI doesn't match the value '" + dataKeyValue + "' specified in the message body. ";
800 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
806 public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
807 return createConfigurationData(payload, uriInfo);
810 // FIXME create RestconfIdetifierHelper and move this method there
811 private static YangInstanceIdentifier checkConsistencyOfNormalizedNodeContext(final NormalizedNodeContext payload) {
812 Preconditions.checkArgument(payload != null);
813 Preconditions.checkArgument(payload.getData() != null);
814 Preconditions.checkArgument(payload.getData().getNodeType() != null);
815 Preconditions.checkArgument(payload.getInstanceIdentifierContext() != null);
816 Preconditions.checkArgument(payload.getInstanceIdentifierContext().getInstanceIdentifier() != null);
818 final QName payloadNodeQname = payload.getData().getNodeType();
819 final YangInstanceIdentifier yangIdent = payload.getInstanceIdentifierContext().getInstanceIdentifier();
820 if (payloadNodeQname.compareTo(yangIdent.getLastPathArgument().getNodeType()) > 0) {
823 final InstanceIdentifierContext<?> parentContext = payload.getInstanceIdentifierContext();
824 final SchemaNode parentSchemaNode = parentContext.getSchemaNode();
825 if(parentSchemaNode instanceof DataNodeContainer) {
826 final DataNodeContainer cast = (DataNodeContainer) parentSchemaNode;
827 for (final DataSchemaNode child : cast.getChildNodes()) {
828 if (payloadNodeQname.compareTo(child.getQName()) == 0) {
829 return YangInstanceIdentifier.builder(yangIdent).node(child.getQName()).build();
833 if (parentSchemaNode instanceof RpcDefinition) {
836 final String errMsg = "Error parsing input: DataSchemaNode has not children ";
837 LOG.info(errMsg + yangIdent);
838 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
842 public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
843 if (payload == null) {
844 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
847 // FIXME: move this to parsing stage (we can have augmentation nodes here which do not have namespace)
848 // final URI payloadNS = payload.getData().getNodeType().getNamespace();
849 // if (payloadNS == null) {
850 // throw new RestconfDocumentedException(
851 // "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
852 // ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
855 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
856 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
857 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
859 CheckedFuture<Void, TransactionCommitFailedException> future;
860 if (mountPoint != null) {
861 future = this.broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData());
863 future = this.broker.commitConfigurationDataPost(this.controllerContext.getGlobalSchema(), normalizedII,
867 final CountDownLatch waiter = new CountDownLatch(1);
868 Futures.addCallback(future, new FutureCallback<Void>() {
871 public void onSuccess(final Void result) {
872 handlerLoggerPost(null, uriInfo);
877 public void onFailure(final Throwable t) {
879 handlerLoggerPost(t, uriInfo);
885 } catch (final InterruptedException e) {
886 final String msg = "Problem while waiting for response";
888 throw new RestconfDocumentedException(msg, e);
891 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
892 // FIXME: Provide path to result.
893 final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
894 if (location != null) {
895 responseBuilder.location(location);
897 return responseBuilder.build();
900 protected void handlerLoggerPost(final Throwable t, final UriInfo uriInfo) {
902 final String errMsg = "Error creating data ";
903 LOG.warn(errMsg + (uriInfo != null ? uriInfo.getPath() : ""), t);
904 throw new RestconfDocumentedException(errMsg, t);
906 LOG.trace("Successfuly create data.");
910 private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint, final YangInstanceIdentifier normalizedII) {
911 if(uriInfo == null) {
912 // This is null if invoked internally
916 final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
917 uriBuilder.path("config");
919 uriBuilder.path(this.controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
920 } catch (final Exception e) {
921 LOG.info("Location for instance identifier" + normalizedII + "wasn't created", e);
924 return uriBuilder.build();
928 public Response deleteConfigurationData(final String identifier) {
929 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
930 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
931 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
933 CheckedFuture<Void, TransactionCommitFailedException> future;
934 if (mountPoint != null) {
935 future = this.broker.commitConfigurationDataDelete(mountPoint, normalizedII);
937 future = this.broker.commitConfigurationDataDelete(normalizedII);
940 final CountDownLatch waiter = new CountDownLatch(1);
941 Futures.addCallback(future, new FutureCallback<Void>() {
944 public void onSuccess(final Void result) {
945 handlerLoggerDelete(null);
950 public void onFailure(final Throwable t) {
952 handlerLoggerDelete(t);
959 } catch (final InterruptedException e) {
960 final String msg = "Problem while waiting for response";
962 throw new RestconfDocumentedException(msg, e);
964 return Response.status(Status.OK).build();
967 protected void handlerLoggerDelete(final Throwable t) {
969 final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(t),
970 Predicates.instanceOf(ModifiedNodeDoesNotExistException.class));
971 if (searchedException.isPresent()) {
972 throw new RestconfDocumentedException("Data specified for deleting doesn't exist.", ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
974 final String errMsg = "Error while deleting data";
976 throw new RestconfDocumentedException(errMsg, t);
978 LOG.trace("Successfuly delete data.");
983 * Subscribes to some path in schema context (stream) to listen on changes on this stream.
985 * Additional parameters for subscribing to stream are loaded via rpc input parameters:
987 * <li>datastore - default CONFIGURATION (other values of {@link LogicalDatastoreType} enum type)</li>
988 * <li>scope - default BASE (other values of {@link DataChangeScope})</li>
992 public Response subscribeToStream(final String identifier, final UriInfo uriInfo) {
993 if (identifier.contains(DATA_SUBSCR)) {
994 return dataSubs(identifier, uriInfo);
995 } else if (identifier.contains(NOTIFICATION_STREAM)) {
996 return notifStream(identifier, uriInfo);
998 final String msg = "Bad type of notification of sal-remote";
1000 throw new RestconfDocumentedException(msg);
1004 * Register notification listener by stream name
1010 * @return {@link Response}
1012 private Response notifStream(final String identifier, final UriInfo uriInfo) {
1013 final String streamName = Notificator.createStreamNameFromUri(identifier);
1014 if (Strings.isNullOrEmpty(streamName)) {
1015 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1017 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
1018 if ((listeners == null) || listeners.isEmpty()) {
1019 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1020 ErrorTag.UNKNOWN_ELEMENT);
1023 for (final NotificationListenerAdapter listener : listeners) {
1024 this.broker.registerToListenNotification(listener);
1027 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1028 int notificationPort = NOTIFICATION_PORT;
1030 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
1031 notificationPort = webSocketServerInstance.getPort();
1032 } catch (final NullPointerException e) {
1033 WebSocketServer.createInstance(NOTIFICATION_PORT);
1035 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1036 final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
1038 return Response.status(Status.OK).location(uriToWebsocketServer).build();
1042 * Register data change listener by stream name
1048 * @return {@link Response}
1050 private Response dataSubs(final String identifier, final UriInfo uriInfo) {
1051 final String streamName = Notificator.createStreamNameFromUri(identifier);
1052 if (Strings.isNullOrEmpty(streamName)) {
1053 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1056 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1057 if (listener == null) {
1058 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
1061 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1062 final LogicalDatastoreType datastore = parserURIEnumParameter(LogicalDatastoreType.class,
1063 paramToValues.get(DATASTORE_PARAM_NAME));
1064 if (datastore == null) {
1065 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1066 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1068 final DataChangeScope scope = parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
1069 if (scope == null) {
1070 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1071 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1074 this.broker.registerToListenDataChanges(datastore, scope, listener);
1076 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1077 int notificationPort = NOTIFICATION_PORT;
1079 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
1080 notificationPort = webSocketServerInstance.getPort();
1081 } catch (final NullPointerException e) {
1082 WebSocketServer.createInstance(NOTIFICATION_PORT);
1084 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1085 final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
1087 return Response.status(Status.OK).location(uriToWebsocketServer).build();
1091 public PATCHStatusContext patchConfigurationData(final String identifier, final PATCHContext context, final UriInfo uriInfo) {
1092 if (context == null) {
1093 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1097 return this.broker.patchConfigurationDataWithinTransaction(context,
1098 this.controllerContext.getGlobalSchema());
1099 } catch (final InterruptedException e) {
1100 LOG.debug("Patch transaction failed", e);
1101 throw new RestconfDocumentedException(e.getMessage());
1106 public PATCHStatusContext patchConfigurationData(final PATCHContext context, @Context final UriInfo uriInfo) {
1107 if (context == null) {
1108 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1112 return this.broker.patchConfigurationDataWithinTransaction(context,
1113 this.controllerContext.getGlobalSchema());
1114 } catch (final InterruptedException e) {
1115 LOG.debug("Patch transaction failed", e);
1116 throw new RestconfDocumentedException(e.getMessage());
1121 * Load parameter for subscribing to stream from input composite node
1125 * @return enum object if its string value is equal to {@code paramName}. In other cases null.
1127 private static <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1128 final String paramName) {
1129 final Optional<DataContainerChild<? extends PathArgument, ?>> augNode = value.getChild(SAL_REMOTE_AUG_IDENTIFIER);
1130 if (!augNode.isPresent() && !(augNode instanceof AugmentationNode)) {
1133 final Optional<DataContainerChild<? extends PathArgument, ?>> enumNode =
1134 ((AugmentationNode) augNode.get()).getChild(new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1135 if (!enumNode.isPresent()) {
1138 final Object rawValue = enumNode.get().getValue();
1139 if (!(rawValue instanceof String)) {
1143 return resolveAsEnum(classDescriptor, (String) rawValue);
1147 * Checks whether {@code value} is one of the string representation of enumeration {@code classDescriptor}
1149 * @return enum object if string value of {@code classDescriptor} enumeration is equal to {@code value}. Other cases
1152 private static <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1153 if (Strings.isNullOrEmpty(value)) {
1156 return resolveAsEnum(classDescriptor, value);
1159 private static <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1160 final T[] enumConstants = classDescriptor.getEnumConstants();
1161 if (enumConstants != null) {
1162 for (final T enm : classDescriptor.getEnumConstants()) {
1163 if (((Enum<?>) enm).name().equals(value)) {
1171 private static Map<String, String> resolveValuesFromUri(final String uri) {
1172 final Map<String, String> result = new HashMap<>();
1173 final String[] tokens = uri.split("/");
1174 for (int i = 1; i < tokens.length; i++) {
1175 final String[] parameterTokens = tokens[i].split("=");
1176 if (parameterTokens.length == 2) {
1177 result.put(parameterTokens[0], parameterTokens[1]);
1183 public BigInteger getOperationalReceived() {
1184 // TODO Auto-generated method stub
1188 private MapNode makeModuleMapNode(final Set<Module> modules) {
1189 Preconditions.checkNotNull(modules);
1190 final Module restconfModule = getRestconfModule();
1191 final DataSchemaNode moduleSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
1192 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1193 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1195 final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder = Builders
1196 .mapBuilder((ListSchemaNode) moduleSchemaNode);
1198 for (final Module module : modules) {
1199 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1201 return listModuleBuilder.build();
1204 protected MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1205 Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1206 "moduleSchemaNode has to be of type ListSchemaNode");
1207 final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1208 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues = Builders
1209 .mapEntryBuilder(listModuleSchemaNode);
1211 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1212 (listModuleSchemaNode), "name");
1213 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1214 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1215 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName())
1218 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1219 (listModuleSchemaNode), "revision");
1220 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1221 Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1222 final String revision = REVISION_FORMAT.format(module.getRevision());
1223 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode).withValue(revision)
1226 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1227 (listModuleSchemaNode), "namespace");
1228 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1229 Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1230 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1231 .withValue(module.getNamespace().toString()).build());
1233 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1234 (listModuleSchemaNode), "feature");
1235 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1236 Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1237 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder = Builders
1238 .leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1239 for (final FeatureDefinition feature : module.getFeatures()) {
1240 featuresBuilder.withChild(Builders.leafSetEntryBuilder(((LeafListSchemaNode) featureSchemaNode))
1241 .withValue(feature.getQName().getLocalName()).build());
1243 moduleNodeValues.withChild(featuresBuilder.build());
1245 return moduleNodeValues.build();
1248 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1249 Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1250 "streamSchemaNode has to be of type ListSchemaNode");
1251 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1252 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues = Builders
1253 .mapEntryBuilder(listStreamSchemaNode);
1255 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1256 (listStreamSchemaNode), "name");
1257 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1258 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1259 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName)
1262 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1263 (listStreamSchemaNode), "description");
1264 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1265 Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1266 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode)
1267 .withValue("DESCRIPTION_PLACEHOLDER").build());
1269 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1270 (listStreamSchemaNode), "replay-support");
1271 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1272 Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1273 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1274 .withValue(Boolean.valueOf(true)).build());
1276 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1277 (listStreamSchemaNode), "replay-log-creation-time");
1278 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1279 Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1280 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode)
1281 .withValue("").build());
1283 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1284 (listStreamSchemaNode), "events");
1285 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1286 Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1287 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode)
1288 .withValue("").build());
1290 return streamNodeValues.build();
1294 * Prepare stream for notification
1297 * - contains list of qnames of notifications
1298 * @return - checked future object
1300 private CheckedFuture<DOMRpcResult, DOMRpcException> invokeSalRemoteRpcNotifiStrRPC(
1301 final NormalizedNodeContext payload) {
1302 final ContainerNode data = (ContainerNode) payload.getData();
1303 LeafSetNode leafSet = null;
1304 String outputType = "XML";
1305 for (final DataContainerChild<? extends PathArgument, ?> dataChild : data.getValue()) {
1306 if (dataChild instanceof LeafSetNode) {
1307 leafSet = (LeafSetNode) dataChild;
1308 } else if (dataChild instanceof AugmentationNode) {
1309 outputType = (String) (((AugmentationNode) dataChild).getValue()).iterator().next().getValue();
1313 final Collection<LeafSetEntryNode> entryNodes = leafSet.getValue();
1314 final List<SchemaPath> paths = new ArrayList<>();
1315 String streamName = CREATE_NOTIFICATION_STREAM + "/";
1317 final Iterator<LeafSetEntryNode> iterator = entryNodes.iterator();
1318 while (iterator.hasNext()) {
1319 final QName valueQName = QName.create((String) iterator.next().getValue());
1320 final Module module = ControllerContext.getInstance()
1321 .findModuleByNamespace(valueQName.getModule().getNamespace());
1322 Preconditions.checkNotNull(module, "Module for namespace " + valueQName.getModule().getNamespace()
1323 + " does not exist");
1324 NotificationDefinition notifiDef = null;
1325 for (final NotificationDefinition notification : module.getNotifications()) {
1326 if (notification.getQName().equals(valueQName)) {
1327 notifiDef = notification;
1331 final String moduleName = module.getName();
1332 Preconditions.checkNotNull(notifiDef,
1333 "Notification " + valueQName + "doesn't exist in module " + moduleName);
1334 paths.add(notifiDef.getPath());
1335 streamName = streamName + moduleName + ":" + valueQName.getLocalName();
1336 if (iterator.hasNext()) {
1337 streamName = streamName + ",";
1341 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
1342 final QName outputQname = QName.create(rpcQName, "output");
1343 final QName streamNameQname = QName.create(rpcQName, "notification-stream-identifier");
1345 final ContainerNode output = ImmutableContainerNodeBuilder.create()
1346 .withNodeIdentifier(new NodeIdentifier(outputQname))
1347 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
1349 if (!Notificator.existNotificationListenerFor(streamName)) {
1350 Notificator.createNotificationListener(paths, streamName, outputType);
1353 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
1355 return Futures.immediateCheckedFuture(defaultDOMRpcResult);
1358 private class TryOfPutData {
1360 boolean done = false;