2 * Copyright (c) 2014, 2015 Brocade Communication Systems, Inc., Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.netconf.sal.restconf.impl;
11 import com.google.common.base.CharMatcher;
12 import com.google.common.base.Optional;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Predicates;
15 import com.google.common.base.Splitter;
16 import com.google.common.base.Strings;
17 import com.google.common.base.Throwables;
18 import com.google.common.collect.ImmutableSet;
19 import com.google.common.collect.Iterables;
20 import com.google.common.collect.Lists;
21 import com.google.common.collect.Maps;
22 import com.google.common.collect.Sets;
23 import com.google.common.util.concurrent.CheckedFuture;
24 import com.google.common.util.concurrent.Futures;
26 import java.net.URISyntaxException;
27 import java.text.DateFormat;
28 import java.text.ParseException;
29 import java.text.SimpleDateFormat;
30 import java.util.ArrayList;
31 import java.util.Collection;
32 import java.util.Collections;
33 import java.util.Date;
34 import java.util.HashMap;
35 import java.util.Iterator;
36 import java.util.List;
38 import java.util.Map.Entry;
40 import java.util.concurrent.CancellationException;
41 import java.util.concurrent.ExecutionException;
42 import javax.ws.rs.core.Context;
43 import javax.ws.rs.core.Response;
44 import javax.ws.rs.core.Response.ResponseBuilder;
45 import javax.ws.rs.core.Response.Status;
46 import javax.ws.rs.core.UriBuilder;
47 import javax.ws.rs.core.UriInfo;
48 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
49 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
50 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
51 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
52 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
53 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
54 import org.opendaylight.controller.md.sal.dom.api.DOMRpcImplementationNotAvailableException;
55 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
56 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
57 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
58 import org.opendaylight.netconf.md.sal.rest.common.RestconfValidationUtils;
59 import org.opendaylight.netconf.sal.rest.api.Draft02;
60 import org.opendaylight.netconf.sal.rest.api.RestconfService;
61 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
62 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
63 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
64 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
65 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
66 import org.opendaylight.netconf.sal.streams.websockets.WebSocketServer;
67 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
68 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
69 import org.opendaylight.yangtools.yang.common.QName;
70 import org.opendaylight.yangtools.yang.common.QNameModule;
71 import org.opendaylight.yangtools.yang.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.api.schema.tree.ModifiedNodeDoesNotExistException;
85 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
86 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
87 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
88 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
89 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
90 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
91 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
92 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
93 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
94 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
95 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
96 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
97 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
98 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
99 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
100 import org.opendaylight.yangtools.yang.model.api.Module;
101 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
102 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
103 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
104 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
105 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
106 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.EffectiveSchemaContext;
107 import org.slf4j.Logger;
108 import org.slf4j.LoggerFactory;
110 public class RestconfImpl implements RestconfService {
112 private static final RestconfImpl INSTANCE = new RestconfImpl();
115 * Notifications are served on port 8181.
117 private static final int NOTIFICATION_PORT = 8181;
119 private static final int CHAR_NOT_FOUND = -1;
121 private static final SimpleDateFormat REVISION_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
123 private static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
125 private BrokerFacade broker;
127 private ControllerContext controllerContext;
129 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
131 private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
133 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
135 private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
137 private static final String DATASTORE_PARAM_NAME = "datastore";
139 private static final String SCOPE_PARAM_NAME = "scope";
141 private static final String OUTPUT_TYPE_PARAM_NAME = "notification-output-type";
143 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
145 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
147 private static final QName NETCONF_BASE_QNAME;
149 private static final QNameModule SAL_REMOTE_AUGMENT;
151 private static final YangInstanceIdentifier.AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER;
153 public static final CharSequence DATA_SUBSCR = "data-change-event-subscription";
154 private static final CharSequence CREATE_DATA_SUBSCR = "create-" + DATA_SUBSCR;
156 public static final CharSequence NOTIFICATION_STREAM = "notification-stream";
157 private static final CharSequence CREATE_NOTIFICATION_STREAM = "create-" + NOTIFICATION_STREAM;
161 final Date eventSubscriptionAugRevision = new SimpleDateFormat("yyyy-MM-dd").parse("2014-07-08");
163 QName.create(QNameModule.create(new URI(NETCONF_BASE), null), NETCONF_BASE_PAYLOAD_NAME);
164 SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT, eventSubscriptionAugRevision);
165 SAL_REMOTE_AUG_IDENTIFIER = new YangInstanceIdentifier.AugmentationIdentifier(Sets.newHashSet(
166 QName.create(SAL_REMOTE_AUGMENT, "scope"), QName.create(SAL_REMOTE_AUGMENT, "datastore"),
167 QName.create(SAL_REMOTE_AUGMENT, "notification-output-type")));
168 } catch (final ParseException e) {
169 final String errMsg = "It wasn't possible to convert revision date of sal-remote-augment to date";
171 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
172 } catch (final URISyntaxException e) {
173 final String errMsg = "It wasn't possible to create instance of URI class with " + NETCONF_BASE + " URI";
174 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
178 public void setBroker(final BrokerFacade broker) {
179 this.broker = broker;
182 public void setControllerContext(final ControllerContext controllerContext) {
183 this.controllerContext = controllerContext;
186 private RestconfImpl() {
189 public static RestconfImpl getInstance() {
194 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
195 final Set<Module> allModules = this.controllerContext.getAllModules();
196 final MapNode allModuleMap = makeModuleMapNode(allModules);
198 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
200 final Module restconfModule = getRestconfModule();
201 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
202 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
203 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
205 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
206 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
207 moduleContainerBuilder.withChild(allModuleMap);
209 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode, null, schemaContext),
210 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
214 * Valid only for mount point
217 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
218 Preconditions.checkNotNull(identifier);
219 if (!identifier.contains(ControllerContext.MOUNT)) {
220 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
221 + " URI has to end with " + ControllerContext.MOUNT;
222 LOG.debug(errMsg + " for " + identifier);
223 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
226 final InstanceIdentifierContext<?> mountPointIdentifier =
227 this.controllerContext.toMountPointIdentifier(identifier);
228 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
229 final Set<Module> modules = this.controllerContext.getAllModules(mountPoint);
230 final MapNode mountPointModulesMap = makeModuleMapNode(modules);
232 final Module restconfModule = getRestconfModule();
233 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
234 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
235 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
237 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
238 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
239 moduleContainerBuilder.withChild(mountPointModulesMap);
241 return new NormalizedNodeContext(
242 new InstanceIdentifierContext<>(null, modulesSchemaNode, mountPoint,
243 this.controllerContext.getGlobalSchema()),
244 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
248 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
249 Preconditions.checkNotNull(identifier);
250 final QName moduleNameAndRevision = getModuleNameAndRevision(identifier);
251 Module module = null;
252 DOMMountPoint mountPoint = null;
253 final SchemaContext schemaContext;
254 if (identifier.contains(ControllerContext.MOUNT)) {
255 final InstanceIdentifierContext<?> mountPointIdentifier =
256 this.controllerContext.toMountPointIdentifier(identifier);
257 mountPoint = mountPointIdentifier.getMountPoint();
258 module = this.controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision);
259 schemaContext = mountPoint.getSchemaContext();
261 module = this.controllerContext.findModuleByNameAndRevision(moduleNameAndRevision);
262 schemaContext = this.controllerContext.getGlobalSchema();
265 if (module == null) {
266 final String errMsg = "Module with name '" + moduleNameAndRevision.getLocalName() + "' and revision '"
267 + moduleNameAndRevision.getRevision() + "' was not found.";
269 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
272 final Module restconfModule = getRestconfModule();
273 final Set<Module> modules = Collections.singleton(module);
274 final MapNode moduleMap = makeModuleMapNode(modules);
276 final DataSchemaNode moduleSchemaNode = this.controllerContext
277 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
278 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
280 return new NormalizedNodeContext(
281 new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint, schemaContext), moduleMap,
282 QueryParametersParser.parseWriterParameters(uriInfo));
286 public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
287 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
288 final Set<String> availableStreams = Notificator.getStreamNames();
289 final Module restconfModule = getRestconfModule();
290 final DataSchemaNode streamSchemaNode = this.controllerContext
291 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
292 Preconditions.checkState(streamSchemaNode instanceof ListSchemaNode);
294 final CollectionNodeBuilder<MapEntryNode, MapNode> listStreamsBuilder =
295 Builders.mapBuilder((ListSchemaNode) streamSchemaNode);
297 for (final String streamName : availableStreams) {
298 listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
301 final DataSchemaNode streamsContainerSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
302 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
303 Preconditions.checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
305 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
306 Builders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
307 streamsContainerBuilder.withChild(listStreamsBuilder.build());
309 return new NormalizedNodeContext(
310 new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null, schemaContext),
311 streamsContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
315 public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
316 final Set<Module> allModules = this.controllerContext.getAllModules();
317 return operationsFromModulesToNormalizedContext(allModules, null);
321 public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
322 Set<Module> modules = null;
323 DOMMountPoint mountPoint = null;
324 if (identifier.contains(ControllerContext.MOUNT)) {
325 final InstanceIdentifierContext<?> mountPointIdentifier =
326 this.controllerContext.toMountPointIdentifier(identifier);
327 mountPoint = mountPointIdentifier.getMountPoint();
328 modules = this.controllerContext.getAllModules(mountPoint);
331 final String errMsg =
332 "URI has bad format. If operations behind mount point should be showed, URI has to " + "end with ";
333 LOG.debug(errMsg + ControllerContext.MOUNT + " for " + identifier);
334 throw new RestconfDocumentedException(errMsg + ControllerContext.MOUNT, ErrorType.PROTOCOL,
335 ErrorTag.INVALID_VALUE);
338 return operationsFromModulesToNormalizedContext(modules, mountPoint);
342 * Special case only for GET restconf/operations use (since moment of
343 * pre-Beryllium Yang parser and Yang model API removal). The method is
344 * creating fake schema context with fake module and fake data by use own
345 * implementations of schema nodes and module.
348 * - set of modules for get RPCs from every module
350 * - mount point, if in use otherwise null
351 * @return {@link NormalizedNodeContext}
353 private NormalizedNodeContext operationsFromModulesToNormalizedContext(final Set<Module> modules,
354 final DOMMountPoint mountPoint) {
356 final Collection<Module> neededModules = new ArrayList<>(modules.size());
357 final ArrayList<LeafSchemaNode> fakeRpcSchema = new ArrayList<>();
359 for (final Module m : modules) {
360 final Set<RpcDefinition> rpcs = m.getRpcs();
361 if (!rpcs.isEmpty()) {
362 neededModules.add(m);
364 fakeRpcSchema.ensureCapacity(fakeRpcSchema.size() + rpcs.size());
365 rpcs.forEach(rpc -> fakeRpcSchema.add(new FakeLeafSchemaNode(rpc.getQName())));
369 final ContainerSchemaNode fakeCont = new FakeContainerSchemaNode(fakeRpcSchema);
370 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> containerBuilder =
371 Builders.containerBuilder(fakeCont);
373 for (final LeafSchemaNode leaf : fakeRpcSchema) {
374 containerBuilder.withChild(Builders.leafBuilder(leaf).build());
377 final Collection<Module> fakeModules = new ArrayList<>(neededModules.size() + 1);
378 neededModules.forEach(imp -> fakeModules.add(new FakeImportedModule(imp)));
379 fakeModules.add(new FakeRestconfModule(neededModules, fakeCont));
381 final SchemaContext fakeSchemaCtx =
382 EffectiveSchemaContext.resolveSchemaContext(ImmutableSet.copyOf(fakeModules));
383 final InstanceIdentifierContext<ContainerSchemaNode> instanceIdentifierContext =
384 new InstanceIdentifierContext<>(null, fakeCont, mountPoint, fakeSchemaCtx);
385 return new NormalizedNodeContext(instanceIdentifierContext, containerBuilder.build());
388 private Module getRestconfModule() {
389 final Module restconfModule = this.controllerContext.getRestconfModule();
390 if (restconfModule == null) {
391 LOG.debug("ietf-restconf module was not found.");
392 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
393 ErrorTag.OPERATION_NOT_SUPPORTED);
396 return restconfModule;
399 private static QName getModuleNameAndRevision(final String identifier) {
400 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
401 String moduleNameAndRevision = "";
402 if (mountIndex >= 0) {
403 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
405 moduleNameAndRevision = identifier;
408 final Splitter splitter = Splitter.on("/").omitEmptyStrings();
409 final Iterable<String> split = splitter.split(moduleNameAndRevision);
410 final List<String> pathArgs = Lists.<String> newArrayList(split);
411 if (pathArgs.size() < 2) {
412 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
413 throw new RestconfDocumentedException(
414 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
415 ErrorTag.INVALID_VALUE);
419 final String moduleName = pathArgs.get(0);
420 final String revision = pathArgs.get(1);
421 final Date moduleRevision = REVISION_FORMAT.parse(revision);
422 return QName.create(null, moduleRevision, moduleName);
423 } catch (final ParseException e) {
424 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
425 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
426 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
431 public Object getRoot() {
436 public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload,
437 final UriInfo uriInfo) {
438 final SchemaPath type = payload.getInstanceIdentifierContext().getSchemaNode().getPath();
439 final URI namespace = payload.getInstanceIdentifierContext().getSchemaNode().getQName().getNamespace();
440 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
441 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
442 final SchemaContext schemaContext;
444 if (mountPoint != null) {
445 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
446 if (!mountRpcServices.isPresent()) {
447 LOG.debug("Error: Rpc service is missing.");
448 throw new RestconfDocumentedException("Rpc service is missing.");
450 schemaContext = mountPoint.getSchemaContext();
451 response = mountRpcServices.get().invokeRpc(type, payload.getData());
453 if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
454 if (identifier.contains(CREATE_DATA_SUBSCR)) {
455 response = invokeSalRemoteRpcSubscribeRPC(payload);
456 } else if (identifier.contains(CREATE_NOTIFICATION_STREAM)) {
457 response = invokeSalRemoteRpcNotifiStrRPC(payload);
459 final String msg = "Not supported operation";
461 throw new RestconfDocumentedException(msg, ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED);
464 response = this.broker.invokeRpc(type, payload.getData());
466 schemaContext = this.controllerContext.getGlobalSchema();
469 final DOMRpcResult result = checkRpcResponse(response);
471 RpcDefinition resultNodeSchema = null;
472 final NormalizedNode<?, ?> resultData = result.getResult();
473 if (result != null && result.getResult() != null) {
474 resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
477 return new NormalizedNodeContext(
478 new InstanceIdentifierContext<>(null, resultNodeSchema, mountPoint, schemaContext),
479 resultData, QueryParametersParser.parseWriterParameters(uriInfo));
482 private static DOMRpcResult checkRpcResponse(final CheckedFuture<DOMRpcResult, DOMRpcException> response) {
483 if (response == null) {
487 final DOMRpcResult retValue = response.get();
488 if (retValue.getErrors() == null || retValue.getErrors().isEmpty()) {
491 LOG.debug("RpcError message", retValue.getErrors());
492 throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
493 } catch (final InterruptedException e) {
494 final String errMsg = "The operation was interrupted while executing and did not complete.";
495 LOG.debug("Rpc Interrupt - " + errMsg, e);
496 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
497 } catch (final ExecutionException e) {
498 LOG.debug("Execution RpcError: ", e);
499 Throwable cause = e.getCause();
501 while (cause.getCause() != null) {
502 cause = cause.getCause();
505 if (cause instanceof IllegalArgumentException) {
506 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL,
507 ErrorTag.INVALID_VALUE);
508 } else if (cause instanceof DOMRpcImplementationNotAvailableException) {
509 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.APPLICATION,
510 ErrorTag.OPERATION_NOT_SUPPORTED);
512 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
515 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
518 } catch (final CancellationException e) {
519 final String errMsg = "The operation was cancelled while executing.";
520 LOG.debug("Cancel RpcExecution: " + errMsg, e);
521 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
525 private static void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
526 if (inputSchema != null && payload.getData() == null) {
527 // expected a non null payload
528 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
529 } else if (inputSchema == null && payload.getData() != null) {
530 // did not expect any input
531 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
535 private CheckedFuture<DOMRpcResult, DOMRpcException>
536 invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
537 final ContainerNode value = (ContainerNode) payload.getData();
538 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
539 final Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(new NodeIdentifier(
540 QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(), "path")));
541 final Object pathValue = path.isPresent() ? path.get().getValue() : null;
543 if (!(pathValue instanceof YangInstanceIdentifier)) {
544 final String errMsg = "Instance identifier was not normalized correctly ";
545 LOG.debug(errMsg + rpcQName);
546 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
549 final YangInstanceIdentifier pathIdentifier = (YangInstanceIdentifier) pathValue;
550 String streamName = (String) CREATE_DATA_SUBSCR;
551 NotificationOutputType outputType = null;
552 if (!pathIdentifier.isEmpty()) {
553 final String fullRestconfIdentifier =
554 DATA_SUBSCR + this.controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
556 LogicalDatastoreType datastore =
557 parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
558 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
560 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
561 scope = scope == null ? DEFAULT_SCOPE : scope;
563 outputType = parseEnumTypeParameter(value, NotificationOutputType.class, OUTPUT_TYPE_PARAM_NAME);
564 outputType = outputType == null ? NotificationOutputType.XML : outputType;
566 streamName = Notificator
567 .createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore + "/scope=" + scope);
570 if (Strings.isNullOrEmpty(streamName)) {
571 final String errMsg = "Path is empty or contains value node which is not Container or List build-in type.";
572 LOG.debug(errMsg + pathIdentifier);
573 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
576 final QName outputQname = QName.create(rpcQName, "output");
577 final QName streamNameQname = QName.create(rpcQName, "stream-name");
579 final ContainerNode output =
580 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
581 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
583 if (!Notificator.existListenerFor(streamName)) {
584 Notificator.createListener(pathIdentifier, streamName, outputType);
587 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
589 return Futures.immediateCheckedFuture(defaultDOMRpcResult);
593 public NormalizedNodeContext invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
594 if (noPayload != null && !CharMatcher.WHITESPACE.matchesAllOf(noPayload)) {
595 throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
598 String identifierEncoded = null;
599 DOMMountPoint mountPoint = null;
600 final SchemaContext schemaContext;
601 if (identifier.contains(ControllerContext.MOUNT)) {
602 // mounted RPC call - look up mount instance.
603 final InstanceIdentifierContext<?> mountPointId = this.controllerContext.toMountPointIdentifier(identifier);
604 mountPoint = mountPointId.getMountPoint();
605 schemaContext = mountPoint.getSchemaContext();
606 final int startOfRemoteRpcName =
607 identifier.lastIndexOf(ControllerContext.MOUNT) + ControllerContext.MOUNT.length() + 1;
608 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
609 identifierEncoded = remoteRpcName;
611 } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
612 final String slashErrorMsg = String.format(
613 "Identifier %n%s%ncan\'t contain slash "
614 + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.",
616 LOG.debug(slashErrorMsg);
617 throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
619 identifierEncoded = identifier;
620 schemaContext = this.controllerContext.getGlobalSchema();
623 final String identifierDecoded = this.controllerContext.urlPathArgDecode(identifierEncoded);
625 RpcDefinition rpc = null;
626 if (mountPoint == null) {
627 rpc = this.controllerContext.getRpcDefinition(identifierDecoded, null);
629 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
633 LOG.debug("RPC " + identifierDecoded + " does not exist.");
634 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
637 if (!rpc.getInput().getChildNodes().isEmpty()) {
638 LOG.debug("RPC " + rpc + " does not need input value.");
639 // FIXME : find a correct Error from specification
640 throw new IllegalStateException("RPC " + rpc + " does'n need input value!");
643 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
644 if (mountPoint != null) {
645 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
646 if (!mountRpcServices.isPresent()) {
647 throw new RestconfDocumentedException("Rpc service is missing.");
649 response = mountRpcServices.get().invokeRpc(rpc.getPath(), null);
651 response = this.broker.invokeRpc(rpc.getPath(), null);
654 final DOMRpcResult result = checkRpcResponse(response);
656 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpc, mountPoint, schemaContext),
657 result.getResult(), QueryParametersParser.parseWriterParameters(uriInfo));
660 private static RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
661 final String[] splittedIdentifier = identifierDecoded.split(":");
662 if (splittedIdentifier.length != 2) {
663 final String errMsg = identifierDecoded + " couldn't be splitted to 2 parts (module:rpc name)";
665 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
667 for (final Module module : schemaContext.getModules()) {
668 if (module.getName().equals(splittedIdentifier[0])) {
669 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
670 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
671 return rpcDefinition;
680 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
681 boolean withDefa_used = false;
682 String withDefa = null;
684 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
685 switch (entry.getKey()) {
686 case "with-defaults":
687 if (!withDefa_used) {
688 withDefa_used = true;
689 withDefa = entry.getValue().iterator().next();
691 throw new RestconfDocumentedException("With-defaults parameter can be used only once.");
696 boolean tagged = false;
698 if (withDefa.equals("report-all-tagged")) {
702 if (withDefa.equals("report-all")) {
707 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
708 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
709 NormalizedNode<?, ?> data = null;
710 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
711 if (mountPoint != null) {
712 data = this.broker.readConfigurationData(mountPoint, normalizedII, withDefa);
714 data = this.broker.readConfigurationData(normalizedII, withDefa);
717 final String errMsg =
718 "Request could not be completed because the relevant data model content does not exist ";
719 LOG.debug(errMsg + identifier);
720 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
722 return new NormalizedNodeContext(iiWithData, data,
723 QueryParametersParser.parseWriterParameters(uriInfo, tagged));
727 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
728 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
729 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
730 NormalizedNode<?, ?> data = null;
731 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
732 if (mountPoint != null) {
733 data = this.broker.readOperationalData(mountPoint, normalizedII);
735 data = this.broker.readOperationalData(normalizedII);
738 final String errMsg =
739 "Request could not be completed because the relevant data model content does not exist ";
740 LOG.debug(errMsg + identifier);
741 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
743 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
747 public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload,
748 final UriInfo uriInfo) {
749 boolean insertUsed = false;
750 boolean pointUsed = false;
751 String insert = null;
754 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
755 switch (entry.getKey()) {
759 insert = entry.getValue().iterator().next();
761 throw new RestconfDocumentedException("Insert parameter can be used only once.");
767 point = entry.getValue().iterator().next();
769 throw new RestconfDocumentedException("Point parameter can be used only once.");
773 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
777 if (pointUsed && !insertUsed) {
778 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
780 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
781 throw new RestconfDocumentedException(
782 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
785 Preconditions.checkNotNull(identifier);
787 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
789 validateInput(iiWithData.getSchemaNode(), payload);
790 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
791 validateListKeysEqualityInPayloadAndUri(payload);
793 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
794 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
797 * There is a small window where another write transaction could be
798 * updating the same data simultaneously and we get an
799 * OptimisticLockFailedException. This error is likely transient and The
800 * WriteTransaction#submit API docs state that a retry will likely
801 * succeed. So we'll try again if that scenario occurs. If it fails a
802 * third time then it probably will never succeed so we'll fail in that
805 * By retrying we're attempting to hide the internal implementation of
806 * the data store and how it handles concurrent updates from the
807 * restconf client. The client has instructed us to put the data and we
808 * should make every effort to do so without pushing optimistic lock
809 * failures back to the client and forcing them to handle it via retry
810 * (and having to document the behavior).
812 PutResult result = null;
815 if (mountPoint != null) {
817 result = this.broker.commitMountPointDataPut(mountPoint, normalizedII, payload.getData(), insert,
820 result = this.broker.commitConfigurationDataPut(this.controllerContext.getGlobalSchema(), normalizedII,
821 payload.getData(), insert, point);
825 result.getFutureOfPutData().checkedGet();
826 return Response.status(result.getStatus()).build();
827 } catch (TransactionCommitFailedException e) {
828 if (e instanceof OptimisticLockFailedException) {
830 LOG.debug("Got OptimisticLockFailedException on last try - failing " + identifier);
831 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
834 LOG.debug("Got OptimisticLockFailedException - trying again " + identifier);
836 LOG.debug("Update failed for " + identifier, e);
837 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
843 private static void validateTopLevelNodeName(final NormalizedNodeContext node,
844 final YangInstanceIdentifier identifier) {
846 final String payloadName = node.getData().getNodeType().getLocalName();
849 if (identifier.isEmpty()) {
851 if (!node.getData().getNodeType().equals(NETCONF_BASE_QNAME)) {
852 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
853 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
857 final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
858 if (!payloadName.equals(identifierName)) {
859 throw new RestconfDocumentedException(
860 "Payload name (" + payloadName + ") is different from identifier name (" + identifierName + ")",
861 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
867 * Validates whether keys in {@code payload} are equal to values of keys in
868 * {@code iiWithData} for list schema node
870 * @throws RestconfDocumentedException
871 * if key values or key count in payload and URI isn't equal
874 private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
875 Preconditions.checkArgument(payload != null);
876 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
877 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
878 final SchemaNode schemaNode = iiWithData.getSchemaNode();
879 final NormalizedNode<?, ?> data = payload.getData();
880 if (schemaNode instanceof ListSchemaNode) {
881 final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
882 if (lastPathArgument instanceof NodeIdentifierWithPredicates && data instanceof MapEntryNode) {
883 final Map<QName, Object> uriKeyValues =
884 ((NodeIdentifierWithPredicates) lastPathArgument).getKeyValues();
885 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
890 private static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final MapEntryNode payload,
891 final List<QName> keyDefinitions) {
893 final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
894 for (final QName keyDefinition : keyDefinitions) {
895 final Object uriKeyValue = mutableCopyUriKeyValues.remove(keyDefinition);
896 // should be caught during parsing URI to InstanceIdentifier
897 RestconfValidationUtils.checkDocumentedError(uriKeyValue != null, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
898 "Missing key " + keyDefinition + " in URI.");
900 final Object dataKeyValue = payload.getIdentifier().getKeyValues().get(keyDefinition);
902 if (!uriKeyValue.equals(dataKeyValue)) {
903 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName()
904 + "' specified in the URI doesn't match the value '" + dataKeyValue
905 + "' specified in the message body. ";
906 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
912 public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload,
913 final UriInfo uriInfo) {
914 return createConfigurationData(payload, uriInfo);
917 // FIXME create RestconfIdetifierHelper and move this method there
918 private static YangInstanceIdentifier checkConsistencyOfNormalizedNodeContext(final NormalizedNodeContext payload) {
919 Preconditions.checkArgument(payload != null);
920 Preconditions.checkArgument(payload.getData() != null);
921 Preconditions.checkArgument(payload.getData().getNodeType() != null);
922 Preconditions.checkArgument(payload.getInstanceIdentifierContext() != null);
923 Preconditions.checkArgument(payload.getInstanceIdentifierContext().getInstanceIdentifier() != null);
925 final QName payloadNodeQname = payload.getData().getNodeType();
926 final YangInstanceIdentifier yangIdent = payload.getInstanceIdentifierContext().getInstanceIdentifier();
927 if (payloadNodeQname.compareTo(yangIdent.getLastPathArgument().getNodeType()) > 0) {
930 final InstanceIdentifierContext<?> parentContext = payload.getInstanceIdentifierContext();
931 final SchemaNode parentSchemaNode = parentContext.getSchemaNode();
932 if (parentSchemaNode instanceof DataNodeContainer) {
933 final DataNodeContainer cast = (DataNodeContainer) parentSchemaNode;
934 for (final DataSchemaNode child : cast.getChildNodes()) {
935 if (payloadNodeQname.compareTo(child.getQName()) == 0) {
936 return YangInstanceIdentifier.builder(yangIdent).node(child.getQName()).build();
940 if (parentSchemaNode instanceof RpcDefinition) {
943 final String errMsg = "Error parsing input: DataSchemaNode has not children ";
944 LOG.info(errMsg + yangIdent);
945 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
949 public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
950 if (payload == null) {
951 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
953 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
954 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
955 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
957 boolean insertUsed = false;
958 boolean pointUsed = false;
959 String insert = null;
962 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
963 switch (entry.getKey()) {
967 insert = entry.getValue().iterator().next();
969 throw new RestconfDocumentedException("Insert parameter can be used only once.");
975 point = entry.getValue().iterator().next();
977 throw new RestconfDocumentedException("Point parameter can be used only once.");
981 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
985 if (pointUsed && !insertUsed) {
986 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
988 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
989 throw new RestconfDocumentedException(
990 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
993 CheckedFuture<Void, TransactionCommitFailedException> future;
994 if (mountPoint != null) {
995 future = this.broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData(), insert,
998 future = this.broker.commitConfigurationDataPost(this.controllerContext.getGlobalSchema(), normalizedII,
999 payload.getData(), insert, point);
1003 future.checkedGet();
1004 } catch (final RestconfDocumentedException e) {
1006 } catch (TransactionCommitFailedException e) {
1007 LOG.info("Error creating data " + (uriInfo != null ? uriInfo.getPath() : ""), e);
1008 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
1011 LOG.trace("Successfuly created data.");
1013 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
1014 // FIXME: Provide path to result.
1015 final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
1016 if (location != null) {
1017 responseBuilder.location(location);
1019 return responseBuilder.build();
1022 private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint,
1023 final YangInstanceIdentifier normalizedII) {
1024 if (uriInfo == null) {
1025 // This is null if invoked internally
1029 final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
1030 uriBuilder.path("config");
1032 uriBuilder.path(this.controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
1033 } catch (final Exception e) {
1034 LOG.info("Location for instance identifier" + normalizedII + "wasn't created", e);
1037 return uriBuilder.build();
1041 public Response deleteConfigurationData(final String identifier) {
1042 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
1043 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
1044 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
1046 final CheckedFuture<Void, TransactionCommitFailedException> future;
1047 if (mountPoint != null) {
1048 future = this.broker.commitConfigurationDataDelete(mountPoint, normalizedII);
1050 future = this.broker.commitConfigurationDataDelete(normalizedII);
1054 future.checkedGet();
1055 } catch (TransactionCommitFailedException e) {
1056 final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
1057 Predicates.instanceOf(ModifiedNodeDoesNotExistException.class));
1058 if (searchedException.isPresent()) {
1059 throw new RestconfDocumentedException("Data specified for delete doesn't exist.", ErrorType.APPLICATION,
1060 ErrorTag.DATA_MISSING);
1063 final String errMsg = "Error while deleting data";
1064 LOG.info(errMsg, e);
1065 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
1068 return Response.status(Status.OK).build();
1072 * Subscribes to some path in schema context (stream) to listen on changes
1075 * Additional parameters for subscribing to stream are loaded via rpc input
1078 * <li>datastore - default CONFIGURATION (other values of
1079 * {@link LogicalDatastoreType} enum type)</li>
1080 * <li>scope - default BASE (other values of {@link DataChangeScope})</li>
1084 public NormalizedNodeContext subscribeToStream(final String identifier, final UriInfo uriInfo) {
1085 boolean startTime_used = false;
1086 boolean stopTime_used = false;
1087 boolean filter_used = false;
1090 String filter = null;
1092 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
1093 switch (entry.getKey()) {
1095 if (!startTime_used) {
1096 startTime_used = true;
1097 start = parseDateFromQueryParam(entry);
1099 throw new RestconfDocumentedException("Start-time parameter can be used only once.");
1103 if (!stopTime_used) {
1104 stopTime_used = true;
1105 stop = parseDateFromQueryParam(entry);
1107 throw new RestconfDocumentedException("Stop-time parameter can be used only once.");
1113 filter = entry.getValue().iterator().next();
1115 throw new RestconfDocumentedException("Filter parameter can be used only once.");
1119 throw new RestconfDocumentedException("Bad parameter used with notifications: " + entry.getKey());
1122 if (!startTime_used && stopTime_used) {
1123 throw new RestconfDocumentedException("Stop-time parameter has to be used with start-time parameter.");
1125 URI response = null;
1126 if (identifier.contains(DATA_SUBSCR)) {
1127 response = dataSubs(identifier, uriInfo, start, stop, filter);
1128 } else if (identifier.contains(NOTIFICATION_STREAM)) {
1129 response = notifStream(identifier, uriInfo, start, stop, filter);
1132 if (response != null) {
1133 // prepare node with value of location
1134 final InstanceIdentifierContext<?> iid = prepareIIDSubsStreamOutput();
1135 final NormalizedNodeAttrBuilder<NodeIdentifier, Object, LeafNode<Object>> builder =
1136 ImmutableLeafNodeBuilder.create().withValue(response.toString());
1137 builder.withNodeIdentifier(
1138 NodeIdentifier.create(QName.create("subscribe:to:notification", "2016-10-28", "location")));
1140 // prepare new header with location
1141 final Map<String, Object> headers = new HashMap<>();
1142 headers.put("Location", response);
1144 return new NormalizedNodeContext(iid, builder.build(), headers);
1147 final String msg = "Bad type of notification of sal-remote";
1149 throw new RestconfDocumentedException(msg);
1152 private Date parseDateFromQueryParam(final Entry<String, List<String>> entry) {
1153 final DateAndTime event = new DateAndTime(entry.getValue().iterator().next());
1154 String numOf_ms = "";
1155 final String value = event.getValue();
1156 if (value.contains(".")) {
1157 numOf_ms = numOf_ms + ".";
1158 final int lastChar = value.contains("Z") ? value.indexOf("Z") : value.contains("+") ? value.indexOf("+")
1159 : value.contains("-") ? value.indexOf("-") : value.length();
1160 for (int i = 0; i < lastChar - value.indexOf(".") - 1; i++) {
1161 numOf_ms = numOf_ms + "S";
1165 if (!value.contains("Z")) {
1166 zone = zone + "XXX";
1168 final DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss" + numOf_ms + zone);
1171 return dateFormatter.parse(value.contains("Z") ? value.replace('T', ' ').substring(0, value.indexOf("Z"))
1172 : value.replace('T', ' '));
1173 } catch (final ParseException e) {
1174 throw new RestconfDocumentedException("Cannot parse of value in date: " + value + e);
1179 * @return {@link InstanceIdentifierContext} of location leaf for
1182 private InstanceIdentifierContext<?> prepareIIDSubsStreamOutput() {
1183 final QName qnameBase = QName.create("subscribe:to:notification", "2016-10-28", "notifi");
1184 final SchemaContext schemaCtx = ControllerContext.getInstance().getGlobalSchema();
1185 final DataSchemaNode location = ((ContainerSchemaNode) schemaCtx
1186 .findModuleByNamespaceAndRevision(qnameBase.getNamespace(), qnameBase.getRevision())
1187 .getDataChildByName(qnameBase)).getDataChildByName(QName.create(qnameBase, "location"));
1188 final List<PathArgument> path = new ArrayList<>();
1189 path.add(NodeIdentifier.create(qnameBase));
1190 path.add(NodeIdentifier.create(QName.create(qnameBase, "location")));
1192 return new InstanceIdentifierContext<SchemaNode>(YangInstanceIdentifier.create(path), location, null,
1197 * Register notification listener by stream name
1204 * - stop-time of getting notification
1206 * - start-time of getting notification
1208 * - indicate wh ich subset of allpossible events are of interest
1209 * @return {@link URI} of location
1211 private URI notifStream(final String identifier, final UriInfo uriInfo, final Date start, final Date stop,
1212 final String filter) {
1213 final String streamName = Notificator.createStreamNameFromUri(identifier);
1214 if (Strings.isNullOrEmpty(streamName)) {
1215 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1217 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
1218 if (listeners == null || listeners.isEmpty()) {
1219 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1220 ErrorTag.UNKNOWN_ELEMENT);
1223 for (final NotificationListenerAdapter listener : listeners) {
1224 this.broker.registerToListenNotification(listener);
1225 listener.setQueryParams(start, stop, filter);
1228 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1229 int notificationPort = NOTIFICATION_PORT;
1231 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
1232 notificationPort = webSocketServerInstance.getPort();
1233 } catch (final NullPointerException e) {
1234 WebSocketServer.createInstance(NOTIFICATION_PORT);
1236 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1237 final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
1239 return uriToWebsocketServer;
1243 * Register data change listener by stream name
1250 * - start-time of getting notification
1252 * - stop-time of getting notification
1254 * - indicate which subset of all possible events are of interest
1255 * @return {@link URI} of location
1257 private URI dataSubs(final String identifier, final UriInfo uriInfo, final Date start, final Date stop,
1258 final String filter) {
1259 final String streamName = Notificator.createStreamNameFromUri(identifier);
1260 if (Strings.isNullOrEmpty(streamName)) {
1261 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1264 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1265 if (listener == null) {
1266 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1267 ErrorTag.UNKNOWN_ELEMENT);
1269 listener.setQueryParams(start, stop, filter);
1271 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1272 final LogicalDatastoreType datastore =
1273 parserURIEnumParameter(LogicalDatastoreType.class, paramToValues.get(DATASTORE_PARAM_NAME));
1274 if (datastore == null) {
1275 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1276 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1278 final DataChangeScope scope =
1279 parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
1280 if (scope == null) {
1281 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1282 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1285 this.broker.registerToListenDataChanges(datastore, scope, listener);
1287 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1288 int notificationPort = NOTIFICATION_PORT;
1290 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
1291 notificationPort = webSocketServerInstance.getPort();
1292 } catch (final NullPointerException e) {
1293 WebSocketServer.createInstance(NOTIFICATION_PORT);
1295 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1296 final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
1298 return uriToWebsocketServer;
1302 public PATCHStatusContext patchConfigurationData(final String identifier, final PATCHContext context,
1303 final UriInfo uriInfo) {
1304 if (context == null) {
1305 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1309 return this.broker.patchConfigurationDataWithinTransaction(context);
1310 } catch (final Exception e) {
1311 LOG.debug("Patch transaction failed", e);
1312 throw new RestconfDocumentedException(e.getMessage());
1317 public PATCHStatusContext patchConfigurationData(final PATCHContext context, @Context final UriInfo uriInfo) {
1318 if (context == null) {
1319 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1323 return this.broker.patchConfigurationDataWithinTransaction(context);
1324 } catch (final Exception e) {
1325 LOG.debug("Patch transaction failed", e);
1326 throw new RestconfDocumentedException(e.getMessage());
1331 * Load parameter for subscribing to stream from input composite node
1335 * @return enum object if its string value is equal to {@code paramName}. In
1338 private static <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1339 final String paramName) {
1340 final Optional<DataContainerChild<? extends PathArgument, ?>> augNode =
1341 value.getChild(SAL_REMOTE_AUG_IDENTIFIER);
1342 if (!augNode.isPresent() && !(augNode instanceof AugmentationNode)) {
1345 final Optional<DataContainerChild<? extends PathArgument, ?>> enumNode = ((AugmentationNode) augNode.get())
1346 .getChild(new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1347 if (!enumNode.isPresent()) {
1350 final Object rawValue = enumNode.get().getValue();
1351 if (!(rawValue instanceof String)) {
1355 return resolveAsEnum(classDescriptor, (String) rawValue);
1359 * Checks whether {@code value} is one of the string representation of
1360 * enumeration {@code classDescriptor}
1362 * @return enum object if string value of {@code classDescriptor}
1363 * enumeration is equal to {@code value}. Other cases null.
1365 private static <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1366 if (Strings.isNullOrEmpty(value)) {
1369 return resolveAsEnum(classDescriptor, value);
1372 private static <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1373 final T[] enumConstants = classDescriptor.getEnumConstants();
1374 if (enumConstants != null) {
1375 for (final T enm : classDescriptor.getEnumConstants()) {
1376 if (((Enum<?>) enm).name().equals(value)) {
1384 private static Map<String, String> resolveValuesFromUri(final String uri) {
1385 final Map<String, String> result = new HashMap<>();
1386 final String[] tokens = uri.split("/");
1387 for (int i = 1; i < tokens.length; i++) {
1388 final String[] parameterTokens = tokens[i].split("=");
1389 if (parameterTokens.length == 2) {
1390 result.put(parameterTokens[0], parameterTokens[1]);
1396 private MapNode makeModuleMapNode(final Set<Module> modules) {
1397 Preconditions.checkNotNull(modules);
1398 final Module restconfModule = getRestconfModule();
1399 final DataSchemaNode moduleSchemaNode = this.controllerContext
1400 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1401 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1403 final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder =
1404 Builders.mapBuilder((ListSchemaNode) moduleSchemaNode);
1406 for (final Module module : modules) {
1407 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1409 return listModuleBuilder.build();
1412 protected MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1413 Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1414 "moduleSchemaNode has to be of type ListSchemaNode");
1415 final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1416 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues =
1417 Builders.mapEntryBuilder(listModuleSchemaNode);
1419 List<DataSchemaNode> instanceDataChildrenByName =
1420 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "name");
1421 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1422 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1424 .withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName()).build());
1426 instanceDataChildrenByName =
1427 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "revision");
1428 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1429 Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1430 final String revision = REVISION_FORMAT.format(module.getRevision());
1432 .withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode).withValue(revision).build());
1434 instanceDataChildrenByName =
1435 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "namespace");
1436 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1437 Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1438 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1439 .withValue(module.getNamespace().toString()).build());
1441 instanceDataChildrenByName =
1442 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "feature");
1443 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1444 Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1445 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder =
1446 Builders.leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1447 for (final FeatureDefinition feature : module.getFeatures()) {
1448 featuresBuilder.withChild(Builders.leafSetEntryBuilder((LeafListSchemaNode) featureSchemaNode)
1449 .withValue(feature.getQName().getLocalName()).build());
1451 moduleNodeValues.withChild(featuresBuilder.build());
1453 return moduleNodeValues.build();
1456 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1457 Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1458 "streamSchemaNode has to be of type ListSchemaNode");
1459 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1460 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues =
1461 Builders.mapEntryBuilder(listStreamSchemaNode);
1463 List<DataSchemaNode> instanceDataChildrenByName =
1464 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "name");
1465 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1466 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1467 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName).build());
1469 instanceDataChildrenByName =
1470 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "description");
1471 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1472 Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1473 streamNodeValues.withChild(
1474 Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue("DESCRIPTION_PLACEHOLDER").build());
1476 instanceDataChildrenByName =
1477 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-support");
1478 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1479 Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1480 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1481 .withValue(Boolean.valueOf(true)).build());
1483 instanceDataChildrenByName =
1484 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-log-creation-time");
1485 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1486 Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1487 streamNodeValues.withChild(
1488 Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode).withValue("").build());
1490 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "events");
1491 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1492 Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1493 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode).withValue("").build());
1495 return streamNodeValues.build();
1499 * Prepare stream for notification
1502 * - contains list of qnames of notifications
1503 * @return - checked future object
1505 private CheckedFuture<DOMRpcResult, DOMRpcException>
1506 invokeSalRemoteRpcNotifiStrRPC(final NormalizedNodeContext payload) {
1507 final ContainerNode data = (ContainerNode) payload.getData();
1508 LeafSetNode leafSet = null;
1509 String outputType = "XML";
1510 for (final DataContainerChild<? extends PathArgument, ?> dataChild : data.getValue()) {
1511 if (dataChild instanceof LeafSetNode) {
1512 leafSet = (LeafSetNode) dataChild;
1513 } else if (dataChild instanceof AugmentationNode) {
1514 outputType = (String) ((AugmentationNode) dataChild).getValue().iterator().next().getValue();
1518 final Collection<LeafSetEntryNode> entryNodes = leafSet.getValue();
1519 final List<SchemaPath> paths = new ArrayList<>();
1520 String streamName = CREATE_NOTIFICATION_STREAM + "/";
1522 final Iterator<LeafSetEntryNode> iterator = entryNodes.iterator();
1523 while (iterator.hasNext()) {
1524 final QName valueQName = QName.create((String) iterator.next().getValue());
1525 final Module module =
1526 ControllerContext.getInstance().findModuleByNamespace(valueQName.getModule().getNamespace());
1527 Preconditions.checkNotNull(module,
1528 "Module for namespace " + valueQName.getModule().getNamespace() + " does not exist");
1529 NotificationDefinition notifiDef = null;
1530 for (final NotificationDefinition notification : module.getNotifications()) {
1531 if (notification.getQName().equals(valueQName)) {
1532 notifiDef = notification;
1536 final String moduleName = module.getName();
1537 Preconditions.checkNotNull(notifiDef,
1538 "Notification " + valueQName + "doesn't exist in module " + moduleName);
1539 paths.add(notifiDef.getPath());
1540 streamName = streamName + moduleName + ":" + valueQName.getLocalName();
1541 if (iterator.hasNext()) {
1542 streamName = streamName + ",";
1546 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
1547 final QName outputQname = QName.create(rpcQName, "output");
1548 final QName streamNameQname = QName.create(rpcQName, "notification-stream-identifier");
1550 final ContainerNode output =
1551 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
1552 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
1554 if (!Notificator.existNotificationListenerFor(streamName)) {
1555 Notificator.createNotificationListener(paths, streamName, outputType);
1558 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
1560 return Futures.immediateCheckedFuture(defaultDOMRpcResult);