1990b1590ea35fd6db614922a0450d4d86b8fd21
[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.util.Optional;
15 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
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.ListSchemaNode;
30 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
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 AtomicReferenceFieldUpdater<InMemoryDataTree, DataTreeState> STATE_UPDATER =
39             AtomicReferenceFieldUpdater.newUpdater(InMemoryDataTree.class, DataTreeState.class, "state");
40     private static final Logger LOG = LoggerFactory.getLogger(InMemoryDataTree.class);
41
42     private final DataTreeConfiguration treeConfig;
43     private final boolean maskMandatory;
44
45     /**
46      * Current data store state generation.
47      */
48     private volatile DataTreeState state;
49
50     InMemoryDataTree(final TreeNode rootNode, final DataTreeConfiguration treeConfig,
51         final SchemaContext schemaContext) {
52         this.treeConfig = requireNonNull(treeConfig, "treeConfig");
53         maskMandatory = true;
54         state = DataTreeState.createInitial(rootNode);
55         if (schemaContext != null) {
56             setSchemaContext(schemaContext);
57         }
58     }
59
60     InMemoryDataTree(final TreeNode rootNode, final DataTreeConfiguration treeConfig,
61             final SchemaContext schemaContext, final DataSchemaNode rootSchemaNode, final boolean maskMandatory) {
62         this.treeConfig = requireNonNull(treeConfig, "treeConfig");
63         this.maskMandatory = maskMandatory;
64
65         state = DataTreeState.createInitial(rootNode).withSchemaContext(schemaContext, getOperation(rootSchemaNode));
66     }
67
68     private ModificationApplyOperation getOperation(final DataSchemaNode rootSchemaNode) {
69         if (rootSchemaNode instanceof ContainerSchemaNode && maskMandatory) {
70             return new ContainerModificationStrategy((ContainerSchemaNode) rootSchemaNode, treeConfig);
71         }
72         if (rootSchemaNode instanceof ListSchemaNode) {
73             final PathArgument arg = treeConfig.getRootPath().getLastPathArgument();
74             if (arg instanceof NodeIdentifierWithPredicates) {
75                 return maskMandatory ? new ListEntryModificationStrategy((ListSchemaNode) rootSchemaNode, treeConfig)
76                         : ListEntryModificationStrategy.of((ListSchemaNode) rootSchemaNode, treeConfig);
77             }
78         }
79
80         return SchemaAwareApplyOperation.from(rootSchemaNode, treeConfig);
81     }
82
83     /*
84      * This method is synchronized to guard against user attempting to install
85      * multiple contexts. Otherwise it runs in a lock-free manner.
86      */
87     @Override
88     public synchronized void setSchemaContext(final SchemaContext newSchemaContext) {
89         requireNonNull(newSchemaContext);
90
91         LOG.debug("Following schema contexts will be attempted {}", newSchemaContext);
92
93         final DataSchemaContextTree contextTree = DataSchemaContextTree.from(newSchemaContext);
94         final Optional<DataSchemaContextNode<?>> rootContextNode = contextTree.findChild(getRootPath());
95         if (!rootContextNode.isPresent()) {
96             LOG.warn("Could not find root {} in new schema context, not upgrading", getRootPath());
97             return;
98         }
99
100         final DataSchemaNode rootSchemaNode = rootContextNode.get().getDataSchemaNode();
101         if (!(rootSchemaNode instanceof DataNodeContainer)) {
102             LOG.warn("Root {} resolves to non-container type {}, not upgrading", getRootPath(), rootSchemaNode);
103             return;
104         }
105
106         final ModificationApplyOperation rootNode = getOperation(rootSchemaNode);
107         DataTreeState currentState;
108         DataTreeState newState;
109         do {
110             currentState = state;
111             newState = currentState.withSchemaContext(newSchemaContext, rootNode);
112         } while (!STATE_UPDATER.compareAndSet(this, currentState, newState));
113     }
114
115     @Override
116     public InMemoryDataTreeSnapshot takeSnapshot() {
117         return state.newSnapshot();
118     }
119
120     @Override
121     public void commit(final DataTreeCandidate candidate) {
122         if (candidate instanceof NoopDataTreeCandidate) {
123             return;
124         }
125         checkArgument(candidate instanceof InMemoryDataTreeCandidate, "Invalid candidate class %s",
126             candidate.getClass());
127         final InMemoryDataTreeCandidate c = (InMemoryDataTreeCandidate)candidate;
128
129         if (LOG.isTraceEnabled()) {
130             LOG.trace("Data Tree is {}", NormalizedNodes.toStringTree(c.getTipRoot().getData()));
131         }
132
133         final TreeNode newRoot = c.getTipRoot();
134         DataTreeState currentState;
135         DataTreeState newState;
136         do {
137             currentState = state;
138             final TreeNode currentRoot = currentState.getRoot();
139             LOG.debug("Updating datastore from {} to {}", currentRoot, newRoot);
140
141             final TreeNode oldRoot = c.getBeforeRoot();
142             if (oldRoot != currentRoot) {
143                 final String oldStr = simpleToString(oldRoot);
144                 final String currentStr = simpleToString(currentRoot);
145                 throw new IllegalStateException("Store tree " + currentStr + " and candidate base " + oldStr
146                     + " differ.");
147             }
148
149             newState = currentState.withRoot(newRoot);
150             LOG.trace("Updated state from {} to {}", currentState, newState);
151         } while (!STATE_UPDATER.compareAndSet(this, currentState, newState));
152     }
153
154     private static String simpleToString(final Object obj) {
155         return obj.getClass().getName() + "@" + Integer.toHexString(obj.hashCode());
156     }
157
158     @Override
159     public YangInstanceIdentifier getRootPath() {
160         return treeConfig.getRootPath();
161     }
162
163     @Override
164     public String toString() {
165         return MoreObjects.toStringHelper(this)
166                 .add("object", super.toString())
167                 .add("config", treeConfig)
168                 .add("state", state)
169                 .toString();
170     }
171
172     @Override
173     protected TreeNode getTipRoot() {
174         return state.getRoot();
175     }
176 }