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.ImmutableSet;
17 import com.google.common.collect.Iterables;
18 import com.google.common.collect.Lists;
19 import com.google.common.collect.Maps;
20 import com.google.common.collect.Sets;
21 import com.google.common.util.concurrent.CheckedFuture;
22 import com.google.common.util.concurrent.FutureCallback;
23 import com.google.common.util.concurrent.Futures;
25 import java.net.URISyntaxException;
26 import java.text.DateFormat;
27 import java.text.ParseException;
28 import java.text.SimpleDateFormat;
29 import java.util.ArrayList;
30 import java.util.Collection;
31 import java.util.Collections;
32 import java.util.Date;
33 import java.util.HashMap;
34 import java.util.Iterator;
35 import java.util.List;
37 import java.util.Map.Entry;
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.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
68 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
69 import org.opendaylight.yangtools.yang.common.QName;
70 import org.opendaylight.yangtools.yang.common.QNameModule;
71 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
72 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
73 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
74 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
75 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
76 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
77 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
78 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
79 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
80 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
81 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
82 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
83 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
84 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
85 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
86 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
87 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
88 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
89 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
90 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
91 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
92 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
93 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
94 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
95 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
96 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
97 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
98 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
99 import org.opendaylight.yangtools.yang.model.api.Module;
100 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
101 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
102 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
103 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
104 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
105 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.EffectiveSchemaContext;
106 import org.slf4j.Logger;
107 import org.slf4j.LoggerFactory;
109 public class RestconfImpl implements RestconfService {
111 private static final RestconfImpl INSTANCE = new RestconfImpl();
114 * Notifications are served on port 8181.
116 private static final int NOTIFICATION_PORT = 8181;
118 private static final int CHAR_NOT_FOUND = -1;
120 private static final SimpleDateFormat REVISION_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
122 private static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
124 private BrokerFacade broker;
126 private ControllerContext controllerContext;
128 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
130 private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
132 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
134 private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
136 private static final String DATASTORE_PARAM_NAME = "datastore";
138 private static final String SCOPE_PARAM_NAME = "scope";
140 private static final String OUTPUT_TYPE_PARAM_NAME = "notification-output-type";
142 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
144 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
146 private static final QName NETCONF_BASE_QNAME;
148 private static final QNameModule SAL_REMOTE_AUGMENT;
150 private static final YangInstanceIdentifier.AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER;
152 public static final CharSequence DATA_SUBSCR = "data-change-event-subscription";
153 private static final CharSequence CREATE_DATA_SUBSCR = "create-" + DATA_SUBSCR;
155 public static final CharSequence NOTIFICATION_STREAM = "notification-stream";
156 private static final CharSequence CREATE_NOTIFICATION_STREAM = "create-" + NOTIFICATION_STREAM;
160 final Date eventSubscriptionAugRevision = new SimpleDateFormat("yyyy-MM-dd").parse("2014-07-08");
162 QName.create(QNameModule.create(new URI(NETCONF_BASE), null), NETCONF_BASE_PAYLOAD_NAME);
163 SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT, eventSubscriptionAugRevision);
164 SAL_REMOTE_AUG_IDENTIFIER = new YangInstanceIdentifier.AugmentationIdentifier(Sets.newHashSet(
165 QName.create(SAL_REMOTE_AUGMENT, "scope"), QName.create(SAL_REMOTE_AUGMENT, "datastore"),
166 QName.create(SAL_REMOTE_AUGMENT, "notification-output-type")));
167 } catch (final ParseException e) {
168 final String errMsg = "It wasn't possible to convert revision date of sal-remote-augment to date";
170 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
171 } catch (final URISyntaxException e) {
172 final String errMsg = "It wasn't possible to create instance of URI class with " + NETCONF_BASE + " URI";
173 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
177 public void setBroker(final BrokerFacade broker) {
178 this.broker = broker;
181 public void setControllerContext(final ControllerContext controllerContext) {
182 this.controllerContext = controllerContext;
185 private RestconfImpl() {
188 public static RestconfImpl getInstance() {
193 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
194 final Set<Module> allModules = this.controllerContext.getAllModules();
195 final MapNode allModuleMap = makeModuleMapNode(allModules);
197 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
199 final Module restconfModule = getRestconfModule();
200 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
201 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
202 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
204 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
205 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
206 moduleContainerBuilder.withChild(allModuleMap);
208 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode, null, schemaContext),
209 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
213 * Valid only for mount point
216 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
217 Preconditions.checkNotNull(identifier);
218 if (!identifier.contains(ControllerContext.MOUNT)) {
219 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
220 + " URI has to end with " + ControllerContext.MOUNT;
221 LOG.debug(errMsg + " for " + identifier);
222 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
225 final InstanceIdentifierContext<?> mountPointIdentifier =
226 this.controllerContext.toMountPointIdentifier(identifier);
227 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
228 final Set<Module> modules = this.controllerContext.getAllModules(mountPoint);
229 final MapNode mountPointModulesMap = makeModuleMapNode(modules);
231 final Module restconfModule = getRestconfModule();
232 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
233 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
234 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
236 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
237 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
238 moduleContainerBuilder.withChild(mountPointModulesMap);
240 return new NormalizedNodeContext(
241 new InstanceIdentifierContext<>(null, modulesSchemaNode, mountPoint,
242 this.controllerContext.getGlobalSchema()),
243 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
247 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
248 Preconditions.checkNotNull(identifier);
249 final QName moduleNameAndRevision = getModuleNameAndRevision(identifier);
250 Module module = null;
251 DOMMountPoint mountPoint = null;
252 final SchemaContext schemaContext;
253 if (identifier.contains(ControllerContext.MOUNT)) {
254 final InstanceIdentifierContext<?> mountPointIdentifier =
255 this.controllerContext.toMountPointIdentifier(identifier);
256 mountPoint = mountPointIdentifier.getMountPoint();
257 module = this.controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision);
258 schemaContext = mountPoint.getSchemaContext();
260 module = this.controllerContext.findModuleByNameAndRevision(moduleNameAndRevision);
261 schemaContext = this.controllerContext.getGlobalSchema();
264 if (module == null) {
265 final String errMsg = "Module with name '" + moduleNameAndRevision.getLocalName() + "' and revision '"
266 + moduleNameAndRevision.getRevision() + "' was not found.";
268 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
271 final Module restconfModule = getRestconfModule();
272 final Set<Module> modules = Collections.singleton(module);
273 final MapNode moduleMap = makeModuleMapNode(modules);
275 final DataSchemaNode moduleSchemaNode = this.controllerContext
276 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
277 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
279 return new NormalizedNodeContext(
280 new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint, schemaContext), moduleMap,
281 QueryParametersParser.parseWriterParameters(uriInfo));
285 public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
286 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
287 final Set<String> availableStreams = Notificator.getStreamNames();
288 final Module restconfModule = getRestconfModule();
289 final DataSchemaNode streamSchemaNode = this.controllerContext
290 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
291 Preconditions.checkState(streamSchemaNode instanceof ListSchemaNode);
293 final CollectionNodeBuilder<MapEntryNode, MapNode> listStreamsBuilder =
294 Builders.mapBuilder((ListSchemaNode) streamSchemaNode);
296 for (final String streamName : availableStreams) {
297 listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
300 final DataSchemaNode streamsContainerSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
301 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
302 Preconditions.checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
304 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
305 Builders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
306 streamsContainerBuilder.withChild(listStreamsBuilder.build());
308 return new NormalizedNodeContext(
309 new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null, schemaContext),
310 streamsContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
314 public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
315 final Set<Module> allModules = this.controllerContext.getAllModules();
316 return operationsFromModulesToNormalizedContext(allModules, null);
320 public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
321 Set<Module> modules = null;
322 DOMMountPoint mountPoint = null;
323 if (identifier.contains(ControllerContext.MOUNT)) {
324 final InstanceIdentifierContext<?> mountPointIdentifier =
325 this.controllerContext.toMountPointIdentifier(identifier);
326 mountPoint = mountPointIdentifier.getMountPoint();
327 modules = this.controllerContext.getAllModules(mountPoint);
330 final String errMsg =
331 "URI has bad format. If operations behind mount point should be showed, URI has to " + "end with ";
332 LOG.debug(errMsg + ControllerContext.MOUNT + " for " + identifier);
333 throw new RestconfDocumentedException(errMsg + ControllerContext.MOUNT, ErrorType.PROTOCOL,
334 ErrorTag.INVALID_VALUE);
337 return operationsFromModulesToNormalizedContext(modules, mountPoint);
341 * Special case only for GET restconf/operations use (since moment of
342 * pre-Beryllium Yang parser and Yang model API removal). The method is
343 * creating fake schema context with fake module and fake data by use own
344 * implementations of schema nodes and module.
347 * - set of modules for get RPCs from every module
349 * - mount point, if in use otherwise null
350 * @return {@link NormalizedNodeContext}
352 private NormalizedNodeContext operationsFromModulesToNormalizedContext(final Set<Module> modules,
353 final DOMMountPoint mountPoint) {
355 final Collection<Module> neededModules = new ArrayList<>(modules.size());
356 final ArrayList<LeafSchemaNode> fakeRpcSchema = new ArrayList<>();
358 for (final Module m : modules) {
359 final Set<RpcDefinition> rpcs = m.getRpcs();
360 if (!rpcs.isEmpty()) {
361 neededModules.add(m);
363 fakeRpcSchema.ensureCapacity(fakeRpcSchema.size() + rpcs.size());
364 rpcs.forEach(rpc -> fakeRpcSchema.add(new FakeLeafSchemaNode(rpc.getQName())));
368 final ContainerSchemaNode fakeCont = new FakeContainerSchemaNode(fakeRpcSchema);
369 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> containerBuilder =
370 Builders.containerBuilder(fakeCont);
372 for (final LeafSchemaNode leaf : fakeRpcSchema) {
373 containerBuilder.withChild(Builders.leafBuilder(leaf).build());
376 final Collection<Module> fakeModules = new ArrayList<>(neededModules.size() + 1);
377 neededModules.forEach(imp -> fakeModules.add(new FakeImportedModule(imp)));
378 fakeModules.add(new FakeRestconfModule(neededModules, fakeCont));
380 final SchemaContext fakeSchemaCtx =
381 EffectiveSchemaContext.resolveSchemaContext(ImmutableSet.copyOf(fakeModules));
382 final InstanceIdentifierContext<ContainerSchemaNode> instanceIdentifierContext =
383 new InstanceIdentifierContext<>(null, fakeCont, mountPoint, fakeSchemaCtx);
384 return new NormalizedNodeContext(instanceIdentifierContext, containerBuilder.build());
387 private Module getRestconfModule() {
388 final Module restconfModule = this.controllerContext.getRestconfModule();
389 if (restconfModule == null) {
390 LOG.debug("ietf-restconf module was not found.");
391 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
392 ErrorTag.OPERATION_NOT_SUPPORTED);
395 return restconfModule;
398 private static QName getModuleNameAndRevision(final String identifier) {
399 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
400 String moduleNameAndRevision = "";
401 if (mountIndex >= 0) {
402 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
404 moduleNameAndRevision = identifier;
407 final Splitter splitter = Splitter.on("/").omitEmptyStrings();
408 final Iterable<String> split = splitter.split(moduleNameAndRevision);
409 final List<String> pathArgs = Lists.<String> newArrayList(split);
410 if (pathArgs.size() < 2) {
411 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
412 throw new RestconfDocumentedException(
413 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
414 ErrorTag.INVALID_VALUE);
418 final String moduleName = pathArgs.get(0);
419 final String revision = pathArgs.get(1);
420 final Date moduleRevision = REVISION_FORMAT.parse(revision);
421 return QName.create(null, moduleRevision, moduleName);
422 } catch (final ParseException e) {
423 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
424 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
425 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
430 public Object getRoot() {
435 public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload,
436 final UriInfo uriInfo) {
437 final SchemaPath type = payload.getInstanceIdentifierContext().getSchemaNode().getPath();
438 final URI namespace = payload.getInstanceIdentifierContext().getSchemaNode().getQName().getNamespace();
439 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
440 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
441 final SchemaContext schemaContext;
443 if (mountPoint != null) {
444 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
445 if (!mountRpcServices.isPresent()) {
446 LOG.debug("Error: Rpc service is missing.");
447 throw new RestconfDocumentedException("Rpc service is missing.");
449 schemaContext = mountPoint.getSchemaContext();
450 response = mountRpcServices.get().invokeRpc(type, payload.getData());
452 if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
453 if (identifier.contains(CREATE_DATA_SUBSCR)) {
454 response = invokeSalRemoteRpcSubscribeRPC(payload);
455 } else if (identifier.contains(CREATE_NOTIFICATION_STREAM)) {
456 response = invokeSalRemoteRpcNotifiStrRPC(payload);
458 final String msg = "Not supported operation";
460 throw new RestconfDocumentedException(msg, ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED);
463 response = this.broker.invokeRpc(type, payload.getData());
465 schemaContext = this.controllerContext.getGlobalSchema();
468 final DOMRpcResult result = checkRpcResponse(response);
470 RpcDefinition resultNodeSchema = null;
471 final NormalizedNode<?, ?> resultData = result.getResult();
472 if ((result != null) && (result.getResult() != null)) {
473 resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
476 return new NormalizedNodeContext(
477 new InstanceIdentifierContext<RpcDefinition>(null, resultNodeSchema, mountPoint, schemaContext),
478 resultData, QueryParametersParser.parseWriterParameters(uriInfo));
481 private static DOMRpcResult checkRpcResponse(final CheckedFuture<DOMRpcResult, DOMRpcException> response) {
482 if (response == null) {
486 final DOMRpcResult retValue = response.get();
487 if ((retValue.getErrors() == null) || retValue.getErrors().isEmpty()) {
490 LOG.debug("RpcError message", retValue.getErrors());
491 throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
492 } catch (final InterruptedException e) {
493 final String errMsg = "The operation was interrupted while executing and did not complete.";
494 LOG.debug("Rpc Interrupt - " + errMsg, e);
495 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
496 } catch (final ExecutionException e) {
497 LOG.debug("Execution RpcError: ", e);
498 Throwable cause = e.getCause();
500 while (cause.getCause() != null) {
501 cause = cause.getCause();
504 if (cause instanceof IllegalArgumentException) {
505 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL,
506 ErrorTag.INVALID_VALUE);
507 } else if (cause instanceof DOMRpcImplementationNotAvailableException) {
508 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.APPLICATION,
509 ErrorTag.OPERATION_NOT_SUPPORTED);
511 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
514 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
517 } catch (final CancellationException e) {
518 final String errMsg = "The operation was cancelled while executing.";
519 LOG.debug("Cancel RpcExecution: " + errMsg, e);
520 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
524 private static void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
525 if ((inputSchema != null) && (payload.getData() == null)) {
526 // expected a non null payload
527 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
528 } else if ((inputSchema == null) && (payload.getData() != null)) {
529 // did not expect any input
530 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
534 private CheckedFuture<DOMRpcResult, DOMRpcException>
535 invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
536 final ContainerNode value = (ContainerNode) payload.getData();
537 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
538 final Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(new NodeIdentifier(
539 QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(), "path")));
540 final Object pathValue = path.isPresent() ? path.get().getValue() : null;
542 if (!(pathValue instanceof YangInstanceIdentifier)) {
543 final String errMsg = "Instance identifier was not normalized correctly ";
544 LOG.debug(errMsg + rpcQName);
545 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
548 final YangInstanceIdentifier pathIdentifier = ((YangInstanceIdentifier) pathValue);
549 String streamName = (String) CREATE_DATA_SUBSCR;
550 NotificationOutputType outputType = null;
551 if (!pathIdentifier.isEmpty()) {
552 final String fullRestconfIdentifier =
553 DATA_SUBSCR + this.controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
555 LogicalDatastoreType datastore =
556 parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
557 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
559 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
560 scope = scope == null ? DEFAULT_SCOPE : scope;
562 outputType = parseEnumTypeParameter(value, NotificationOutputType.class, OUTPUT_TYPE_PARAM_NAME);
563 outputType = outputType == null ? NotificationOutputType.XML : outputType;
565 streamName = Notificator
566 .createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore + "/scope=" + scope);
569 if (Strings.isNullOrEmpty(streamName)) {
570 final String errMsg = "Path is empty or contains value node which is not Container or List build-in type.";
571 LOG.debug(errMsg + pathIdentifier);
572 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
575 final QName outputQname = QName.create(rpcQName, "output");
576 final QName streamNameQname = QName.create(rpcQName, "stream-name");
578 final ContainerNode output =
579 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
580 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
582 if (!Notificator.existListenerFor(streamName)) {
583 Notificator.createListener(pathIdentifier, streamName, outputType);
586 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
588 return Futures.immediateCheckedFuture(defaultDOMRpcResult);
592 public NormalizedNodeContext invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
593 if ((noPayload != null) && !CharMatcher.WHITESPACE.matchesAllOf(noPayload)) {
594 throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
597 String identifierEncoded = null;
598 DOMMountPoint mountPoint = null;
599 final SchemaContext schemaContext;
600 if (identifier.contains(ControllerContext.MOUNT)) {
601 // mounted RPC call - look up mount instance.
602 final InstanceIdentifierContext<?> mountPointId = this.controllerContext.toMountPointIdentifier(identifier);
603 mountPoint = mountPointId.getMountPoint();
604 schemaContext = mountPoint.getSchemaContext();
605 final int startOfRemoteRpcName =
606 identifier.lastIndexOf(ControllerContext.MOUNT) + ControllerContext.MOUNT.length() + 1;
607 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
608 identifierEncoded = remoteRpcName;
610 } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
611 final String slashErrorMsg = String.format(
612 "Identifier %n%s%ncan\'t contain slash "
613 + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.",
615 LOG.debug(slashErrorMsg);
616 throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
618 identifierEncoded = identifier;
619 schemaContext = this.controllerContext.getGlobalSchema();
622 final String identifierDecoded = this.controllerContext.urlPathArgDecode(identifierEncoded);
624 RpcDefinition rpc = null;
625 if (mountPoint == null) {
626 rpc = this.controllerContext.getRpcDefinition(identifierDecoded, null);
628 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
632 LOG.debug("RPC " + identifierDecoded + " does not exist.");
633 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
636 if (rpc.getInput() != null) {
637 LOG.debug("RPC " + rpc + " does not need input value.");
638 // FIXME : find a correct Error from specification
639 throw new IllegalStateException("RPC " + rpc + " does'n need input value!");
642 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
643 if (mountPoint != null) {
644 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
645 if (!mountRpcServices.isPresent()) {
646 throw new RestconfDocumentedException("Rpc service is missing.");
648 response = mountRpcServices.get().invokeRpc(rpc.getPath(), null);
650 response = this.broker.invokeRpc(rpc.getPath(), null);
653 final DOMRpcResult result = checkRpcResponse(response);
655 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpc, mountPoint, schemaContext),
656 result.getResult(), QueryParametersParser.parseWriterParameters(uriInfo));
659 private static RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
660 final String[] splittedIdentifier = identifierDecoded.split(":");
661 if (splittedIdentifier.length != 2) {
662 final String errMsg = identifierDecoded + " couldn't be splitted to 2 parts (module:rpc name)";
664 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
666 for (final Module module : schemaContext.getModules()) {
667 if (module.getName().equals(splittedIdentifier[0])) {
668 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
669 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
670 return rpcDefinition;
679 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
680 boolean withDefa_used = false;
681 String withDefa = null;
683 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
684 switch (entry.getKey()) {
685 case "with-defaults":
686 if (!withDefa_used) {
687 withDefa_used = true;
688 withDefa = entry.getValue().iterator().next();
690 throw new RestconfDocumentedException("With-defaults parameter can be used only once.");
695 boolean tagged = false;
697 if (withDefa.equals("report-all-tagged")) {
701 if (withDefa.equals("report-all")) {
706 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
707 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
708 NormalizedNode<?, ?> data = null;
709 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
710 if (mountPoint != null) {
711 data = this.broker.readConfigurationData(mountPoint, normalizedII, withDefa);
713 data = this.broker.readConfigurationData(normalizedII, withDefa);
716 final String errMsg =
717 "Request could not be completed because the relevant data model content does not exist ";
718 LOG.debug(errMsg + identifier);
719 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
721 return new NormalizedNodeContext(iiWithData, data,
722 QueryParametersParser.parseWriterParameters(uriInfo, tagged));
726 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
727 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
728 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
729 NormalizedNode<?, ?> data = null;
730 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
731 if (mountPoint != null) {
732 data = this.broker.readOperationalData(mountPoint, normalizedII);
734 data = this.broker.readOperationalData(normalizedII);
737 final String errMsg =
738 "Request could not be completed because the relevant data model content does not exist ";
739 LOG.debug(errMsg + identifier);
740 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
742 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
746 public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload,
747 final UriInfo uriInfo) {
748 boolean insert_used = false;
749 boolean point_used = false;
750 String insert = null;
753 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
754 switch (entry.getKey()) {
758 insert = entry.getValue().iterator().next();
760 throw new RestconfDocumentedException("Insert parameter can be used only once.");
766 point = entry.getValue().iterator().next();
768 throw new RestconfDocumentedException("Point parameter can be used only once.");
772 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
776 if (point_used && !insert_used) {
777 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
779 if (point_used && (insert.equals("first") || insert.equals("last"))) {
780 throw new RestconfDocumentedException(
781 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
784 Preconditions.checkNotNull(identifier);
786 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
788 validateInput(iiWithData.getSchemaNode(), payload);
789 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
790 validateListKeysEqualityInPayloadAndUri(payload);
792 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
793 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
796 * There is a small window where another write transaction could be
797 * updating the same data simultaneously and we get an
798 * OptimisticLockFailedException. This error is likely transient and The
799 * WriteTransaction#submit API docs state that a retry will likely
800 * succeed. So we'll try again if that scenario occurs. If it fails a
801 * third time then it probably will never succeed so we'll fail in that
804 * By retrying we're attempting to hide the internal implementation of
805 * the data store and how it handles concurrent updates from the
806 * restconf client. The client has instructed us to put the data and we
807 * should make every effort to do so without pushing optimistic lock
808 * failures back to the client and forcing them to handle it via retry
809 * (and having to document the behavior).
811 PutResult result = null;
812 final TryOfPutData tryPutData = new TryOfPutData();
814 if (mountPoint != null) {
816 result = this.broker.commitMountPointDataPut(mountPoint, normalizedII, payload.getData(), insert,
819 result = this.broker.commitConfigurationDataPut(this.controllerContext.getGlobalSchema(), normalizedII,
820 payload.getData(), insert, point);
822 final CountDownLatch waiter = new CountDownLatch(1);
823 Futures.addCallback(result.getFutureOfPutData(), new FutureCallback<Void>() {
826 public void onSuccess(final Void result) {
827 handlingLoggerPut(null, tryPutData, identifier);
832 public void onFailure(final Throwable t) {
834 handlingLoggerPut(t, tryPutData, identifier);
840 } catch (final Exception e) {
841 final String msg = "Problem while waiting for response";
843 throw new RestconfDocumentedException(msg, e);
846 if (tryPutData.isDone()) {
849 throw new RestconfDocumentedException("Problem while PUT operations");
853 return Response.status(result.getStatus()).build();
856 protected void handlingLoggerPut(final Throwable t, final TryOfPutData tryPutData, final String identifier) {
858 if (t instanceof OptimisticLockFailedException) {
859 if (tryPutData.countGet() <= 0) {
860 LOG.debug("Got OptimisticLockFailedException on last try - failing " + identifier);
861 throw new RestconfDocumentedException(t.getMessage(), t);
863 LOG.debug("Got OptimisticLockFailedException - trying again " + identifier);
864 tryPutData.countDown();
866 LOG.debug("Update ConfigDataStore fail " + identifier, t);
867 throw new RestconfDocumentedException(t.getMessage(), t);
870 LOG.trace("PUT Successful " + identifier);
875 private static void validateTopLevelNodeName(final NormalizedNodeContext node,
876 final YangInstanceIdentifier identifier) {
878 final String payloadName = node.getData().getNodeType().getLocalName();
881 if (identifier.isEmpty()) {
883 if (!node.getData().getNodeType().equals(NETCONF_BASE_QNAME)) {
884 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
885 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
889 final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
890 if (!payloadName.equals(identifierName)) {
891 throw new RestconfDocumentedException(
892 "Payload name (" + payloadName + ") is different from identifier name (" + identifierName + ")",
893 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
899 * Validates whether keys in {@code payload} are equal to values of keys in
900 * {@code iiWithData} for list schema node
902 * @throws RestconfDocumentedException
903 * if key values or key count in payload and URI isn't equal
906 private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
907 Preconditions.checkArgument(payload != null);
908 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
909 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
910 final SchemaNode schemaNode = iiWithData.getSchemaNode();
911 final NormalizedNode<?, ?> data = payload.getData();
912 if (schemaNode instanceof ListSchemaNode) {
913 final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
914 if ((lastPathArgument instanceof NodeIdentifierWithPredicates) && (data instanceof MapEntryNode)) {
915 final Map<QName, Object> uriKeyValues =
916 ((NodeIdentifierWithPredicates) lastPathArgument).getKeyValues();
917 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
922 private static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final MapEntryNode payload,
923 final List<QName> keyDefinitions) {
925 final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
926 for (final QName keyDefinition : keyDefinitions) {
927 final Object uriKeyValue = mutableCopyUriKeyValues.remove(keyDefinition);
928 // should be caught during parsing URI to InstanceIdentifier
929 RestconfValidationUtils.checkDocumentedError(uriKeyValue != null, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
930 "Missing key " + keyDefinition + " in URI.");
932 final Object dataKeyValue = payload.getIdentifier().getKeyValues().get(keyDefinition);
934 if (!uriKeyValue.equals(dataKeyValue)) {
935 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName()
936 + "' specified in the URI doesn't match the value '" + dataKeyValue
937 + "' specified in the message body. ";
938 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
944 public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload,
945 final UriInfo uriInfo) {
946 return createConfigurationData(payload, uriInfo);
949 // FIXME create RestconfIdetifierHelper and move this method there
950 private static YangInstanceIdentifier checkConsistencyOfNormalizedNodeContext(final NormalizedNodeContext payload) {
951 Preconditions.checkArgument(payload != null);
952 Preconditions.checkArgument(payload.getData() != null);
953 Preconditions.checkArgument(payload.getData().getNodeType() != null);
954 Preconditions.checkArgument(payload.getInstanceIdentifierContext() != null);
955 Preconditions.checkArgument(payload.getInstanceIdentifierContext().getInstanceIdentifier() != null);
957 final QName payloadNodeQname = payload.getData().getNodeType();
958 final YangInstanceIdentifier yangIdent = payload.getInstanceIdentifierContext().getInstanceIdentifier();
959 if (payloadNodeQname.compareTo(yangIdent.getLastPathArgument().getNodeType()) > 0) {
962 final InstanceIdentifierContext<?> parentContext = payload.getInstanceIdentifierContext();
963 final SchemaNode parentSchemaNode = parentContext.getSchemaNode();
964 if (parentSchemaNode instanceof DataNodeContainer) {
965 final DataNodeContainer cast = (DataNodeContainer) parentSchemaNode;
966 for (final DataSchemaNode child : cast.getChildNodes()) {
967 if (payloadNodeQname.compareTo(child.getQName()) == 0) {
968 return YangInstanceIdentifier.builder(yangIdent).node(child.getQName()).build();
972 if (parentSchemaNode instanceof RpcDefinition) {
975 final String errMsg = "Error parsing input: DataSchemaNode has not children ";
976 LOG.info(errMsg + yangIdent);
977 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
981 public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
982 if (payload == null) {
983 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
985 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
986 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
987 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
989 boolean insert_used = false;
990 boolean point_used = false;
991 String insert = null;
994 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
995 switch (entry.getKey()) {
999 insert = entry.getValue().iterator().next();
1001 throw new RestconfDocumentedException("Insert parameter can be used only once.");
1007 point = entry.getValue().iterator().next();
1009 throw new RestconfDocumentedException("Point parameter can be used only once.");
1013 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
1017 if (point_used && !insert_used) {
1018 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
1020 if (point_used && (insert.equals("first") || insert.equals("last"))) {
1021 throw new RestconfDocumentedException(
1022 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
1025 CheckedFuture<Void, TransactionCommitFailedException> future;
1026 if (mountPoint != null) {
1027 future = this.broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData(), insert,
1030 future = this.broker.commitConfigurationDataPost(this.controllerContext.getGlobalSchema(), normalizedII,
1031 payload.getData(), insert, point);
1034 final CountDownLatch waiter = new CountDownLatch(1);
1035 Futures.addCallback(future, new FutureCallback<Void>() {
1038 public void onSuccess(final Void result) {
1039 handlerLoggerPost(null, uriInfo);
1044 public void onFailure(final Throwable t) {
1046 handlerLoggerPost(t, uriInfo);
1052 } catch (final Exception e) {
1053 final String msg = "Problem while waiting for response";
1055 throw new RestconfDocumentedException(msg, e);
1058 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
1059 // FIXME: Provide path to result.
1060 final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
1061 if (location != null) {
1062 responseBuilder.location(location);
1064 return responseBuilder.build();
1067 protected void handlerLoggerPost(final Throwable t, final UriInfo uriInfo) {
1069 final String errMsg = "Error creating data ";
1070 LOG.warn(errMsg + (uriInfo != null ? uriInfo.getPath() : ""), t);
1071 throw new RestconfDocumentedException(errMsg, t);
1073 LOG.trace("Successfuly create data.");
1077 private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint,
1078 final YangInstanceIdentifier normalizedII) {
1079 if (uriInfo == null) {
1080 // This is null if invoked internally
1084 final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
1085 uriBuilder.path("config");
1087 uriBuilder.path(this.controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
1088 } catch (final Exception e) {
1089 LOG.info("Location for instance identifier" + normalizedII + "wasn't created", e);
1092 return uriBuilder.build();
1096 public Response deleteConfigurationData(final String identifier) {
1097 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
1098 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
1099 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
1101 final CheckedFuture<Void, TransactionCommitFailedException> future;
1102 if (mountPoint != null) {
1103 future = this.broker.commitConfigurationDataDelete(mountPoint, normalizedII);
1105 future = this.broker.commitConfigurationDataDelete(normalizedII);
1108 final CountDownLatch waiter = new CountDownLatch(1);
1109 final ResultOperation result = new ResultOperation();
1110 Futures.addCallback(future, new FutureCallback<Void>() {
1113 public void onSuccess(final Void result) {
1114 LOG.trace("Successfuly delete data.");
1119 public void onFailure(final Throwable t) {
1121 result.setFailed(t);
1128 } catch (final Exception e) {
1129 final String msg = "Problem while waiting for response";
1131 throw new RestconfDocumentedException(msg, e);
1133 if (result.failed() != null) {
1134 final Throwable t = result.failed();
1135 final String errMsg = "Error while deleting data";
1136 LOG.info(errMsg, t);
1137 throw new RestconfDocumentedException(errMsg, RestconfError.ErrorType.APPLICATION,
1138 RestconfError.ErrorTag.OPERATION_FAILED, t);
1140 return Response.status(Status.OK).build();
1143 private class ResultOperation {
1144 private Throwable t = null;
1146 public void setFailed(final Throwable t) {
1150 public Throwable failed() {
1156 * Subscribes to some path in schema context (stream) to listen on changes
1159 * Additional parameters for subscribing to stream are loaded via rpc input
1162 * <li>datastore - default CONFIGURATION (other values of
1163 * {@link LogicalDatastoreType} enum type)</li>
1164 * <li>scope - default BASE (other values of {@link DataChangeScope})</li>
1168 public NormalizedNodeContext subscribeToStream(final String identifier, final UriInfo uriInfo) {
1169 boolean startTime_used = false;
1170 boolean stopTime_used = false;
1171 boolean filter_used = false;
1174 String filter = null;
1176 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
1177 switch (entry.getKey()) {
1179 if (!startTime_used) {
1180 startTime_used = true;
1181 start = parseDateFromQueryParam(entry);
1183 throw new RestconfDocumentedException("Start-time parameter can be used only once.");
1187 if (!stopTime_used) {
1188 stopTime_used = true;
1189 stop = parseDateFromQueryParam(entry);
1191 throw new RestconfDocumentedException("Stop-time parameter can be used only once.");
1197 filter = entry.getValue().iterator().next();
1199 throw new RestconfDocumentedException("Filter parameter can be used only once.");
1203 throw new RestconfDocumentedException("Bad parameter used with notifications: " + entry.getKey());
1206 if (!startTime_used && stopTime_used) {
1207 throw new RestconfDocumentedException("Stop-time parameter has to be used with start-time parameter.");
1209 URI response = null;
1210 if (identifier.contains(DATA_SUBSCR)) {
1211 response = dataSubs(identifier, uriInfo, start, stop, filter);
1212 } else if (identifier.contains(NOTIFICATION_STREAM)) {
1213 response = notifStream(identifier, uriInfo, start, stop, filter);
1216 if (response != null) {
1217 // prepare node with value of location
1218 final InstanceIdentifierContext<?> iid = prepareIIDSubsStreamOutput();
1219 final NormalizedNodeAttrBuilder<NodeIdentifier, Object, LeafNode<Object>> builder =
1220 ImmutableLeafNodeBuilder.create().withValue(response.toString());
1221 builder.withNodeIdentifier(
1222 NodeIdentifier.create(QName.create("subscribe:to:notification", "2016-10-28", "location")));
1224 // prepare new header with location
1225 final Map<String, Object> headers = new HashMap<>();
1226 headers.put("Location", response);
1228 return new NormalizedNodeContext(iid, builder.build(), headers);
1231 final String msg = "Bad type of notification of sal-remote";
1233 throw new RestconfDocumentedException(msg);
1236 private Date parseDateFromQueryParam(final Entry<String, List<String>> entry) {
1237 final DateAndTime event = new DateAndTime(entry.getValue().iterator().next());
1238 String numOf_ms = "";
1239 final String value = event.getValue();
1240 if (value.contains(".")) {
1241 numOf_ms = numOf_ms + ".";
1242 final int lastChar = value.contains("Z") ? value.indexOf("Z") : (value.contains("+") ? value.indexOf("+")
1243 : (value.contains("-") ? value.indexOf("-") : value.length()));
1244 for (int i = 0; i < (lastChar - value.indexOf(".") - 1); i++) {
1245 numOf_ms = numOf_ms + "S";
1249 if (!value.contains("Z")) {
1250 zone = zone + "XXX";
1252 final DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss" + numOf_ms + zone);
1255 return dateFormatter.parse(value.contains("Z") ? value.replace('T', ' ').substring(0, value.indexOf("Z"))
1256 : value.replace('T', ' '));
1257 } catch (final ParseException e) {
1258 throw new RestconfDocumentedException("Cannot parse of value in date: " + value + e);
1263 * @return {@link InstanceIdentifierContext} of location leaf for
1266 private InstanceIdentifierContext<?> prepareIIDSubsStreamOutput() {
1267 final QName qnameBase = QName.create("subscribe:to:notification", "2016-10-28", "notifi");
1268 final SchemaContext schemaCtx = ControllerContext.getInstance().getGlobalSchema();
1269 final DataSchemaNode location = ((ContainerSchemaNode) schemaCtx
1270 .findModuleByNamespaceAndRevision(qnameBase.getNamespace(), qnameBase.getRevision())
1271 .getDataChildByName(qnameBase)).getDataChildByName(QName.create(qnameBase, "location"));
1272 final List<PathArgument> path = new ArrayList<>();
1273 path.add(NodeIdentifier.create(qnameBase));
1274 path.add(NodeIdentifier.create(QName.create(qnameBase, "location")));
1276 return new InstanceIdentifierContext<SchemaNode>(YangInstanceIdentifier.create(path), location, null,
1281 * Register notification listener by stream name
1288 * - stop-time of getting notification
1290 * - start-time of getting notification
1292 * - indicate wh ich subset of allpossible events are of interest
1293 * @return {@link URI} of location
1295 private URI notifStream(final String identifier, final UriInfo uriInfo, final Date start, final Date stop,
1296 final String filter) {
1297 final String streamName = Notificator.createStreamNameFromUri(identifier);
1298 if (Strings.isNullOrEmpty(streamName)) {
1299 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1301 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
1302 if ((listeners == null) || listeners.isEmpty()) {
1303 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1304 ErrorTag.UNKNOWN_ELEMENT);
1307 for (final NotificationListenerAdapter listener : listeners) {
1308 this.broker.registerToListenNotification(listener);
1309 listener.setQueryParams(start, stop, filter);
1312 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1313 int notificationPort = NOTIFICATION_PORT;
1315 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
1316 notificationPort = webSocketServerInstance.getPort();
1317 } catch (final NullPointerException e) {
1318 WebSocketServer.createInstance(NOTIFICATION_PORT);
1320 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1321 final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
1323 return uriToWebsocketServer;
1327 * Register data change listener by stream name
1334 * - start-time of getting notification
1336 * - stop-time of getting notification
1338 * - indicate which subset of all possible events are of interest
1339 * @return {@link URI} of location
1341 private URI dataSubs(final String identifier, final UriInfo uriInfo, final Date start, final Date stop,
1342 final String filter) {
1343 final String streamName = Notificator.createStreamNameFromUri(identifier);
1344 if (Strings.isNullOrEmpty(streamName)) {
1345 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1348 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1349 if (listener == null) {
1350 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1351 ErrorTag.UNKNOWN_ELEMENT);
1353 listener.setQueryParams(start, stop, filter);
1355 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1356 final LogicalDatastoreType datastore =
1357 parserURIEnumParameter(LogicalDatastoreType.class, paramToValues.get(DATASTORE_PARAM_NAME));
1358 if (datastore == null) {
1359 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1360 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1362 final DataChangeScope scope =
1363 parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
1364 if (scope == null) {
1365 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1366 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1369 this.broker.registerToListenDataChanges(datastore, scope, listener);
1371 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1372 int notificationPort = NOTIFICATION_PORT;
1374 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
1375 notificationPort = webSocketServerInstance.getPort();
1376 } catch (final NullPointerException e) {
1377 WebSocketServer.createInstance(NOTIFICATION_PORT);
1379 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1380 final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
1382 return uriToWebsocketServer;
1386 public PATCHStatusContext patchConfigurationData(final String identifier, final PATCHContext context,
1387 final UriInfo uriInfo) {
1388 if (context == null) {
1389 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1393 return this.broker.patchConfigurationDataWithinTransaction(context);
1394 } catch (final Exception e) {
1395 LOG.debug("Patch transaction failed", e);
1396 throw new RestconfDocumentedException(e.getMessage());
1401 public PATCHStatusContext patchConfigurationData(final PATCHContext context, @Context final UriInfo uriInfo) {
1402 if (context == null) {
1403 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1407 return this.broker.patchConfigurationDataWithinTransaction(context);
1408 } catch (final Exception e) {
1409 LOG.debug("Patch transaction failed", e);
1410 throw new RestconfDocumentedException(e.getMessage());
1415 * Load parameter for subscribing to stream from input composite node
1419 * @return enum object if its string value is equal to {@code paramName}. In
1422 private static <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1423 final String paramName) {
1424 final Optional<DataContainerChild<? extends PathArgument, ?>> augNode =
1425 value.getChild(SAL_REMOTE_AUG_IDENTIFIER);
1426 if (!augNode.isPresent() && !(augNode instanceof AugmentationNode)) {
1429 final Optional<DataContainerChild<? extends PathArgument, ?>> enumNode = ((AugmentationNode) augNode.get())
1430 .getChild(new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1431 if (!enumNode.isPresent()) {
1434 final Object rawValue = enumNode.get().getValue();
1435 if (!(rawValue instanceof String)) {
1439 return resolveAsEnum(classDescriptor, (String) rawValue);
1443 * Checks whether {@code value} is one of the string representation of
1444 * enumeration {@code classDescriptor}
1446 * @return enum object if string value of {@code classDescriptor}
1447 * enumeration is equal to {@code value}. Other cases null.
1449 private static <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1450 if (Strings.isNullOrEmpty(value)) {
1453 return resolveAsEnum(classDescriptor, value);
1456 private static <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1457 final T[] enumConstants = classDescriptor.getEnumConstants();
1458 if (enumConstants != null) {
1459 for (final T enm : classDescriptor.getEnumConstants()) {
1460 if (((Enum<?>) enm).name().equals(value)) {
1468 private static Map<String, String> resolveValuesFromUri(final String uri) {
1469 final Map<String, String> result = new HashMap<>();
1470 final String[] tokens = uri.split("/");
1471 for (int i = 1; i < tokens.length; i++) {
1472 final String[] parameterTokens = tokens[i].split("=");
1473 if (parameterTokens.length == 2) {
1474 result.put(parameterTokens[0], parameterTokens[1]);
1480 private MapNode makeModuleMapNode(final Set<Module> modules) {
1481 Preconditions.checkNotNull(modules);
1482 final Module restconfModule = getRestconfModule();
1483 final DataSchemaNode moduleSchemaNode = this.controllerContext
1484 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1485 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1487 final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder =
1488 Builders.mapBuilder((ListSchemaNode) moduleSchemaNode);
1490 for (final Module module : modules) {
1491 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1493 return listModuleBuilder.build();
1496 protected MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1497 Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1498 "moduleSchemaNode has to be of type ListSchemaNode");
1499 final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1500 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues =
1501 Builders.mapEntryBuilder(listModuleSchemaNode);
1503 List<DataSchemaNode> instanceDataChildrenByName =
1504 ControllerContext.findInstanceDataChildrenByName((listModuleSchemaNode), "name");
1505 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1506 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1508 .withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName()).build());
1510 instanceDataChildrenByName =
1511 ControllerContext.findInstanceDataChildrenByName((listModuleSchemaNode), "revision");
1512 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1513 Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1514 final String revision = REVISION_FORMAT.format(module.getRevision());
1516 .withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode).withValue(revision).build());
1518 instanceDataChildrenByName =
1519 ControllerContext.findInstanceDataChildrenByName((listModuleSchemaNode), "namespace");
1520 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1521 Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1522 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1523 .withValue(module.getNamespace().toString()).build());
1525 instanceDataChildrenByName =
1526 ControllerContext.findInstanceDataChildrenByName((listModuleSchemaNode), "feature");
1527 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1528 Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1529 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder =
1530 Builders.leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1531 for (final FeatureDefinition feature : module.getFeatures()) {
1532 featuresBuilder.withChild(Builders.leafSetEntryBuilder(((LeafListSchemaNode) featureSchemaNode))
1533 .withValue(feature.getQName().getLocalName()).build());
1535 moduleNodeValues.withChild(featuresBuilder.build());
1537 return moduleNodeValues.build();
1540 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1541 Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1542 "streamSchemaNode has to be of type ListSchemaNode");
1543 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1544 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues =
1545 Builders.mapEntryBuilder(listStreamSchemaNode);
1547 List<DataSchemaNode> instanceDataChildrenByName =
1548 ControllerContext.findInstanceDataChildrenByName((listStreamSchemaNode), "name");
1549 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1550 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1551 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName).build());
1553 instanceDataChildrenByName =
1554 ControllerContext.findInstanceDataChildrenByName((listStreamSchemaNode), "description");
1555 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1556 Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1557 streamNodeValues.withChild(
1558 Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue("DESCRIPTION_PLACEHOLDER").build());
1560 instanceDataChildrenByName =
1561 ControllerContext.findInstanceDataChildrenByName((listStreamSchemaNode), "replay-support");
1562 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1563 Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1564 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1565 .withValue(Boolean.valueOf(true)).build());
1567 instanceDataChildrenByName =
1568 ControllerContext.findInstanceDataChildrenByName((listStreamSchemaNode), "replay-log-creation-time");
1569 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1570 Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1571 streamNodeValues.withChild(
1572 Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode).withValue("").build());
1574 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName((listStreamSchemaNode), "events");
1575 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1576 Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1577 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode).withValue("").build());
1579 return streamNodeValues.build();
1583 * Prepare stream for notification
1586 * - contains list of qnames of notifications
1587 * @return - checked future object
1589 private CheckedFuture<DOMRpcResult, DOMRpcException>
1590 invokeSalRemoteRpcNotifiStrRPC(final NormalizedNodeContext payload) {
1591 final ContainerNode data = (ContainerNode) payload.getData();
1592 LeafSetNode leafSet = null;
1593 String outputType = "XML";
1594 for (final DataContainerChild<? extends PathArgument, ?> dataChild : data.getValue()) {
1595 if (dataChild instanceof LeafSetNode) {
1596 leafSet = (LeafSetNode) dataChild;
1597 } else if (dataChild instanceof AugmentationNode) {
1598 outputType = (String) (((AugmentationNode) dataChild).getValue()).iterator().next().getValue();
1602 final Collection<LeafSetEntryNode> entryNodes = leafSet.getValue();
1603 final List<SchemaPath> paths = new ArrayList<>();
1604 String streamName = CREATE_NOTIFICATION_STREAM + "/";
1606 final Iterator<LeafSetEntryNode> iterator = entryNodes.iterator();
1607 while (iterator.hasNext()) {
1608 final QName valueQName = QName.create((String) iterator.next().getValue());
1609 final Module module =
1610 ControllerContext.getInstance().findModuleByNamespace(valueQName.getModule().getNamespace());
1611 Preconditions.checkNotNull(module,
1612 "Module for namespace " + valueQName.getModule().getNamespace() + " does not exist");
1613 NotificationDefinition notifiDef = null;
1614 for (final NotificationDefinition notification : module.getNotifications()) {
1615 if (notification.getQName().equals(valueQName)) {
1616 notifiDef = notification;
1620 final String moduleName = module.getName();
1621 Preconditions.checkNotNull(notifiDef,
1622 "Notification " + valueQName + "doesn't exist in module " + moduleName);
1623 paths.add(notifiDef.getPath());
1624 streamName = streamName + moduleName + ":" + valueQName.getLocalName();
1625 if (iterator.hasNext()) {
1626 streamName = streamName + ",";
1630 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
1631 final QName outputQname = QName.create(rpcQName, "output");
1632 final QName streamNameQname = QName.create(rpcQName, "notification-stream-identifier");
1634 final ContainerNode output =
1635 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
1636 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
1638 if (!Notificator.existNotificationListenerFor(streamName)) {
1639 Notificator.createNotificationListener(paths, streamName, outputType);
1642 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
1644 return Futures.immediateCheckedFuture(defaultDOMRpcResult);
1647 private class TryOfPutData {
1649 boolean done = false;