2 * Copyright (c) 2014 - 2016 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.annotations.VisibleForTesting;
12 import com.google.common.base.CharMatcher;
13 import com.google.common.base.Optional;
14 import com.google.common.base.Preconditions;
15 import com.google.common.base.Predicates;
16 import com.google.common.base.Splitter;
17 import com.google.common.base.Strings;
18 import com.google.common.base.Throwables;
19 import com.google.common.collect.ImmutableSet;
20 import com.google.common.collect.Iterables;
21 import com.google.common.collect.Lists;
22 import com.google.common.collect.Maps;
23 import com.google.common.util.concurrent.CheckedFuture;
24 import com.google.common.util.concurrent.Futures;
26 import java.text.ParseException;
27 import java.time.Instant;
28 import java.time.format.DateTimeFormatter;
29 import java.time.format.DateTimeFormatterBuilder;
30 import java.time.format.DateTimeParseException;
31 import java.time.temporal.ChronoField;
32 import java.time.temporal.TemporalAccessor;
33 import java.util.ArrayList;
34 import java.util.Collection;
35 import java.util.Collections;
36 import java.util.HashMap;
37 import java.util.Iterator;
38 import java.util.List;
40 import java.util.Map.Entry;
41 import java.util.Objects;
43 import java.util.concurrent.CancellationException;
44 import java.util.concurrent.ExecutionException;
45 import javax.ws.rs.core.Context;
46 import javax.ws.rs.core.Response;
47 import javax.ws.rs.core.Response.ResponseBuilder;
48 import javax.ws.rs.core.Response.Status;
49 import javax.ws.rs.core.UriBuilder;
50 import javax.ws.rs.core.UriInfo;
51 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
52 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
53 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
54 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
55 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
56 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
57 import org.opendaylight.controller.md.sal.dom.api.DOMRpcImplementationNotAvailableException;
58 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
59 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
60 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
61 import org.opendaylight.netconf.md.sal.rest.common.RestconfValidationUtils;
62 import org.opendaylight.netconf.sal.rest.api.Draft02;
63 import org.opendaylight.netconf.sal.rest.api.RestconfService;
64 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
65 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
66 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
67 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
68 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
69 import org.opendaylight.netconf.sal.streams.websockets.WebSocketServer;
70 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
71 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
72 import org.opendaylight.yangtools.yang.common.QName;
73 import org.opendaylight.yangtools.yang.common.QNameModule;
74 import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
75 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
76 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
77 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
78 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
79 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
80 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
81 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
82 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
83 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
84 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
85 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
86 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
87 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
88 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
89 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
90 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
91 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
92 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
93 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
94 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
95 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
96 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
97 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
98 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
99 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
100 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
101 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
102 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
103 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
104 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
105 import org.opendaylight.yangtools.yang.model.api.Module;
106 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
107 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
108 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
109 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
110 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
111 import org.opendaylight.yangtools.yang.model.util.SimpleSchemaContext;
112 import org.slf4j.Logger;
113 import org.slf4j.LoggerFactory;
115 public class RestconfImpl implements RestconfService {
117 private static final RestconfImpl INSTANCE = new RestconfImpl();
120 * Notifications are served on port 8181.
122 private static final int NOTIFICATION_PORT = 8181;
124 private static final int CHAR_NOT_FOUND = -1;
126 private static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
128 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
130 private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
132 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
134 private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
136 private static final String DATASTORE_PARAM_NAME = "datastore";
138 private static final String SCOPE_PARAM_NAME = "scope";
140 private static final String OUTPUT_TYPE_PARAM_NAME = "notification-output-type";
142 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
144 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
146 private static final QName NETCONF_BASE_QNAME = QName.create(QNameModule.create(URI.create(NETCONF_BASE), null),
147 NETCONF_BASE_PAYLOAD_NAME).intern();
149 private static final QNameModule SAL_REMOTE_AUGMENT;
153 SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
154 SimpleDateFormatUtil.getRevisionFormat().parse("2014-07-08"));
155 } catch (final ParseException e) {
156 throw new ExceptionInInitializerError(e);
160 private static final AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER =
161 new AugmentationIdentifier(ImmutableSet.of(
162 QName.create(SAL_REMOTE_AUGMENT, "scope"), QName.create(SAL_REMOTE_AUGMENT, "datastore"),
163 QName.create(SAL_REMOTE_AUGMENT, "notification-output-type")));
165 public static final CharSequence DATA_SUBSCR = "data-change-event-subscription";
166 private static final CharSequence CREATE_DATA_SUBSCR = "create-" + DATA_SUBSCR;
168 public static final CharSequence NOTIFICATION_STREAM = "notification-stream";
169 private static final CharSequence CREATE_NOTIFICATION_STREAM = "create-" + NOTIFICATION_STREAM;
171 private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
172 .appendValue(ChronoField.YEAR, 4).appendLiteral('-')
173 .appendValue(ChronoField.MONTH_OF_YEAR, 2).appendLiteral('-')
174 .appendValue(ChronoField.DAY_OF_MONTH, 2).appendLiteral('T')
175 .appendValue(ChronoField.HOUR_OF_DAY, 2).appendLiteral(':')
176 .appendValue(ChronoField.MINUTE_OF_HOUR, 2).appendLiteral(':')
177 .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
178 .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
179 .appendOffset("+HH:MM", "Z").toFormatter();
181 private BrokerFacade broker;
183 private ControllerContext controllerContext;
185 public void setBroker(final BrokerFacade broker) {
186 this.broker = broker;
189 public void setControllerContext(final ControllerContext controllerContext) {
190 this.controllerContext = controllerContext;
193 private RestconfImpl() {
196 public static RestconfImpl getInstance() {
201 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
202 final Set<Module> allModules = this.controllerContext.getAllModules();
203 final MapNode allModuleMap = makeModuleMapNode(allModules);
205 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
207 final Module restconfModule = getRestconfModule();
208 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
209 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
210 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
212 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
213 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
214 moduleContainerBuilder.withChild(allModuleMap);
216 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode, null, schemaContext),
217 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
221 * Valid only for mount point.
224 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
225 Preconditions.checkNotNull(identifier);
226 if (!identifier.contains(ControllerContext.MOUNT)) {
227 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
228 + " URI has to end with " + ControllerContext.MOUNT;
229 LOG.debug(errMsg + " for " + identifier);
230 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
233 final InstanceIdentifierContext<?> mountPointIdentifier =
234 this.controllerContext.toMountPointIdentifier(identifier);
235 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
236 final Set<Module> modules = this.controllerContext.getAllModules(mountPoint);
237 final MapNode mountPointModulesMap = makeModuleMapNode(modules);
239 final Module restconfModule = getRestconfModule();
240 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
241 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
242 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
244 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
245 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
246 moduleContainerBuilder.withChild(mountPointModulesMap);
248 return new NormalizedNodeContext(
249 new InstanceIdentifierContext<>(null, modulesSchemaNode, mountPoint,
250 this.controllerContext.getGlobalSchema()),
251 moduleContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
255 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
256 Preconditions.checkNotNull(identifier);
257 final QName moduleNameAndRevision = getModuleNameAndRevision(identifier);
258 Module module = null;
259 DOMMountPoint mountPoint = null;
260 final SchemaContext schemaContext;
261 if (identifier.contains(ControllerContext.MOUNT)) {
262 final InstanceIdentifierContext<?> mountPointIdentifier =
263 this.controllerContext.toMountPointIdentifier(identifier);
264 mountPoint = mountPointIdentifier.getMountPoint();
265 module = this.controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision);
266 schemaContext = mountPoint.getSchemaContext();
268 module = this.controllerContext.findModuleByNameAndRevision(moduleNameAndRevision);
269 schemaContext = this.controllerContext.getGlobalSchema();
272 if (module == null) {
273 final String errMsg = "Module with name '" + moduleNameAndRevision.getLocalName() + "' and revision '"
274 + moduleNameAndRevision.getRevision() + "' was not found.";
276 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
279 final Module restconfModule = getRestconfModule();
280 final Set<Module> modules = Collections.singleton(module);
281 final MapNode moduleMap = makeModuleMapNode(modules);
283 final DataSchemaNode moduleSchemaNode = this.controllerContext
284 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
285 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
287 return new NormalizedNodeContext(
288 new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint, schemaContext), moduleMap,
289 QueryParametersParser.parseWriterParameters(uriInfo));
293 public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
294 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
295 final Set<String> availableStreams = Notificator.getStreamNames();
296 final Module restconfModule = getRestconfModule();
297 final DataSchemaNode streamSchemaNode = this.controllerContext
298 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
299 Preconditions.checkState(streamSchemaNode instanceof ListSchemaNode);
301 final CollectionNodeBuilder<MapEntryNode, MapNode> listStreamsBuilder =
302 Builders.mapBuilder((ListSchemaNode) streamSchemaNode);
304 for (final String streamName : availableStreams) {
305 listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
308 final DataSchemaNode streamsContainerSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
309 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
310 Preconditions.checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
312 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
313 Builders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
314 streamsContainerBuilder.withChild(listStreamsBuilder.build());
316 return new NormalizedNodeContext(
317 new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null, schemaContext),
318 streamsContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
322 public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
323 final Set<Module> allModules = this.controllerContext.getAllModules();
324 return operationsFromModulesToNormalizedContext(allModules, null);
328 public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
329 Set<Module> modules = null;
330 DOMMountPoint mountPoint = null;
331 if (identifier.contains(ControllerContext.MOUNT)) {
332 final InstanceIdentifierContext<?> mountPointIdentifier =
333 this.controllerContext.toMountPointIdentifier(identifier);
334 mountPoint = mountPointIdentifier.getMountPoint();
335 modules = this.controllerContext.getAllModules(mountPoint);
338 final String errMsg =
339 "URI has bad format. If operations behind mount point should be showed, URI has to " + "end with ";
340 LOG.debug(errMsg + ControllerContext.MOUNT + " for " + identifier);
341 throw new RestconfDocumentedException(errMsg + ControllerContext.MOUNT, ErrorType.PROTOCOL,
342 ErrorTag.INVALID_VALUE);
345 return operationsFromModulesToNormalizedContext(modules, mountPoint);
349 * Special case only for GET restconf/operations use (since moment of
350 * pre-Beryllium Yang parser and Yang model API removal). The method is
351 * creating fake schema context with fake module and fake data by use own
352 * implementations of schema nodes and module.
355 * set of modules for get RPCs from every module
357 * mount point, if in use otherwise null
358 * @return {@link NormalizedNodeContext}
360 private static NormalizedNodeContext operationsFromModulesToNormalizedContext(final Set<Module> modules,
361 final DOMMountPoint mountPoint) {
363 final Collection<Module> neededModules = new ArrayList<>(modules.size());
364 final ArrayList<LeafSchemaNode> fakeRpcSchema = new ArrayList<>();
366 for (final Module m : modules) {
367 final Set<RpcDefinition> rpcs = m.getRpcs();
368 if (!rpcs.isEmpty()) {
369 neededModules.add(m);
371 fakeRpcSchema.ensureCapacity(fakeRpcSchema.size() + rpcs.size());
372 rpcs.forEach(rpc -> fakeRpcSchema.add(new FakeLeafSchemaNode(rpc.getQName())));
376 final ContainerSchemaNode fakeCont = new FakeContainerSchemaNode(fakeRpcSchema);
377 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> containerBuilder =
378 Builders.containerBuilder(fakeCont);
380 for (final LeafSchemaNode leaf : fakeRpcSchema) {
381 containerBuilder.withChild(Builders.leafBuilder(leaf).build());
384 final Collection<Module> fakeModules = new ArrayList<>(neededModules.size() + 1);
385 neededModules.forEach(imp -> fakeModules.add(new FakeImportedModule(imp)));
386 fakeModules.add(new FakeRestconfModule(neededModules, fakeCont));
388 final SchemaContext fakeSchemaCtx = SimpleSchemaContext.forModules(ImmutableSet.copyOf(fakeModules));
389 final InstanceIdentifierContext<ContainerSchemaNode> instanceIdentifierContext =
390 new InstanceIdentifierContext<>(null, fakeCont, mountPoint, fakeSchemaCtx);
391 return new NormalizedNodeContext(instanceIdentifierContext, containerBuilder.build());
394 private Module getRestconfModule() {
395 final Module restconfModule = this.controllerContext.getRestconfModule();
396 if (restconfModule == null) {
397 LOG.debug("ietf-restconf module was not found.");
398 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
399 ErrorTag.OPERATION_NOT_SUPPORTED);
402 return restconfModule;
405 private static QName getModuleNameAndRevision(final String identifier) {
406 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
407 String moduleNameAndRevision = "";
408 if (mountIndex >= 0) {
409 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
411 moduleNameAndRevision = identifier;
414 final Splitter splitter = Splitter.on("/").omitEmptyStrings();
415 final Iterable<String> split = splitter.split(moduleNameAndRevision);
416 final List<String> pathArgs = Lists.<String>newArrayList(split);
417 if (pathArgs.size() < 2) {
418 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
419 throw new RestconfDocumentedException(
420 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
421 ErrorTag.INVALID_VALUE);
425 final String moduleName = pathArgs.get(0);
426 final String revision = pathArgs.get(1);
427 return QName.create(null, SimpleDateFormatUtil.getRevisionFormat().parse(revision), moduleName);
428 } catch (final ParseException e) {
429 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
430 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
431 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
436 public Object getRoot() {
441 public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload,
442 final UriInfo uriInfo) {
443 final SchemaPath type = payload.getInstanceIdentifierContext().getSchemaNode().getPath();
444 final URI namespace = payload.getInstanceIdentifierContext().getSchemaNode().getQName().getNamespace();
445 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
446 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
447 final SchemaContext schemaContext;
449 if (mountPoint != null) {
450 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
451 if (!mountRpcServices.isPresent()) {
452 LOG.debug("Error: Rpc service is missing.");
453 throw new RestconfDocumentedException("Rpc service is missing.");
455 schemaContext = mountPoint.getSchemaContext();
456 response = mountRpcServices.get().invokeRpc(type, payload.getData());
458 if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
459 if (identifier.contains(CREATE_DATA_SUBSCR)) {
460 response = invokeSalRemoteRpcSubscribeRPC(payload);
461 } else if (identifier.contains(CREATE_NOTIFICATION_STREAM)) {
462 response = invokeSalRemoteRpcNotifiStrRPC(payload);
464 final String msg = "Not supported operation";
466 throw new RestconfDocumentedException(msg, ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED);
469 response = this.broker.invokeRpc(type, payload.getData());
471 schemaContext = this.controllerContext.getGlobalSchema();
474 final DOMRpcResult result = checkRpcResponse(response);
476 RpcDefinition resultNodeSchema = null;
477 final NormalizedNode<?, ?> resultData = result.getResult();
478 if (result != null && result.getResult() != null) {
479 resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
482 return new NormalizedNodeContext(
483 new InstanceIdentifierContext<>(null, resultNodeSchema, mountPoint, schemaContext),
484 resultData, QueryParametersParser.parseWriterParameters(uriInfo));
488 public NormalizedNodeContext invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
489 if (noPayload != null && !CharMatcher.WHITESPACE.matchesAllOf(noPayload)) {
490 throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
493 String identifierEncoded = null;
494 DOMMountPoint mountPoint = null;
495 final SchemaContext schemaContext;
496 if (identifier.contains(ControllerContext.MOUNT)) {
497 // mounted RPC call - look up mount instance.
498 final InstanceIdentifierContext<?> mountPointId = this.controllerContext.toMountPointIdentifier(identifier);
499 mountPoint = mountPointId.getMountPoint();
500 schemaContext = mountPoint.getSchemaContext();
501 final int startOfRemoteRpcName =
502 identifier.lastIndexOf(ControllerContext.MOUNT) + ControllerContext.MOUNT.length() + 1;
503 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
504 identifierEncoded = remoteRpcName;
506 } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
507 final String slashErrorMsg = String.format(
508 "Identifier %n%s%ncan\'t contain slash "
509 + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.",
511 LOG.debug(slashErrorMsg);
512 throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
514 identifierEncoded = identifier;
515 schemaContext = this.controllerContext.getGlobalSchema();
518 final String identifierDecoded = this.controllerContext.urlPathArgDecode(identifierEncoded);
520 RpcDefinition rpc = null;
521 if (mountPoint == null) {
522 rpc = this.controllerContext.getRpcDefinition(identifierDecoded, null);
524 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
528 LOG.debug("RPC " + identifierDecoded + " does not exist.");
529 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
532 if (!rpc.getInput().getChildNodes().isEmpty()) {
533 LOG.debug("RPC " + rpc + " does not need input value.");
534 // FIXME : find a correct Error from specification
535 throw new IllegalStateException("RPC " + rpc + " does'n need input value!");
538 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
539 if (mountPoint != null) {
540 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
541 if (!mountRpcServices.isPresent()) {
542 throw new RestconfDocumentedException("Rpc service is missing.");
544 response = mountRpcServices.get().invokeRpc(rpc.getPath(), null);
546 response = this.broker.invokeRpc(rpc.getPath(), null);
549 final DOMRpcResult result = checkRpcResponse(response);
551 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpc, mountPoint, schemaContext),
552 result.getResult(), QueryParametersParser.parseWriterParameters(uriInfo));
555 private static DOMRpcResult checkRpcResponse(final CheckedFuture<DOMRpcResult, DOMRpcException> response) {
556 if (response == null) {
560 final DOMRpcResult retValue = response.get();
561 if (retValue.getErrors() == null || retValue.getErrors().isEmpty()) {
564 LOG.debug("RpcError message", retValue.getErrors());
565 throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
566 } catch (final InterruptedException e) {
567 final String errMsg = "The operation was interrupted while executing and did not complete.";
568 LOG.debug("Rpc Interrupt - " + errMsg, e);
569 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
570 } catch (final ExecutionException e) {
571 LOG.debug("Execution RpcError: ", e);
572 Throwable cause = e.getCause();
574 while (cause.getCause() != null) {
575 cause = cause.getCause();
578 if (cause instanceof IllegalArgumentException) {
579 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL,
580 ErrorTag.INVALID_VALUE);
581 } else if (cause instanceof DOMRpcImplementationNotAvailableException) {
582 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.APPLICATION,
583 ErrorTag.OPERATION_NOT_SUPPORTED);
585 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
588 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
591 } catch (final CancellationException e) {
592 final String errMsg = "The operation was cancelled while executing.";
593 LOG.debug("Cancel RpcExecution: " + errMsg, e);
594 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
598 private static void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
599 if (inputSchema != null && payload.getData() == null) {
600 // expected a non null payload
601 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
602 } else if (inputSchema == null && payload.getData() != null) {
603 // did not expect any input
604 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
608 private CheckedFuture<DOMRpcResult, DOMRpcException>
609 invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
610 final ContainerNode value = (ContainerNode) payload.getData();
611 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
612 final Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(new NodeIdentifier(
613 QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(), "path")));
614 final Object pathValue = path.isPresent() ? path.get().getValue() : null;
616 if (!(pathValue instanceof YangInstanceIdentifier)) {
617 final String errMsg = "Instance identifier was not normalized correctly ";
618 LOG.debug(errMsg + rpcQName);
619 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
622 final YangInstanceIdentifier pathIdentifier = (YangInstanceIdentifier) pathValue;
623 String streamName = (String) CREATE_DATA_SUBSCR;
624 NotificationOutputType outputType = null;
625 if (!pathIdentifier.isEmpty()) {
626 final String fullRestconfIdentifier =
627 DATA_SUBSCR + this.controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
629 LogicalDatastoreType datastore =
630 parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
631 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
633 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
634 scope = scope == null ? DEFAULT_SCOPE : scope;
636 outputType = parseEnumTypeParameter(value, NotificationOutputType.class, OUTPUT_TYPE_PARAM_NAME);
637 outputType = outputType == null ? NotificationOutputType.XML : outputType;
639 streamName = Notificator
640 .createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore + "/scope=" + scope);
643 if (Strings.isNullOrEmpty(streamName)) {
644 final String errMsg = "Path is empty or contains value node which is not Container or List build-in type.";
645 LOG.debug(errMsg + pathIdentifier);
646 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
649 final QName outputQname = QName.create(rpcQName, "output");
650 final QName streamNameQname = QName.create(rpcQName, "stream-name");
652 final ContainerNode output =
653 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
654 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
656 if (!Notificator.existListenerFor(streamName)) {
657 Notificator.createListener(pathIdentifier, streamName, outputType);
660 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
662 return Futures.immediateCheckedFuture(defaultDOMRpcResult);
665 private static RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
666 final String[] splittedIdentifier = identifierDecoded.split(":");
667 if (splittedIdentifier.length != 2) {
668 final String errMsg = identifierDecoded + " couldn't be splitted to 2 parts (module:rpc name)";
670 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
672 for (final Module module : schemaContext.getModules()) {
673 if (module.getName().equals(splittedIdentifier[0])) {
674 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
675 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
676 return rpcDefinition;
685 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
686 boolean withDefaUsed = false;
687 String withDefa = null;
689 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
690 switch (entry.getKey()) {
691 case "with-defaults":
694 withDefa = entry.getValue().iterator().next();
696 throw new RestconfDocumentedException("With-defaults parameter can be used only once.");
700 LOG.info("Unknown key : {}.", entry.getKey());
704 boolean tagged = false;
706 if (withDefa.equals("report-all-tagged")) {
710 if (withDefa.equals("report-all")) {
715 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
716 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
717 NormalizedNode<?, ?> data = null;
718 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
719 if (mountPoint != null) {
720 data = this.broker.readConfigurationData(mountPoint, normalizedII, withDefa);
722 data = this.broker.readConfigurationData(normalizedII, withDefa);
725 final String errMsg =
726 "Request could not be completed because the relevant data model content does not exist ";
727 LOG.debug(errMsg + identifier);
728 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
730 return new NormalizedNodeContext(iiWithData, data,
731 QueryParametersParser.parseWriterParameters(uriInfo, tagged));
735 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
736 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
737 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
738 NormalizedNode<?, ?> data = null;
739 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
740 if (mountPoint != null) {
741 data = this.broker.readOperationalData(mountPoint, normalizedII);
743 data = this.broker.readOperationalData(normalizedII);
746 final String errMsg =
747 "Request could not be completed because the relevant data model content does not exist ";
748 LOG.debug(errMsg + identifier);
749 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
751 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
755 public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload,
756 final UriInfo uriInfo) {
757 boolean insertUsed = false;
758 boolean pointUsed = false;
759 String insert = null;
762 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
763 switch (entry.getKey()) {
767 insert = entry.getValue().iterator().next();
769 throw new RestconfDocumentedException("Insert parameter can be used only once.");
775 point = entry.getValue().iterator().next();
777 throw new RestconfDocumentedException("Point parameter can be used only once.");
781 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
785 if (pointUsed && !insertUsed) {
786 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
788 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
789 throw new RestconfDocumentedException(
790 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
793 Preconditions.checkNotNull(identifier);
795 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
797 validateInput(iiWithData.getSchemaNode(), payload);
798 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
799 validateListKeysEqualityInPayloadAndUri(payload);
801 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
802 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
805 * There is a small window where another write transaction could be
806 * updating the same data simultaneously and we get an
807 * OptimisticLockFailedException. This error is likely transient and The
808 * WriteTransaction#submit API docs state that a retry will likely
809 * succeed. So we'll try again if that scenario occurs. If it fails a
810 * third time then it probably will never succeed so we'll fail in that
813 * By retrying we're attempting to hide the internal implementation of
814 * the data store and how it handles concurrent updates from the
815 * restconf client. The client has instructed us to put the data and we
816 * should make every effort to do so without pushing optimistic lock
817 * failures back to the client and forcing them to handle it via retry
818 * (and having to document the behavior).
820 PutResult result = null;
823 if (mountPoint != null) {
825 result = this.broker.commitMountPointDataPut(mountPoint, normalizedII, payload.getData(), insert,
828 result = this.broker.commitConfigurationDataPut(this.controllerContext.getGlobalSchema(), normalizedII,
829 payload.getData(), insert, point);
833 result.getFutureOfPutData().checkedGet();
834 return Response.status(result.getStatus()).build();
835 } catch (final TransactionCommitFailedException e) {
836 if (e instanceof OptimisticLockFailedException) {
838 LOG.debug("Got OptimisticLockFailedException on last try - failing " + identifier);
839 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
842 LOG.debug("Got OptimisticLockFailedException - trying again " + identifier);
844 LOG.debug("Update failed for " + identifier, e);
845 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
851 private static void validateTopLevelNodeName(final NormalizedNodeContext node,
852 final YangInstanceIdentifier identifier) {
854 final String payloadName = node.getData().getNodeType().getLocalName();
857 if (identifier.isEmpty()) {
859 if (!node.getData().getNodeType().equals(NETCONF_BASE_QNAME)) {
860 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
861 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
865 final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
866 if (!payloadName.equals(identifierName)) {
867 throw new RestconfDocumentedException(
868 "Payload name (" + payloadName + ") is different from identifier name (" + identifierName + ")",
869 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
875 * Validates whether keys in {@code payload} are equal to values of keys in
876 * {@code iiWithData} for list schema node.
878 * @throws RestconfDocumentedException
879 * if key values or key count in payload and URI isn't equal
882 private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
883 Preconditions.checkArgument(payload != null);
884 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
885 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
886 final SchemaNode schemaNode = iiWithData.getSchemaNode();
887 final NormalizedNode<?, ?> data = payload.getData();
888 if (schemaNode instanceof ListSchemaNode) {
889 final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
890 if (lastPathArgument instanceof NodeIdentifierWithPredicates && data instanceof MapEntryNode) {
891 final Map<QName, Object> uriKeyValues =
892 ((NodeIdentifierWithPredicates) lastPathArgument).getKeyValues();
893 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
899 public static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final MapEntryNode payload,
900 final List<QName> keyDefinitions) {
902 final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
903 for (final QName keyDefinition : keyDefinitions) {
904 final Object uriKeyValue = mutableCopyUriKeyValues.remove(keyDefinition);
905 // should be caught during parsing URI to InstanceIdentifier
906 RestconfValidationUtils.checkDocumentedError(uriKeyValue != null, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
907 "Missing key " + keyDefinition + " in URI.");
909 final Object dataKeyValue = payload.getIdentifier().getKeyValues().get(keyDefinition);
911 if (!Objects.deepEquals(uriKeyValue, dataKeyValue)) {
912 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName()
913 + "' specified in the URI doesn't match the value '" + dataKeyValue
914 + "' specified in the message body. ";
915 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
921 public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload,
922 final UriInfo uriInfo) {
923 return createConfigurationData(payload, uriInfo);
927 public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
928 if (payload == null) {
929 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
931 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
932 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
933 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
935 boolean insertUsed = false;
936 boolean pointUsed = false;
937 String insert = null;
940 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
941 switch (entry.getKey()) {
945 insert = entry.getValue().iterator().next();
947 throw new RestconfDocumentedException("Insert parameter can be used only once.");
953 point = entry.getValue().iterator().next();
955 throw new RestconfDocumentedException("Point parameter can be used only once.");
959 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
963 if (pointUsed && !insertUsed) {
964 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
966 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
967 throw new RestconfDocumentedException(
968 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
971 CheckedFuture<Void, TransactionCommitFailedException> future;
972 if (mountPoint != null) {
973 future = this.broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData(), insert,
976 future = this.broker.commitConfigurationDataPost(this.controllerContext.getGlobalSchema(), normalizedII,
977 payload.getData(), insert, point);
982 } catch (final RestconfDocumentedException e) {
984 } catch (final TransactionCommitFailedException e) {
985 LOG.info("Error creating data " + (uriInfo != null ? uriInfo.getPath() : ""), e);
986 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
989 LOG.trace("Successfuly created data.");
991 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
992 // FIXME: Provide path to result.
993 final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
994 if (location != null) {
995 responseBuilder.location(location);
997 return responseBuilder.build();
1000 // FIXME create RestconfIdetifierHelper and move this method there
1001 private static YangInstanceIdentifier checkConsistencyOfNormalizedNodeContext(final NormalizedNodeContext payload) {
1002 Preconditions.checkArgument(payload != null);
1003 Preconditions.checkArgument(payload.getData() != null);
1004 Preconditions.checkArgument(payload.getData().getNodeType() != null);
1005 Preconditions.checkArgument(payload.getInstanceIdentifierContext() != null);
1006 Preconditions.checkArgument(payload.getInstanceIdentifierContext().getInstanceIdentifier() != null);
1008 final QName payloadNodeQname = payload.getData().getNodeType();
1009 final YangInstanceIdentifier yangIdent = payload.getInstanceIdentifierContext().getInstanceIdentifier();
1010 if (payloadNodeQname.compareTo(yangIdent.getLastPathArgument().getNodeType()) > 0) {
1013 final InstanceIdentifierContext<?> parentContext = payload.getInstanceIdentifierContext();
1014 final SchemaNode parentSchemaNode = parentContext.getSchemaNode();
1015 if (parentSchemaNode instanceof DataNodeContainer) {
1016 final DataNodeContainer cast = (DataNodeContainer) parentSchemaNode;
1017 for (final DataSchemaNode child : cast.getChildNodes()) {
1018 if (payloadNodeQname.compareTo(child.getQName()) == 0) {
1019 return YangInstanceIdentifier.builder(yangIdent).node(child.getQName()).build();
1023 if (parentSchemaNode instanceof RpcDefinition) {
1026 final String errMsg = "Error parsing input: DataSchemaNode has not children ";
1027 LOG.info(errMsg + yangIdent);
1028 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1031 @SuppressWarnings("checkstyle:IllegalCatch")
1032 private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint,
1033 final YangInstanceIdentifier normalizedII) {
1034 if (uriInfo == null) {
1035 // This is null if invoked internally
1039 final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
1040 uriBuilder.path("config");
1042 uriBuilder.path(this.controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
1043 } catch (final Exception e) {
1044 LOG.info("Location for instance identifier" + normalizedII + "wasn't created", e);
1047 return uriBuilder.build();
1051 public Response deleteConfigurationData(final String identifier) {
1052 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
1053 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
1054 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
1056 final CheckedFuture<Void, TransactionCommitFailedException> future;
1057 if (mountPoint != null) {
1058 future = this.broker.commitConfigurationDataDelete(mountPoint, normalizedII);
1060 future = this.broker.commitConfigurationDataDelete(normalizedII);
1064 future.checkedGet();
1065 } catch (final TransactionCommitFailedException e) {
1066 final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
1067 Predicates.instanceOf(ModifiedNodeDoesNotExistException.class));
1068 if (searchedException.isPresent()) {
1069 throw new RestconfDocumentedException("Data specified for delete doesn't exist.", ErrorType.APPLICATION,
1070 ErrorTag.DATA_MISSING);
1073 final String errMsg = "Error while deleting data";
1074 LOG.info(errMsg, e);
1075 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
1078 return Response.status(Status.OK).build();
1082 * Subscribes to some path in schema context (stream) to listen on changes
1086 * Additional parameters for subscribing to stream are loaded via rpc input
1089 * <li>datastore - default CONFIGURATION (other values of
1090 * {@link LogicalDatastoreType} enum type)</li>
1091 * <li>scope - default BASE (other values of {@link DataChangeScope})</li>
1095 public NormalizedNodeContext subscribeToStream(final String identifier, final UriInfo uriInfo) {
1096 boolean startTimeUsed = false;
1097 boolean stopTimeUsed = false;
1098 Instant start = Instant.now();
1099 Instant stop = null;
1100 boolean filterUsed = false;
1101 String filter = null;
1102 boolean leafNodesOnlyUsed = false;
1103 boolean leafNodesOnly = false;
1105 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
1106 switch (entry.getKey()) {
1108 if (!startTimeUsed) {
1109 startTimeUsed = true;
1110 start = parseDateFromQueryParam(entry);
1112 throw new RestconfDocumentedException("Start-time parameter can be used only once.");
1116 if (!stopTimeUsed) {
1117 stopTimeUsed = true;
1118 stop = parseDateFromQueryParam(entry);
1120 throw new RestconfDocumentedException("Stop-time parameter can be used only once.");
1126 filter = entry.getValue().iterator().next();
1128 throw new RestconfDocumentedException("Filter parameter can be used only once.");
1131 case "odl-leaf-nodes-only":
1132 if (!leafNodesOnlyUsed) {
1133 leafNodesOnlyUsed = true;
1134 leafNodesOnly = Boolean.parseBoolean(entry.getValue().iterator().next());
1136 throw new RestconfDocumentedException("Odl-leaf-nodes-only parameter can be used only once.");
1140 throw new RestconfDocumentedException("Bad parameter used with notifications: " + entry.getKey());
1143 if (!startTimeUsed && stopTimeUsed) {
1144 throw new RestconfDocumentedException("Stop-time parameter has to be used with start-time parameter.");
1146 URI response = null;
1147 if (identifier.contains(DATA_SUBSCR)) {
1148 response = dataSubs(identifier, uriInfo, start, stop, filter, leafNodesOnly);
1149 } else if (identifier.contains(NOTIFICATION_STREAM)) {
1150 response = notifStream(identifier, uriInfo, start, stop, filter);
1153 if (response != null) {
1154 // prepare node with value of location
1155 final InstanceIdentifierContext<?> iid = prepareIIDSubsStreamOutput();
1156 final NormalizedNodeAttrBuilder<NodeIdentifier, Object, LeafNode<Object>> builder =
1157 ImmutableLeafNodeBuilder.create().withValue(response.toString());
1158 builder.withNodeIdentifier(
1159 NodeIdentifier.create(QName.create("subscribe:to:notification", "2016-10-28", "location")));
1161 // prepare new header with location
1162 final Map<String, Object> headers = new HashMap<>();
1163 headers.put("Location", response);
1165 return new NormalizedNodeContext(iid, builder.build(), headers);
1168 final String msg = "Bad type of notification of sal-remote";
1170 throw new RestconfDocumentedException(msg);
1173 private static Instant parseDateFromQueryParam(final Entry<String, List<String>> entry) {
1174 final DateAndTime event = new DateAndTime(entry.getValue().iterator().next());
1175 final String value = event.getValue();
1176 final TemporalAccessor p;
1178 p = FORMATTER.parse(value);
1179 } catch (final DateTimeParseException e) {
1180 throw new RestconfDocumentedException("Cannot parse of value in date: " + value, e);
1182 return Instant.from(p);
1186 * Prepare instance identifier.
1188 * @return {@link InstanceIdentifierContext} of location leaf for
1191 private static InstanceIdentifierContext<?> prepareIIDSubsStreamOutput() {
1192 final QName qnameBase = QName.create("subscribe:to:notification", "2016-10-28", "notifi");
1193 final SchemaContext schemaCtx = ControllerContext.getInstance().getGlobalSchema();
1194 final DataSchemaNode location = ((ContainerSchemaNode) schemaCtx
1195 .findModuleByNamespaceAndRevision(qnameBase.getNamespace(), qnameBase.getRevision())
1196 .getDataChildByName(qnameBase)).getDataChildByName(QName.create(qnameBase, "location"));
1197 final List<PathArgument> path = new ArrayList<>();
1198 path.add(NodeIdentifier.create(qnameBase));
1199 path.add(NodeIdentifier.create(QName.create(qnameBase, "location")));
1201 return new InstanceIdentifierContext<SchemaNode>(YangInstanceIdentifier.create(path), location, null,
1206 * Register notification listener by stream name.
1213 * stop-time of getting notification
1215 * start-time of getting notification
1217 * indicate which subset of all possible events are of interest
1218 * @return {@link URI} of location
1220 private URI notifStream(final String identifier, final UriInfo uriInfo, final Instant start,
1221 final Instant stop, final String filter) {
1222 final String streamName = Notificator.createStreamNameFromUri(identifier);
1223 if (Strings.isNullOrEmpty(streamName)) {
1224 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1226 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
1227 if (listeners == null || listeners.isEmpty()) {
1228 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1229 ErrorTag.UNKNOWN_ELEMENT);
1232 for (final NotificationListenerAdapter listener : listeners) {
1233 this.broker.registerToListenNotification(listener);
1234 listener.setQueryParams(start,
1235 java.util.Optional.ofNullable(stop), java.util.Optional.ofNullable(filter), false);
1238 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1239 int notificationPort = NOTIFICATION_PORT;
1241 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
1242 notificationPort = webSocketServerInstance.getPort();
1243 } catch (final NullPointerException e) {
1244 WebSocketServer.createInstance(NOTIFICATION_PORT);
1246 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1247 final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
1249 return uriToWebsocketServer;
1253 * Register data change listener by stream name.
1260 * start-time of getting notification
1262 * stop-time of getting notification
1264 * indicate which subset of all possible events are of interest
1265 * @return {@link URI} of location
1267 private URI dataSubs(final String identifier, final UriInfo uriInfo, final Instant start, final Instant stop,
1268 final String filter, final boolean leafNodesOnly) {
1269 final String streamName = Notificator.createStreamNameFromUri(identifier);
1270 if (Strings.isNullOrEmpty(streamName)) {
1271 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1274 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1275 if (listener == null) {
1276 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1277 ErrorTag.UNKNOWN_ELEMENT);
1279 listener.setQueryParams(start, java.util.Optional.ofNullable(stop),
1280 java.util.Optional.ofNullable(filter), leafNodesOnly);
1282 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1283 final LogicalDatastoreType datastore =
1284 parserURIEnumParameter(LogicalDatastoreType.class, paramToValues.get(DATASTORE_PARAM_NAME));
1285 if (datastore == null) {
1286 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1287 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1289 final DataChangeScope scope =
1290 parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
1291 if (scope == null) {
1292 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1293 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1296 this.broker.registerToListenDataChanges(datastore, scope, listener);
1298 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1299 int notificationPort = NOTIFICATION_PORT;
1301 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
1302 notificationPort = webSocketServerInstance.getPort();
1303 } catch (final NullPointerException e) {
1304 WebSocketServer.createInstance(NOTIFICATION_PORT);
1306 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1307 final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
1309 return uriToWebsocketServer;
1312 @SuppressWarnings("checkstyle:IllegalCatch")
1314 public PatchStatusContext patchConfigurationData(final String identifier, final PatchContext context,
1315 final UriInfo uriInfo) {
1316 if (context == null) {
1317 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1321 return this.broker.patchConfigurationDataWithinTransaction(context);
1322 } catch (final Exception e) {
1323 LOG.debug("Patch transaction failed", e);
1324 throw new RestconfDocumentedException(e.getMessage());
1328 @SuppressWarnings("checkstyle:IllegalCatch")
1330 public PatchStatusContext patchConfigurationData(final PatchContext context, @Context final UriInfo uriInfo) {
1331 if (context == null) {
1332 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1336 return this.broker.patchConfigurationDataWithinTransaction(context);
1337 } catch (final Exception e) {
1338 LOG.debug("Patch transaction failed", e);
1339 throw new RestconfDocumentedException(e.getMessage());
1344 * Load parameter for subscribing to stream from input composite node.
1348 * @return enum object if its string value is equal to {@code paramName}. In
1351 private static <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1352 final String paramName) {
1353 final Optional<DataContainerChild<? extends PathArgument, ?>> augNode =
1354 value.getChild(SAL_REMOTE_AUG_IDENTIFIER);
1355 if (!augNode.isPresent() && !(augNode instanceof AugmentationNode)) {
1358 final Optional<DataContainerChild<? extends PathArgument, ?>> enumNode = ((AugmentationNode) augNode.get())
1359 .getChild(new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1360 if (!enumNode.isPresent()) {
1363 final Object rawValue = enumNode.get().getValue();
1364 if (!(rawValue instanceof String)) {
1368 return resolveAsEnum(classDescriptor, (String) rawValue);
1372 * Checks whether {@code value} is one of the string representation of
1373 * enumeration {@code classDescriptor}.
1375 * @return enum object if string value of {@code classDescriptor}
1376 * enumeration is equal to {@code value}. Other cases null.
1378 private static <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1379 if (Strings.isNullOrEmpty(value)) {
1382 return resolveAsEnum(classDescriptor, value);
1385 private static <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1386 final T[] enumConstants = classDescriptor.getEnumConstants();
1387 if (enumConstants != null) {
1388 for (final T enm : classDescriptor.getEnumConstants()) {
1389 if (((Enum<?>) enm).name().equals(value)) {
1397 private static Map<String, String> resolveValuesFromUri(final String uri) {
1398 final Map<String, String> result = new HashMap<>();
1399 final String[] tokens = uri.split("/");
1400 for (int i = 1; i < tokens.length; i++) {
1401 final String[] parameterTokens = tokens[i].split("=");
1402 if (parameterTokens.length == 2) {
1403 result.put(parameterTokens[0], parameterTokens[1]);
1409 private MapNode makeModuleMapNode(final Set<Module> modules) {
1410 Preconditions.checkNotNull(modules);
1411 final Module restconfModule = getRestconfModule();
1412 final DataSchemaNode moduleSchemaNode = this.controllerContext
1413 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1414 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1416 final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder =
1417 Builders.mapBuilder((ListSchemaNode) moduleSchemaNode);
1419 for (final Module module : modules) {
1420 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1422 return listModuleBuilder.build();
1425 protected MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1426 Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1427 "moduleSchemaNode has to be of type ListSchemaNode");
1428 final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1429 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues =
1430 Builders.mapEntryBuilder(listModuleSchemaNode);
1432 List<DataSchemaNode> instanceDataChildrenByName =
1433 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "name");
1434 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1435 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1437 .withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName()).build());
1439 instanceDataChildrenByName =
1440 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "revision");
1441 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1442 Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1443 final String revision = module.getQNameModule().getFormattedRevision();
1445 .withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode).withValue(revision).build());
1447 instanceDataChildrenByName =
1448 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "namespace");
1449 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1450 Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1451 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1452 .withValue(module.getNamespace().toString()).build());
1454 instanceDataChildrenByName =
1455 ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "feature");
1456 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1457 Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1458 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder =
1459 Builders.leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1460 for (final FeatureDefinition feature : module.getFeatures()) {
1461 featuresBuilder.withChild(Builders.leafSetEntryBuilder((LeafListSchemaNode) featureSchemaNode)
1462 .withValue(feature.getQName().getLocalName()).build());
1464 moduleNodeValues.withChild(featuresBuilder.build());
1466 return moduleNodeValues.build();
1469 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1470 Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1471 "streamSchemaNode has to be of type ListSchemaNode");
1472 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1473 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues =
1474 Builders.mapEntryBuilder(listStreamSchemaNode);
1476 List<DataSchemaNode> instanceDataChildrenByName =
1477 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "name");
1478 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1479 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1480 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName).build());
1482 instanceDataChildrenByName =
1483 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "description");
1484 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1485 Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1486 streamNodeValues.withChild(
1487 Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue("DESCRIPTION_PLACEHOLDER").build());
1489 instanceDataChildrenByName =
1490 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-support");
1491 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1492 Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1493 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1494 .withValue(Boolean.valueOf(true)).build());
1496 instanceDataChildrenByName =
1497 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-log-creation-time");
1498 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1499 Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1500 streamNodeValues.withChild(
1501 Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode).withValue("").build());
1503 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "events");
1504 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1505 Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1506 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode).withValue("").build());
1508 return streamNodeValues.build();
1512 * Prepare stream for notification.
1515 * contains list of qnames of notifications
1516 * @return - checked future object
1518 private static CheckedFuture<DOMRpcResult, DOMRpcException> invokeSalRemoteRpcNotifiStrRPC(
1519 final NormalizedNodeContext payload) {
1520 final ContainerNode data = (ContainerNode) payload.getData();
1521 LeafSetNode leafSet = null;
1522 String outputType = "XML";
1523 for (final DataContainerChild<? extends PathArgument, ?> dataChild : data.getValue()) {
1524 if (dataChild instanceof LeafSetNode) {
1525 leafSet = (LeafSetNode) dataChild;
1526 } else if (dataChild instanceof AugmentationNode) {
1527 outputType = (String) ((AugmentationNode) dataChild).getValue().iterator().next().getValue();
1531 final Collection<LeafSetEntryNode> entryNodes = leafSet.getValue();
1532 final List<SchemaPath> paths = new ArrayList<>();
1533 String streamName = CREATE_NOTIFICATION_STREAM + "/";
1535 final Iterator<LeafSetEntryNode> iterator = entryNodes.iterator();
1536 while (iterator.hasNext()) {
1537 final QName valueQName = QName.create((String) iterator.next().getValue());
1538 final Module module =
1539 ControllerContext.getInstance().findModuleByNamespace(valueQName.getModule().getNamespace());
1540 Preconditions.checkNotNull(module,
1541 "Module for namespace " + valueQName.getModule().getNamespace() + " does not exist");
1542 NotificationDefinition notifiDef = null;
1543 for (final NotificationDefinition notification : module.getNotifications()) {
1544 if (notification.getQName().equals(valueQName)) {
1545 notifiDef = notification;
1549 final String moduleName = module.getName();
1550 Preconditions.checkNotNull(notifiDef,
1551 "Notification " + valueQName + "doesn't exist in module " + moduleName);
1552 paths.add(notifiDef.getPath());
1553 streamName = streamName + moduleName + ":" + valueQName.getLocalName();
1554 if (iterator.hasNext()) {
1555 streamName = streamName + ",";
1559 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
1560 final QName outputQname = QName.create(rpcQName, "output");
1561 final QName streamNameQname = QName.create(rpcQName, "notification-stream-identifier");
1563 final ContainerNode output =
1564 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
1565 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
1567 if (!Notificator.existNotificationListenerFor(streamName)) {
1568 Notificator.createNotificationListener(paths, streamName, outputType);
1571 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
1573 return Futures.immediateCheckedFuture(defaultDOMRpcResult);