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