Propagate shard name to FrontendClientMetadataBuilder
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / FrontendClientMetadataBuilder.java
1 /*
2  * Copyright (c) 2016 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.cluster.datastore;
9
10 import com.google.common.base.MoreObjects;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Verify;
13 import com.google.common.collect.Collections2;
14 import com.google.common.collect.Range;
15 import com.google.common.collect.RangeSet;
16 import com.google.common.collect.TreeRangeSet;
17 import com.google.common.primitives.UnsignedLong;
18 import java.util.HashMap;
19 import java.util.Map;
20 import javax.annotation.Nonnull;
21 import javax.annotation.concurrent.NotThreadSafe;
22 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
23 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
24 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
25 import org.opendaylight.controller.cluster.datastore.persisted.FrontendClientMetadata;
26 import org.opendaylight.controller.cluster.datastore.persisted.FrontendHistoryMetadata;
27 import org.opendaylight.yangtools.concepts.Builder;
28 import org.opendaylight.yangtools.concepts.Identifiable;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32 @NotThreadSafe
33 final class FrontendClientMetadataBuilder implements Builder<FrontendClientMetadata>, Identifiable<ClientIdentifier> {
34     private static final Logger LOG = LoggerFactory.getLogger(FrontendClientMetadataBuilder.class);
35
36     private final Map<LocalHistoryIdentifier, FrontendHistoryMetadataBuilder> currentHistories = new HashMap<>();
37     private final RangeSet<UnsignedLong> purgedHistories;
38     private final ClientIdentifier identifier;
39     private final String shardName;
40
41     FrontendClientMetadataBuilder(final String shardName, final ClientIdentifier identifier) {
42         this.shardName = Preconditions.checkNotNull(shardName);
43         this.identifier = Preconditions.checkNotNull(identifier);
44         purgedHistories = TreeRangeSet.create();
45
46         // History for stand-alone transactions is always present
47         final LocalHistoryIdentifier standaloneId = standaloneHistoryId();
48         currentHistories.put(standaloneId, new FrontendHistoryMetadataBuilder(standaloneId));
49     }
50
51     FrontendClientMetadataBuilder(final String shardName, final FrontendClientMetadata meta) {
52         this.shardName = Preconditions.checkNotNull(shardName);
53         this.identifier = Preconditions.checkNotNull(meta.getIdentifier());
54         purgedHistories = TreeRangeSet.create(meta.getPurgedHistories());
55
56         for (FrontendHistoryMetadata h : meta.getCurrentHistories()) {
57             final FrontendHistoryMetadataBuilder b = new FrontendHistoryMetadataBuilder(identifier, h);
58             currentHistories.put(b.getIdentifier(), b);
59         }
60
61         // Sanity check and recovery
62         final LocalHistoryIdentifier standaloneId = standaloneHistoryId();
63         if (!currentHistories.containsKey(standaloneId)) {
64             LOG.warn("{}: Client {} recovered histories {} do not contain stand-alone history, attempting recovery",
65                 shardName, identifier, currentHistories);
66             currentHistories.put(standaloneId, new FrontendHistoryMetadataBuilder(standaloneId));
67         }
68     }
69
70     private LocalHistoryIdentifier standaloneHistoryId() {
71         return new LocalHistoryIdentifier(identifier, 0);
72     }
73
74     @Override
75     public FrontendClientMetadata build() {
76         return new FrontendClientMetadata(identifier, purgedHistories,
77             Collections2.transform(currentHistories.values(), FrontendHistoryMetadataBuilder::build));
78     }
79
80     @Override
81     public ClientIdentifier getIdentifier() {
82         return identifier;
83     }
84
85     void onHistoryCreated(final LocalHistoryIdentifier historyId) {
86         final FrontendHistoryMetadataBuilder newMeta = new FrontendHistoryMetadataBuilder(historyId);
87         final FrontendHistoryMetadataBuilder oldMeta = currentHistories.putIfAbsent(historyId, newMeta);
88         if (oldMeta != null) {
89             // This should not be happening, warn about it
90             LOG.warn("{}: Reused local history {}", shardName, historyId);
91         } else {
92             LOG.debug("{}: Created local history {}", shardName, historyId);
93         }
94     }
95
96     void onHistoryClosed(final LocalHistoryIdentifier historyId) {
97         final FrontendHistoryMetadataBuilder builder = currentHistories.get(historyId);
98         if (builder != null) {
99             builder.onHistoryClosed();
100             LOG.debug("{}: Closed history {}", shardName, historyId);
101         } else {
102             LOG.warn("{}: Closed unknown history {}, ignoring", shardName, historyId);
103         }
104     }
105
106     void onHistoryPurged(final LocalHistoryIdentifier historyId) {
107         final FrontendHistoryMetadataBuilder history = currentHistories.remove(historyId);
108         if (history == null) {
109             LOG.warn("{}: Purging unknown history {}", shardName, historyId);
110         }
111
112         // XXX: do we need to account for cookies?
113         purgedHistories.add(Range.singleton(UnsignedLong.fromLongBits(historyId.getHistoryId())));
114         LOG.debug("{}: Purged history {}", historyId);
115     }
116
117     void onTransactionAborted(final TransactionIdentifier txId) {
118         final FrontendHistoryMetadataBuilder history = getHistory(txId);
119         if (history != null) {
120             history.onTransactionAborted(txId);
121             LOG.debug("{}: Committed transaction {}", shardName, txId);
122         } else {
123             LOG.warn("{}: Unknown history for aborted transaction {}, ignoring", shardName, txId);
124         }
125     }
126
127     void onTransactionCommitted(final TransactionIdentifier txId) {
128         final FrontendHistoryMetadataBuilder history = getHistory(txId);
129         if (history != null) {
130             history.onTransactionCommitted(txId);
131             LOG.debug("{}: Aborted transaction {}", txId);
132         } else {
133             LOG.warn("{}: Unknown history for commited transaction {}, ignoring", shardName, txId);
134         }
135     }
136
137     void onTransactionPurged(final TransactionIdentifier txId) {
138         final FrontendHistoryMetadataBuilder history = getHistory(txId);
139         if (history != null) {
140             history.onTransactionPurged(txId);
141             LOG.debug("{}: Purged transaction {}", txId);
142         } else {
143             LOG.warn("{}: Unknown history for purged transaction {}, ignoring", shardName, txId);
144         }
145     }
146
147     /**
148      * Transform frontend metadata for a particular client into its {@link LeaderFrontendState} counterpart.
149      *
150      * @param shard parent shard
151      * @return Leader frontend state
152      */
153     @Nonnull LeaderFrontendState toLeaderState(@Nonnull final Shard shard) {
154         // Note: we have to make sure to *copy* all current state and not leak any views, otherwise leader/follower
155         //       interactions would get intertwined leading to inconsistencies.
156         final Map<LocalHistoryIdentifier, LocalFrontendHistory> histories = new HashMap<>();
157         for (FrontendHistoryMetadataBuilder e : currentHistories.values()) {
158             if (e.getIdentifier().getHistoryId() != 0) {
159                 final AbstractFrontendHistory state = e.toLeaderState(shard);
160                 Verify.verify(state instanceof LocalFrontendHistory);
161                 histories.put(e.getIdentifier(), (LocalFrontendHistory) state);
162             }
163         }
164
165         final AbstractFrontendHistory singleHistory;
166         final FrontendHistoryMetadataBuilder singleHistoryMeta = currentHistories.get(
167             new LocalHistoryIdentifier(identifier, 0));
168         if (singleHistoryMeta == null) {
169             final ShardDataTree tree = shard.getDataStore();
170             singleHistory = StandaloneFrontendHistory.create(shard.persistenceId(), getIdentifier(), tree);
171         } else {
172             singleHistory = singleHistoryMeta.toLeaderState(shard);
173         }
174
175         return new LeaderFrontendState(shard.persistenceId(), getIdentifier(), shard.getDataStore(),
176             TreeRangeSet.create(purgedHistories), singleHistory, histories);
177     }
178
179     private FrontendHistoryMetadataBuilder getHistory(final TransactionIdentifier txId) {
180         return currentHistories.get(txId.getHistoryId());
181     }
182
183     @Override
184     public String toString() {
185         return MoreObjects.toStringHelper(this).add("identifier", identifier).add("current", currentHistories)
186                 .add("purged", purgedHistories).toString();
187     }
188 }