Merge changes I8dc2b4df,I09e448f4
[controller.git] / opendaylight / md-sal / sal-dom-broker / src / main / java / org / opendaylight / controller / md / sal / dom / store / impl / tree / data / NormalizedNodeContainerModificationStrategy.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.md.sal.dom.store.impl.tree.data;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11
12 import java.util.Map;
13
14 import org.opendaylight.controller.md.sal.dom.store.impl.tree.DataPreconditionFailedException;
15 import org.opendaylight.controller.md.sal.dom.store.impl.tree.ModificationType;
16 import org.opendaylight.controller.md.sal.dom.store.impl.tree.StoreUtils;
17 import org.opendaylight.controller.md.sal.dom.store.impl.tree.data.DataNodeContainerModificationStrategy.ListEntryModificationStrategy;
18 import org.opendaylight.controller.md.sal.dom.store.impl.tree.data.ValueNodeModificationStrategy.LeafSetEntryModificationStrategy;
19 import org.opendaylight.controller.md.sal.dom.store.impl.tree.spi.MutableTreeNode;
20 import org.opendaylight.controller.md.sal.dom.store.impl.tree.spi.TreeNode;
21 import org.opendaylight.controller.md.sal.dom.store.impl.tree.spi.TreeNodeFactory;
22 import org.opendaylight.controller.md.sal.dom.store.impl.tree.spi.Version;
23 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
24 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifier;
25 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifierWithPredicates;
26 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeWithValue;
27 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
28 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
29 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
30 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
31 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
32 import org.opendaylight.yangtools.yang.data.api.schema.OrderedLeafSetNode;
33 import org.opendaylight.yangtools.yang.data.api.schema.OrderedMapNode;
34 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
35 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
36 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableChoiceNodeBuilder;
37 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafSetNodeBuilder;
38 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapNodeBuilder;
39 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableOrderedLeafSetNodeBuilder;
40 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableOrderedMapNodeBuilder;
41 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
42 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
43 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
46
47 import com.google.common.base.Optional;
48 import com.google.common.collect.ImmutableMap;
49 import com.google.common.collect.Iterables;
50
51 abstract class NormalizedNodeContainerModificationStrategy extends SchemaAwareApplyOperation {
52
53     private final Class<? extends NormalizedNode<?, ?>> nodeClass;
54
55     protected NormalizedNodeContainerModificationStrategy(final Class<? extends NormalizedNode<?, ?>> nodeClass) {
56         this.nodeClass = nodeClass;
57     }
58
59     @Override
60     public void verifyStructure(final ModifiedNode modification) throws IllegalArgumentException {
61         if (modification.getType() == ModificationType.WRITE) {
62
63         }
64         for (ModifiedNode childModification : modification.getChildren()) {
65             resolveChildOperation(childModification.getIdentifier()).verifyStructure(childModification);
66         }
67     }
68
69     @Override
70     protected void checkWriteApplicable(final InstanceIdentifier path, final NodeModification modification,
71             final Optional<TreeNode> current) throws DataPreconditionFailedException {
72         // FIXME: Implement proper write check for replacement of node container
73         //        prerequisite is to have transaction chain available for clients
74         //        otherwise this will break chained writes to same node.
75     }
76
77     @SuppressWarnings("rawtypes")
78     @Override
79     protected void verifyWrittenStructure(final NormalizedNode<?, ?> writtenValue) {
80         checkArgument(nodeClass.isInstance(writtenValue), "Node should must be of type %s", nodeClass);
81         checkArgument(writtenValue instanceof NormalizedNodeContainer);
82
83         NormalizedNodeContainer container = (NormalizedNodeContainer) writtenValue;
84         for (Object child : container.getValue()) {
85             checkArgument(child instanceof NormalizedNode);
86
87             /*
88              * FIXME: fail-fast semantics:
89              *
90              * We can validate the data structure here, aborting the commit
91              * before it ever progresses to being committed.
92              */
93         }
94     }
95
96     @Override
97     protected TreeNode applyWrite(final ModifiedNode modification,
98             final Optional<TreeNode> currentMeta, final Version subtreeVersion) {
99         final Version nodeVersion;
100         if (currentMeta.isPresent()) {
101             nodeVersion = currentMeta.get().getVersion().next();
102         } else {
103             nodeVersion = subtreeVersion;
104         }
105
106         final NormalizedNode<?, ?> newValue = modification.getWrittenValue();
107         final TreeNode newValueMeta = TreeNodeFactory.createTreeNode(newValue, nodeVersion);
108
109         if (Iterables.isEmpty(modification.getChildren())) {
110             return newValueMeta;
111         }
112
113         /*
114          * This is where things get interesting. The user has performed a write and
115          * then she applied some more modifications to it. So we need to make sense
116          * of that an apply the operations on top of the written value. We could have
117          * done it during the write, but this operation is potentially expensive, so
118          * we have left it out of the fast path.
119          *
120          * As it turns out, once we materialize the written data, we can share the
121          * code path with the subtree change. So let's create an unsealed TreeNode
122          * and run the common parts on it -- which end with the node being sealed.
123          */
124         final MutableTreeNode mutable = newValueMeta.mutable();
125         mutable.setSubtreeVersion(subtreeVersion);
126
127         @SuppressWarnings("rawtypes")
128         final NormalizedNodeContainerBuilder dataBuilder = createBuilder(newValue);
129
130         return mutateChildren(mutable, dataBuilder, nodeVersion, modification.getChildren());
131     }
132
133     @SuppressWarnings({ "rawtypes", "unchecked" })
134     private TreeNode mutateChildren(final MutableTreeNode meta, final NormalizedNodeContainerBuilder data,
135             final Version nodeVersion, final Iterable<ModifiedNode> modifications) {
136
137         for (ModifiedNode mod : modifications) {
138             final PathArgument id = mod.getIdentifier();
139             final Optional<TreeNode> cm = meta.getChild(id);
140
141             Optional<TreeNode> result = resolveChildOperation(id).apply(mod, cm, nodeVersion);
142             if (result.isPresent()) {
143                 final TreeNode tn = result.get();
144                 meta.addChild(tn);
145                 data.addChild(tn.getData());
146             } else {
147                 meta.removeChild(id);
148                 data.removeChild(id);
149             }
150         }
151
152         meta.setData(data.build());
153         return meta.seal();
154     }
155
156     @Override
157     protected TreeNode applyMerge(final ModifiedNode modification, final TreeNode currentMeta,
158             final Version subtreeVersion) {
159         // For Node Containers - merge is same as subtree change - we only replace children.
160         return applySubtreeChange(modification, currentMeta, subtreeVersion);
161     }
162
163     @Override
164     public TreeNode applySubtreeChange(final ModifiedNode modification,
165             final TreeNode currentMeta, final Version subtreeVersion) {
166         // Bump subtree version to its new target
167         final Version updatedSubtreeVersion = currentMeta.getSubtreeVersion().next();
168
169         final MutableTreeNode newMeta = currentMeta.mutable();
170         newMeta.setSubtreeVersion(updatedSubtreeVersion);
171
172         @SuppressWarnings("rawtypes")
173         NormalizedNodeContainerBuilder dataBuilder = createBuilder(currentMeta.getData());
174
175         return mutateChildren(newMeta, dataBuilder, updatedSubtreeVersion, modification.getChildren());
176     }
177
178     @Override
179     protected void checkSubtreeModificationApplicable(final InstanceIdentifier path, final NodeModification modification,
180             final Optional<TreeNode> current) throws DataPreconditionFailedException {
181         checkDataPrecondition(path, current.isPresent(), "Node was deleted by other transaction.");
182         checkChildPreconditions(path, modification, current);
183     }
184
185     private void checkChildPreconditions(final InstanceIdentifier path, final NodeModification modification, final Optional<TreeNode> current) throws DataPreconditionFailedException {
186         final TreeNode currentMeta = current.get();
187         for (NodeModification childMod : modification.getChildren()) {
188             final PathArgument childId = childMod.getIdentifier();
189             final Optional<TreeNode> childMeta = currentMeta.getChild(childId);
190
191             InstanceIdentifier childPath = StoreUtils.append(path, childId);
192             resolveChildOperation(childId).checkApplicable(childPath, childMod, childMeta);
193         }
194     }
195
196     @Override
197     protected void checkMergeApplicable(final InstanceIdentifier path, final NodeModification modification,
198             final Optional<TreeNode> current) throws DataPreconditionFailedException {
199         if(current.isPresent()) {
200             checkChildPreconditions(path, modification,current);
201         }
202     }
203
204     @SuppressWarnings("rawtypes")
205     protected abstract NormalizedNodeContainerBuilder createBuilder(NormalizedNode<?, ?> original);
206
207     public static class ChoiceModificationStrategy extends NormalizedNodeContainerModificationStrategy {
208
209         private final Map<PathArgument, ModificationApplyOperation> childNodes;
210
211         public ChoiceModificationStrategy(final ChoiceNode schemaNode) {
212             super(org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode.class);
213             ImmutableMap.Builder<PathArgument, ModificationApplyOperation> child = ImmutableMap.builder();
214
215             for (ChoiceCaseNode caze : schemaNode.getCases()) {
216                 for (DataSchemaNode cazeChild : caze.getChildNodes()) {
217                     SchemaAwareApplyOperation childNode = from(cazeChild);
218                     child.put(new NodeIdentifier(cazeChild.getQName()), childNode);
219                 }
220             }
221             childNodes = child.build();
222         }
223
224         @Override
225         public Optional<ModificationApplyOperation> getChild(final PathArgument child) {
226             return Optional.fromNullable(childNodes.get(child));
227         }
228
229         @Override
230         @SuppressWarnings("rawtypes")
231         protected DataContainerNodeBuilder createBuilder(final NormalizedNode<?, ?> original) {
232             checkArgument(original instanceof org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode);
233             return ImmutableChoiceNodeBuilder.create((org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode) original);
234         }
235     }
236
237     public static class OrderedLeafSetModificationStrategy extends NormalizedNodeContainerModificationStrategy {
238
239         private final Optional<ModificationApplyOperation> entryStrategy;
240
241         @SuppressWarnings({ "unchecked", "rawtypes" })
242         protected OrderedLeafSetModificationStrategy(final LeafListSchemaNode schema) {
243             super((Class) LeafSetNode.class);
244             entryStrategy = Optional.<ModificationApplyOperation> of(new LeafSetEntryModificationStrategy(schema));
245         }
246
247         @SuppressWarnings("rawtypes")
248         @Override
249         protected NormalizedNodeContainerBuilder createBuilder(final NormalizedNode<?, ?> original) {
250             checkArgument(original instanceof OrderedLeafSetNode<?>);
251             return ImmutableOrderedLeafSetNodeBuilder.create((OrderedLeafSetNode<?>) original);
252         }
253
254         @Override
255         public Optional<ModificationApplyOperation> getChild(final PathArgument identifier) {
256             if (identifier instanceof NodeWithValue) {
257                 return entryStrategy;
258             }
259             return Optional.absent();
260         }
261     }
262
263     public static class OrderedMapModificationStrategy extends NormalizedNodeContainerModificationStrategy {
264
265         private final Optional<ModificationApplyOperation> entryStrategy;
266
267         protected OrderedMapModificationStrategy(final ListSchemaNode schema) {
268             super(OrderedMapNode.class);
269             entryStrategy = Optional.<ModificationApplyOperation> of(new ListEntryModificationStrategy(schema));
270         }
271
272         @SuppressWarnings("rawtypes")
273         @Override
274         protected NormalizedNodeContainerBuilder createBuilder(final NormalizedNode<?, ?> original) {
275             checkArgument(original instanceof OrderedMapNode);
276             return ImmutableOrderedMapNodeBuilder.create((OrderedMapNode) original);
277         }
278
279         @Override
280         public Optional<ModificationApplyOperation> getChild(final PathArgument identifier) {
281             if (identifier instanceof NodeIdentifierWithPredicates) {
282                 return entryStrategy;
283             }
284             return Optional.absent();
285         }
286
287         @Override
288         public String toString() {
289             return "OrderedMapModificationStrategy [entry=" + entryStrategy + "]";
290         }
291     }
292
293     public static class UnorderedLeafSetModificationStrategy extends NormalizedNodeContainerModificationStrategy {
294
295         private final Optional<ModificationApplyOperation> entryStrategy;
296
297         @SuppressWarnings({ "unchecked", "rawtypes" })
298         protected UnorderedLeafSetModificationStrategy(final LeafListSchemaNode schema) {
299             super((Class) LeafSetNode.class);
300             entryStrategy = Optional.<ModificationApplyOperation> of(new LeafSetEntryModificationStrategy(schema));
301         }
302
303         @SuppressWarnings("rawtypes")
304         @Override
305         protected NormalizedNodeContainerBuilder createBuilder(final NormalizedNode<?, ?> original) {
306             checkArgument(original instanceof LeafSetNode<?>);
307             return ImmutableLeafSetNodeBuilder.create((LeafSetNode<?>) original);
308         }
309
310         @Override
311         public Optional<ModificationApplyOperation> getChild(final PathArgument identifier) {
312             if (identifier instanceof NodeWithValue) {
313                 return entryStrategy;
314             }
315             return Optional.absent();
316         }
317     }
318
319     public static class UnorderedMapModificationStrategy extends NormalizedNodeContainerModificationStrategy {
320
321         private final Optional<ModificationApplyOperation> entryStrategy;
322
323         protected UnorderedMapModificationStrategy(final ListSchemaNode schema) {
324             super(MapNode.class);
325             entryStrategy = Optional.<ModificationApplyOperation> of(new ListEntryModificationStrategy(schema));
326         }
327
328         @SuppressWarnings("rawtypes")
329         @Override
330         protected NormalizedNodeContainerBuilder createBuilder(final NormalizedNode<?, ?> original) {
331             checkArgument(original instanceof MapNode);
332             return ImmutableMapNodeBuilder.create((MapNode) original);
333         }
334
335         @Override
336         public Optional<ModificationApplyOperation> getChild(final PathArgument identifier) {
337             if (identifier instanceof NodeIdentifierWithPredicates) {
338                 return entryStrategy;
339             }
340             return Optional.absent();
341         }
342
343         @Override
344         public String toString() {
345             return "UnorderedMapModificationStrategy [entry=" + entryStrategy + "]";
346         }
347     }
348 }