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.netconf.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;
13 import com.google.common.base.Optional;
14 import com.google.common.base.Preconditions;
15 import com.google.common.collect.ImmutableList;
16 import com.google.common.util.concurrent.CheckedFuture;
17 import com.google.common.util.concurrent.ListenableFuture;
18 import java.util.ArrayList;
19 import java.util.Iterator;
20 import java.util.List;
21 import java.util.concurrent.ExecutionException;
22 import javax.ws.rs.core.Response.Status;
23 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
24 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
25 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
26 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
27 import org.opendaylight.controller.md.sal.dom.api.DOMDataChangeListener;
28 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadTransaction;
29 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
30 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
31 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
32 import org.opendaylight.controller.md.sal.dom.api.DOMNotificationListener;
33 import org.opendaylight.controller.md.sal.dom.api.DOMNotificationService;
34 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
35 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
36 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
37 import org.opendaylight.controller.sal.core.api.Broker.ConsumerSession;
38 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
39 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
40 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
41 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
42 import org.opendaylight.yangtools.concepts.ListenerRegistration;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
44 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
45 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
46 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
47 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
48 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
49 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
50 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
54 public class BrokerFacade {
55 private final static Logger LOG = LoggerFactory.getLogger(BrokerFacade.class);
57 private final static BrokerFacade INSTANCE = new BrokerFacade();
58 private volatile DOMRpcService rpcService;
59 private volatile ConsumerSession context;
60 private DOMDataBroker domDataBroker;
61 private DOMNotificationService domNotification;
63 private BrokerFacade() {
66 public void setRpcService(final DOMRpcService router) {
67 this.rpcService = router;
70 public void setDomNotificationService(final DOMNotificationService domNotification) {
71 this.domNotification = domNotification;
74 public void setContext(final ConsumerSession context) {
75 this.context = context;
78 public static BrokerFacade getInstance() {
79 return BrokerFacade.INSTANCE;
82 private void checkPreconditions() {
83 if ((this.context == null) || (this.domDataBroker == null)) {
84 throw new RestconfDocumentedException(Status.SERVICE_UNAVAILABLE);
89 public NormalizedNode<?, ?> readConfigurationData(final YangInstanceIdentifier path) {
91 return readDataViaTransaction(this.domDataBroker.newReadOnlyTransaction(), CONFIGURATION, path);
94 public NormalizedNode<?, ?> readConfigurationData(final DOMMountPoint mountPoint, final YangInstanceIdentifier path) {
95 final Optional<DOMDataBroker> domDataBrokerService = mountPoint.getService(DOMDataBroker.class);
96 if (domDataBrokerService.isPresent()) {
97 return readDataViaTransaction(domDataBrokerService.get().newReadOnlyTransaction(), CONFIGURATION, path);
99 final String errMsg = "DOM data broker service isn't available for mount point " + path;
101 throw new RestconfDocumentedException(errMsg);
105 public NormalizedNode<?, ?> readOperationalData(final YangInstanceIdentifier path) {
106 checkPreconditions();
107 return readDataViaTransaction(this.domDataBroker.newReadOnlyTransaction(), OPERATIONAL, path);
110 public NormalizedNode<?, ?> readOperationalData(final DOMMountPoint mountPoint, final YangInstanceIdentifier path) {
111 final Optional<DOMDataBroker> domDataBrokerService = mountPoint.getService(DOMDataBroker.class);
112 if (domDataBrokerService.isPresent()) {
113 return readDataViaTransaction(domDataBrokerService.get().newReadOnlyTransaction(), OPERATIONAL, path);
115 final String errMsg = "DOM data broker service isn't available for mount point " + path;
117 throw new RestconfDocumentedException(errMsg);
121 public CheckedFuture<Void, TransactionCommitFailedException> commitConfigurationDataPut(
122 final SchemaContext globalSchema, final YangInstanceIdentifier path, final NormalizedNode<?, ?> payload) {
123 checkPreconditions();
124 return putDataViaTransaction(this.domDataBroker.newReadWriteTransaction(), CONFIGURATION, path, payload, globalSchema);
127 public CheckedFuture<Void, TransactionCommitFailedException> commitConfigurationDataPut(
128 final DOMMountPoint mountPoint, final YangInstanceIdentifier path, final NormalizedNode<?, ?> payload) {
129 final Optional<DOMDataBroker> domDataBrokerService = mountPoint.getService(DOMDataBroker.class);
130 if (domDataBrokerService.isPresent()) {
131 return putDataViaTransaction(domDataBrokerService.get().newReadWriteTransaction(), CONFIGURATION, path,
132 payload, mountPoint.getSchemaContext());
134 final String errMsg = "DOM data broker service isn't available for mount point " + path;
136 throw new RestconfDocumentedException(errMsg);
139 public PATCHStatusContext patchConfigurationDataWithinTransaction(final PATCHContext context,
140 final SchemaContext globalSchema) {
141 final DOMDataReadWriteTransaction patchTransaction = this.domDataBroker.newReadWriteTransaction();
142 final List<PATCHStatusEntity> editCollection = new ArrayList<>();
143 List<RestconfError> editErrors;
144 final List<RestconfError> globalErrors = null;
145 int errorCounter = 0;
147 for (final PATCHEntity patchEntity : context.getData()) {
148 final PATCHEditOperation operation = PATCHEditOperation.valueOf(patchEntity.getOperation().toUpperCase());
152 if (errorCounter == 0) {
154 postDataWithinTransaction(patchTransaction, CONFIGURATION, patchEntity.getTargetNode(),
155 patchEntity.getNode(), globalSchema);
156 editCollection.add(new PATCHStatusEntity(patchEntity.getEditId(), true, null));
157 } catch (final RestconfDocumentedException e) {
158 editErrors = new ArrayList<>();
159 editErrors.addAll(e.getErrors());
160 editCollection.add(new PATCHStatusEntity(patchEntity.getEditId(), false, editErrors));
166 if (errorCounter == 0) {
168 putDataWithinTransaction(patchTransaction, CONFIGURATION, patchEntity
169 .getTargetNode(), patchEntity.getNode(), globalSchema);
170 editCollection.add(new PATCHStatusEntity(patchEntity.getEditId(), true, null));
171 } catch (final RestconfDocumentedException e) {
172 editErrors = new ArrayList<>();
173 editErrors.addAll(e.getErrors());
174 editCollection.add(new PATCHStatusEntity(patchEntity.getEditId(), false, editErrors));
180 if (errorCounter == 0) {
182 deleteDataWithinTransaction(patchTransaction, CONFIGURATION, patchEntity
184 editCollection.add(new PATCHStatusEntity(patchEntity.getEditId(), true, null));
185 } catch (final RestconfDocumentedException e) {
186 editErrors = new ArrayList<>();
187 editErrors.addAll(e.getErrors());
188 editCollection.add(new PATCHStatusEntity(patchEntity.getEditId(), false, editErrors));
194 if (errorCounter == 0) {
196 deleteDataWithinTransaction(patchTransaction, CONFIGURATION, patchEntity
198 editCollection.add(new PATCHStatusEntity(patchEntity.getEditId(), true, null));
199 } catch (final RestconfDocumentedException e) {
200 LOG.error("Error removing {} by {} operation", patchEntity.getTargetNode().toString(),
201 patchEntity.getEditId(), e);
208 //TODO: make sure possible global errors are filled up correctly and decide transaction submission based on that
209 //globalErrors = new ArrayList<>();
210 if (errorCounter == 0) {
211 final CheckedFuture<Void, TransactionCommitFailedException> submit = patchTransaction.submit();
212 return new PATCHStatusContext(context.getPatchId(), ImmutableList.copyOf(editCollection), true,
215 patchTransaction.cancel();
216 return new PATCHStatusContext(context.getPatchId(), ImmutableList.copyOf(editCollection), false,
221 // POST configuration
222 public CheckedFuture<Void, TransactionCommitFailedException> commitConfigurationDataPost(
223 final SchemaContext globalSchema, final YangInstanceIdentifier path, final NormalizedNode<?, ?> payload) {
224 checkPreconditions();
225 return postDataViaTransaction(this.domDataBroker.newReadWriteTransaction(), CONFIGURATION, path, payload, globalSchema);
228 public CheckedFuture<Void, TransactionCommitFailedException> commitConfigurationDataPost(
229 final DOMMountPoint mountPoint, final YangInstanceIdentifier path, final NormalizedNode<?, ?> payload) {
230 final Optional<DOMDataBroker> domDataBrokerService = mountPoint.getService(DOMDataBroker.class);
231 if (domDataBrokerService.isPresent()) {
232 return postDataViaTransaction(domDataBrokerService.get().newReadWriteTransaction(), CONFIGURATION, path,
233 payload, mountPoint.getSchemaContext());
235 final String errMsg = "DOM data broker service isn't available for mount point " + path;
237 throw new RestconfDocumentedException(errMsg);
240 // DELETE configuration
241 public CheckedFuture<Void, TransactionCommitFailedException> commitConfigurationDataDelete(
242 final YangInstanceIdentifier path) {
243 checkPreconditions();
244 return deleteDataViaTransaction(this.domDataBroker.newWriteOnlyTransaction(), CONFIGURATION, path);
247 public CheckedFuture<Void, TransactionCommitFailedException> commitConfigurationDataDelete(
248 final DOMMountPoint mountPoint, final YangInstanceIdentifier path) {
249 final Optional<DOMDataBroker> domDataBrokerService = mountPoint.getService(DOMDataBroker.class);
250 if (domDataBrokerService.isPresent()) {
251 return deleteDataViaTransaction(domDataBrokerService.get().newWriteOnlyTransaction(), CONFIGURATION, path);
253 final String errMsg = "DOM data broker service isn't available for mount point " + path;
255 throw new RestconfDocumentedException(errMsg);
259 public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(final SchemaPath type, final NormalizedNode<?, ?> input) {
260 checkPreconditions();
261 if (this.rpcService == null) {
262 throw new RestconfDocumentedException(Status.SERVICE_UNAVAILABLE);
264 LOG.trace("Invoke RPC {} with input: {}", type, input);
265 return this.rpcService.invokeRpc(type, input);
268 public void registerToListenDataChanges(final LogicalDatastoreType datastore, final DataChangeScope scope,
269 final ListenerAdapter listener) {
270 checkPreconditions();
272 if (listener.isListening()) {
276 final YangInstanceIdentifier path = listener.getPath();
277 final ListenerRegistration<DOMDataChangeListener> registration = this.domDataBroker.registerDataChangeListener(
278 datastore, path, listener, scope);
280 listener.setRegistration(registration);
283 private NormalizedNode<?, ?> readDataViaTransaction(final DOMDataReadTransaction transaction,
284 final LogicalDatastoreType datastore, final YangInstanceIdentifier path) {
285 LOG.trace("Read {} via Restconf: {}", datastore.name(), path);
286 final ListenableFuture<Optional<NormalizedNode<?, ?>>> listenableFuture = transaction.read(datastore, path);
287 if (listenableFuture != null) {
288 Optional<NormalizedNode<?, ?>> optional;
290 LOG.debug("Reading result data from transaction.");
291 optional = listenableFuture.get();
292 } catch (InterruptedException | ExecutionException e) {
293 LOG.warn("Exception by reading {} via Restconf: {}", datastore.name(), path, e);
294 throw new RestconfDocumentedException("Problem to get data from transaction.", e.getCause());
297 if (optional != null) {
298 if (optional.isPresent()) {
299 return optional.get();
306 private CheckedFuture<Void, TransactionCommitFailedException> postDataViaTransaction(
307 final DOMDataReadWriteTransaction rWTransaction, final LogicalDatastoreType datastore,
308 final YangInstanceIdentifier path, final NormalizedNode<?, ?> payload, final SchemaContext schemaContext) {
309 // FIXME: This is doing correct post for container and list children
310 // not sure if this will work for choice case
311 if(payload instanceof MapNode) {
312 LOG.trace("POST {} via Restconf: {} with payload {}", datastore.name(), path, payload);
313 final NormalizedNode<?, ?> emptySubtree = ImmutableNodes.fromInstanceId(schemaContext, path);
314 rWTransaction.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
315 ensureParentsByMerge(datastore, path, rWTransaction, schemaContext);
316 for(final MapEntryNode child : ((MapNode) payload).getValue()) {
317 final YangInstanceIdentifier childPath = path.node(child.getIdentifier());
318 checkItemDoesNotExists(rWTransaction, datastore, childPath);
319 rWTransaction.put(datastore, childPath, child);
322 checkItemDoesNotExists(rWTransaction,datastore, path);
323 ensureParentsByMerge(datastore, path, rWTransaction, schemaContext);
324 rWTransaction.put(datastore, path, payload);
326 return rWTransaction.submit();
329 private void postDataWithinTransaction(
330 final DOMDataReadWriteTransaction rWTransaction, final LogicalDatastoreType datastore,
331 final YangInstanceIdentifier path, final NormalizedNode<?, ?> payload, final SchemaContext schemaContext) {
332 // FIXME: This is doing correct post for container and list children
333 // not sure if this will work for choice case
334 if(payload instanceof MapNode) {
335 LOG.trace("POST {} within Restconf PATCH: {} with payload {}", datastore.name(), path, payload);
336 final NormalizedNode<?, ?> emptySubtree = ImmutableNodes.fromInstanceId(schemaContext, path);
337 rWTransaction.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
338 ensureParentsByMerge(datastore, path, rWTransaction, schemaContext);
339 for(final MapEntryNode child : ((MapNode) payload).getValue()) {
340 final YangInstanceIdentifier childPath = path.node(child.getIdentifier());
341 checkItemDoesNotExists(rWTransaction, datastore, childPath);
342 rWTransaction.put(datastore, childPath, child);
345 checkItemDoesNotExists(rWTransaction,datastore, path);
346 ensureParentsByMerge(datastore, path, rWTransaction, schemaContext);
347 rWTransaction.put(datastore, path, payload);
351 private void checkItemDoesNotExists(final DOMDataReadWriteTransaction rWTransaction,final LogicalDatastoreType store, final YangInstanceIdentifier path) {
352 final ListenableFuture<Boolean> futureDatastoreData = rWTransaction.exists(store, path);
354 if (futureDatastoreData.get()) {
355 final String errMsg = "Post Configuration via Restconf was not executed because data already exists";
356 LOG.trace("{}:{}", errMsg, path);
357 rWTransaction.cancel();
358 throw new RestconfDocumentedException("Data already exists for path: " + path, ErrorType.PROTOCOL,
359 ErrorTag.DATA_EXISTS);
361 } catch (InterruptedException | ExecutionException e) {
362 LOG.warn("It wasn't possible to get data loaded from datastore at path {}", path, e);
367 private CheckedFuture<Void, TransactionCommitFailedException> putDataViaTransaction(
368 final DOMDataReadWriteTransaction writeTransaction, final LogicalDatastoreType datastore,
369 final YangInstanceIdentifier path, final NormalizedNode<?, ?> payload, final SchemaContext schemaContext) {
370 LOG.trace("Put {} via Restconf: {} with payload {}", datastore.name(), path, payload);
371 ensureParentsByMerge(datastore, path, writeTransaction, schemaContext);
372 writeTransaction.put(datastore, path, payload);
373 return writeTransaction.submit();
376 private void putDataWithinTransaction(
377 final DOMDataReadWriteTransaction writeTransaction, final LogicalDatastoreType datastore,
378 final YangInstanceIdentifier path, final NormalizedNode<?, ?> payload, final SchemaContext schemaContext) {
379 LOG.trace("Put {} within Restconf PATCH: {} with payload {}", datastore.name(), path, payload);
380 ensureParentsByMerge(datastore, path, writeTransaction, schemaContext);
381 writeTransaction.put(datastore, path, payload);
384 private CheckedFuture<Void, TransactionCommitFailedException> deleteDataViaTransaction(
385 final DOMDataWriteTransaction writeTransaction, final LogicalDatastoreType datastore,
386 final YangInstanceIdentifier path) {
387 LOG.trace("Delete {} via Restconf: {}", datastore.name(), path);
388 writeTransaction.delete(datastore, path);
389 return writeTransaction.submit();
392 private void deleteDataWithinTransaction(
393 final DOMDataWriteTransaction writeTransaction, final LogicalDatastoreType datastore,
394 final YangInstanceIdentifier path) {
395 LOG.trace("Delete {} within Restconf PATCH: {}", datastore.name(), path);
396 writeTransaction.delete(datastore, path);
399 public void setDomDataBroker(final DOMDataBroker domDataBroker) {
400 this.domDataBroker = domDataBroker;
403 private void ensureParentsByMerge(final LogicalDatastoreType store,
404 final YangInstanceIdentifier normalizedPath, final DOMDataReadWriteTransaction rwTx, final SchemaContext schemaContext) {
405 final List<PathArgument> normalizedPathWithoutChildArgs = new ArrayList<>();
406 YangInstanceIdentifier rootNormalizedPath = null;
408 final Iterator<PathArgument> it = normalizedPath.getPathArguments().iterator();
410 while(it.hasNext()) {
411 final PathArgument pathArgument = it.next();
412 if(rootNormalizedPath == null) {
413 rootNormalizedPath = YangInstanceIdentifier.create(pathArgument);
416 // Skip last element, its not a parent
418 normalizedPathWithoutChildArgs.add(pathArgument);
422 // No parent structure involved, no need to ensure parents
423 if(normalizedPathWithoutChildArgs.isEmpty()) {
427 Preconditions.checkArgument(rootNormalizedPath != null, "Empty path received");
429 final NormalizedNode<?, ?> parentStructure =
430 ImmutableNodes.fromInstanceId(schemaContext, YangInstanceIdentifier.create(normalizedPathWithoutChildArgs));
431 rwTx.merge(store, rootNormalizedPath, parentStructure);
434 public void registerToListenNotification(final NotificationListenerAdapter listener) {
435 checkPreconditions();
437 if (listener.isListening()) {
441 final SchemaPath path = listener.getSchemaPath();
442 final ListenerRegistration<DOMNotificationListener> registration = this.domNotification
443 .registerNotificationListener(listener, path);
445 listener.setRegistration(registration);