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.util.concurrent.CheckedFuture;
23 import com.google.common.util.concurrent.Futures;
25 import java.text.ParseException;
26 import java.time.Instant;
27 import java.time.format.DateTimeFormatter;
28 import java.time.format.DateTimeFormatterBuilder;
29 import java.time.format.DateTimeParseException;
30 import java.time.temporal.ChronoField;
31 import java.time.temporal.TemporalAccessor;
32 import java.util.ArrayList;
33 import java.util.Collection;
34 import java.util.Collections;
35 import java.util.HashMap;
36 import java.util.Iterator;
37 import java.util.List;
39 import java.util.Map.Entry;
41 import java.util.concurrent.CancellationException;
42 import java.util.concurrent.ExecutionException;
43 import javax.ws.rs.core.Context;
44 import javax.ws.rs.core.Response;
45 import javax.ws.rs.core.Response.ResponseBuilder;
46 import javax.ws.rs.core.Response.Status;
47 import javax.ws.rs.core.UriBuilder;
48 import javax.ws.rs.core.UriInfo;
49 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
50 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
51 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
52 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
53 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
54 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
55 import org.opendaylight.controller.md.sal.dom.api.DOMRpcImplementationNotAvailableException;
56 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
57 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
58 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
59 import org.opendaylight.netconf.md.sal.rest.common.RestconfValidationUtils;
60 import org.opendaylight.netconf.sal.rest.api.Draft02;
61 import org.opendaylight.netconf.sal.rest.api.RestconfService;
62 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
63 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
64 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
65 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
66 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
67 import org.opendaylight.netconf.sal.streams.websockets.WebSocketServer;
68 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
69 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
70 import org.opendaylight.yangtools.yang.common.QName;
71 import org.opendaylight.yangtools.yang.common.QNameModule;
72 import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
73 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
74 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
75 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
76 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
77 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
78 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
79 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
80 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
81 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
82 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
83 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
84 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
85 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
86 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
87 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
88 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
89 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
90 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
91 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
92 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
93 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
94 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
95 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
96 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
97 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
98 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
99 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
100 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
101 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
102 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
103 import org.opendaylight.yangtools.yang.model.api.Module;
104 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
105 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
106 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
107 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
108 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
109 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.EffectiveSchemaContext;
110 import org.slf4j.Logger;
111 import org.slf4j.LoggerFactory;
113 public class RestconfImpl implements RestconfService {
115 private static final RestconfImpl INSTANCE = new RestconfImpl();
118 * Notifications are served on port 8181.
120 private static final int NOTIFICATION_PORT = 8181;
122 private static final int CHAR_NOT_FOUND = -1;
124 private static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
126 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
128 private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
130 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
132 private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
134 private static final String DATASTORE_PARAM_NAME = "datastore";
136 private static final String SCOPE_PARAM_NAME = "scope";
138 private static final String OUTPUT_TYPE_PARAM_NAME = "notification-output-type";
140 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
142 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
144 private static final QName NETCONF_BASE_QNAME = QName.create(QNameModule.create(URI.create(NETCONF_BASE), null),
145 NETCONF_BASE_PAYLOAD_NAME).intern();
147 private static final QNameModule SAL_REMOTE_AUGMENT;
150 SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
151 SimpleDateFormatUtil.getRevisionFormat().parse("2014-07-08"));
152 } catch (final ParseException e) {
153 throw new ExceptionInInitializerError(e);
157 private static final AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER =
158 new AugmentationIdentifier(ImmutableSet.of(
159 QName.create(SAL_REMOTE_AUGMENT, "scope"), QName.create(SAL_REMOTE_AUGMENT, "datastore"),
160 QName.create(SAL_REMOTE_AUGMENT, "notification-output-type")));
162 public static final CharSequence DATA_SUBSCR = "data-change-event-subscription";
163 private static final CharSequence CREATE_DATA_SUBSCR = "create-" + DATA_SUBSCR;
165 public static final CharSequence NOTIFICATION_STREAM = "notification-stream";
166 private static final CharSequence CREATE_NOTIFICATION_STREAM = "create-" + NOTIFICATION_STREAM;
168 private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
169 .appendValue(ChronoField.YEAR, 4).appendLiteral('-')
170 .appendValue(ChronoField.MONTH_OF_YEAR, 2).appendLiteral('-')
171 .appendValue(ChronoField.DAY_OF_MONTH, 2).appendLiteral('T')
172 .appendValue(ChronoField.HOUR_OF_DAY, 2).appendLiteral(':')
173 .appendValue(ChronoField.MINUTE_OF_HOUR, 2).appendLiteral(':')
174 .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
175 .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
176 .appendOffset("+HH:MM", "Z").toFormatter();
178 private BrokerFacade broker;
180 private ControllerContext controllerContext;
182 public void setBroker(final BrokerFacade broker) {
183 this.broker = broker;
186 public void setControllerContext(final ControllerContext controllerContext) {
187 this.controllerContext = controllerContext;
190 private RestconfImpl() {
193 public static RestconfImpl getInstance() {
198 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
199 final Set<Module> allModules = this.controllerContext.getAllModules();
200 final MapNode allModuleMap = makeModuleMapNode(allModules);
202 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
204 final Module restconfModule = getRestconfModule();
205 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
206 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
207 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
209 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
210 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
211 moduleContainerBuilder.withChild(allModuleMap);
213 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode, null, schemaContext),
214 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
218 * Valid only for mount point
221 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
222 Preconditions.checkNotNull(identifier);
223 if (!identifier.contains(ControllerContext.MOUNT)) {
224 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
225 + " URI has to end with " + ControllerContext.MOUNT;
226 LOG.debug(errMsg + " for " + identifier);
227 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
230 final InstanceIdentifierContext<?> mountPointIdentifier =
231 this.controllerContext.toMountPointIdentifier(identifier);
232 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
233 final Set<Module> modules = this.controllerContext.getAllModules(mountPoint);
234 final MapNode mountPointModulesMap = makeModuleMapNode(modules);
236 final Module restconfModule = getRestconfModule();
237 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
238 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
239 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
241 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
242 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
243 moduleContainerBuilder.withChild(mountPointModulesMap);
245 return new NormalizedNodeContext(
246 new InstanceIdentifierContext<>(null, modulesSchemaNode, mountPoint,
247 this.controllerContext.getGlobalSchema()),
248 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
252 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
253 Preconditions.checkNotNull(identifier);
254 final QName moduleNameAndRevision = getModuleNameAndRevision(identifier);
255 Module module = null;
256 DOMMountPoint mountPoint = null;
257 final SchemaContext schemaContext;
258 if (identifier.contains(ControllerContext.MOUNT)) {
259 final InstanceIdentifierContext<?> mountPointIdentifier =
260 this.controllerContext.toMountPointIdentifier(identifier);
261 mountPoint = mountPointIdentifier.getMountPoint();
262 module = this.controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision);
263 schemaContext = mountPoint.getSchemaContext();
265 module = this.controllerContext.findModuleByNameAndRevision(moduleNameAndRevision);
266 schemaContext = this.controllerContext.getGlobalSchema();
269 if (module == null) {
270 final String errMsg = "Module with name '" + moduleNameAndRevision.getLocalName() + "' and revision '"
271 + moduleNameAndRevision.getRevision() + "' was not found.";
273 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
276 final Module restconfModule = getRestconfModule();
277 final Set<Module> modules = Collections.singleton(module);
278 final MapNode moduleMap = makeModuleMapNode(modules);
280 final DataSchemaNode moduleSchemaNode = this.controllerContext
281 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
282 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
284 return new NormalizedNodeContext(
285 new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint, schemaContext), moduleMap,
286 QueryParametersParser.parseWriterParameters(uriInfo));
290 public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
291 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
292 final Set<String> availableStreams = Notificator.getStreamNames();
293 final Module restconfModule = getRestconfModule();
294 final DataSchemaNode streamSchemaNode = this.controllerContext
295 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
296 Preconditions.checkState(streamSchemaNode instanceof ListSchemaNode);
298 final CollectionNodeBuilder<MapEntryNode, MapNode> listStreamsBuilder =
299 Builders.mapBuilder((ListSchemaNode) streamSchemaNode);
301 for (final String streamName : availableStreams) {
302 listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
305 final DataSchemaNode streamsContainerSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
306 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
307 Preconditions.checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
309 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
310 Builders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
311 streamsContainerBuilder.withChild(listStreamsBuilder.build());
313 return new NormalizedNodeContext(
314 new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null, schemaContext),
315 streamsContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
319 public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
320 final Set<Module> allModules = this.controllerContext.getAllModules();
321 return operationsFromModulesToNormalizedContext(allModules, null);
325 public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
326 Set<Module> modules = null;
327 DOMMountPoint mountPoint = null;
328 if (identifier.contains(ControllerContext.MOUNT)) {
329 final InstanceIdentifierContext<?> mountPointIdentifier =
330 this.controllerContext.toMountPointIdentifier(identifier);
331 mountPoint = mountPointIdentifier.getMountPoint();
332 modules = this.controllerContext.getAllModules(mountPoint);
335 final String errMsg =
336 "URI has bad format. If operations behind mount point should be showed, URI has to " + "end with ";
337 LOG.debug(errMsg + ControllerContext.MOUNT + " for " + identifier);
338 throw new RestconfDocumentedException(errMsg + ControllerContext.MOUNT, ErrorType.PROTOCOL,
339 ErrorTag.INVALID_VALUE);
342 return operationsFromModulesToNormalizedContext(modules, mountPoint);
346 * Special case only for GET restconf/operations use (since moment of
347 * pre-Beryllium Yang parser and Yang model API removal). The method is
348 * creating fake schema context with fake module and fake data by use own
349 * implementations of schema nodes and module.
352 * - set of modules for get RPCs from every module
354 * - mount point, if in use otherwise null
355 * @return {@link NormalizedNodeContext}
357 private static NormalizedNodeContext operationsFromModulesToNormalizedContext(final Set<Module> modules,
358 final DOMMountPoint mountPoint) {
360 final Collection<Module> neededModules = new ArrayList<>(modules.size());
361 final ArrayList<LeafSchemaNode> fakeRpcSchema = new ArrayList<>();
363 for (final Module m : modules) {
364 final Set<RpcDefinition> rpcs = m.getRpcs();
365 if (!rpcs.isEmpty()) {
366 neededModules.add(m);
368 fakeRpcSchema.ensureCapacity(fakeRpcSchema.size() + rpcs.size());
369 rpcs.forEach(rpc -> fakeRpcSchema.add(new FakeLeafSchemaNode(rpc.getQName())));
373 final ContainerSchemaNode fakeCont = new FakeContainerSchemaNode(fakeRpcSchema);
374 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> containerBuilder =
375 Builders.containerBuilder(fakeCont);
377 for (final LeafSchemaNode leaf : fakeRpcSchema) {
378 containerBuilder.withChild(Builders.leafBuilder(leaf).build());
381 final Collection<Module> fakeModules = new ArrayList<>(neededModules.size() + 1);
382 neededModules.forEach(imp -> fakeModules.add(new FakeImportedModule(imp)));
383 fakeModules.add(new FakeRestconfModule(neededModules, fakeCont));
385 final SchemaContext fakeSchemaCtx =
386 EffectiveSchemaContext.resolveSchemaContext(ImmutableSet.copyOf(fakeModules));
387 final InstanceIdentifierContext<ContainerSchemaNode> instanceIdentifierContext =
388 new InstanceIdentifierContext<>(null, fakeCont, mountPoint, fakeSchemaCtx);
389 return new NormalizedNodeContext(instanceIdentifierContext, containerBuilder.build());
392 private Module getRestconfModule() {
393 final Module restconfModule = this.controllerContext.getRestconfModule();
394 if (restconfModule == null) {
395 LOG.debug("ietf-restconf module was not found.");
396 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
397 ErrorTag.OPERATION_NOT_SUPPORTED);
400 return restconfModule;
403 private static QName getModuleNameAndRevision(final String identifier) {
404 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
405 String moduleNameAndRevision = "";
406 if (mountIndex >= 0) {
407 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
409 moduleNameAndRevision = identifier;
412 final Splitter splitter = Splitter.on("/").omitEmptyStrings();
413 final Iterable<String> split = splitter.split(moduleNameAndRevision);
414 final List<String> pathArgs = Lists.<String> newArrayList(split);
415 if (pathArgs.size() < 2) {
416 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
417 throw new RestconfDocumentedException(
418 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
419 ErrorTag.INVALID_VALUE);
423 final String moduleName = pathArgs.get(0);
424 final String revision = pathArgs.get(1);
425 return QName.create(null, SimpleDateFormatUtil.getRevisionFormat().parse(revision), moduleName);
426 } catch (final ParseException e) {
427 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
428 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
429 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
434 public Object getRoot() {
439 public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload,
440 final UriInfo uriInfo) {
441 final SchemaPath type = payload.getInstanceIdentifierContext().getSchemaNode().getPath();
442 final URI namespace = payload.getInstanceIdentifierContext().getSchemaNode().getQName().getNamespace();
443 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
444 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
445 final SchemaContext schemaContext;
447 if (mountPoint != null) {
448 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
449 if (!mountRpcServices.isPresent()) {
450 LOG.debug("Error: Rpc service is missing.");
451 throw new RestconfDocumentedException("Rpc service is missing.");
453 schemaContext = mountPoint.getSchemaContext();
454 response = mountRpcServices.get().invokeRpc(type, payload.getData());
456 if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
457 if (identifier.contains(CREATE_DATA_SUBSCR)) {
458 response = invokeSalRemoteRpcSubscribeRPC(payload);
459 } else if (identifier.contains(CREATE_NOTIFICATION_STREAM)) {
460 response = invokeSalRemoteRpcNotifiStrRPC(payload);
462 final String msg = "Not supported operation";
464 throw new RestconfDocumentedException(msg, ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED);
467 response = this.broker.invokeRpc(type, payload.getData());
469 schemaContext = this.controllerContext.getGlobalSchema();
472 final DOMRpcResult result = checkRpcResponse(response);
474 RpcDefinition resultNodeSchema = null;
475 final NormalizedNode<?, ?> resultData = result.getResult();
476 if (result != null && result.getResult() != null) {
477 resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
480 return new NormalizedNodeContext(
481 new InstanceIdentifierContext<>(null, resultNodeSchema, mountPoint, schemaContext),
482 resultData, QueryParametersParser.parseWriterParameters(uriInfo));
485 private static DOMRpcResult checkRpcResponse(final CheckedFuture<DOMRpcResult, DOMRpcException> response) {
486 if (response == null) {
490 final DOMRpcResult retValue = response.get();
491 if (retValue.getErrors() == null || retValue.getErrors().isEmpty()) {
494 LOG.debug("RpcError message", retValue.getErrors());
495 throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
496 } catch (final InterruptedException e) {
497 final String errMsg = "The operation was interrupted while executing and did not complete.";
498 LOG.debug("Rpc Interrupt - " + errMsg, e);
499 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
500 } catch (final ExecutionException e) {
501 LOG.debug("Execution RpcError: ", e);
502 Throwable cause = e.getCause();
504 while (cause.getCause() != null) {
505 cause = cause.getCause();
508 if (cause instanceof IllegalArgumentException) {
509 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL,
510 ErrorTag.INVALID_VALUE);
511 } else if (cause instanceof DOMRpcImplementationNotAvailableException) {
512 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.APPLICATION,
513 ErrorTag.OPERATION_NOT_SUPPORTED);
515 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
518 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
521 } catch (final CancellationException e) {
522 final String errMsg = "The operation was cancelled while executing.";
523 LOG.debug("Cancel RpcExecution: " + errMsg, e);
524 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
528 private static void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
529 if (inputSchema != null && payload.getData() == null) {
530 // expected a non null payload
531 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
532 } else if (inputSchema == null && payload.getData() != null) {
533 // did not expect any input
534 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
538 private CheckedFuture<DOMRpcResult, DOMRpcException>
539 invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
540 final ContainerNode value = (ContainerNode) payload.getData();
541 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
542 final Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(new NodeIdentifier(
543 QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(), "path")));
544 final Object pathValue = path.isPresent() ? path.get().getValue() : null;
546 if (!(pathValue instanceof YangInstanceIdentifier)) {
547 final String errMsg = "Instance identifier was not normalized correctly ";
548 LOG.debug(errMsg + rpcQName);
549 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
552 final YangInstanceIdentifier pathIdentifier = (YangInstanceIdentifier) pathValue;
553 String streamName = (String) CREATE_DATA_SUBSCR;
554 NotificationOutputType outputType = null;
555 if (!pathIdentifier.isEmpty()) {
556 final String fullRestconfIdentifier =
557 DATA_SUBSCR + this.controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
559 LogicalDatastoreType datastore =
560 parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
561 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
563 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
564 scope = scope == null ? DEFAULT_SCOPE : scope;
566 outputType = parseEnumTypeParameter(value, NotificationOutputType.class, OUTPUT_TYPE_PARAM_NAME);
567 outputType = outputType == null ? NotificationOutputType.XML : outputType;
569 streamName = Notificator
570 .createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore + "/scope=" + scope);
573 if (Strings.isNullOrEmpty(streamName)) {
574 final String errMsg = "Path is empty or contains value node which is not Container or List build-in type.";
575 LOG.debug(errMsg + pathIdentifier);
576 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
579 final QName outputQname = QName.create(rpcQName, "output");
580 final QName streamNameQname = QName.create(rpcQName, "stream-name");
582 final ContainerNode output =
583 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
584 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
586 if (!Notificator.existListenerFor(streamName)) {
587 Notificator.createListener(pathIdentifier, streamName, outputType);
590 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
592 return Futures.immediateCheckedFuture(defaultDOMRpcResult);
596 public NormalizedNodeContext invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
597 if (noPayload != null && !CharMatcher.WHITESPACE.matchesAllOf(noPayload)) {
598 throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
601 String identifierEncoded = null;
602 DOMMountPoint mountPoint = null;
603 final SchemaContext schemaContext;
604 if (identifier.contains(ControllerContext.MOUNT)) {
605 // mounted RPC call - look up mount instance.
606 final InstanceIdentifierContext<?> mountPointId = this.controllerContext.toMountPointIdentifier(identifier);
607 mountPoint = mountPointId.getMountPoint();
608 schemaContext = mountPoint.getSchemaContext();
609 final int startOfRemoteRpcName =
610 identifier.lastIndexOf(ControllerContext.MOUNT) + ControllerContext.MOUNT.length() + 1;
611 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
612 identifierEncoded = remoteRpcName;
614 } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
615 final String slashErrorMsg = String.format(
616 "Identifier %n%s%ncan\'t contain slash "
617 + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.",
619 LOG.debug(slashErrorMsg);
620 throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
622 identifierEncoded = identifier;
623 schemaContext = this.controllerContext.getGlobalSchema();
626 final String identifierDecoded = this.controllerContext.urlPathArgDecode(identifierEncoded);
628 RpcDefinition rpc = null;
629 if (mountPoint == null) {
630 rpc = this.controllerContext.getRpcDefinition(identifierDecoded, null);
632 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
636 LOG.debug("RPC " + identifierDecoded + " does not exist.");
637 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
640 if (!rpc.getInput().getChildNodes().isEmpty()) {
641 LOG.debug("RPC " + rpc + " does not need input value.");
642 // FIXME : find a correct Error from specification
643 throw new IllegalStateException("RPC " + rpc + " does'n need input value!");
646 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
647 if (mountPoint != null) {
648 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
649 if (!mountRpcServices.isPresent()) {
650 throw new RestconfDocumentedException("Rpc service is missing.");
652 response = mountRpcServices.get().invokeRpc(rpc.getPath(), null);
654 response = this.broker.invokeRpc(rpc.getPath(), null);
657 final DOMRpcResult result = checkRpcResponse(response);
659 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpc, mountPoint, schemaContext),
660 result.getResult(), QueryParametersParser.parseWriterParameters(uriInfo));
663 private static RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
664 final String[] splittedIdentifier = identifierDecoded.split(":");
665 if (splittedIdentifier.length != 2) {
666 final String errMsg = identifierDecoded + " couldn't be splitted to 2 parts (module:rpc name)";
668 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
670 for (final Module module : schemaContext.getModules()) {
671 if (module.getName().equals(splittedIdentifier[0])) {
672 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
673 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
674 return rpcDefinition;
683 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
684 boolean withDefa_used = false;
685 String withDefa = null;
687 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
688 switch (entry.getKey()) {
689 case "with-defaults":
690 if (!withDefa_used) {
691 withDefa_used = true;
692 withDefa = entry.getValue().iterator().next();
694 throw new RestconfDocumentedException("With-defaults parameter can be used only once.");
699 boolean tagged = false;
701 if (withDefa.equals("report-all-tagged")) {
705 if (withDefa.equals("report-all")) {
710 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
711 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
712 NormalizedNode<?, ?> data = null;
713 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
714 if (mountPoint != null) {
715 data = this.broker.readConfigurationData(mountPoint, normalizedII, withDefa);
717 data = this.broker.readConfigurationData(normalizedII, withDefa);
720 final String errMsg =
721 "Request could not be completed because the relevant data model content does not exist ";
722 LOG.debug(errMsg + identifier);
723 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
725 return new NormalizedNodeContext(iiWithData, data,
726 QueryParametersParser.parseWriterParameters(uriInfo, tagged));
730 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
731 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
732 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
733 NormalizedNode<?, ?> data = null;
734 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
735 if (mountPoint != null) {
736 data = this.broker.readOperationalData(mountPoint, normalizedII);
738 data = this.broker.readOperationalData(normalizedII);
741 final String errMsg =
742 "Request could not be completed because the relevant data model content does not exist ";
743 LOG.debug(errMsg + identifier);
744 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
746 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
750 public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload,
751 final UriInfo uriInfo) {
752 boolean insertUsed = false;
753 boolean pointUsed = false;
754 String insert = null;
757 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
758 switch (entry.getKey()) {
762 insert = entry.getValue().iterator().next();
764 throw new RestconfDocumentedException("Insert parameter can be used only once.");
770 point = entry.getValue().iterator().next();
772 throw new RestconfDocumentedException("Point parameter can be used only once.");
776 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
780 if (pointUsed && !insertUsed) {
781 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
783 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
784 throw new RestconfDocumentedException(
785 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
788 Preconditions.checkNotNull(identifier);
790 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
792 validateInput(iiWithData.getSchemaNode(), payload);
793 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
794 validateListKeysEqualityInPayloadAndUri(payload);
796 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
797 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
800 * There is a small window where another write transaction could be
801 * updating the same data simultaneously and we get an
802 * OptimisticLockFailedException. This error is likely transient and The
803 * WriteTransaction#submit API docs state that a retry will likely
804 * succeed. So we'll try again if that scenario occurs. If it fails a
805 * third time then it probably will never succeed so we'll fail in that
808 * By retrying we're attempting to hide the internal implementation of
809 * the data store and how it handles concurrent updates from the
810 * restconf client. The client has instructed us to put the data and we
811 * should make every effort to do so without pushing optimistic lock
812 * failures back to the client and forcing them to handle it via retry
813 * (and having to document the behavior).
815 PutResult result = null;
818 if (mountPoint != null) {
820 result = this.broker.commitMountPointDataPut(mountPoint, normalizedII, payload.getData(), insert,
823 result = this.broker.commitConfigurationDataPut(this.controllerContext.getGlobalSchema(), normalizedII,
824 payload.getData(), insert, point);
828 result.getFutureOfPutData().checkedGet();
829 return Response.status(result.getStatus()).build();
830 } catch (TransactionCommitFailedException e) {
831 if (e instanceof OptimisticLockFailedException) {
833 LOG.debug("Got OptimisticLockFailedException on last try - failing " + identifier);
834 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
837 LOG.debug("Got OptimisticLockFailedException - trying again " + identifier);
839 LOG.debug("Update failed for " + identifier, e);
840 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
846 private static void validateTopLevelNodeName(final NormalizedNodeContext node,
847 final YangInstanceIdentifier identifier) {
849 final String payloadName = node.getData().getNodeType().getLocalName();
852 if (identifier.isEmpty()) {
854 if (!node.getData().getNodeType().equals(NETCONF_BASE_QNAME)) {
855 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
856 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
860 final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
861 if (!payloadName.equals(identifierName)) {
862 throw new RestconfDocumentedException(
863 "Payload name (" + payloadName + ") is different from identifier name (" + identifierName + ")",
864 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
870 * Validates whether keys in {@code payload} are equal to values of keys in
871 * {@code iiWithData} for list schema node
873 * @throws RestconfDocumentedException
874 * if key values or key count in payload and URI isn't equal
877 private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
878 Preconditions.checkArgument(payload != null);
879 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
880 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
881 final SchemaNode schemaNode = iiWithData.getSchemaNode();
882 final NormalizedNode<?, ?> data = payload.getData();
883 if (schemaNode instanceof ListSchemaNode) {
884 final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
885 if (lastPathArgument instanceof NodeIdentifierWithPredicates && data instanceof MapEntryNode) {
886 final Map<QName, Object> uriKeyValues =
887 ((NodeIdentifierWithPredicates) lastPathArgument).getKeyValues();
888 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
893 private static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final MapEntryNode payload,
894 final List<QName> keyDefinitions) {
896 final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
897 for (final QName keyDefinition : keyDefinitions) {
898 final Object uriKeyValue = mutableCopyUriKeyValues.remove(keyDefinition);
899 // should be caught during parsing URI to InstanceIdentifier
900 RestconfValidationUtils.checkDocumentedError(uriKeyValue != null, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
901 "Missing key " + keyDefinition + " in URI.");
903 final Object dataKeyValue = payload.getIdentifier().getKeyValues().get(keyDefinition);
905 if (!uriKeyValue.equals(dataKeyValue)) {
906 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName()
907 + "' specified in the URI doesn't match the value '" + dataKeyValue
908 + "' specified in the message body. ";
909 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
915 public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload,
916 final UriInfo uriInfo) {
917 return createConfigurationData(payload, uriInfo);
920 // FIXME create RestconfIdetifierHelper and move this method there
921 private static YangInstanceIdentifier checkConsistencyOfNormalizedNodeContext(final NormalizedNodeContext payload) {
922 Preconditions.checkArgument(payload != null);
923 Preconditions.checkArgument(payload.getData() != null);
924 Preconditions.checkArgument(payload.getData().getNodeType() != null);
925 Preconditions.checkArgument(payload.getInstanceIdentifierContext() != null);
926 Preconditions.checkArgument(payload.getInstanceIdentifierContext().getInstanceIdentifier() != null);
928 final QName payloadNodeQname = payload.getData().getNodeType();
929 final YangInstanceIdentifier yangIdent = payload.getInstanceIdentifierContext().getInstanceIdentifier();
930 if (payloadNodeQname.compareTo(yangIdent.getLastPathArgument().getNodeType()) > 0) {
933 final InstanceIdentifierContext<?> parentContext = payload.getInstanceIdentifierContext();
934 final SchemaNode parentSchemaNode = parentContext.getSchemaNode();
935 if (parentSchemaNode instanceof DataNodeContainer) {
936 final DataNodeContainer cast = (DataNodeContainer) parentSchemaNode;
937 for (final DataSchemaNode child : cast.getChildNodes()) {
938 if (payloadNodeQname.compareTo(child.getQName()) == 0) {
939 return YangInstanceIdentifier.builder(yangIdent).node(child.getQName()).build();
943 if (parentSchemaNode instanceof RpcDefinition) {
946 final String errMsg = "Error parsing input: DataSchemaNode has not children ";
947 LOG.info(errMsg + yangIdent);
948 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
952 public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
953 if (payload == null) {
954 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
956 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
957 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
958 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
960 boolean insertUsed = false;
961 boolean pointUsed = false;
962 String insert = null;
965 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
966 switch (entry.getKey()) {
970 insert = entry.getValue().iterator().next();
972 throw new RestconfDocumentedException("Insert parameter can be used only once.");
978 point = entry.getValue().iterator().next();
980 throw new RestconfDocumentedException("Point parameter can be used only once.");
984 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
988 if (pointUsed && !insertUsed) {
989 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
991 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
992 throw new RestconfDocumentedException(
993 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
996 CheckedFuture<Void, TransactionCommitFailedException> future;
997 if (mountPoint != null) {
998 future = this.broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData(), insert,
1001 future = this.broker.commitConfigurationDataPost(this.controllerContext.getGlobalSchema(), normalizedII,
1002 payload.getData(), insert, point);
1006 future.checkedGet();
1007 } catch (final RestconfDocumentedException e) {
1009 } catch (TransactionCommitFailedException e) {
1010 LOG.info("Error creating data " + (uriInfo != null ? uriInfo.getPath() : ""), e);
1011 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
1014 LOG.trace("Successfuly created data.");
1016 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
1017 // FIXME: Provide path to result.
1018 final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
1019 if (location != null) {
1020 responseBuilder.location(location);
1022 return responseBuilder.build();
1025 private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint,
1026 final YangInstanceIdentifier normalizedII) {
1027 if (uriInfo == null) {
1028 // This is null if invoked internally
1032 final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
1033 uriBuilder.path("config");
1035 uriBuilder.path(this.controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
1036 } catch (final Exception e) {
1037 LOG.info("Location for instance identifier" + normalizedII + "wasn't created", e);
1040 return uriBuilder.build();
1044 public Response deleteConfigurationData(final String identifier) {
1045 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
1046 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
1047 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
1049 final CheckedFuture<Void, TransactionCommitFailedException> future;
1050 if (mountPoint != null) {
1051 future = this.broker.commitConfigurationDataDelete(mountPoint, normalizedII);
1053 future = this.broker.commitConfigurationDataDelete(normalizedII);
1057 future.checkedGet();
1058 } catch (TransactionCommitFailedException e) {
1059 final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
1060 Predicates.instanceOf(ModifiedNodeDoesNotExistException.class));
1061 if (searchedException.isPresent()) {
1062 throw new RestconfDocumentedException("Data specified for delete doesn't exist.", ErrorType.APPLICATION,
1063 ErrorTag.DATA_MISSING);
1066 final String errMsg = "Error while deleting data";
1067 LOG.info(errMsg, e);
1068 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
1071 return Response.status(Status.OK).build();
1075 * Subscribes to some path in schema context (stream) to listen on changes
1078 * Additional parameters for subscribing to stream are loaded via rpc input
1081 * <li>datastore - default CONFIGURATION (other values of
1082 * {@link LogicalDatastoreType} enum type)</li>
1083 * <li>scope - default BASE (other values of {@link DataChangeScope})</li>
1087 public NormalizedNodeContext subscribeToStream(final String identifier, final UriInfo uriInfo) {
1088 boolean startTime_used = false;
1089 boolean stopTime_used = false;
1090 boolean filter_used = false;
1091 Instant start = Instant.now();
1092 Instant stop = null;
1093 String filter = null;
1095 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
1096 switch (entry.getKey()) {
1098 if (!startTime_used) {
1099 startTime_used = true;
1100 start = parseDateFromQueryParam(entry);
1102 throw new RestconfDocumentedException("Start-time parameter can be used only once.");
1106 if (!stopTime_used) {
1107 stopTime_used = true;
1108 stop = parseDateFromQueryParam(entry);
1110 throw new RestconfDocumentedException("Stop-time parameter can be used only once.");
1116 filter = entry.getValue().iterator().next();
1118 throw new RestconfDocumentedException("Filter parameter can be used only once.");
1122 throw new RestconfDocumentedException("Bad parameter used with notifications: " + entry.getKey());
1125 if (!startTime_used && stopTime_used) {
1126 throw new RestconfDocumentedException("Stop-time parameter has to be used with start-time parameter.");
1128 URI response = null;
1129 if (identifier.contains(DATA_SUBSCR)) {
1130 response = dataSubs(identifier, uriInfo, start, stop, filter);
1131 } else if (identifier.contains(NOTIFICATION_STREAM)) {
1132 response = notifStream(identifier, uriInfo, start, stop, filter);
1135 if (response != null) {
1136 // prepare node with value of location
1137 final InstanceIdentifierContext<?> iid = prepareIIDSubsStreamOutput();
1138 final NormalizedNodeAttrBuilder<NodeIdentifier, Object, LeafNode<Object>> builder =
1139 ImmutableLeafNodeBuilder.create().withValue(response.toString());
1140 builder.withNodeIdentifier(
1141 NodeIdentifier.create(QName.create("subscribe:to:notification", "2016-10-28", "location")));
1143 // prepare new header with location
1144 final Map<String, Object> headers = new HashMap<>();
1145 headers.put("Location", response);
1147 return new NormalizedNodeContext(iid, builder.build(), headers);
1150 final String msg = "Bad type of notification of sal-remote";
1152 throw new RestconfDocumentedException(msg);
1155 private static Instant parseDateFromQueryParam(final Entry<String, List<String>> entry) {
1156 final DateAndTime event = new DateAndTime(entry.getValue().iterator().next());
1157 final String value = event.getValue();
1158 final TemporalAccessor p;
1160 p = FORMATTER.parse(value);
1161 } catch (DateTimeParseException e) {
1162 throw new RestconfDocumentedException("Cannot parse of value in date: " + value, e);
1164 return Instant.from(p);
1168 * @return {@link InstanceIdentifierContext} of location leaf for
1171 private static InstanceIdentifierContext<?> prepareIIDSubsStreamOutput() {
1172 final QName qnameBase = QName.create("subscribe:to:notification", "2016-10-28", "notifi");
1173 final SchemaContext schemaCtx = ControllerContext.getInstance().getGlobalSchema();
1174 final DataSchemaNode location = ((ContainerSchemaNode) schemaCtx
1175 .findModuleByNamespaceAndRevision(qnameBase.getNamespace(), qnameBase.getRevision())
1176 .getDataChildByName(qnameBase)).getDataChildByName(QName.create(qnameBase, "location"));
1177 final List<PathArgument> path = new ArrayList<>();
1178 path.add(NodeIdentifier.create(qnameBase));
1179 path.add(NodeIdentifier.create(QName.create(qnameBase, "location")));
1181 return new InstanceIdentifierContext<SchemaNode>(YangInstanceIdentifier.create(path), location, null,
1186 * Register notification listener by stream name
1193 * - stop-time of getting notification
1195 * - start-time of getting notification
1197 * - indicate which subset of all possible events are of interest
1198 * @return {@link URI} of location
1200 private URI notifStream(final String identifier, final UriInfo uriInfo, final Instant start,
1201 final Instant stop, final String filter) {
1202 final String streamName = Notificator.createStreamNameFromUri(identifier);
1203 if (Strings.isNullOrEmpty(streamName)) {
1204 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1206 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
1207 if (listeners == null || listeners.isEmpty()) {
1208 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1209 ErrorTag.UNKNOWN_ELEMENT);
1212 for (final NotificationListenerAdapter listener : listeners) {
1213 this.broker.registerToListenNotification(listener);
1214 listener.setQueryParams(start, java.util.Optional.ofNullable(stop), java.util.Optional.ofNullable(filter));
1217 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1218 int notificationPort = NOTIFICATION_PORT;
1220 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
1221 notificationPort = webSocketServerInstance.getPort();
1222 } catch (final NullPointerException e) {
1223 WebSocketServer.createInstance(NOTIFICATION_PORT);
1225 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1226 final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
1228 return uriToWebsocketServer;
1232 * Register data change listener by stream name
1239 * - start-time of getting notification
1241 * - stop-time of getting notification
1243 * - indicate which subset of all possible events are of interest
1244 * @return {@link URI} of location
1246 private URI dataSubs(final String identifier, final UriInfo uriInfo, final Instant start, final Instant stop,
1247 final String filter) {
1248 final String streamName = Notificator.createStreamNameFromUri(identifier);
1249 if (Strings.isNullOrEmpty(streamName)) {
1250 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1253 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1254 if (listener == null) {
1255 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1256 ErrorTag.UNKNOWN_ELEMENT);
1258 listener.setQueryParams(start, java.util.Optional.ofNullable(stop), java.util.Optional.ofNullable(filter));
1260 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1261 final LogicalDatastoreType datastore =
1262 parserURIEnumParameter(LogicalDatastoreType.class, paramToValues.get(DATASTORE_PARAM_NAME));
1263 if (datastore == null) {
1264 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1265 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1267 final DataChangeScope scope =
1268 parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
1269 if (scope == null) {
1270 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1271 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1274 this.broker.registerToListenDataChanges(datastore, scope, listener);
1276 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1277 int notificationPort = NOTIFICATION_PORT;
1279 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
1280 notificationPort = webSocketServerInstance.getPort();
1281 } catch (final NullPointerException e) {
1282 WebSocketServer.createInstance(NOTIFICATION_PORT);
1284 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1285 final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
1287 return uriToWebsocketServer;
1291 public PATCHStatusContext patchConfigurationData(final String identifier, final PATCHContext context,
1292 final UriInfo uriInfo) {
1293 if (context == null) {
1294 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1298 return this.broker.patchConfigurationDataWithinTransaction(context);
1299 } catch (final Exception e) {
1300 LOG.debug("Patch transaction failed", e);
1301 throw new RestconfDocumentedException(e.getMessage());
1306 public PATCHStatusContext patchConfigurationData(final PATCHContext context, @Context final UriInfo uriInfo) {
1307 if (context == null) {
1308 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1312 return this.broker.patchConfigurationDataWithinTransaction(context);
1313 } catch (final Exception e) {
1314 LOG.debug("Patch transaction failed", e);
1315 throw new RestconfDocumentedException(e.getMessage());
1320 * Load parameter for subscribing to stream from input composite node
1324 * @return enum object if its string value is equal to {@code paramName}. In
1327 private static <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1328 final String paramName) {
1329 final Optional<DataContainerChild<? extends PathArgument, ?>> augNode =
1330 value.getChild(SAL_REMOTE_AUG_IDENTIFIER);
1331 if (!augNode.isPresent() && !(augNode instanceof AugmentationNode)) {
1334 final Optional<DataContainerChild<? extends PathArgument, ?>> enumNode = ((AugmentationNode) augNode.get())
1335 .getChild(new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1336 if (!enumNode.isPresent()) {
1339 final Object rawValue = enumNode.get().getValue();
1340 if (!(rawValue instanceof String)) {
1344 return resolveAsEnum(classDescriptor, (String) rawValue);
1348 * Checks whether {@code value} is one of the string representation of
1349 * enumeration {@code classDescriptor}
1351 * @return enum object if string value of {@code classDescriptor}
1352 * enumeration is equal to {@code value}. Other cases null.
1354 private static <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1355 if (Strings.isNullOrEmpty(value)) {
1358 return resolveAsEnum(classDescriptor, value);
1361 private static <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1362 final T[] enumConstants = classDescriptor.getEnumConstants();
1363 if (enumConstants != null) {
1364 for (final T enm : classDescriptor.getEnumConstants()) {
1365 if (((Enum<?>) enm).name().equals(value)) {
1373 private static Map<String, String> resolveValuesFromUri(final String uri) {
1374 final Map<String, String> result = new HashMap<>();
1375 final String[] tokens = uri.split("/");
1376 for (int i = 1; i < tokens.length; i++) {
1377 final String[] parameterTokens = tokens[i].split("=");
1378 if (parameterTokens.length == 2) {
1379 result.put(parameterTokens[0], parameterTokens[1]);
1385 private MapNode makeModuleMapNode(final Set<Module> modules) {
1386 Preconditions.checkNotNull(modules);
1387 final Module restconfModule = getRestconfModule();
1388 final DataSchemaNode moduleSchemaNode = this.controllerContext
1389 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1390 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1392 final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder =
1393 Builders.mapBuilder((ListSchemaNode) moduleSchemaNode);
1395 for (final Module module : modules) {
1396 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1398 return listModuleBuilder.build();
1401 protected MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1402 Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1403 "moduleSchemaNode has to be of type ListSchemaNode");
1404 final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1405 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues =
1406 Builders.mapEntryBuilder(listModuleSchemaNode);
1408 List<DataSchemaNode> instanceDataChildrenByName =
1409 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "name");
1410 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1411 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1413 .withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName()).build());
1415 instanceDataChildrenByName =
1416 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "revision");
1417 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1418 Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1419 final String revision = module.getQNameModule().getFormattedRevision();
1421 .withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode).withValue(revision).build());
1423 instanceDataChildrenByName =
1424 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "namespace");
1425 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1426 Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1427 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1428 .withValue(module.getNamespace().toString()).build());
1430 instanceDataChildrenByName =
1431 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "feature");
1432 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1433 Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1434 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder =
1435 Builders.leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1436 for (final FeatureDefinition feature : module.getFeatures()) {
1437 featuresBuilder.withChild(Builders.leafSetEntryBuilder((LeafListSchemaNode) featureSchemaNode)
1438 .withValue(feature.getQName().getLocalName()).build());
1440 moduleNodeValues.withChild(featuresBuilder.build());
1442 return moduleNodeValues.build();
1445 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1446 Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1447 "streamSchemaNode has to be of type ListSchemaNode");
1448 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1449 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues =
1450 Builders.mapEntryBuilder(listStreamSchemaNode);
1452 List<DataSchemaNode> instanceDataChildrenByName =
1453 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "name");
1454 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1455 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1456 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName).build());
1458 instanceDataChildrenByName =
1459 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "description");
1460 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1461 Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1462 streamNodeValues.withChild(
1463 Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue("DESCRIPTION_PLACEHOLDER").build());
1465 instanceDataChildrenByName =
1466 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-support");
1467 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1468 Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1469 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1470 .withValue(Boolean.valueOf(true)).build());
1472 instanceDataChildrenByName =
1473 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-log-creation-time");
1474 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1475 Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1476 streamNodeValues.withChild(
1477 Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode).withValue("").build());
1479 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "events");
1480 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1481 Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1482 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode).withValue("").build());
1484 return streamNodeValues.build();
1488 * Prepare stream for notification
1491 * - contains list of qnames of notifications
1492 * @return - checked future object
1494 private static CheckedFuture<DOMRpcResult, DOMRpcException> invokeSalRemoteRpcNotifiStrRPC(
1495 final NormalizedNodeContext payload) {
1496 final ContainerNode data = (ContainerNode) payload.getData();
1497 LeafSetNode leafSet = null;
1498 String outputType = "XML";
1499 for (final DataContainerChild<? extends PathArgument, ?> dataChild : data.getValue()) {
1500 if (dataChild instanceof LeafSetNode) {
1501 leafSet = (LeafSetNode) dataChild;
1502 } else if (dataChild instanceof AugmentationNode) {
1503 outputType = (String) ((AugmentationNode) dataChild).getValue().iterator().next().getValue();
1507 final Collection<LeafSetEntryNode> entryNodes = leafSet.getValue();
1508 final List<SchemaPath> paths = new ArrayList<>();
1509 String streamName = CREATE_NOTIFICATION_STREAM + "/";
1511 final Iterator<LeafSetEntryNode> iterator = entryNodes.iterator();
1512 while (iterator.hasNext()) {
1513 final QName valueQName = QName.create((String) iterator.next().getValue());
1514 final Module module =
1515 ControllerContext.getInstance().findModuleByNamespace(valueQName.getModule().getNamespace());
1516 Preconditions.checkNotNull(module,
1517 "Module for namespace " + valueQName.getModule().getNamespace() + " does not exist");
1518 NotificationDefinition notifiDef = null;
1519 for (final NotificationDefinition notification : module.getNotifications()) {
1520 if (notification.getQName().equals(valueQName)) {
1521 notifiDef = notification;
1525 final String moduleName = module.getName();
1526 Preconditions.checkNotNull(notifiDef,
1527 "Notification " + valueQName + "doesn't exist in module " + moduleName);
1528 paths.add(notifiDef.getPath());
1529 streamName = streamName + moduleName + ":" + valueQName.getLocalName();
1530 if (iterator.hasNext()) {
1531 streamName = streamName + ",";
1535 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
1536 final QName outputQname = QName.create(rpcQName, "output");
1537 final QName streamNameQname = QName.create(rpcQName, "notification-stream-identifier");
1539 final ContainerNode output =
1540 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
1541 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
1543 if (!Notificator.existNotificationListenerFor(streamName)) {
1544 Notificator.createNotificationListener(paths, streamName, outputType);
1547 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
1549 return Futures.immediateCheckedFuture(defaultDOMRpcResult);