2 * Copyright (c) 2014 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
8 package org.opendaylight.controller.sal.restconf.impl;
10 import static org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType.CONFIGURATION;
11 import static org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType.OPERATIONAL;
12 import com.google.common.base.Optional;
13 import com.google.common.base.Preconditions;
14 import com.google.common.util.concurrent.CheckedFuture;
15 import com.google.common.util.concurrent.ListenableFuture;
16 import java.util.ArrayList;
17 import java.util.Iterator;
18 import java.util.List;
19 import java.util.concurrent.ExecutionException;
20 import javax.ws.rs.core.Response.Status;
21 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
22 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
23 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
24 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
25 import org.opendaylight.controller.md.sal.dom.api.DOMDataChangeListener;
26 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadTransaction;
27 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
28 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
29 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
30 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
31 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
32 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
33 import org.opendaylight.controller.sal.core.api.Broker.ConsumerSession;
34 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
35 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
36 import org.opendaylight.controller.sal.streams.listeners.ListenerAdapter;
37 import org.opendaylight.yangtools.concepts.ListenerRegistration;
38 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
39 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
40 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
41 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
42 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
43 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
44 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
45 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
49 public class BrokerFacade {
50 private final static Logger LOG = LoggerFactory.getLogger(BrokerFacade.class);
52 private final static BrokerFacade INSTANCE = new BrokerFacade();
53 private volatile DOMRpcService rpcService;
54 private volatile ConsumerSession context;
55 private DOMDataBroker domDataBroker;
57 private BrokerFacade() {
60 public void setRpcService(final DOMRpcService router) {
64 public void setContext(final ConsumerSession context) {
65 this.context = context;
68 public static BrokerFacade getInstance() {
69 return BrokerFacade.INSTANCE;
72 private void checkPreconditions() {
73 if (context == null || domDataBroker == null) {
74 throw new RestconfDocumentedException(Status.SERVICE_UNAVAILABLE);
79 public NormalizedNode<?, ?> readConfigurationData(final YangInstanceIdentifier path) {
81 return readDataViaTransaction(domDataBroker.newReadOnlyTransaction(), CONFIGURATION, path);
84 public NormalizedNode<?, ?> readConfigurationData(final DOMMountPoint mountPoint, final YangInstanceIdentifier path) {
85 final Optional<DOMDataBroker> domDataBrokerService = mountPoint.getService(DOMDataBroker.class);
86 if (domDataBrokerService.isPresent()) {
87 return readDataViaTransaction(domDataBrokerService.get().newReadOnlyTransaction(), CONFIGURATION, path);
89 final String errMsg = "DOM data broker service isn't available for mount point " + path;
91 throw new RestconfDocumentedException(errMsg);
95 public NormalizedNode<?, ?> readOperationalData(final YangInstanceIdentifier path) {
97 return readDataViaTransaction(domDataBroker.newReadOnlyTransaction(), OPERATIONAL, path);
100 public NormalizedNode<?, ?> readOperationalData(final DOMMountPoint mountPoint, final YangInstanceIdentifier path) {
101 final Optional<DOMDataBroker> domDataBrokerService = mountPoint.getService(DOMDataBroker.class);
102 if (domDataBrokerService.isPresent()) {
103 return readDataViaTransaction(domDataBrokerService.get().newReadOnlyTransaction(), OPERATIONAL, path);
105 final String errMsg = "DOM data broker service isn't available for mount point " + path;
107 throw new RestconfDocumentedException(errMsg);
111 public CheckedFuture<Void, TransactionCommitFailedException> commitConfigurationDataPut(
112 final SchemaContext globalSchema, final YangInstanceIdentifier path, final NormalizedNode<?, ?> payload) {
113 checkPreconditions();
114 return putDataViaTransaction(domDataBroker, CONFIGURATION, path, payload, globalSchema);
117 public CheckedFuture<Void, TransactionCommitFailedException> commitConfigurationDataPut(
118 final DOMMountPoint mountPoint, final YangInstanceIdentifier path, final NormalizedNode<?, ?> payload) {
119 final Optional<DOMDataBroker> domDataBrokerService = mountPoint.getService(DOMDataBroker.class);
120 if (domDataBrokerService.isPresent()) {
121 return putDataViaTransaction(domDataBrokerService.get(), CONFIGURATION, path,
122 payload, mountPoint.getSchemaContext());
124 final String errMsg = "DOM data broker service isn't available for mount point " + path;
126 throw new RestconfDocumentedException(errMsg);
129 // POST configuration
130 public CheckedFuture<Void, TransactionCommitFailedException> commitConfigurationDataPost(
131 final SchemaContext globalSchema, final YangInstanceIdentifier path, final NormalizedNode<?, ?> payload) {
132 checkPreconditions();
133 return postDataViaTransaction(domDataBroker, CONFIGURATION, path, payload, globalSchema);
136 public CheckedFuture<Void, TransactionCommitFailedException> commitConfigurationDataPost(
137 final DOMMountPoint mountPoint, final YangInstanceIdentifier path, final NormalizedNode<?, ?> payload) {
138 final Optional<DOMDataBroker> domDataBrokerService = mountPoint.getService(DOMDataBroker.class);
139 if (domDataBrokerService.isPresent()) {
140 return postDataViaTransaction(domDataBrokerService.get(), CONFIGURATION, path,
141 payload, mountPoint.getSchemaContext());
143 final String errMsg = "DOM data broker service isn't available for mount point " + path;
145 throw new RestconfDocumentedException(errMsg);
148 // DELETE configuration
149 public CheckedFuture<Void, TransactionCommitFailedException> commitConfigurationDataDelete(
150 final YangInstanceIdentifier path) {
151 checkPreconditions();
152 return deleteDataViaTransaction(domDataBroker.newWriteOnlyTransaction(), CONFIGURATION, path);
155 public CheckedFuture<Void, TransactionCommitFailedException> commitConfigurationDataDelete(
156 final DOMMountPoint mountPoint, final YangInstanceIdentifier path) {
157 final Optional<DOMDataBroker> domDataBrokerService = mountPoint.getService(DOMDataBroker.class);
158 if (domDataBrokerService.isPresent()) {
159 return deleteDataViaTransaction(domDataBrokerService.get().newWriteOnlyTransaction(), CONFIGURATION, path);
161 final String errMsg = "DOM data broker service isn't available for mount point " + path;
163 throw new RestconfDocumentedException(errMsg);
167 public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(final SchemaPath type, final NormalizedNode<?, ?> input) {
168 checkPreconditions();
169 if (rpcService == null) {
170 throw new RestconfDocumentedException(Status.SERVICE_UNAVAILABLE);
172 return rpcService.invokeRpc(type, input);
175 public void registerToListenDataChanges(final LogicalDatastoreType datastore, final DataChangeScope scope,
176 final ListenerAdapter listener) {
177 checkPreconditions();
179 if (listener.isListening()) {
183 final YangInstanceIdentifier path = listener.getPath();
184 final ListenerRegistration<DOMDataChangeListener> registration = domDataBroker.registerDataChangeListener(
185 datastore, path, listener, scope);
187 listener.setRegistration(registration);
190 private NormalizedNode<?, ?> readDataViaTransaction(final DOMDataReadTransaction transaction,
191 final LogicalDatastoreType datastore, final YangInstanceIdentifier path) {
192 LOG.trace("Read " + datastore.name() + " via Restconf: {}", path);
193 final ListenableFuture<Optional<NormalizedNode<?, ?>>> listenableFuture = transaction.read(datastore, path);
194 if (listenableFuture != null) {
195 Optional<NormalizedNode<?, ?>> optional;
197 LOG.debug("Reading result data from transaction.");
198 optional = listenableFuture.get();
199 } catch (InterruptedException | ExecutionException e) {
200 LOG.warn("Exception by reading " + datastore.name() + " via Restconf: {}", path, e);
201 throw new RestconfDocumentedException("Problem to get data from transaction.", e.getCause());
204 if (optional != null) {
205 if (optional.isPresent()) {
206 return optional.get();
213 private CheckedFuture<Void, TransactionCommitFailedException> postDataViaTransaction(
214 final DOMDataBroker domDataBroker, final LogicalDatastoreType datastore,
215 final YangInstanceIdentifier path, final NormalizedNode<?, ?> payload, final SchemaContext schemaContext) {
216 // FIXME: This is doing correct post for container and list children
217 // not sure if this will work for choice case
218 DOMDataReadWriteTransaction transaction = domDataBroker.newReadWriteTransaction();
219 if(payload instanceof MapNode) {
220 LOG.trace("POST " + datastore.name() + " via Restconf: {} with payload {}", path, payload);
221 final NormalizedNode<?, ?> emptySubtree = ImmutableNodes.fromInstanceId(schemaContext, path);
223 transaction.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
224 } catch (RuntimeException e) {
225 transaction.cancel();
226 transaction = domDataBroker.newReadWriteTransaction();
227 LOG.debug("Empty subtree merge failed", e);
229 if (!ensureParentsByMerge(datastore, path, transaction, schemaContext)) {
230 transaction.cancel();
231 transaction = domDataBroker.newReadWriteTransaction();
233 for(final MapEntryNode child : ((MapNode) payload).getValue()) {
234 final YangInstanceIdentifier childPath = path.node(child.getIdentifier());
235 checkItemDoesNotExists(transaction, datastore, childPath);
236 transaction.put(datastore, childPath, child);
239 checkItemDoesNotExists(transaction,datastore, path);
240 if(!ensureParentsByMerge(datastore, path, transaction, schemaContext)) {
241 transaction.cancel();
242 transaction = domDataBroker.newReadWriteTransaction();
244 transaction.put(datastore, path, payload);
246 return transaction.submit();
249 private void checkItemDoesNotExists(final DOMDataReadWriteTransaction rWTransaction,final LogicalDatastoreType store, final YangInstanceIdentifier path) {
250 final ListenableFuture<Boolean> futureDatastoreData = rWTransaction.exists(store, path);
252 if (futureDatastoreData.get()) {
253 final String errMsg = "Post Configuration via Restconf was not executed because data already exists";
254 LOG.trace(errMsg + ":{}", path);
255 rWTransaction.cancel();
256 throw new RestconfDocumentedException("Data already exists for path: " + path, ErrorType.PROTOCOL,
257 ErrorTag.DATA_EXISTS);
259 } catch (InterruptedException | ExecutionException e) {
260 LOG.warn("It wasn't possible to get data loaded from datastore at path " + path, e);
265 private CheckedFuture<Void, TransactionCommitFailedException> putDataViaTransaction(
266 final DOMDataBroker domDataBroker, final LogicalDatastoreType datastore,
267 final YangInstanceIdentifier path, final NormalizedNode<?, ?> payload, final SchemaContext schemaContext)
269 DOMDataReadWriteTransaction transaction = domDataBroker.newReadWriteTransaction();
270 LOG.trace("Put " + datastore.name() + " via Restconf: {} with payload {}", path, payload);
271 if (!ensureParentsByMerge(datastore, path, transaction, schemaContext)) {
272 transaction.cancel();
273 transaction = domDataBroker.newReadWriteTransaction();
275 transaction.put(datastore, path, payload);
276 return transaction.submit();
279 private CheckedFuture<Void, TransactionCommitFailedException> deleteDataViaTransaction(
280 final DOMDataWriteTransaction writeTransaction, final LogicalDatastoreType datastore,
281 final YangInstanceIdentifier path) {
282 LOG.trace("Delete " + datastore.name() + " via Restconf: {}", path);
283 writeTransaction.delete(datastore, path);
284 return writeTransaction.submit();
287 public void setDomDataBroker(final DOMDataBroker domDataBroker) {
288 this.domDataBroker = domDataBroker;
291 private boolean ensureParentsByMerge(final LogicalDatastoreType store,
292 final YangInstanceIdentifier normalizedPath, final DOMDataReadWriteTransaction rwTx, final SchemaContext schemaContext) {
294 boolean mergeResult = true;
295 final List<PathArgument> normalizedPathWithoutChildArgs = new ArrayList<>();
296 YangInstanceIdentifier rootNormalizedPath = null;
298 final Iterator<PathArgument> it = normalizedPath.getPathArguments().iterator();
300 while(it.hasNext()) {
301 final PathArgument pathArgument = it.next();
302 if(rootNormalizedPath == null) {
303 rootNormalizedPath = YangInstanceIdentifier.create(pathArgument);
306 // Skip last element, its not a parent
308 normalizedPathWithoutChildArgs.add(pathArgument);
312 // No parent structure involved, no need to ensure parents
313 if(normalizedPathWithoutChildArgs.isEmpty()) {
317 Preconditions.checkArgument(rootNormalizedPath != null, "Empty path received");
319 final NormalizedNode<?, ?> parentStructure =
320 ImmutableNodes.fromInstanceId(schemaContext, YangInstanceIdentifier.create(normalizedPathWithoutChildArgs));
322 rwTx.merge(store, rootNormalizedPath, parentStructure);
323 } catch (RuntimeException e) {
325 * Catching the exception here, logging it and proceeding further
326 * for the following reasons.
328 * 1. For MD-SAL store if it fails we'll go with the next call
329 * anyway and let the failure happen there. 2. For NETCONF devices
330 * that can not handle these calls such as creation of empty lists
331 * etc, instead of failing we'll go with the actual call. Devices
332 * should be able to handle the actual calls made without the need
333 * to create parents. So instead of failing we will give a device a
334 * chance to configure the management entity in question. 3. If this
335 * merge call is handled properly by MD-SAL data store or a Netconf
336 * device this is a no-op.
339 LOG.debug("Exception while creating the parent in ensureParentsByMerge. Proceeding with the actual request", e);