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