37c90515abab3c33cff7f38ecb2f06a3e881b17b
[netconf.git] / restconf / sal-rest-connector / src / main / java / org / opendaylight / netconf / sal / restconf / impl / BrokerFacade.java
1 /**
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.netconf.sal.restconf.impl;
9
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
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;
53
54 public class BrokerFacade {
55     private final static Logger LOG = LoggerFactory.getLogger(BrokerFacade.class);
56
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;
62
63     private BrokerFacade() {
64     }
65
66     public void setRpcService(final DOMRpcService router) {
67         this.rpcService = router;
68     }
69
70     public void setDomNotificationService(final DOMNotificationService domNotification) {
71         this.domNotification = domNotification;
72     }
73
74     public void setContext(final ConsumerSession context) {
75         this.context = context;
76     }
77
78     public static BrokerFacade getInstance() {
79         return BrokerFacade.INSTANCE;
80     }
81
82     private void checkPreconditions() {
83         if ((this.context == null) || (this.domDataBroker == null)) {
84             throw new RestconfDocumentedException(Status.SERVICE_UNAVAILABLE);
85         }
86     }
87
88     // READ configuration
89     public NormalizedNode<?, ?> readConfigurationData(final YangInstanceIdentifier path) {
90         checkPreconditions();
91         return readDataViaTransaction(this.domDataBroker.newReadOnlyTransaction(), CONFIGURATION, path);
92     }
93
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);
98         }
99         final String errMsg = "DOM data broker service isn't available for mount point " + path;
100         LOG.warn(errMsg);
101         throw new RestconfDocumentedException(errMsg);
102     }
103
104     // READ operational
105     public NormalizedNode<?, ?> readOperationalData(final YangInstanceIdentifier path) {
106         checkPreconditions();
107         return readDataViaTransaction(this.domDataBroker.newReadOnlyTransaction(), OPERATIONAL, path);
108     }
109
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);
114         }
115         final String errMsg = "DOM data broker service isn't available for mount point " + path;
116         LOG.warn(errMsg);
117         throw new RestconfDocumentedException(errMsg);
118     }
119
120     // PUT configuration
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);
125     }
126
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());
133         }
134         final String errMsg = "DOM data broker service isn't available for mount point " + path;
135         LOG.warn(errMsg);
136         throw new RestconfDocumentedException(errMsg);
137     }
138
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;
146
147         for (final PATCHEntity patchEntity : context.getData()) {
148             final PATCHEditOperation operation = PATCHEditOperation.valueOf(patchEntity.getOperation().toUpperCase());
149
150             switch (operation) {
151                 case CREATE:
152                     if (errorCounter == 0) {
153                         try {
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));
161                             errorCounter++;
162                         }
163                     }
164                     break;
165                 case REPLACE:
166                     if (errorCounter == 0) {
167                         try {
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));
175                             errorCounter++;
176                         }
177                     }
178                     break;
179                 case DELETE:
180                     if (errorCounter == 0) {
181                         try {
182                             deleteDataWithinTransaction(patchTransaction, CONFIGURATION, patchEntity
183                                     .getTargetNode());
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));
189                             errorCounter++;
190                         }
191                     }
192                     break;
193                 case REMOVE:
194                     if (errorCounter == 0) {
195                         try {
196                             deleteDataWithinTransaction(patchTransaction, CONFIGURATION, patchEntity
197                                     .getTargetNode());
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);
202                         }
203                     }
204                     break;
205             }
206         }
207
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,
213                     globalErrors);
214         } else {
215             patchTransaction.cancel();
216             return new PATCHStatusContext(context.getPatchId(), ImmutableList.copyOf(editCollection), false,
217                     globalErrors);
218         }
219     }
220
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);
226     }
227
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());
234         }
235         final String errMsg = "DOM data broker service isn't available for mount point " + path;
236         LOG.warn(errMsg);
237         throw new RestconfDocumentedException(errMsg);
238     }
239
240     // DELETE configuration
241     public CheckedFuture<Void, TransactionCommitFailedException> commitConfigurationDataDelete(
242             final YangInstanceIdentifier path) {
243         checkPreconditions();
244         return deleteDataViaTransaction(this.domDataBroker.newWriteOnlyTransaction(), CONFIGURATION, path);
245     }
246
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);
252         }
253         final String errMsg = "DOM data broker service isn't available for mount point " + path;
254         LOG.warn(errMsg);
255         throw new RestconfDocumentedException(errMsg);
256     }
257
258     // RPC
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);
263         }
264         LOG.trace("Invoke RPC {} with input: {}", type, input);
265         return this.rpcService.invokeRpc(type, input);
266     }
267
268     public void registerToListenDataChanges(final LogicalDatastoreType datastore, final DataChangeScope scope,
269             final ListenerAdapter listener) {
270         checkPreconditions();
271
272         if (listener.isListening()) {
273             return;
274         }
275
276         final YangInstanceIdentifier path = listener.getPath();
277         final ListenerRegistration<DOMDataChangeListener> registration = this.domDataBroker.registerDataChangeListener(
278                 datastore, path, listener, scope);
279
280         listener.setRegistration(registration);
281     }
282
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;
289             try {
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());
295
296             }
297             if (optional != null) {
298                 if (optional.isPresent()) {
299                     return optional.get();
300                 }
301             }
302         }
303         return null;
304     }
305
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);
320             }
321         } else {
322             checkItemDoesNotExists(rWTransaction,datastore, path);
323             ensureParentsByMerge(datastore, path, rWTransaction, schemaContext);
324             rWTransaction.put(datastore, path, payload);
325         }
326         return rWTransaction.submit();
327     }
328
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);
343             }
344         } else {
345             checkItemDoesNotExists(rWTransaction,datastore, path);
346             ensureParentsByMerge(datastore, path, rWTransaction, schemaContext);
347             rWTransaction.put(datastore, path, payload);
348         }
349     }
350
351     private void checkItemDoesNotExists(final DOMDataReadWriteTransaction rWTransaction,final LogicalDatastoreType store, final YangInstanceIdentifier path) {
352         final ListenableFuture<Boolean> futureDatastoreData = rWTransaction.exists(store, path);
353         try {
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);
360             }
361         } catch (InterruptedException | ExecutionException e) {
362             LOG.warn("It wasn't possible to get data loaded from datastore at path {}", path, e);
363         }
364
365     }
366
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();
374     }
375
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);
382     }
383
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();
390     }
391
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);
397     }
398
399     public void setDomDataBroker(final DOMDataBroker domDataBroker) {
400         this.domDataBroker = domDataBroker;
401     }
402
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;
407
408         final Iterator<PathArgument> it = normalizedPath.getPathArguments().iterator();
409
410         while(it.hasNext()) {
411             final PathArgument pathArgument = it.next();
412             if(rootNormalizedPath == null) {
413                 rootNormalizedPath = YangInstanceIdentifier.create(pathArgument);
414             }
415
416             // Skip last element, its not a parent
417             if(it.hasNext()) {
418                 normalizedPathWithoutChildArgs.add(pathArgument);
419             }
420         }
421
422         // No parent structure involved, no need to ensure parents
423         if(normalizedPathWithoutChildArgs.isEmpty()) {
424             return;
425         }
426
427         Preconditions.checkArgument(rootNormalizedPath != null, "Empty path received");
428
429         final NormalizedNode<?, ?> parentStructure =
430                 ImmutableNodes.fromInstanceId(schemaContext, YangInstanceIdentifier.create(normalizedPathWithoutChildArgs));
431         rwTx.merge(store, rootNormalizedPath, parentStructure);
432     }
433
434     public void registerToListenNotification(final NotificationListenerAdapter listener) {
435         checkPreconditions();
436
437         if (listener.isListening()) {
438             return;
439         }
440
441         final SchemaPath path = listener.getSchemaPath();
442         final ListenerRegistration<DOMNotificationListener> registration = this.domNotification
443                 .registerNotificationListener(listener, path);
444
445         listener.setRegistration(registration);
446     }
447 }