Bump odlparent to 13.0.9
[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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
14 import java.lang.invoke.MethodHandles;
15 import java.lang.invoke.VarHandle;
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.tree.api.DataTree;
21 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidate;
22 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeConfiguration;
23 import org.opendaylight.yangtools.yang.data.tree.impl.node.TreeNode;
24 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
25 import org.opendaylight.yangtools.yang.model.api.ContainerLike;
26 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
27 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
28 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
29 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32
33 /**
34  * Read-only snapshot of the data tree.
35  */
36 public final class InMemoryDataTree extends AbstractDataTreeTip implements DataTree {
37     private static final VarHandle STATE;
38
39     static {
40         try {
41             STATE = MethodHandles.lookup().findVarHandle(InMemoryDataTree.class, "state", DataTreeState.class);
42         } catch (NoSuchFieldException | IllegalAccessException e) {
43             throw new ExceptionInInitializerError(e);
44         }
45     }
46
47     private static final Logger LOG = LoggerFactory.getLogger(InMemoryDataTree.class);
48
49     private final DataTreeConfiguration treeConfig;
50     private final boolean maskMandatory;
51
52     /**
53      * Current data store state generation. All accesses need to go through {@link #STATE}
54      */
55     @SuppressWarnings("unused")
56     @SuppressFBWarnings(value = "URF_UNREAD_FIELD", justification = "https://github.com/spotbugs/spotbugs/issues/2749")
57     private volatile DataTreeState state;
58
59     public 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     public 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 rootContainerLike && maskMandatory) {
80             return new ContainerModificationStrategy(rootContainerLike, treeConfig);
81         }
82         if (rootSchemaNode instanceof ListSchemaNode rootList) {
83             final PathArgument arg = treeConfig.getRootPath().getLastPathArgument();
84             if (arg instanceof NodeIdentifierWithPredicates) {
85                 return maskMandatory ? new MapEntryModificationStrategy(rootList, treeConfig)
86                         : MapEntryModificationStrategy.of(rootList, 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 var contextTree = DataSchemaContextTree.from(newSchemaContext);
112         final var rootContextNode = contextTree.childByPath(getRootPath());
113         if (rootContextNode == null) {
114             LOG.warn("Could not find root {} in new schema context, not upgrading", getRootPath());
115             return;
116         }
117
118         final var rootSchemaNode = rootContextNode.dataSchemaNode();
119         if (!(rootSchemaNode instanceof DataNodeContainer)) {
120             LOG.warn("Root {} resolves to non-container type {}, not upgrading", getRootPath(), rootSchemaNode);
121             return;
122         }
123
124         final var 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 c)) {
145             throw new IllegalArgumentException("Invalid candidate class " + candidate.getClass());
146         }
147
148         if (LOG.isTraceEnabled()) {
149             LOG.trace("Data Tree is {}", NormalizedNodes.toStringTree(c.getTipRoot().getData()));
150         }
151
152         final TreeNode newRoot = c.getTipRoot();
153         DataTreeState currentState;
154         DataTreeState newState;
155         do {
156             currentState = currentState();
157             final TreeNode currentRoot = currentState.getRoot();
158             LOG.debug("Updating datastore from {} to {}", currentRoot, newRoot);
159
160             final TreeNode oldRoot = c.getBeforeRoot();
161             if (oldRoot != currentRoot) {
162                 final String oldStr = simpleToString(oldRoot);
163                 final String currentStr = simpleToString(currentRoot);
164                 throw new IllegalStateException("Store tree " + currentStr + " and candidate base " + oldStr
165                     + " differ.");
166             }
167
168             newState = currentState.withRoot(newRoot);
169             LOG.trace("Updated state from {} to {}", currentState, newState);
170             // TODO: can we lower this to compareAndSwapRelease?
171         } while (!STATE.compareAndSet(this, currentState, newState));
172     }
173
174     private static String simpleToString(final Object obj) {
175         return obj.getClass().getName() + "@" + Integer.toHexString(obj.hashCode());
176     }
177
178     private DataTreeState currentState() {
179         return (DataTreeState) STATE.getAcquire(this);
180     }
181
182     @Override
183     public YangInstanceIdentifier getRootPath() {
184         return treeConfig.getRootPath();
185     }
186
187     @Override
188     public String toString() {
189         return MoreObjects.toStringHelper(this)
190                 .add("object", super.toString())
191                 .add("config", treeConfig)
192                 .add("state", currentState())
193                 .toString();
194     }
195
196     @Override
197     protected TreeNode getTipRoot() {
198         return currentState().getRoot();
199     }
200 }