29cd2d4de893bb52c0fb1ab7701b0948793ee7cf
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / schema / tree / InMemoryDataTree.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.yangtools.yang.data.impl.schema.tree;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.base.MoreObjects;
13 import java.lang.invoke.MethodHandles;
14 import java.lang.invoke.VarHandle;
15 import java.util.Optional;
16 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
17 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
18 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
19 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodes;
20 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
21 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
22 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeConfiguration;
23 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
24 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
25 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
26 import org.opendaylight.yangtools.yang.model.api.ContainerLike;
27 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
28 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
29 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
30 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34 /**
35  * Read-only snapshot of the data tree.
36  */
37 final class InMemoryDataTree extends AbstractDataTreeTip implements DataTree {
38     private static final VarHandle STATE;
39
40     static {
41         try {
42             STATE = MethodHandles.lookup().findVarHandle(InMemoryDataTree.class, "state", DataTreeState.class);
43         } catch (NoSuchFieldException | IllegalAccessException e) {
44             throw new ExceptionInInitializerError(e);
45         }
46     }
47
48     private static final Logger LOG = LoggerFactory.getLogger(InMemoryDataTree.class);
49
50     private final DataTreeConfiguration treeConfig;
51     private final boolean maskMandatory;
52
53     /**
54      * Current data store state generation. All accesses need to go through {@link #STATE}
55      */
56     @SuppressWarnings("unused")
57     private volatile DataTreeState state;
58
59     InMemoryDataTree(final TreeNode rootNode, final DataTreeConfiguration treeConfig,
60             final EffectiveModelContext schemaContext) {
61         this.treeConfig = requireNonNull(treeConfig, "treeConfig");
62         maskMandatory = true;
63         state = DataTreeState.createInitial(rootNode);
64         if (schemaContext != null) {
65             setEffectiveModelContext(schemaContext);
66         }
67     }
68
69     InMemoryDataTree(final TreeNode rootNode, final DataTreeConfiguration treeConfig,
70             final EffectiveModelContext schemaContext, final DataSchemaNode rootSchemaNode,
71             final boolean maskMandatory) {
72         this.treeConfig = requireNonNull(treeConfig, "treeConfig");
73         this.maskMandatory = maskMandatory;
74
75         state = DataTreeState.createInitial(rootNode).withSchemaContext(schemaContext, getOperation(rootSchemaNode));
76     }
77
78     private ModificationApplyOperation getOperation(final DataSchemaNode rootSchemaNode) {
79         if (rootSchemaNode instanceof ContainerLike && maskMandatory) {
80             return new ContainerModificationStrategy((ContainerLike) rootSchemaNode, treeConfig);
81         }
82         if (rootSchemaNode instanceof ListSchemaNode) {
83             final PathArgument arg = treeConfig.getRootPath().getLastPathArgument();
84             if (arg instanceof NodeIdentifierWithPredicates) {
85                 return maskMandatory ? new ListEntryModificationStrategy((ListSchemaNode) rootSchemaNode, treeConfig)
86                         : ListEntryModificationStrategy.of((ListSchemaNode) rootSchemaNode, treeConfig);
87             }
88         }
89
90         try {
91             return SchemaAwareApplyOperation.from(rootSchemaNode, treeConfig);
92         } catch (ExcludedDataSchemaNodeException e) {
93             throw new IllegalArgumentException("Root node does not belong current data tree", e);
94         }
95     }
96
97     @Override
98     public void setEffectiveModelContext(final EffectiveModelContext newModelContext) {
99         internalSetSchemaContext(newModelContext);
100     }
101
102     /*
103      * This method is synchronized to guard against user attempting to install
104      * multiple contexts. Otherwise it runs in a lock-free manner.
105      */
106     private synchronized void internalSetSchemaContext(final EffectiveModelContext newSchemaContext) {
107         requireNonNull(newSchemaContext);
108
109         LOG.debug("Following schema contexts will be attempted {}", newSchemaContext);
110
111         final DataSchemaContextTree contextTree = DataSchemaContextTree.from(newSchemaContext);
112         final Optional<DataSchemaContextNode<?>> rootContextNode = contextTree.findChild(getRootPath());
113         if (!rootContextNode.isPresent()) {
114             LOG.warn("Could not find root {} in new schema context, not upgrading", getRootPath());
115             return;
116         }
117
118         final DataSchemaNode rootSchemaNode = rootContextNode.get().getDataSchemaNode();
119         if (!(rootSchemaNode instanceof DataNodeContainer)) {
120             LOG.warn("Root {} resolves to non-container type {}, not upgrading", getRootPath(), rootSchemaNode);
121             return;
122         }
123
124         final ModificationApplyOperation rootNode = getOperation(rootSchemaNode);
125         DataTreeState currentState;
126         DataTreeState newState;
127         do {
128             currentState = currentState();
129             newState = currentState.withSchemaContext(newSchemaContext, rootNode);
130             // TODO: can we lower this to compareAndSwapRelease?
131         } while (!STATE.compareAndSet(this, currentState, newState));
132     }
133
134     @Override
135     public InMemoryDataTreeSnapshot takeSnapshot() {
136         return currentState().newSnapshot();
137     }
138
139     @Override
140     public void commit(final DataTreeCandidate candidate) {
141         if (candidate instanceof NoopDataTreeCandidate) {
142             return;
143         }
144         if (!(candidate instanceof InMemoryDataTreeCandidate)) {
145             throw new IllegalArgumentException("Invalid candidate class " + candidate.getClass());
146         }
147
148         final InMemoryDataTreeCandidate c = (InMemoryDataTreeCandidate)candidate;
149         if (LOG.isTraceEnabled()) {
150             LOG.trace("Data Tree is {}", NormalizedNodes.toStringTree(c.getTipRoot().getData()));
151         }
152
153         final TreeNode newRoot = c.getTipRoot();
154         DataTreeState currentState;
155         DataTreeState newState;
156         do {
157             currentState = currentState();
158             final TreeNode currentRoot = currentState.getRoot();
159             LOG.debug("Updating datastore from {} to {}", currentRoot, newRoot);
160
161             final TreeNode oldRoot = c.getBeforeRoot();
162             if (oldRoot != currentRoot) {
163                 final String oldStr = simpleToString(oldRoot);
164                 final String currentStr = simpleToString(currentRoot);
165                 throw new IllegalStateException("Store tree " + currentStr + " and candidate base " + oldStr
166                     + " differ.");
167             }
168
169             newState = currentState.withRoot(newRoot);
170             LOG.trace("Updated state from {} to {}", currentState, newState);
171             // TODO: can we lower this to compareAndSwapRelease?
172         } while (!STATE.compareAndSet(this, currentState, newState));
173     }
174
175     private static String simpleToString(final Object obj) {
176         return obj.getClass().getName() + "@" + Integer.toHexString(obj.hashCode());
177     }
178
179     private DataTreeState currentState() {
180         return (DataTreeState) STATE.getAcquire(this);
181     }
182
183     @Override
184     public YangInstanceIdentifier getRootPath() {
185         return treeConfig.getRootPath();
186     }
187
188     @Override
189     public String toString() {
190         return MoreObjects.toStringHelper(this)
191                 .add("object", super.toString())
192                 .add("config", treeConfig)
193                 .add("state", currentState())
194                 .toString();
195     }
196
197     @Override
198     protected TreeNode getTipRoot() {
199         return currentState().getRoot();
200     }
201 }