Bug 1073: Implemented Transaction chain on InMemoryDOMDataStore level.
[controller.git] / opendaylight / md-sal / sal-netconf-connector / src / main / java / org / opendaylight / controller / sal / connect / netconf / NetconfDeviceTwoPhaseCommitTransaction.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.controller.sal.connect.netconf;
9
10 import static org.opendaylight.controller.sal.connect.netconf.NetconfMapping.NETCONF_CANDIDATE_QNAME;
11 import static org.opendaylight.controller.sal.connect.netconf.NetconfMapping.NETCONF_COMMIT_QNAME;
12 import static org.opendaylight.controller.sal.connect.netconf.NetconfMapping.NETCONF_CONFIG_QNAME;
13 import static org.opendaylight.controller.sal.connect.netconf.NetconfMapping.NETCONF_EDIT_CONFIG_QNAME;
14 import static org.opendaylight.controller.sal.connect.netconf.NetconfMapping.NETCONF_ERROR_OPTION_QNAME;
15 import static org.opendaylight.controller.sal.connect.netconf.NetconfMapping.NETCONF_OPERATION_QNAME;
16 import static org.opendaylight.controller.sal.connect.netconf.NetconfMapping.NETCONF_RUNNING_QNAME;
17 import static org.opendaylight.controller.sal.connect.netconf.NetconfMapping.NETCONF_TARGET_QNAME;
18 import static org.opendaylight.controller.sal.connect.netconf.NetconfMapping.ROLLBACK_ON_ERROR_OPTION;
19
20 import java.util.Collection;
21 import java.util.Collections;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.Map.Entry;
25 import java.util.concurrent.ExecutionException;
26
27 import org.opendaylight.controller.md.sal.common.api.data.DataCommitHandler.DataCommitTransaction;
28 import org.opendaylight.controller.md.sal.common.api.data.DataModification;
29 import org.opendaylight.yangtools.yang.common.QName;
30 import org.opendaylight.yangtools.yang.common.RpcError;
31 import org.opendaylight.yangtools.yang.common.RpcResult;
32 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
33 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
34 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifierWithPredicates;
35 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
36 import org.opendaylight.yangtools.yang.data.api.Node;
37 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
38 import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 import com.google.common.base.Optional;
43 import com.google.common.base.Preconditions;
44 import com.google.common.collect.ImmutableList;
45 import com.google.common.collect.Lists;
46
47 class NetconfDeviceTwoPhaseCommitTransaction implements DataCommitTransaction<InstanceIdentifier, CompositeNode> {
48     private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceTwoPhaseCommitTransaction.class);
49     private final DataModification<InstanceIdentifier, CompositeNode> modification;
50     private final NetconfDevice device;
51     private final boolean candidateSupported;
52     private final boolean rollbackSupported;
53
54     public NetconfDeviceTwoPhaseCommitTransaction(final NetconfDevice device,
55             final DataModification<InstanceIdentifier, CompositeNode> modification,
56             final boolean candidateSupported, final boolean rollbackOnErrorSupported) {
57         this.device = Preconditions.checkNotNull(device);
58         this.modification = Preconditions.checkNotNull(modification);
59         this.candidateSupported = candidateSupported;
60         this.rollbackSupported = rollbackOnErrorSupported;
61     }
62
63     void prepare() throws InterruptedException, ExecutionException {
64         for (InstanceIdentifier toRemove : modification.getRemovedConfigurationData()) {
65             sendDelete(toRemove);
66         }
67         for(Entry<InstanceIdentifier, CompositeNode> toUpdate : modification.getUpdatedConfigurationData().entrySet()) {
68             sendMerge(toUpdate.getKey(),toUpdate.getValue());
69         }
70     }
71
72     private void sendMerge(final InstanceIdentifier key, final CompositeNode value) throws InterruptedException, ExecutionException {
73         sendEditRpc(createEditStructure(key, Optional.<String>absent(), Optional.of(value)));
74     }
75
76     private void sendDelete(final InstanceIdentifier toDelete) throws InterruptedException, ExecutionException {
77         sendEditRpc(createEditStructure(toDelete, Optional.of("delete"), Optional.<CompositeNode> absent()));
78     }
79
80     private void sendEditRpc(final CompositeNode editStructure) throws InterruptedException, ExecutionException {
81         CompositeNodeBuilder<ImmutableCompositeNode> builder = configurationRpcBuilder();
82         builder.setQName(NETCONF_EDIT_CONFIG_QNAME);
83         builder.add(editStructure);
84
85         RpcResult<CompositeNode> rpcResult = device.invokeRpc(NETCONF_EDIT_CONFIG_QNAME, builder.toInstance()).get();
86         Preconditions.checkState(rpcResult.isSuccessful(),"Rpc Result was unsuccessful");
87     }
88
89     private CompositeNodeBuilder<ImmutableCompositeNode> configurationRpcBuilder() {
90         CompositeNodeBuilder<ImmutableCompositeNode> ret = ImmutableCompositeNode.builder();
91
92         Node<?> targetNode;
93         if(candidateSupported) {
94             targetNode = ImmutableCompositeNode.create(NETCONF_CANDIDATE_QNAME, ImmutableList.<Node<?>>of());
95         } else {
96             targetNode = ImmutableCompositeNode.create(NETCONF_RUNNING_QNAME, ImmutableList.<Node<?>>of());
97         }
98
99         Node<?> targetWrapperNode = ImmutableCompositeNode.create(NETCONF_TARGET_QNAME, ImmutableList.<Node<?>>of(targetNode));
100
101         if(rollbackSupported) {
102             LOG.debug("Rollback-on-error supported, setting {} to {}", NETCONF_ERROR_OPTION_QNAME, ROLLBACK_ON_ERROR_OPTION);
103             ret.addLeaf(NETCONF_ERROR_OPTION_QNAME, ROLLBACK_ON_ERROR_OPTION);
104         }
105
106         ret.add(targetWrapperNode);
107         return ret;
108     }
109
110     private CompositeNode createEditStructure(final InstanceIdentifier dataPath, final Optional<String> operation,
111             final Optional<CompositeNode> lastChildOverride) {
112         List<PathArgument> path = dataPath.getPath();
113         List<PathArgument> reversed = Lists.reverse(path);
114         CompositeNode previous = null;
115         boolean isLast = true;
116         for (PathArgument arg : reversed) {
117             CompositeNodeBuilder<ImmutableCompositeNode> builder = ImmutableCompositeNode.builder();
118             builder.setQName(arg.getNodeType());
119             Map<QName, Object> predicates = Collections.emptyMap();
120             if (arg instanceof NodeIdentifierWithPredicates) {
121                 predicates = ((NodeIdentifierWithPredicates) arg).getKeyValues();
122             }
123             for (Entry<QName, Object> entry : predicates.entrySet()) {
124                 builder.addLeaf(entry.getKey(), entry.getValue());
125             }
126
127             if (isLast) {
128                 if (operation.isPresent()) {
129                     builder.setAttribute(NETCONF_OPERATION_QNAME, operation.get());
130                 }
131                 if (lastChildOverride.isPresent()) {
132                     List<Node<?>> children = lastChildOverride.get().getValue();
133                     for(Node<?> child : children) {
134                         if(!predicates.containsKey(child.getKey())) {
135                             builder.add(child);
136                         }
137                     }
138
139                 }
140             } else {
141                 builder.add(previous);
142             }
143             previous = builder.toInstance();
144             isLast = false;
145         }
146         return ImmutableCompositeNode.create(NETCONF_CONFIG_QNAME, ImmutableList.<Node<?>>of(previous));
147     }
148
149     @Override
150     public RpcResult<Void> finish() {
151         CompositeNodeBuilder<ImmutableCompositeNode> commitInput = ImmutableCompositeNode.builder();
152         commitInput.setQName(NETCONF_COMMIT_QNAME);
153         try {
154             final RpcResult<?> rpcResult = device.invokeRpc(NetconfMapping.NETCONF_COMMIT_QNAME, commitInput.toInstance()).get();
155             return new RpcResult<Void>() {
156
157                 @Override
158                 public boolean isSuccessful() {
159                     return rpcResult.isSuccessful();
160                 }
161
162                 @Override
163                 public Void getResult() {
164                     return null;
165                 }
166
167                 @Override
168                 public Collection<RpcError> getErrors() {
169                     return rpcResult.getErrors();
170                 }
171             };
172         } catch (final InterruptedException | ExecutionException e) {
173             LOG.warn("Failed to finish operation", e);
174             return new RpcResult<Void>() {
175                 @Override
176                 public boolean isSuccessful() {
177                     return false;
178                 }
179
180                 @Override
181                 public Void getResult() {
182                     return null;
183                 }
184
185                 @Override
186                 public Collection<RpcError> getErrors() {
187                     // FIXME: wrap the exception
188                     return Collections.emptySet();
189                 }
190             };
191         }
192     }
193
194     @Override
195     public DataModification<InstanceIdentifier, CompositeNode> getModification() {
196         return this.modification;
197     }
198
199     @Override
200     public RpcResult<Void> rollback() throws IllegalStateException {
201         // TODO Auto-generated method stub
202         return null;
203     }
204 }