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