Merge "Bug#1854 - Exit command in console causing OOM."
[controller.git] / opendaylight / md-sal / sal-inmemory-datastore / src / main / java / org / opendaylight / controller / md / sal / dom / store / impl / SnapshotBackedWriteTransaction.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.controller.md.sal.dom.store.impl;
9
10 import static com.google.common.base.Preconditions.checkState;
11 import com.google.common.base.Objects.ToStringHelper;
12 import com.google.common.base.Optional;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Throwables;
15 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
16 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
17 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
18 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
19 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
20 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
21 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeSnapshot;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
24
25 /**
26  * Implementation of Write transaction which is backed by
27  * {@link DataTreeSnapshot} and executed according to
28  * {@link org.opendaylight.controller.md.sal.dom.store.impl.SnapshotBackedWriteTransaction.TransactionReadyPrototype}.
29  *
30  */
31 class SnapshotBackedWriteTransaction extends AbstractDOMStoreTransaction implements DOMStoreWriteTransaction {
32     private static final Logger LOG = LoggerFactory.getLogger(SnapshotBackedWriteTransaction.class);
33     private static final AtomicReferenceFieldUpdater<SnapshotBackedWriteTransaction, TransactionReadyPrototype> READY_UPDATER =
34             AtomicReferenceFieldUpdater.newUpdater(SnapshotBackedWriteTransaction.class, TransactionReadyPrototype.class, "readyImpl");
35     private static final AtomicReferenceFieldUpdater<SnapshotBackedWriteTransaction, DataTreeModification> TREE_UPDATER =
36             AtomicReferenceFieldUpdater.newUpdater(SnapshotBackedWriteTransaction.class, DataTreeModification.class, "mutableTree");
37
38     // non-null when not ready
39     private volatile TransactionReadyPrototype readyImpl;
40     // non-null when not committed/closed
41     private volatile DataTreeModification mutableTree;
42
43     /**
44      * Creates new write-only transaction.
45      *
46      * @param identifier
47      *            transaction Identifier
48      * @param snapshot
49      *            Snapshot which will be modified.
50      * @param readyImpl
51      *            Implementation of ready method.
52      */
53     public SnapshotBackedWriteTransaction(final Object identifier, final boolean debug,
54             final DataTreeSnapshot snapshot, final TransactionReadyPrototype readyImpl) {
55         super(identifier, debug);
56         this.readyImpl = Preconditions.checkNotNull(readyImpl, "readyImpl must not be null.");
57         mutableTree = snapshot.newModification();
58         LOG.debug("Write Tx: {} allocated with snapshot {}", identifier, snapshot);
59     }
60
61     @Override
62     public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
63         checkNotReady();
64
65         final DataTreeModification tree = mutableTree;
66         LOG.debug("Tx: {} Write: {}:{}", getIdentifier(), path, data);
67
68         try {
69             tree.write(path, data);
70             // FIXME: Add checked exception
71         } catch (Exception e) {
72             LOG.error("Tx: {}, failed to write {}:{} in {}", getIdentifier(), path, data, tree, e);
73             // Rethrow original ones if they are subclasses of RuntimeException
74             // or Error
75             Throwables.propagateIfPossible(e);
76             // FIXME: Introduce proper checked exception
77             throw new IllegalArgumentException("Illegal input data.", e);
78         }
79     }
80
81     @Override
82     public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
83         checkNotReady();
84
85         final DataTreeModification tree = mutableTree;
86         LOG.debug("Tx: {} Merge: {}:{}", getIdentifier(), path, data);
87
88         try {
89             tree.merge(path, data);
90             // FIXME: Add checked exception
91         } catch (Exception e) {
92             LOG.error("Tx: {}, failed to write {}:{} in {}", getIdentifier(), path, data, tree, e);
93             // Rethrow original ones if they are subclasses of RuntimeException
94             // or Error
95             Throwables.propagateIfPossible(e);
96             // FIXME: Introduce proper checked exception
97             throw new IllegalArgumentException("Illegal input data.", e);
98         }
99     }
100
101     @Override
102     public void delete(final YangInstanceIdentifier path) {
103         checkNotReady();
104
105         final DataTreeModification tree = mutableTree;
106         LOG.debug("Tx: {} Delete: {}", getIdentifier(), path);
107
108         try {
109             tree.delete(path);
110             // FIXME: Add checked exception
111         } catch (Exception e) {
112             LOG.error("Tx: {}, failed to delete {} in {}", getIdentifier(), path, tree, e);
113             // Rethrow original ones if they are subclasses of RuntimeException
114             // or Error
115             Throwables.propagateIfPossible(e);
116             // FIXME: Introduce proper checked exception
117             throw new IllegalArgumentException("Illegal path to delete.", e);
118         }
119     }
120
121     /**
122      * Exposed for {@link SnapshotBackedReadWriteTransaction}'s sake only. The contract does
123      * not allow data access after the transaction has been closed or readied.
124      *
125      * @param path Path to read
126      * @return null if the the transaction has been closed;
127      */
128     protected final Optional<NormalizedNode<?, ?>> readSnapshotNode(final YangInstanceIdentifier path) {
129         return readyImpl == null ? null : mutableTree.readNode(path);
130     }
131
132     private final void checkNotReady() {
133         checkState(readyImpl != null, "Transaction %s is no longer open. No further modifications allowed.", getIdentifier());
134     }
135
136     @Override
137     public DOMStoreThreePhaseCommitCohort ready() {
138         final TransactionReadyPrototype wasReady = READY_UPDATER.getAndSet(this, null);
139         checkState(wasReady != null, "Transaction %s is no longer open", getIdentifier());
140
141         LOG.debug("Store transaction: {} : Ready", getIdentifier());
142
143         final DataTreeModification tree = mutableTree;
144         TREE_UPDATER.lazySet(this, null);
145         tree.ready();
146         return wasReady.transactionReady(this, tree);
147     }
148
149     @Override
150     public void close() {
151         final TransactionReadyPrototype wasReady = READY_UPDATER.getAndSet(this, null);
152         if (wasReady != null) {
153             LOG.debug("Store transaction: {} : Closed", getIdentifier());
154             TREE_UPDATER.lazySet(this, null);
155             wasReady.transactionAborted(this);
156         } else {
157             LOG.debug("Store transaction: {} : Closed after submit", getIdentifier());
158         }
159     }
160
161     @Override
162     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
163         return toStringHelper.add("ready", readyImpl == null);
164     }
165
166     /**
167      * Prototype implementation of
168      * {@link #ready(org.opendaylight.controller.md.sal.dom.store.impl.SnapshotBackedWriteTransaction)}
169      *
170      * This class is intended to be implemented by Transaction factories
171      * responsible for allocation of {@link org.opendaylight.controller.md.sal.dom.store.impl.SnapshotBackedWriteTransaction} and
172      * providing underlying logic for applying implementation.
173      *
174      */
175     abstract static class TransactionReadyPrototype {
176         /**
177          * Called when a transaction is closed without being readied. This is not invoked for
178          * transactions which are ready.
179          *
180          * @param tx Transaction which got aborted.
181          */
182         protected abstract void transactionAborted(final SnapshotBackedWriteTransaction tx);
183
184         /**
185          * Returns a commit coordinator associated with supplied transactions.
186          *
187          * This call must not fail.
188          *
189          * @param tx
190          *            Transaction on which ready was invoked.
191          * @param tree
192          *            Modified data tree which has been constructed.
193          * @return DOMStoreThreePhaseCommitCohort associated with transaction
194          */
195         protected abstract DOMStoreThreePhaseCommitCohort transactionReady(SnapshotBackedWriteTransaction tx, DataTreeModification tree);
196     }
197 }