3 import java.util.Iterator;
4 import java.util.Random;
5 import java.util.Arrays;
9 import java.util.Vector;
10 import java.util.HashMap;
11 import java.util.HashSet;
12 import java.util.ArrayList;
13 import java.util.Collections;
14 import java.nio.ByteBuffer;
17 * IoTTable data structure. Provides client interface.
18 * @author Brian Demsky
22 final public class Table {
25 static final int FREE_SLOTS = 10; // Number of slots that should be kept free
26 static final int SKIP_THRESHOLD = 10;
27 static final double RESIZE_MULTIPLE = 1.2;
28 static final double RESIZE_THRESHOLD = 0.75;
29 static final int REJECTED_THRESHOLD = 5;
32 private SlotBuffer buffer = null;
33 private CloudComm cloud = null;
34 private Random random = null;
35 private TableStatus liveTableStatus = null;
36 private PendingTransaction pendingTransactionBuilder = null; // Pending Transaction used in building a Pending Transaction
37 private Transaction lastPendingTransactionSpeculatedOn = null; // Last transaction that was speculated on from the pending transaction
38 private Transaction firstPendingTransaction = null; // first transaction in the pending transaction list
41 private int numberOfSlots = 0; // Number of slots stored in buffer
42 private int bufferResizeThreshold = 0; // Threshold on the number of live slots before a resize is needed
43 private long liveSlotCount = 0; // Number of currently live slots
44 private long oldestLiveSlotSequenceNumver = 0; // Smallest sequence number of the slot with a live entry
45 private long localMachineId = 0; // Machine ID of this client device
46 private long sequenceNumber = 0; // Largest sequence number a client has received
47 // private int smallestTableStatusSeen = -1; // Smallest Table Status that was seen in the latest slots sent from the server
48 // private int largestTableStatusSeen = -1; // Largest Table Status that was seen in the latest slots sent from the server
49 private long localTransactionSequenceNumber = 0; // Local sequence number counter for transactions
50 private long lastTransactionSequenceNumberSpeculatedOn = -1; // the last transaction that was speculated on
51 private long oldestTransactionSequenceNumberSpeculatedOn = -1; // the oldest transaction that was speculated on
52 private long localArbitrationSequenceNumber = 0;
53 private boolean hadPartialSendToServer = false;
54 private boolean attemptedToSendToServer = false;
55 private long expectedsize;
56 private boolean didFindTableStatus = false;
57 private long currMaxSize = 0;
59 private Slot lastSlotAttemptedToSend = null;
60 private boolean lastIsNewKey = false;
61 private int lastNewSize = 0;
62 private Map<Transaction, List<Integer>> lastTransactionPartsSent = null;
63 private List<Entry> lastPendingSendArbitrationEntriesToDelete = null;
64 private NewKey lastNewKey = null;
68 private Map<IoTString, KeyValue> committedKeyValueTable = null; // Table of committed key value pairs
69 private Map<IoTString, KeyValue> speculatedKeyValueTable = null; // Table of speculated key value pairs, if there is a speculative value
70 private Map<IoTString, KeyValue> pendingTransactionSpeculatedKeyValueTable = null; // Table of speculated key value pairs, if there is a speculative value from the pending transactions
71 private Map<IoTString, NewKey> liveNewKeyTable = null; // Table of live new keys
72 private HashMap<Long, Pair<Long, Liveness>> lastMessageTable = null; // Last message sent by a client machine id -> (Seq Num, Slot or LastMessage);
73 private HashMap<Long, HashSet<RejectedMessage>> rejectedMessageWatchListTable = null; // Table of machine Ids and the set of rejected messages they have not seen yet
74 private Map<IoTString, Long> arbitratorTable = null; // Table of keys and their arbitrators
75 private Map<Pair<Long, Long>, Abort> liveAbortTable = null; // Table live abort messages
76 private Map<Long, Map<Pair<Long, Integer>, TransactionPart>> newTransactionParts = null; // transaction parts that are seen in this latest round of slots from the server
77 private Map<Long, Map<Pair<Long, Integer>, CommitPart>> newCommitParts = null; // commit parts that are seen in this latest round of slots from the server
78 private Map<Long, Long> lastArbitratedTransactionNumberByArbitratorTable = null; // Last transaction sequence number that an arbitrator arbitrated on
79 private Map<Long, Transaction> liveTransactionBySequenceNumberTable = null; // live transaction grouped by the sequence number
80 private Map<Pair<Long, Long>, Transaction> liveTransactionByTransactionIdTable = null; // live transaction grouped by the transaction ID
81 private Map<Long, Map<Long, Commit>> liveCommitsTable = null;
82 private Map<IoTString, Commit> liveCommitsByKeyTable = null;
83 private Map<Long, Long> lastCommitSeenSequenceNumberByArbitratorTable = null;
84 private Vector<Long> rejectedSlotList = null; // List of rejected slots that have yet to be sent to the server
85 private List<Transaction> pendingTransactionQueue = null;
86 private List<ArbitrationRound> pendingSendArbitrationRounds = null;
87 private List<Entry> pendingSendArbitrationEntriesToDelete = null;
88 private Map<Transaction, List<Integer>> transactionPartsSent = null;
89 private Map<Long, TransactionStatus> outstandingTransactionStatus = null;
90 private Map<Long, Abort> liveAbortsGeneratedByLocal = null;
91 private Set<Pair<Long, Long>> offlineTransactionsCommittedAndAtServer = null;
92 private Map<Long, Pair<String, Integer>> localCommunicationTable = null;
93 private Map<Long, Long> lastTransactionSeenFromMachineFromServer = null;
94 private Map<Long, Long> lastArbitrationDataLocalSequenceNumberSeenFromArbitrator = null;
97 public Table(String baseurl, String password, long _localMachineId, int listeningPort) {
98 localMachineId = _localMachineId;
99 cloud = new CloudComm(this, baseurl, password, listeningPort);
104 public Table(CloudComm _cloud, long _localMachineId) {
105 localMachineId = _localMachineId;
112 * Init all the stuff needed for for table usage
114 private void init() {
116 // Init helper objects
117 random = new Random();
118 buffer = new SlotBuffer();
121 oldestLiveSlotSequenceNumver = 1;
124 committedKeyValueTable = new HashMap<IoTString, KeyValue>();
125 speculatedKeyValueTable = new HashMap<IoTString, KeyValue>();
126 pendingTransactionSpeculatedKeyValueTable = new HashMap<IoTString, KeyValue>();
127 liveNewKeyTable = new HashMap<IoTString, NewKey>();
128 lastMessageTable = new HashMap<Long, Pair<Long, Liveness>>();
129 rejectedMessageWatchListTable = new HashMap<Long, HashSet<RejectedMessage>>();
130 arbitratorTable = new HashMap<IoTString, Long>();
131 liveAbortTable = new HashMap<Pair<Long, Long>, Abort>();
132 newTransactionParts = new HashMap<Long, Map<Pair<Long, Integer>, TransactionPart>>();
133 newCommitParts = new HashMap<Long, Map<Pair<Long, Integer>, CommitPart>>();
134 lastArbitratedTransactionNumberByArbitratorTable = new HashMap<Long, Long>();
135 liveTransactionBySequenceNumberTable = new HashMap<Long, Transaction>();
136 liveTransactionByTransactionIdTable = new HashMap<Pair<Long, Long>, Transaction>();
137 liveCommitsTable = new HashMap<Long, Map<Long, Commit>>();
138 liveCommitsByKeyTable = new HashMap<IoTString, Commit>();
139 lastCommitSeenSequenceNumberByArbitratorTable = new HashMap<Long, Long>();
140 rejectedSlotList = new Vector<Long>();
141 pendingTransactionQueue = new ArrayList<Transaction>();
142 pendingSendArbitrationEntriesToDelete = new ArrayList<Entry>();
143 transactionPartsSent = new HashMap<Transaction, List<Integer>>();
144 outstandingTransactionStatus = new HashMap<Long, TransactionStatus>();
145 liveAbortsGeneratedByLocal = new HashMap<Long, Abort>();
146 offlineTransactionsCommittedAndAtServer = new HashSet<Pair<Long, Long>>();
147 localCommunicationTable = new HashMap<Long, Pair<String, Integer>>();
148 lastTransactionSeenFromMachineFromServer = new HashMap<Long, Long>();
149 pendingSendArbitrationRounds = new ArrayList<ArbitrationRound>();
150 lastArbitrationDataLocalSequenceNumberSeenFromArbitrator = new HashMap<Long, Long>();
154 numberOfSlots = buffer.capacity();
155 setResizeThreshold();
158 // TODO: delete method
159 public synchronized void printSlots() {
160 long o = buffer.getOldestSeqNum();
161 long n = buffer.getNewestSeqNum();
163 int[] types = new int[10];
169 for (long i = o; i < (n + 1); i++) {
170 Slot s = buffer.getSlot(i);
172 Vector<Entry> entries = s.getEntries();
174 for (Entry e : entries) {
176 int type = e.getType();
177 types[type] = types[type] + 1;
186 for (int i = 0; i < 10; i++) {
187 System.out.println(i + " " + types[i]);
189 System.out.println("Live count: " + livec);
190 System.out.println("Dead count: " + deadc);
191 System.out.println("Old: " + o);
192 System.out.println("New: " + n);
193 System.out.println("Size: " + buffer.size());
194 // System.out.println("Commits: " + liveCommitsTable.size());
195 System.out.println("pendingTrans: " + pendingTransactionQueue.size());
196 System.out.println("Trans Status Out: " + outstandingTransactionStatus.size());
198 for (Long k : lastArbitratedTransactionNumberByArbitratorTable.keySet()) {
199 System.out.println(k + ": " + lastArbitratedTransactionNumberByArbitratorTable.get(k));
203 for (Long a : liveCommitsTable.keySet()) {
204 for (Long b : liveCommitsTable.get(a).keySet()) {
205 for (KeyValue kv : liveCommitsTable.get(a).get(b).getKeyValueUpdateSet()) {
206 System.out.print(kv + " ");
208 System.out.print("|| ");
210 System.out.println();
216 * Initialize the table by inserting a table status as the first entry into the table status
217 * also initialize the crypto stuff.
219 public synchronized void initTable() throws ServerException {
220 cloud.initSecurity();
222 // Create the first insertion into the block chain which is the table status
223 Slot s = new Slot(this, 1, localMachineId);
224 TableStatus status = new TableStatus(s, numberOfSlots);
226 Slot[] array = cloud.putSlot(s, numberOfSlots);
229 array = new Slot[] {s};
230 // update local block chain
231 validateAndUpdate(array, true);
232 } else if (array.length == 1) {
233 // in case we did push the slot BUT we failed to init it
234 validateAndUpdate(array, true);
236 throw new Error("Error on initialization");
241 * Rebuild the table from scratch by pulling the latest block chain from the server.
243 public synchronized void rebuild() throws ServerException {
244 // Just pull the latest slots from the server
245 Slot[] newslots = cloud.getSlots(sequenceNumber + 1);
246 validateAndUpdate(newslots, true);
249 // public String toString() {
250 // String retString = " Committed Table: \n";
251 // retString += "---------------------------\n";
252 // retString += commitedTable.toString();
254 // retString += "\n\n";
256 // retString += " Speculative Table: \n";
257 // retString += "---------------------------\n";
258 // retString += speculativeTable.toString();
263 public synchronized void addLocalCommunication(long arbitrator, String hostName, int portNumber) {
264 localCommunicationTable.put(arbitrator, new Pair<String, Integer>(hostName, portNumber));
267 public synchronized Long getArbitrator(IoTString key) {
268 return arbitratorTable.get(key);
271 public synchronized void close() {
275 public synchronized IoTString getCommitted(IoTString key) {
276 KeyValue kv = committedKeyValueTable.get(key);
279 return kv.getValue();
285 public synchronized IoTString getSpeculative(IoTString key) {
286 KeyValue kv = pendingTransactionSpeculatedKeyValueTable.get(key);
289 kv = speculatedKeyValueTable.get(key);
293 kv = committedKeyValueTable.get(key);
297 return kv.getValue();
303 public synchronized IoTString getCommittedAtomic(IoTString key) {
304 KeyValue kv = committedKeyValueTable.get(key);
306 if (arbitratorTable.get(key) == null) {
307 throw new Error("Key not Found.");
310 // Make sure new key value pair matches the current arbitrator
311 if (!pendingTransactionBuilder.checkArbitrator(arbitratorTable.get(key))) {
312 // TODO: Maybe not throw en error
313 throw new Error("Not all Key Values Match Arbitrator.");
317 pendingTransactionBuilder.addKVGuard(new KeyValue(key, kv.getValue()));
318 return kv.getValue();
320 pendingTransactionBuilder.addKVGuard(new KeyValue(key, null));
325 public synchronized IoTString getSpeculativeAtomic(IoTString key) {
326 if (arbitratorTable.get(key) == null) {
327 throw new Error("Key not Found.");
330 // Make sure new key value pair matches the current arbitrator
331 if (!pendingTransactionBuilder.checkArbitrator(arbitratorTable.get(key))) {
332 // TODO: Maybe not throw en error
333 throw new Error("Not all Key Values Match Arbitrator.");
336 KeyValue kv = pendingTransactionSpeculatedKeyValueTable.get(key);
339 kv = speculatedKeyValueTable.get(key);
343 kv = committedKeyValueTable.get(key);
347 pendingTransactionBuilder.addKVGuard(new KeyValue(key, kv.getValue()));
348 return kv.getValue();
350 pendingTransactionBuilder.addKVGuard(new KeyValue(key, null));
355 public synchronized boolean update() {
357 Slot[] newSlots = cloud.getSlots(sequenceNumber + 1);
358 validateAndUpdate(newSlots, false);
362 updateLiveTransactionsAndStatus();
365 } catch (Exception e) {
366 // e.printStackTrace();
368 for (Long m : localCommunicationTable.keySet()) {
376 public synchronized boolean createNewKey(IoTString keyName, long machineId) throws ServerException {
378 if (arbitratorTable.get(keyName) != null) {
379 // There is already an arbitrator
383 NewKey newKey = new NewKey(null, keyName, machineId);
384 if (sendToServer(newKey)) {
385 // If successfully inserted
391 public synchronized void startTransaction() {
392 // Create a new transaction, invalidates any old pending transactions.
393 pendingTransactionBuilder = new PendingTransaction(localMachineId);
396 public synchronized void addKV(IoTString key, IoTString value) {
398 // Make sure it is a valid key
399 if (arbitratorTable.get(key) == null) {
400 throw new Error("Key not Found.");
403 // Make sure new key value pair matches the current arbitrator
404 if (!pendingTransactionBuilder.checkArbitrator(arbitratorTable.get(key))) {
405 // TODO: Maybe not throw en error
406 throw new Error("Not all Key Values Match Arbitrator.");
409 // Add the key value to this transaction
410 KeyValue kv = new KeyValue(key, value);
411 pendingTransactionBuilder.addKV(kv);
414 public synchronized TransactionStatus commitTransaction() {
416 if (pendingTransactionBuilder.getKVUpdates().size() == 0) {
417 // transaction with no updates will have no effect on the system
418 return new TransactionStatus(TransactionStatus.StatusNoEffect, -1);
421 // Set the local transaction sequence number and increment
422 pendingTransactionBuilder.setClientLocalSequenceNumber(localTransactionSequenceNumber);
423 localTransactionSequenceNumber++;
425 // Create the transaction status
426 TransactionStatus transactionStatus = new TransactionStatus(TransactionStatus.StatusPending, pendingTransactionBuilder.getArbitrator());
428 // Create the new transaction
429 Transaction newTransaction = pendingTransactionBuilder.createTransaction();
430 newTransaction.setTransactionStatus(transactionStatus);
432 if (pendingTransactionBuilder.getArbitrator() != localMachineId) {
433 // Add it to the queue and invalidate the builder for safety
434 pendingTransactionQueue.add(newTransaction);
436 arbitrateOnLocalTransaction(newTransaction);
437 updateLiveStateFromLocal();
440 pendingTransactionBuilder = new PendingTransaction(localMachineId);
444 } catch (ServerException e) {
446 Set<Long> arbitratorTriedAndFailed = new HashSet<Long>();
447 for (Iterator<Transaction> iter = pendingTransactionQueue.iterator(); iter.hasNext(); ) {
448 Transaction transaction = iter.next();
450 if (arbitratorTriedAndFailed.contains(transaction.getArbitrator())) {
451 // Already contacted this client so ignore all attempts to contact this client
452 // to preserve ordering for arbitrator
456 Pair<Boolean, Boolean> sendReturn = sendTransactionToLocal(transaction);
458 if (sendReturn.getFirst()) {
459 // Failed to contact over local
460 arbitratorTriedAndFailed.add(transaction.getArbitrator());
462 // Successful contact or should not contact
464 if (sendReturn.getSecond()) {
472 updateLiveStateFromLocal();
474 return transactionStatus;
478 * Get the machine ID for this client
480 public long getMachineId() {
481 return localMachineId;
485 * Decrement the number of live slots that we currently have
487 public void decrementLiveCount() {
492 * Recalculate the new resize threshold
494 private void setResizeThreshold() {
495 int resizeLower = (int) (RESIZE_THRESHOLD * numberOfSlots);
496 bufferResizeThreshold = resizeLower - 1 + random.nextInt(numberOfSlots - resizeLower);
500 boolean lastInsertedNewKey = false;
502 private boolean sendToServer(NewKey newKey) throws ServerException {
504 boolean fromRetry = false;
507 if (hadPartialSendToServer) {
508 Slot[] newSlots = cloud.getSlots(sequenceNumber + 1);
509 if (newSlots.length == 0) {
511 ThreeTuple<Boolean, Boolean, Slot[]> sendSlotsReturn = sendSlotsToServer(lastSlotAttemptedToSend, lastNewSize, lastIsNewKey);
513 if (sendSlotsReturn.getFirst()) {
514 if (newKey != null) {
515 if (lastInsertedNewKey && (lastNewKey.getKey() == newKey.getKey()) && (lastNewKey.getMachineID() == newKey.getMachineID())) {
520 for (Transaction transaction : lastTransactionPartsSent.keySet()) {
521 transaction.resetServerFailure();
523 // Update which transactions parts still need to be sent
524 transaction.removeSentParts(lastTransactionPartsSent.get(transaction));
526 // Add the transaction status to the outstanding list
527 outstandingTransactionStatus.put(transaction.getSequenceNumber(), transaction.getTransactionStatus());
529 // Update the transaction status
530 transaction.getTransactionStatus().setStatus(TransactionStatus.StatusSentPartial);
532 // Check if all the transaction parts were successfully sent and if so then remove it from pending
533 if (transaction.didSendAllParts()) {
534 transaction.getTransactionStatus().setStatus(TransactionStatus.StatusSentFully);
535 pendingTransactionQueue.remove(transaction);
540 newSlots = sendSlotsReturn.getThird();
542 boolean isInserted = false;
543 for (Slot s : newSlots) {
544 if ((s.getSequenceNumber() == lastSlotAttemptedToSend.getSequenceNumber()) && (s.getMachineID() == localMachineId)) {
550 for (Slot s : newSlots) {
555 // Process each entry in the slot
556 for (Entry entry : s.getEntries()) {
558 if (entry.getType() == Entry.TypeLastMessage) {
559 LastMessage lastMessage = (LastMessage)entry;
560 if ((lastMessage.getMachineID() == localMachineId) && (lastMessage.getSequenceNumber() == lastSlotAttemptedToSend.getSequenceNumber())) {
569 if (newKey != null) {
570 if (lastInsertedNewKey && (lastNewKey.getKey() == newKey.getKey()) && (lastNewKey.getMachineID() == newKey.getMachineID())) {
575 for (Transaction transaction : lastTransactionPartsSent.keySet()) {
576 transaction.resetServerFailure();
578 // Update which transactions parts still need to be sent
579 transaction.removeSentParts(lastTransactionPartsSent.get(transaction));
581 // Add the transaction status to the outstanding list
582 outstandingTransactionStatus.put(transaction.getSequenceNumber(), transaction.getTransactionStatus());
584 // Update the transaction status
585 transaction.getTransactionStatus().setStatus(TransactionStatus.StatusSentPartial);
587 // Check if all the transaction parts were successfully sent and if so then remove it from pending
588 if (transaction.didSendAllParts()) {
589 transaction.getTransactionStatus().setStatus(TransactionStatus.StatusSentFully);
590 pendingTransactionQueue.remove(transaction);
592 transaction.resetServerFailure();
593 // Set the transaction sequence number back to nothing
594 if (!transaction.didSendAPartToServer()) {
595 transaction.setSequenceNumber(-1);
602 for (Transaction transaction : lastTransactionPartsSent.keySet()) {
603 transaction.resetServerFailure();
604 // Set the transaction sequence number back to nothing
605 if (!transaction.didSendAPartToServer()) {
606 transaction.setSequenceNumber(-1);
610 if (sendSlotsReturn.getThird().length != 0) {
611 // insert into the local block chain
612 validateAndUpdate(sendSlotsReturn.getThird(), true);
616 boolean isInserted = false;
617 for (Slot s : newSlots) {
618 if ((s.getSequenceNumber() == lastSlotAttemptedToSend.getSequenceNumber()) && (s.getMachineID() == localMachineId)) {
624 for (Slot s : newSlots) {
629 // Process each entry in the slot
630 for (Entry entry : s.getEntries()) {
632 if (entry.getType() == Entry.TypeLastMessage) {
633 LastMessage lastMessage = (LastMessage)entry;
634 if ((lastMessage.getMachineID() == localMachineId) && (lastMessage.getSequenceNumber() == lastSlotAttemptedToSend.getSequenceNumber())) {
643 if (newKey != null) {
644 if (lastInsertedNewKey && (lastNewKey.getKey() == newKey.getKey()) && (lastNewKey.getMachineID() == newKey.getMachineID())) {
649 for (Transaction transaction : lastTransactionPartsSent.keySet()) {
650 transaction.resetServerFailure();
652 // Update which transactions parts still need to be sent
653 transaction.removeSentParts(lastTransactionPartsSent.get(transaction));
655 // Add the transaction status to the outstanding list
656 outstandingTransactionStatus.put(transaction.getSequenceNumber(), transaction.getTransactionStatus());
658 // Update the transaction status
659 transaction.getTransactionStatus().setStatus(TransactionStatus.StatusSentPartial);
661 // Check if all the transaction parts were successfully sent and if so then remove it from pending
662 if (transaction.didSendAllParts()) {
663 transaction.getTransactionStatus().setStatus(TransactionStatus.StatusSentFully);
664 pendingTransactionQueue.remove(transaction);
666 transaction.resetServerFailure();
667 // Set the transaction sequence number back to nothing
668 if (!transaction.didSendAPartToServer()) {
669 transaction.setSequenceNumber(-1);
674 for (Transaction transaction : lastTransactionPartsSent.keySet()) {
675 transaction.resetServerFailure();
676 // Set the transaction sequence number back to nothing
677 if (!transaction.didSendAPartToServer()) {
678 transaction.setSequenceNumber(-1);
683 // insert into the local block chain
684 validateAndUpdate(newSlots, true);
687 } catch (ServerException e) {
693 // While we have stuff that needs inserting into the block chain
694 while ((pendingTransactionQueue.size() > 0) || (pendingSendArbitrationRounds.size() > 0) || (newKey != null)) {
697 if (hadPartialSendToServer) {
698 throw new Error("Should Be error free");
703 // If there is a new key with same name then end
704 if ((newKey != null) && (arbitratorTable.get(newKey.getKey()) != null)) {
709 Slot slot = new Slot(this, sequenceNumber + 1, localMachineId, buffer.getSlot(sequenceNumber).getHMAC());
711 // Try to fill the slot with data
712 ThreeTuple<Boolean, Integer, Boolean> fillSlotsReturn = fillSlot(slot, false, newKey);
713 boolean needsResize = fillSlotsReturn.getFirst();
714 int newSize = fillSlotsReturn.getSecond();
715 Boolean insertedNewKey = fillSlotsReturn.getThird();
718 // Reset which transaction to send
719 for (Transaction transaction : transactionPartsSent.keySet()) {
720 transaction.resetNextPartToSend();
722 // Set the transaction sequence number back to nothing
723 if (!transaction.didSendAPartToServer() && !transaction.getServerFailure()) {
724 transaction.setSequenceNumber(-1);
728 // Clear the sent data since we are trying again
729 pendingSendArbitrationEntriesToDelete.clear();
730 transactionPartsSent.clear();
732 // We needed a resize so try again
733 fillSlot(slot, true, newKey);
736 lastSlotAttemptedToSend = slot;
737 lastIsNewKey = (newKey != null);
738 lastInsertedNewKey = insertedNewKey;
739 lastNewSize = newSize;
741 lastTransactionPartsSent = new HashMap<Transaction, List<Integer>>(transactionPartsSent);
742 lastPendingSendArbitrationEntriesToDelete = new ArrayList<Entry>(pendingSendArbitrationEntriesToDelete);
745 ThreeTuple<Boolean, Boolean, Slot[]> sendSlotsReturn = sendSlotsToServer(slot, newSize, newKey != null);
747 if (sendSlotsReturn.getFirst()) {
749 // Did insert into the block chain
751 if (insertedNewKey) {
752 // This slot was what was inserted not a previous slot
754 // New Key was successfully inserted into the block chain so dont want to insert it again
758 // Remove the aborts and commit parts that were sent from the pending to send queue
759 for (Iterator<ArbitrationRound> iter = pendingSendArbitrationRounds.iterator(); iter.hasNext(); ) {
760 ArbitrationRound round = iter.next();
761 round.removeParts(pendingSendArbitrationEntriesToDelete);
763 if (round.isDoneSending()) {
764 // Sent all the parts
769 for (Transaction transaction : transactionPartsSent.keySet()) {
770 transaction.resetServerFailure();
772 // Update which transactions parts still need to be sent
773 transaction.removeSentParts(transactionPartsSent.get(transaction));
775 // Add the transaction status to the outstanding list
776 outstandingTransactionStatus.put(transaction.getSequenceNumber(), transaction.getTransactionStatus());
778 // Update the transaction status
779 transaction.getTransactionStatus().setStatus(TransactionStatus.StatusSentPartial);
781 // Check if all the transaction parts were successfully sent and if so then remove it from pending
782 if (transaction.didSendAllParts()) {
783 transaction.getTransactionStatus().setStatus(TransactionStatus.StatusSentFully);
784 pendingTransactionQueue.remove(transaction);
789 // if (!sendSlotsReturn.getSecond()) {
790 // for (Transaction transaction : lastTransactionPartsSent.keySet()) {
791 // transaction.resetServerFailure();
794 // for (Transaction transaction : lastTransactionPartsSent.keySet()) {
795 // transaction.resetServerFailure();
797 // // Update which transactions parts still need to be sent
798 // transaction.removeSentParts(transactionPartsSent.get(transaction));
800 // // Add the transaction status to the outstanding list
801 // outstandingTransactionStatus.put(transaction.getSequenceNumber(), transaction.getTransactionStatus());
803 // // Update the transaction status
804 // transaction.getTransactionStatus().setStatus(TransactionStatus.StatusSentPartial);
806 // // Check if all the transaction parts were successfully sent and if so then remove it from pending
807 // if (transaction.didSendAllParts()) {
808 // transaction.getTransactionStatus().setStatus(TransactionStatus.StatusSentFully);
809 // pendingTransactionQueue.remove(transaction);
811 // for (KeyValue kv : transaction.getKeyValueUpdateSet()) {
812 // System.out.println("Sent: " + kv + " from: " + localMachineId + " Slot:" + lastSlotAttemptedToSend.getSequenceNumber() + " Claimed:" + transaction.getSequenceNumber());
818 // Reset which transaction to send
819 for (Transaction transaction : transactionPartsSent.keySet()) {
820 transaction.resetNextPartToSend();
821 // transaction.resetNextPartToSend();
823 // Set the transaction sequence number back to nothing
824 if (!transaction.didSendAPartToServer() && !transaction.getServerFailure()) {
825 transaction.setSequenceNumber(-1);
830 // Clear the sent data in preparation for next send
831 pendingSendArbitrationEntriesToDelete.clear();
832 transactionPartsSent.clear();
834 if (sendSlotsReturn.getThird().length != 0) {
835 // insert into the local block chain
836 validateAndUpdate(sendSlotsReturn.getThird(), true);
840 } catch (ServerException e) {
842 if (e.getType() != ServerException.TypeInputTimeout) {
843 // e.printStackTrace();
845 // Nothing was able to be sent to the server so just clear these data structures
846 for (Transaction transaction : transactionPartsSent.keySet()) {
847 transaction.resetNextPartToSend();
849 // Set the transaction sequence number back to nothing
850 if (!transaction.didSendAPartToServer() && !transaction.getServerFailure()) {
851 transaction.setSequenceNumber(-1);
855 // There was a partial send to the server
856 hadPartialSendToServer = true;
860 // lastTransactionPartsSent = new HashMap<Transaction, List<Integer>>(transactionPartsSent);
861 // lastPendingSendArbitrationEntriesToDelete = new ArrayList<Entry>(pendingSendArbitrationEntriesToDelete);
864 // Nothing was able to be sent to the server so just clear these data structures
865 for (Transaction transaction : transactionPartsSent.keySet()) {
866 transaction.resetNextPartToSend();
867 transaction.setServerFailure();
871 pendingSendArbitrationEntriesToDelete.clear();
872 transactionPartsSent.clear();
877 return newKey == null;
880 private synchronized boolean updateFromLocal(long machineId) {
881 Pair<String, Integer> localCommunicationInformation = localCommunicationTable.get(machineId);
882 if (localCommunicationInformation == null) {
883 // Cant talk to that device locally so do nothing
887 // Get the size of the send data
888 int sendDataSize = Integer.BYTES + Long.BYTES;
890 Long lastArbitrationDataLocalSequenceNumber = (long) - 1;
891 if (lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(machineId) != null) {
892 lastArbitrationDataLocalSequenceNumber = lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(machineId);
895 byte[] sendData = new byte[sendDataSize];
896 ByteBuffer bbEncode = ByteBuffer.wrap(sendData);
899 bbEncode.putLong(lastArbitrationDataLocalSequenceNumber);
903 byte[] returnData = cloud.sendLocalData(sendData, localCommunicationInformation.getFirst(), localCommunicationInformation.getSecond());
905 if (returnData == null) {
906 // Could not contact server
911 ByteBuffer bbDecode = ByteBuffer.wrap(returnData);
912 int numberOfEntries = bbDecode.getInt();
914 for (int i = 0; i < numberOfEntries; i++) {
915 byte type = bbDecode.get();
916 if (type == Entry.TypeAbort) {
917 Abort abort = (Abort)Abort.decode(null, bbDecode);
919 } else if (type == Entry.TypeCommitPart) {
920 CommitPart commitPart = (CommitPart)CommitPart.decode(null, bbDecode);
921 processEntry(commitPart);
925 updateLiveStateFromLocal();
930 private Pair<Boolean, Boolean> sendTransactionToLocal(Transaction transaction) {
932 // Get the devices local communications
933 Pair<String, Integer> localCommunicationInformation = localCommunicationTable.get(transaction.getArbitrator());
935 if (localCommunicationInformation == null) {
936 // Cant talk to that device locally so do nothing
937 return new Pair<Boolean, Boolean>(true, false);
940 // Get the size of the send data
941 int sendDataSize = Integer.BYTES + Long.BYTES;
942 for (TransactionPart part : transaction.getParts().values()) {
943 sendDataSize += part.getSize();
946 Long lastArbitrationDataLocalSequenceNumber = (long) - 1;
947 if (lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(transaction.getArbitrator()) != null) {
948 lastArbitrationDataLocalSequenceNumber = lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(transaction.getArbitrator());
951 // Make the send data size
952 byte[] sendData = new byte[sendDataSize];
953 ByteBuffer bbEncode = ByteBuffer.wrap(sendData);
956 bbEncode.putLong(lastArbitrationDataLocalSequenceNumber);
957 bbEncode.putInt(transaction.getParts().size());
958 for (TransactionPart part : transaction.getParts().values()) {
959 part.encode(bbEncode);
964 byte[] returnData = cloud.sendLocalData(sendData, localCommunicationInformation.getFirst(), localCommunicationInformation.getSecond());
966 if (returnData == null) {
967 // Could not contact server
968 return new Pair<Boolean, Boolean>(true, false);
972 ByteBuffer bbDecode = ByteBuffer.wrap(returnData);
973 boolean didCommit = bbDecode.get() == 1;
974 boolean couldArbitrate = bbDecode.get() == 1;
975 int numberOfEntries = bbDecode.getInt();
976 boolean foundAbort = false;
978 for (int i = 0; i < numberOfEntries; i++) {
979 byte type = bbDecode.get();
980 if (type == Entry.TypeAbort) {
981 Abort abort = (Abort)Abort.decode(null, bbDecode);
983 if ((abort.getTransactionMachineId() == localMachineId) && (abort.getTransactionClientLocalSequenceNumber() == transaction.getClientLocalSequenceNumber())) {
988 } else if (type == Entry.TypeCommitPart) {
989 CommitPart commitPart = (CommitPart)CommitPart.decode(null, bbDecode);
990 processEntry(commitPart);
994 updateLiveStateFromLocal();
996 if (couldArbitrate) {
997 TransactionStatus status = transaction.getTransactionStatus();
999 status.setStatus(TransactionStatus.StatusCommitted);
1001 status.setStatus(TransactionStatus.StatusAborted);
1004 TransactionStatus status = transaction.getTransactionStatus();
1006 status.setStatus(TransactionStatus.StatusAborted);
1008 status.setStatus(TransactionStatus.StatusCommitted);
1012 return new Pair<Boolean, Boolean>(false, true);
1015 public synchronized byte[] acceptDataFromLocal(byte[] data) {
1018 ByteBuffer bbDecode = ByteBuffer.wrap(data);
1019 long lastArbitratedSequenceNumberSeen = bbDecode.getLong();
1020 int numberOfParts = bbDecode.getInt();
1022 // If we did commit a transaction or not
1023 boolean didCommit = false;
1024 boolean couldArbitrate = false;
1026 if (numberOfParts != 0) {
1028 // decode the transaction
1029 Transaction transaction = new Transaction();
1030 for (int i = 0; i < numberOfParts; i++) {
1032 TransactionPart newPart = (TransactionPart)TransactionPart.decode(null, bbDecode);
1033 transaction.addPartDecode(newPart);
1036 // Arbitrate on transaction and pull relevant return data
1037 Pair<Boolean, Boolean> localArbitrateReturn = arbitrateOnLocalTransaction(transaction);
1038 couldArbitrate = localArbitrateReturn.getFirst();
1039 didCommit = localArbitrateReturn.getSecond();
1041 updateLiveStateFromLocal();
1043 // Transaction was sent to the server so keep track of it to prevent double commit
1044 if (transaction.getSequenceNumber() != -1) {
1045 offlineTransactionsCommittedAndAtServer.add(transaction.getId());
1049 // The data to send back
1050 int returnDataSize = 0;
1051 List<Entry> unseenArbitrations = new ArrayList<Entry>();
1053 // Get the aborts to send back
1054 List<Long> abortLocalSequenceNumbers = new ArrayList<Long >(liveAbortsGeneratedByLocal.keySet());
1055 Collections.sort(abortLocalSequenceNumbers);
1056 for (Long localSequenceNumber : abortLocalSequenceNumbers) {
1057 if (localSequenceNumber <= lastArbitratedSequenceNumberSeen) {
1061 Abort abort = liveAbortsGeneratedByLocal.get(localSequenceNumber);
1062 unseenArbitrations.add(abort);
1063 returnDataSize += abort.getSize();
1066 // Get the commits to send back
1067 Map<Long, Commit> commitForClientTable = liveCommitsTable.get(localMachineId);
1068 if (commitForClientTable != null) {
1069 List<Long> commitLocalSequenceNumbers = new ArrayList<Long>(commitForClientTable.keySet());
1070 Collections.sort(commitLocalSequenceNumbers);
1072 for (Long localSequenceNumber : commitLocalSequenceNumbers) {
1073 Commit commit = commitForClientTable.get(localSequenceNumber);
1075 if (localSequenceNumber <= lastArbitratedSequenceNumberSeen) {
1079 unseenArbitrations.addAll(commit.getParts().values());
1081 for (CommitPart commitPart : commit.getParts().values()) {
1082 returnDataSize += commitPart.getSize();
1087 // Number of arbitration entries to decode
1088 returnDataSize += 2 * Integer.BYTES;
1090 // Boolean of did commit or not
1091 if (numberOfParts != 0) {
1092 returnDataSize += Byte.BYTES;
1095 // Data to send Back
1096 byte[] returnData = new byte[returnDataSize];
1097 ByteBuffer bbEncode = ByteBuffer.wrap(returnData);
1099 if (numberOfParts != 0) {
1101 bbEncode.put((byte)1);
1103 bbEncode.put((byte)0);
1105 if (couldArbitrate) {
1106 bbEncode.put((byte)1);
1108 bbEncode.put((byte)0);
1112 bbEncode.putInt(unseenArbitrations.size());
1113 for (Entry entry : unseenArbitrations) {
1114 entry.encode(bbEncode);
1120 private ThreeTuple<Boolean, Boolean, Slot[]> sendSlotsToServer(Slot slot, int newSize, boolean isNewKey) throws ServerException {
1122 boolean attemptedToSendToServerTmp = attemptedToSendToServer;
1123 attemptedToSendToServer = true;
1125 boolean inserted = false;
1126 boolean lastTryInserted = false;
1128 Slot[] array = cloud.putSlot(slot, newSize);
1129 if (array == null) {
1130 array = new Slot[] {slot};
1131 rejectedSlotList.clear();
1134 if (array.length == 0) {
1135 throw new Error("Server Error: Did not send any slots");
1138 // if (attemptedToSendToServerTmp) {
1139 if (hadPartialSendToServer) {
1141 boolean isInserted = false;
1142 for (Slot s : array) {
1143 if ((s.getSequenceNumber() == slot.getSequenceNumber()) && (s.getMachineID() == localMachineId)) {
1149 for (Slot s : array) {
1154 // Process each entry in the slot
1155 for (Entry entry : s.getEntries()) {
1157 if (entry.getType() == Entry.TypeLastMessage) {
1158 LastMessage lastMessage = (LastMessage)entry;
1160 if ((lastMessage.getMachineID() == localMachineId) && (lastMessage.getSequenceNumber() == slot.getSequenceNumber())) {
1169 rejectedSlotList.add(slot.getSequenceNumber());
1170 lastTryInserted = false;
1172 lastTryInserted = true;
1175 rejectedSlotList.add(slot.getSequenceNumber());
1176 lastTryInserted = false;
1180 return new ThreeTuple<Boolean, Boolean, Slot[]>(inserted, lastTryInserted, array);
1184 * Returns false if a resize was needed
1186 private ThreeTuple<Boolean, Integer, Boolean> fillSlot(Slot slot, boolean resize, NewKey newKeyEntry) {
1188 if (liveSlotCount > bufferResizeThreshold) {
1189 resize = true; //Resize is forced
1193 newSize = (int) (numberOfSlots * RESIZE_MULTIPLE);
1194 TableStatus status = new TableStatus(slot, newSize);
1195 slot.addEntry(status);
1198 // Fill with rejected slots first before doing anything else
1199 doRejectedMessages(slot);
1201 // Do mandatory rescue of entries
1202 ThreeTuple<Boolean, Boolean, Long> mandatoryRescueReturn = doMandatoryResuce(slot, resize);
1204 // Extract working variables
1205 boolean needsResize = mandatoryRescueReturn.getFirst();
1206 boolean seenLiveSlot = mandatoryRescueReturn.getSecond();
1207 long currentRescueSequenceNumber = mandatoryRescueReturn.getThird();
1209 if (needsResize && !resize) {
1210 // We need to resize but we are not resizing so return false
1211 return new ThreeTuple<Boolean, Integer, Boolean>(true, null, null);
1214 boolean inserted = false;
1215 if (newKeyEntry != null) {
1216 newKeyEntry.setSlot(slot);
1217 if (slot.hasSpace(newKeyEntry)) {
1218 slot.addEntry(newKeyEntry);
1223 // Clear the transactions, aborts and commits that were sent previously
1224 transactionPartsSent.clear();
1225 pendingSendArbitrationEntriesToDelete.clear();
1227 for (ArbitrationRound round : pendingSendArbitrationRounds) {
1228 boolean isFull = false;
1229 round.generateParts();
1230 List<Entry> parts = round.getParts();
1232 // Insert pending arbitration data
1233 for (Entry arbitrationData : parts) {
1235 // If it is an abort then we need to set some information
1236 if (arbitrationData instanceof Abort) {
1237 ((Abort)arbitrationData).setSequenceNumber(slot.getSequenceNumber());
1240 if (!slot.hasSpace(arbitrationData)) {
1241 // No space so cant do anything else with these data entries
1246 // Add to this current slot and add it to entries to delete
1247 slot.addEntry(arbitrationData);
1248 pendingSendArbitrationEntriesToDelete.add(arbitrationData);
1256 if (pendingTransactionQueue.size() > 0) {
1258 Transaction transaction = pendingTransactionQueue.get(0);
1260 // Set the transaction sequence number if it has yet to be inserted into the block chain
1261 // if ((!transaction.didSendAPartToServer() && !transaction.getServerFailure()) || (transaction.getSequenceNumber() == -1)) {
1262 // transaction.setSequenceNumber(slot.getSequenceNumber());
1265 if ((!transaction.didSendAPartToServer()) || (transaction.getSequenceNumber() == -1)) {
1266 transaction.setSequenceNumber(slot.getSequenceNumber());
1271 TransactionPart part = transaction.getNextPartToSend();
1274 // Ran out of parts to send for this transaction so move on
1278 if (slot.hasSpace(part)) {
1279 slot.addEntry(part);
1280 List<Integer> partsSent = transactionPartsSent.get(transaction);
1281 if (partsSent == null) {
1282 partsSent = new ArrayList<Integer>();
1283 transactionPartsSent.put(transaction, partsSent);
1285 partsSent.add(part.getPartNumber());
1286 transactionPartsSent.put(transaction, partsSent);
1293 // Fill the remainder of the slot with rescue data
1294 doOptionalRescue(slot, seenLiveSlot, currentRescueSequenceNumber, resize);
1296 return new ThreeTuple<Boolean, Integer, Boolean>(false, newSize, inserted);
1299 private void doRejectedMessages(Slot s) {
1300 if (! rejectedSlotList.isEmpty()) {
1301 /* TODO: We should avoid generating a rejected message entry if
1302 * there is already a sufficient entry in the queue (e.g.,
1303 * equalsto value of true and same sequence number). */
1305 long old_seqn = rejectedSlotList.firstElement();
1306 if (rejectedSlotList.size() > REJECTED_THRESHOLD) {
1307 long new_seqn = rejectedSlotList.lastElement();
1308 RejectedMessage rm = new RejectedMessage(s, s.getSequenceNumber(), localMachineId, old_seqn, new_seqn, false);
1311 long prev_seqn = -1;
1313 /* Go through list of missing messages */
1314 for (; i < rejectedSlotList.size(); i++) {
1315 long curr_seqn = rejectedSlotList.get(i);
1316 Slot s_msg = buffer.getSlot(curr_seqn);
1319 prev_seqn = curr_seqn;
1321 /* Generate rejected message entry for missing messages */
1322 if (prev_seqn != -1) {
1323 RejectedMessage rm = new RejectedMessage(s, s.getSequenceNumber(), localMachineId, old_seqn, prev_seqn, false);
1326 /* Generate rejected message entries for present messages */
1327 for (; i < rejectedSlotList.size(); i++) {
1328 long curr_seqn = rejectedSlotList.get(i);
1329 Slot s_msg = buffer.getSlot(curr_seqn);
1330 long machineid = s_msg.getMachineID();
1331 RejectedMessage rm = new RejectedMessage(s, s.getSequenceNumber(), machineid, curr_seqn, curr_seqn, true);
1338 private ThreeTuple<Boolean, Boolean, Long> doMandatoryResuce(Slot slot, boolean resize) {
1339 long newestSequenceNumber = buffer.getNewestSeqNum();
1340 long oldestSequenceNumber = buffer.getOldestSeqNum();
1341 if (oldestLiveSlotSequenceNumver < oldestSequenceNumber) {
1342 oldestLiveSlotSequenceNumver = oldestSequenceNumber;
1345 long currentSequenceNumber = oldestLiveSlotSequenceNumver;
1346 boolean seenLiveSlot = false;
1347 long firstIfFull = newestSequenceNumber + 1 - numberOfSlots; // smallest seq number in the buffer if it is full
1348 long threshold = firstIfFull + FREE_SLOTS; // we want the buffer to be clear of live entries up to this point
1352 for (; currentSequenceNumber < threshold; currentSequenceNumber++) {
1353 Slot previousSlot = buffer.getSlot(currentSequenceNumber);
1354 // Push slot number forward
1355 if (! seenLiveSlot) {
1356 oldestLiveSlotSequenceNumver = currentSequenceNumber;
1359 if (!previousSlot.isLive()) {
1363 // We have seen a live slot
1364 seenLiveSlot = true;
1366 // Get all the live entries for a slot
1367 Vector<Entry> liveEntries = previousSlot.getLiveEntries(resize);
1369 // Iterate over all the live entries and try to rescue them
1370 for (Entry liveEntry : liveEntries) {
1371 if (slot.hasSpace(liveEntry)) {
1373 // Enough space to rescue the entry
1374 slot.addEntry(liveEntry);
1375 } else if (currentSequenceNumber == firstIfFull) {
1376 //if there's no space but the entry is about to fall off the queue
1377 System.out.println("B"); //?
1378 return new ThreeTuple<Boolean, Boolean, Long>(true, seenLiveSlot, currentSequenceNumber);
1385 return new ThreeTuple<Boolean, Boolean, Long>(false, seenLiveSlot, currentSequenceNumber);
1388 private void doOptionalRescue(Slot s, boolean seenliveslot, long seqn, boolean resize) {
1389 /* now go through live entries from least to greatest sequence number until
1390 * either all live slots added, or the slot doesn't have enough room
1391 * for SKIP_THRESHOLD consecutive entries*/
1393 long newestseqnum = buffer.getNewestSeqNum();
1395 for (; seqn <= newestseqnum; seqn++) {
1396 Slot prevslot = buffer.getSlot(seqn);
1397 //Push slot number forward
1399 oldestLiveSlotSequenceNumver = seqn;
1401 if (!prevslot.isLive())
1403 seenliveslot = true;
1404 Vector<Entry> liveentries = prevslot.getLiveEntries(resize);
1405 for (Entry liveentry : liveentries) {
1406 if (s.hasSpace(liveentry))
1407 s.addEntry(liveentry);
1410 if (skipcount > SKIP_THRESHOLD)
1418 * Checks for malicious activity and updates the local copy of the block chain.
1420 private void validateAndUpdate(Slot[] newSlots, boolean acceptUpdatesToLocal) {
1422 // The cloud communication layer has checked slot HMACs already before decoding
1423 if (newSlots.length == 0) {
1427 // Make sure all slots are newer than the last largest slot this client has seen
1428 long firstSeqNum = newSlots[0].getSequenceNumber();
1429 if (firstSeqNum <= sequenceNumber) {
1430 throw new Error("Server Error: Sent older slots!");
1433 // Create an object that can access both new slots and slots in our local chain
1434 // without committing slots to our local chain
1435 SlotIndexer indexer = new SlotIndexer(newSlots, buffer);
1437 // Check that the HMAC chain is not broken
1438 checkHMACChain(indexer, newSlots);
1440 // Set to keep track of messages from clients
1441 HashSet<Long> machineSet = new HashSet<Long>(lastMessageTable.keySet());
1443 // Process each slots data
1444 for (Slot slot : newSlots) {
1445 processSlot(indexer, slot, acceptUpdatesToLocal, machineSet);
1446 updateExpectedSize();
1449 // If there is a gap, check to see if the server sent us everything.
1450 if (firstSeqNum != (sequenceNumber + 1)) {
1452 // Check the size of the slots that were sent down by the server.
1453 // Can only check the size if there was a gap
1454 checkNumSlots(newSlots.length);
1456 // Since there was a gap every machine must have pushed a slot or must have
1457 // a last message message. If not then the server is hiding slots
1458 if (!machineSet.isEmpty()) {
1459 throw new Error("Missing record for machines: " + machineSet);
1463 // Update the size of our local block chain.
1466 // Commit new to slots to the local block chain.
1467 for (Slot slot : newSlots) {
1469 // Insert this slot into our local block chain copy.
1470 buffer.putSlot(slot);
1472 // Keep track of how many slots are currently live (have live data in them).
1476 // Get the sequence number of the latest slot in the system
1477 sequenceNumber = newSlots[newSlots.length - 1].getSequenceNumber();
1479 updateLiveStateFromServer();
1481 // No Need to remember after we pulled from the server
1482 offlineTransactionsCommittedAndAtServer.clear();
1484 // This is invalidated now
1485 hadPartialSendToServer = false;
1488 private void updateLiveStateFromServer() {
1489 // Process the new transaction parts
1490 processNewTransactionParts();
1492 // Do arbitration on new transactions that were received
1493 arbitrateFromServer();
1495 // Update all the committed keys
1496 boolean didCommitOrSpeculate = updateCommittedTable();
1498 // Delete the transactions that are now dead
1499 updateLiveTransactionsAndStatus();
1502 didCommitOrSpeculate |= updateSpeculativeTable(didCommitOrSpeculate);
1503 updatePendingTransactionSpeculativeTable(didCommitOrSpeculate);
1506 private void updateLiveStateFromLocal() {
1507 // Update all the committed keys
1508 boolean didCommitOrSpeculate = updateCommittedTable();
1510 // Delete the transactions that are now dead
1511 updateLiveTransactionsAndStatus();
1514 didCommitOrSpeculate |= updateSpeculativeTable(didCommitOrSpeculate);
1515 updatePendingTransactionSpeculativeTable(didCommitOrSpeculate);
1518 private void initExpectedSize(long firstSequenceNumber, long numberOfSlots) {
1519 if (didFindTableStatus) {
1522 long prevslots = firstSequenceNumber;
1523 expectedsize = (prevslots < ((long) numberOfSlots)) ? (int) prevslots : numberOfSlots;
1524 currMaxSize = numberOfSlots;
1527 private void updateExpectedSize() {
1529 if (expectedsize > currMaxSize) {
1530 expectedsize = currMaxSize;
1536 * Check the size of the block chain to make sure there are enough slots sent back by the server.
1537 * This is only called when we have a gap between the slots that we have locally and the slots
1538 * sent by the server therefore in the slots sent by the server there will be at least 1 Table
1541 private void checkNumSlots(int numberOfSlots) {
1542 if (numberOfSlots != expectedsize) {
1543 throw new Error("Server Error: Server did not send all slots. Expected: " + expectedsize + " Received:" + numberOfSlots);
1547 private void updateCurrMaxSize(int newmaxsize) {
1548 currMaxSize = newmaxsize;
1553 * Update the size of of the local buffer if it is needed.
1555 private void commitNewMaxSize() {
1556 didFindTableStatus = false;
1558 // Resize the local slot buffer
1559 if (numberOfSlots != currMaxSize) {
1560 buffer.resize((int)currMaxSize);
1563 // Change the number of local slots to the new size
1564 numberOfSlots = (int)currMaxSize;
1566 // Recalculate the resize threshold since the size of the local buffer has changed
1567 setResizeThreshold();
1571 * Process the new transaction parts from this latest round of slots received from the server
1573 private void processNewTransactionParts() {
1575 if (newTransactionParts.size() == 0) {
1576 // Nothing new to process
1580 // Iterate through all the machine Ids that we received new parts for
1581 for (Long machineId : newTransactionParts.keySet()) {
1582 Map<Pair<Long, Integer>, TransactionPart> parts = newTransactionParts.get(machineId);
1584 // Iterate through all the parts for that machine Id
1585 for (Pair<Long, Integer> partId : parts.keySet()) {
1586 TransactionPart part = parts.get(partId);
1588 Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(part.getArbitratorId());
1589 if ((lastTransactionNumber != null) && (lastTransactionNumber >= part.getSequenceNumber())) {
1590 // Set dead the transaction part
1595 // Get the transaction object for that sequence number
1596 Transaction transaction = liveTransactionBySequenceNumberTable.get(part.getSequenceNumber());
1598 if (transaction == null) {
1599 // This is a new transaction that we dont have so make a new one
1600 transaction = new Transaction();
1602 // Insert this new transaction into the live tables
1603 liveTransactionBySequenceNumberTable.put(part.getSequenceNumber(), transaction);
1604 liveTransactionByTransactionIdTable.put(part.getTransactionId(), transaction);
1607 // Add that part to the transaction
1608 transaction.addPartDecode(part);
1612 // Clear all the new transaction parts in preparation for the next time the server sends slots
1613 newTransactionParts.clear();
1617 private long lastSeqNumArbOn = 0;
1619 private void arbitrateFromServer() {
1621 if (liveTransactionBySequenceNumberTable.size() == 0) {
1622 // Nothing to arbitrate on so move on
1626 // Get the transaction sequence numbers and sort from oldest to newest
1627 List<Long> transactionSequenceNumbers = new ArrayList<Long>(liveTransactionBySequenceNumberTable.keySet());
1628 Collections.sort(transactionSequenceNumbers);
1630 // Collection of key value pairs that are
1631 Map<IoTString, KeyValue> speculativeTableTmp = new HashMap<IoTString, KeyValue>();
1633 // The last transaction arbitrated on
1634 long lastTransactionCommitted = -1;
1635 Set<Abort> generatedAborts = new HashSet<Abort>();
1637 for (Long transactionSequenceNumber : transactionSequenceNumbers) {
1638 Transaction transaction = liveTransactionBySequenceNumberTable.get(transactionSequenceNumber);
1642 // Check if this machine arbitrates for this transaction if not then we cant arbitrate this transaction
1643 if (transaction.getArbitrator() != localMachineId) {
1647 if (transactionSequenceNumber < lastSeqNumArbOn) {
1651 if (offlineTransactionsCommittedAndAtServer.contains(transaction.getId())) {
1652 // We have seen this already locally so dont commit again
1657 if (!transaction.isComplete()) {
1658 // Will arbitrate in incorrect order if we continue so just break
1664 // update the largest transaction seen by arbitrator from server
1665 if (lastTransactionSeenFromMachineFromServer.get(transaction.getMachineId()) == null) {
1666 lastTransactionSeenFromMachineFromServer.put(transaction.getMachineId(), transaction.getClientLocalSequenceNumber());
1668 Long lastTransactionSeenFromMachine = lastTransactionSeenFromMachineFromServer.get(transaction.getMachineId());
1669 if (transaction.getClientLocalSequenceNumber() > lastTransactionSeenFromMachine) {
1670 lastTransactionSeenFromMachineFromServer.put(transaction.getMachineId(), transaction.getClientLocalSequenceNumber());
1674 if (transaction.evaluateGuard(committedKeyValueTable, speculativeTableTmp, null)) {
1675 // Guard evaluated as true
1677 // Update the local changes so we can make the commit
1678 for (KeyValue kv : transaction.getKeyValueUpdateSet()) {
1679 speculativeTableTmp.put(kv.getKey(), kv);
1682 // Update what the last transaction committed was for use in batch commit
1683 lastTransactionCommitted = transactionSequenceNumber;
1685 // Guard evaluated was false so create abort
1688 Abort newAbort = new Abort(null,
1689 transaction.getClientLocalSequenceNumber(),
1690 transaction.getSequenceNumber(),
1691 transaction.getMachineId(),
1692 transaction.getArbitrator(),
1693 localArbitrationSequenceNumber);
1694 localArbitrationSequenceNumber++;
1696 generatedAborts.add(newAbort);
1698 // Insert the abort so we can process
1699 processEntry(newAbort);
1702 lastSeqNumArbOn = transactionSequenceNumber;
1704 // liveTransactionBySequenceNumberTable.remove(transactionSequenceNumber);
1707 Commit newCommit = null;
1709 // If there is something to commit
1710 if (speculativeTableTmp.size() != 0) {
1712 // Create the commit and increment the commit sequence number
1713 newCommit = new Commit(localArbitrationSequenceNumber, localMachineId, lastTransactionCommitted);
1714 localArbitrationSequenceNumber++;
1716 // Add all the new keys to the commit
1717 for (KeyValue kv : speculativeTableTmp.values()) {
1718 newCommit.addKV(kv);
1721 // create the commit parts
1722 newCommit.createCommitParts();
1724 // Append all the commit parts to the end of the pending queue waiting for sending to the server
1726 // Insert the commit so we can process it
1727 for (CommitPart commitPart : newCommit.getParts().values()) {
1728 processEntry(commitPart);
1732 if ((newCommit != null) || (generatedAborts.size() > 0)) {
1733 ArbitrationRound arbitrationRound = new ArbitrationRound(newCommit, generatedAborts);
1734 pendingSendArbitrationRounds.add(arbitrationRound);
1736 if (compactArbitrationData()) {
1737 ArbitrationRound newArbitrationRound = pendingSendArbitrationRounds.get(pendingSendArbitrationRounds.size() - 1);
1738 if (newArbitrationRound.getCommit() != null) {
1739 for (CommitPart commitPart : newArbitrationRound.getCommit().getParts().values()) {
1740 processEntry(commitPart);
1747 private Pair<Boolean, Boolean> arbitrateOnLocalTransaction(Transaction transaction) {
1749 // Check if this machine arbitrates for this transaction if not then we cant arbitrate this transaction
1750 if (transaction.getArbitrator() != localMachineId) {
1751 return new Pair<Boolean, Boolean>(false, false);
1754 if (!transaction.isComplete()) {
1755 // Will arbitrate in incorrect order if we continue so just break
1757 return new Pair<Boolean, Boolean>(false, false);
1760 if (transaction.getMachineId() != localMachineId) {
1761 // dont do this check for local transactions
1762 if (lastTransactionSeenFromMachineFromServer.get(transaction.getMachineId()) != null) {
1763 if (lastTransactionSeenFromMachineFromServer.get(transaction.getMachineId()) > transaction.getClientLocalSequenceNumber()) {
1764 // We've have already seen this from the server
1765 return new Pair<Boolean, Boolean>(false, false);
1770 if (transaction.evaluateGuard(committedKeyValueTable, null, null)) {
1771 // Guard evaluated as true
1773 // Create the commit and increment the commit sequence number
1774 Commit newCommit = new Commit(localArbitrationSequenceNumber, localMachineId, -1);
1775 localArbitrationSequenceNumber++;
1777 // Update the local changes so we can make the commit
1778 for (KeyValue kv : transaction.getKeyValueUpdateSet()) {
1779 newCommit.addKV(kv);
1782 // create the commit parts
1783 newCommit.createCommitParts();
1785 // Append all the commit parts to the end of the pending queue waiting for sending to the server
1786 ArbitrationRound arbitrationRound = new ArbitrationRound(newCommit, new HashSet<Abort>());
1787 pendingSendArbitrationRounds.add(arbitrationRound);
1789 if (compactArbitrationData()) {
1790 ArbitrationRound newArbitrationRound = pendingSendArbitrationRounds.get(pendingSendArbitrationRounds.size() - 1);
1791 for (CommitPart commitPart : newArbitrationRound.getCommit().getParts().values()) {
1792 processEntry(commitPart);
1795 // Insert the commit so we can process it
1796 for (CommitPart commitPart : newCommit.getParts().values()) {
1797 processEntry(commitPart);
1801 if (transaction.getMachineId() == localMachineId) {
1802 TransactionStatus status = transaction.getTransactionStatus();
1803 if (status != null) {
1804 status.setStatus(TransactionStatus.StatusCommitted);
1808 updateLiveStateFromLocal();
1809 return new Pair<Boolean, Boolean>(true, true);
1812 if (transaction.getMachineId() == localMachineId) {
1813 // For locally created messages update the status
1815 // Guard evaluated was false so create abort
1816 TransactionStatus status = transaction.getTransactionStatus();
1817 if (status != null) {
1818 status.setStatus(TransactionStatus.StatusAborted);
1821 Set addAbortSet = new HashSet<Abort>();
1825 Abort newAbort = new Abort(null,
1826 transaction.getClientLocalSequenceNumber(),
1828 transaction.getMachineId(),
1829 transaction.getArbitrator(),
1830 localArbitrationSequenceNumber);
1831 localArbitrationSequenceNumber++;
1833 addAbortSet.add(newAbort);
1836 // Append all the commit parts to the end of the pending queue waiting for sending to the server
1837 ArbitrationRound arbitrationRound = new ArbitrationRound(null, addAbortSet);
1838 pendingSendArbitrationRounds.add(arbitrationRound);
1840 if (compactArbitrationData()) {
1841 ArbitrationRound newArbitrationRound = pendingSendArbitrationRounds.get(pendingSendArbitrationRounds.size() - 1);
1842 for (CommitPart commitPart : newArbitrationRound.getCommit().getParts().values()) {
1843 processEntry(commitPart);
1848 updateLiveStateFromLocal();
1849 return new Pair<Boolean, Boolean>(true, false);
1854 * Compacts the arbitration data my merging commits and aggregating aborts so that a single large push of commits can be done instead of many small updates
1856 private boolean compactArbitrationData() {
1858 if (pendingSendArbitrationRounds.size() < 2) {
1859 // Nothing to compact so do nothing
1863 ArbitrationRound lastRound = pendingSendArbitrationRounds.get(pendingSendArbitrationRounds.size() - 1);
1864 if (lastRound.didSendPart()) {
1868 boolean hadCommit = (lastRound.getCommit() == null);
1869 boolean gotNewCommit = false;
1871 int numberToDelete = 1;
1872 while (numberToDelete < pendingSendArbitrationRounds.size()) {
1873 ArbitrationRound round = pendingSendArbitrationRounds.get(pendingSendArbitrationRounds.size() - numberToDelete - 1);
1875 if (round.isFull() || round.didSendPart()) {
1876 // Stop since there is a part that cannot be compacted and we need to compact in order
1880 if (round.getCommit() == null) {
1882 // Try compacting aborts only
1883 int newSize = round.getCurrentSize() + lastRound.getAbortsCount();
1884 if (newSize > ArbitrationRound.MAX_PARTS) {
1885 // Cant compact since it would be too large
1888 lastRound.addAborts(round.getAborts());
1891 // Create a new larger commit
1892 Commit newCommit = Commit.merge(lastRound.getCommit(), round.getCommit(), localArbitrationSequenceNumber);
1893 localArbitrationSequenceNumber++;
1895 // Create the commit parts so that we can count them
1896 newCommit.createCommitParts();
1898 // Calculate the new size of the parts
1899 int newSize = newCommit.getNumberOfParts();
1900 newSize += lastRound.getAbortsCount();
1901 newSize += round.getAbortsCount();
1903 if (newSize > ArbitrationRound.MAX_PARTS) {
1904 // Cant compact since it would be too large
1908 // Set the new compacted part
1909 lastRound.setCommit(newCommit);
1910 lastRound.addAborts(round.getAborts());
1911 gotNewCommit = true;
1917 if (numberToDelete != 1) {
1918 // If there is a compaction
1920 // Delete the previous pieces that are now in the new compacted piece
1921 if (numberToDelete == pendingSendArbitrationRounds.size()) {
1922 pendingSendArbitrationRounds.clear();
1924 for (int i = 0; i < numberToDelete; i++) {
1925 pendingSendArbitrationRounds.remove(pendingSendArbitrationRounds.size() - 1);
1929 // Add the new compacted into the pending to send list
1930 pendingSendArbitrationRounds.add(lastRound);
1932 // Should reinsert into the commit processor
1933 if (hadCommit && gotNewCommit) {
1940 // private boolean compactArbitrationData() {
1945 * Update all the commits and the committed tables, sets dead the dead transactions
1947 private boolean updateCommittedTable() {
1949 if (newCommitParts.size() == 0) {
1950 // Nothing new to process
1954 // Iterate through all the machine Ids that we received new parts for
1955 for (Long machineId : newCommitParts.keySet()) {
1956 Map<Pair<Long, Integer>, CommitPart> parts = newCommitParts.get(machineId);
1958 // Iterate through all the parts for that machine Id
1959 for (Pair<Long, Integer> partId : parts.keySet()) {
1960 CommitPart part = parts.get(partId);
1962 // Get the transaction object for that sequence number
1963 Map<Long, Commit> commitForClientTable = liveCommitsTable.get(part.getMachineId());
1965 if (commitForClientTable == null) {
1966 // This is the first commit from this device
1967 commitForClientTable = new HashMap<Long, Commit>();
1968 liveCommitsTable.put(part.getMachineId(), commitForClientTable);
1971 Commit commit = commitForClientTable.get(part.getSequenceNumber());
1973 if (commit == null) {
1974 // This is a new commit that we dont have so make a new one
1975 commit = new Commit();
1977 // Insert this new commit into the live tables
1978 commitForClientTable.put(part.getSequenceNumber(), commit);
1981 // Add that part to the commit
1982 commit.addPartDecode(part);
1986 // Clear all the new commits parts in preparation for the next time the server sends slots
1987 newCommitParts.clear();
1989 // If we process a new commit keep track of it for future use
1990 boolean didProcessANewCommit = false;
1992 // Process the commits one by one
1993 for (Long arbitratorId : liveCommitsTable.keySet()) {
1995 // Get all the commits for a specific arbitrator
1996 Map<Long, Commit> commitForClientTable = liveCommitsTable.get(arbitratorId);
1998 // Sort the commits in order
1999 List<Long> commitSequenceNumbers = new ArrayList<Long>(commitForClientTable.keySet());
2000 Collections.sort(commitSequenceNumbers);
2002 // Get the last commit seen from this arbitrator
2003 long lastCommitSeenSequenceNumber = -1;
2004 if (lastCommitSeenSequenceNumberByArbitratorTable.get(arbitratorId) != null) {
2005 lastCommitSeenSequenceNumber = lastCommitSeenSequenceNumberByArbitratorTable.get(arbitratorId);
2008 // Go through each new commit one by one
2009 for (int i = 0; i < commitSequenceNumbers.size(); i++) {
2010 Long commitSequenceNumber = commitSequenceNumbers.get(i);
2011 Commit commit = commitForClientTable.get(commitSequenceNumber);
2013 // Special processing if a commit is not complete
2014 if (!commit.isComplete()) {
2015 if (i == (commitSequenceNumbers.size() - 1)) {
2016 // If there is an incomplete commit and this commit is the latest one seen then this commit cannot be processed and there are no other commits
2019 // This is a commit that was already dead but parts of it are still in the block chain (not flushed out yet).
2020 // Delete it and move on
2022 commitForClientTable.remove(commit.getSequenceNumber());
2027 // Update the last transaction that was updated if we can
2028 if (commit.getTransactionSequenceNumber() != -1) {
2029 Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(commit.getMachineId());
2031 // Update the last transaction sequence number that the arbitrator arbitrated on
2032 if ((lastTransactionNumber == null) || (lastTransactionNumber < commit.getTransactionSequenceNumber())) {
2033 lastArbitratedTransactionNumberByArbitratorTable.put(commit.getMachineId(), commit.getTransactionSequenceNumber());
2037 // Update the last arbitration data that we have seen so far
2038 if (lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(commit.getMachineId()) != null) {
2040 long lastArbitrationSequenceNumber = lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(commit.getMachineId());
2041 if (commit.getSequenceNumber() > lastArbitrationSequenceNumber) {
2043 lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.put(commit.getMachineId(), commit.getSequenceNumber());
2046 // Never seen any data from this arbitrator so record the first one
2047 lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.put(commit.getMachineId(), commit.getSequenceNumber());
2050 // We have already seen this commit before so need to do the full processing on this commit
2051 if (commit.getSequenceNumber() <= lastCommitSeenSequenceNumber) {
2053 // Update the last transaction that was updated if we can
2054 if (commit.getTransactionSequenceNumber() != -1) {
2055 Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(commit.getMachineId());
2057 // Update the last transaction sequence number that the arbitrator arbitrated on
2058 if ((lastTransactionNumber == null) || (lastTransactionNumber < commit.getTransactionSequenceNumber())) {
2059 lastArbitratedTransactionNumberByArbitratorTable.put(commit.getMachineId(), commit.getTransactionSequenceNumber());
2066 // If we got here then this is a brand new commit and needs full processing
2068 // Get what commits should be edited, these are the commits that have live values for their keys
2069 Set<Commit> commitsToEdit = new HashSet<Commit>();
2070 for (KeyValue kv : commit.getKeyValueUpdateSet()) {
2071 commitsToEdit.add(liveCommitsByKeyTable.get(kv.getKey()));
2073 commitsToEdit.remove(null); // remove null since it could be in this set
2075 // Update each previous commit that needs to be updated
2076 for (Commit previousCommit : commitsToEdit) {
2078 // Only bother with live commits (TODO: Maybe remove this check)
2079 if (previousCommit.isLive()) {
2081 // Update which keys in the old commits are still live
2082 for (KeyValue kv : commit.getKeyValueUpdateSet()) {
2083 previousCommit.invalidateKey(kv.getKey());
2086 // if the commit is now dead then remove it
2087 if (!previousCommit.isLive()) {
2088 commitForClientTable.remove(previousCommit);
2093 // Update the last seen sequence number from this arbitrator
2094 if (lastCommitSeenSequenceNumberByArbitratorTable.get(commit.getMachineId()) != null) {
2095 if (commit.getSequenceNumber() > lastCommitSeenSequenceNumberByArbitratorTable.get(commit.getMachineId())) {
2096 lastCommitSeenSequenceNumberByArbitratorTable.put(commit.getMachineId(), commit.getSequenceNumber());
2099 lastCommitSeenSequenceNumberByArbitratorTable.put(commit.getMachineId(), commit.getSequenceNumber());
2102 // We processed a new commit that we havent seen before
2103 didProcessANewCommit = true;
2105 // Update the committed table of keys and which commit is using which key
2106 for (KeyValue kv : commit.getKeyValueUpdateSet()) {
2107 committedKeyValueTable.put(kv.getKey(), kv);
2108 liveCommitsByKeyTable.put(kv.getKey(), commit);
2113 return didProcessANewCommit;
2117 * Create the speculative table from transactions that are still live and have come from the cloud
2119 private boolean updateSpeculativeTable(boolean didProcessNewCommits) {
2120 if (liveTransactionBySequenceNumberTable.keySet().size() == 0) {
2121 // There is nothing to speculate on
2125 // Create a list of the transaction sequence numbers and sort them from oldest to newest
2126 List<Long> transactionSequenceNumbersSorted = new ArrayList<Long>(liveTransactionBySequenceNumberTable.keySet());
2127 Collections.sort(transactionSequenceNumbersSorted);
2129 boolean hasGapInTransactionSequenceNumbers = transactionSequenceNumbersSorted.get(0) != oldestTransactionSequenceNumberSpeculatedOn;
2132 if (hasGapInTransactionSequenceNumbers || didProcessNewCommits) {
2133 // If there is a gap in the transaction sequence numbers then there was a commit or an abort of a transaction
2134 // OR there was a new commit (Could be from offline commit) so a redo the speculation from scratch
2136 // Start from scratch
2137 speculatedKeyValueTable.clear();
2138 lastTransactionSequenceNumberSpeculatedOn = -1;
2139 oldestTransactionSequenceNumberSpeculatedOn = -1;
2143 // Remember the front of the transaction list
2144 oldestTransactionSequenceNumberSpeculatedOn = transactionSequenceNumbersSorted.get(0);
2146 // Find where to start arbitration from
2147 int startIndex = transactionSequenceNumbersSorted.indexOf(lastTransactionSequenceNumberSpeculatedOn) + 1;
2149 if (startIndex >= transactionSequenceNumbersSorted.size()) {
2150 // Make sure we are not out of bounds
2151 return false; // did not speculate
2154 Set<Long> incompleteTransactionArbitrator = new HashSet<Long>();
2155 boolean didSkip = true;
2157 for (int i = startIndex; i < transactionSequenceNumbersSorted.size(); i++) {
2158 long transactionSequenceNumber = transactionSequenceNumbersSorted.get(i);
2159 Transaction transaction = liveTransactionBySequenceNumberTable.get(transactionSequenceNumber);
2161 if (!transaction.isComplete()) {
2162 // If there is an incomplete transaction then there is nothing we can do
2163 // add this transactions arbitrator to the list of arbitrators we should ignore
2164 incompleteTransactionArbitrator.add(transaction.getArbitrator());
2169 if (incompleteTransactionArbitrator.contains(transaction.getArbitrator())) {
2173 lastTransactionSequenceNumberSpeculatedOn = transactionSequenceNumber;
2175 if (transaction.evaluateGuard(committedKeyValueTable, speculatedKeyValueTable, null)) {
2176 // Guard evaluated to true so update the speculative table
2177 for (KeyValue kv : transaction.getKeyValueUpdateSet()) {
2178 speculatedKeyValueTable.put(kv.getKey(), kv);
2184 // Since there was a skip we need to redo the speculation next time around
2185 lastTransactionSequenceNumberSpeculatedOn = -1;
2186 oldestTransactionSequenceNumberSpeculatedOn = -1;
2189 // We did some speculation
2194 * Create the pending transaction speculative table from transactions that are still in the pending transaction buffer
2196 private void updatePendingTransactionSpeculativeTable(boolean didProcessNewCommitsOrSpeculate) {
2197 if (pendingTransactionQueue.size() == 0) {
2198 // There is nothing to speculate on
2203 if (didProcessNewCommitsOrSpeculate || (firstPendingTransaction != pendingTransactionQueue.get(0))) {
2204 // need to reset on the pending speculation
2205 lastPendingTransactionSpeculatedOn = null;
2206 firstPendingTransaction = pendingTransactionQueue.get(0);
2207 pendingTransactionSpeculatedKeyValueTable.clear();
2210 // Find where to start arbitration from
2211 int startIndex = pendingTransactionQueue.indexOf(firstPendingTransaction) + 1;
2213 if (startIndex >= pendingTransactionQueue.size()) {
2214 // Make sure we are not out of bounds
2218 for (int i = startIndex; i < pendingTransactionQueue.size(); i++) {
2219 Transaction transaction = pendingTransactionQueue.get(i);
2221 lastPendingTransactionSpeculatedOn = transaction;
2223 if (transaction.evaluateGuard(committedKeyValueTable, speculatedKeyValueTable, pendingTransactionSpeculatedKeyValueTable)) {
2224 // Guard evaluated to true so update the speculative table
2225 for (KeyValue kv : transaction.getKeyValueUpdateSet()) {
2226 pendingTransactionSpeculatedKeyValueTable.put(kv.getKey(), kv);
2233 * Set dead and remove from the live transaction tables the transactions that are dead
2235 private void updateLiveTransactionsAndStatus() {
2237 // Go through each of the transactions
2238 for (Iterator<Map.Entry<Long, Transaction>> iter = liveTransactionBySequenceNumberTable.entrySet().iterator(); iter.hasNext();) {
2239 Transaction transaction = iter.next().getValue();
2241 // Check if the transaction is dead
2242 Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(transaction.getArbitrator());
2243 if ((lastTransactionNumber != null) && (lastTransactionNumber >= transaction.getSequenceNumber())) {
2245 // Set dead the transaction
2246 transaction.setDead();
2248 // Remove the transaction from the live table
2250 liveTransactionByTransactionIdTable.remove(transaction.getId());
2254 // Go through each of the transactions
2255 for (Iterator<Map.Entry<Long, TransactionStatus>> iter = outstandingTransactionStatus.entrySet().iterator(); iter.hasNext();) {
2256 TransactionStatus status = iter.next().getValue();
2258 // Check if the transaction is dead
2259 Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(status.getTransactionArbitrator());
2260 if ((lastTransactionNumber != null) && (lastTransactionNumber >= status.getTransactionSequenceNumber())) {
2263 status.setStatus(TransactionStatus.StatusCommitted);
2272 * Process this slot, entry by entry. Also update the latest message sent by slot
2274 private void processSlot(SlotIndexer indexer, Slot slot, boolean acceptUpdatesToLocal, HashSet<Long> machineSet) {
2276 // Update the last message seen
2277 updateLastMessage(slot.getMachineID(), slot.getSequenceNumber(), slot, acceptUpdatesToLocal, machineSet);
2279 // Process each entry in the slot
2280 for (Entry entry : slot.getEntries()) {
2281 switch (entry.getType()) {
2283 case Entry.TypeCommitPart:
2284 processEntry((CommitPart)entry);
2287 case Entry.TypeAbort:
2288 processEntry((Abort)entry);
2291 case Entry.TypeTransactionPart:
2292 processEntry((TransactionPart)entry);
2295 case Entry.TypeNewKey:
2296 processEntry((NewKey)entry);
2299 case Entry.TypeLastMessage:
2300 processEntry((LastMessage)entry, machineSet);
2303 case Entry.TypeRejectedMessage:
2304 processEntry((RejectedMessage)entry, indexer);
2307 case Entry.TypeTableStatus:
2308 processEntry((TableStatus)entry, slot.getSequenceNumber());
2312 throw new Error("Unrecognized type: " + entry.getType());
2318 * Update the last message that was sent for a machine Id
2320 private void processEntry(LastMessage entry, HashSet<Long> machineSet) {
2321 // Update what the last message received by a machine was
2322 updateLastMessage(entry.getMachineID(), entry.getSequenceNumber(), entry, false, machineSet);
2326 * Add the new key to the arbitrators table and update the set of live new keys (in case of a rescued new key message)
2328 private void processEntry(NewKey entry) {
2330 // Update the arbitrator table with the new key information
2331 arbitratorTable.put(entry.getKey(), entry.getMachineID());
2333 // Update what the latest live new key is
2334 NewKey oldNewKey = liveNewKeyTable.put(entry.getKey(), entry);
2335 if (oldNewKey != null) {
2336 // Delete the old new key messages
2337 oldNewKey.setDead();
2342 * Process new table status entries and set dead the old ones as new ones come in.
2343 * keeps track of the largest and smallest table status seen in this current round
2344 * of updating the local copy of the block chain
2346 private void processEntry(TableStatus entry, long seq) {
2347 int newNumSlots = entry.getMaxSlots();
2348 updateCurrMaxSize(newNumSlots);
2350 initExpectedSize(seq, newNumSlots);
2352 if (liveTableStatus != null) {
2353 // We have a larger table status so the old table status is no longer alive
2354 liveTableStatus.setDead();
2357 // Make this new table status the latest alive table status
2358 liveTableStatus = entry;
2362 * Check old messages to see if there is a block chain violation. Also
2364 private void processEntry(RejectedMessage entry, SlotIndexer indexer) {
2365 long oldSeqNum = entry.getOldSeqNum();
2366 long newSeqNum = entry.getNewSeqNum();
2367 boolean isequal = entry.getEqual();
2368 long machineId = entry.getMachineID();
2369 long seq = entry.getSequenceNumber();
2372 // Check if we have messages that were supposed to be rejected in our local block chain
2373 for (long seqNum = oldSeqNum; seqNum <= newSeqNum; seqNum++) {
2376 Slot slot = indexer.getSlot(seqNum);
2379 // If we have this slot make sure that it was not supposed to be a rejected slot
2381 long slotMachineId = slot.getMachineID();
2382 if (isequal != (slotMachineId == machineId)) {
2383 throw new Error("Server Error: Trying to insert rejected message for slot " + seqNum);
2389 // Create a list of clients to watch until they see this rejected message entry.
2390 HashSet<Long> deviceWatchSet = new HashSet<Long>();
2391 for (Map.Entry<Long, Pair<Long, Liveness>> lastMessageEntry : lastMessageTable.entrySet()) {
2393 // Machine ID for the last message entry
2394 long lastMessageEntryMachineId = lastMessageEntry.getKey();
2396 // We've seen it, don't need to continue to watch. Our next
2397 // message will implicitly acknowledge it.
2398 if (lastMessageEntryMachineId == localMachineId) {
2402 Pair<Long, Liveness> lastMessageValue = lastMessageEntry.getValue();
2403 long entrySequenceNumber = lastMessageValue.getFirst();
2405 if (entrySequenceNumber < seq) {
2407 // Add this rejected message to the set of messages that this machine ID did not see yet
2408 addWatchList(lastMessageEntryMachineId, entry);
2410 // This client did not see this rejected message yet so add it to the watch set to monitor
2411 deviceWatchSet.add(lastMessageEntryMachineId);
2415 if (deviceWatchSet.isEmpty()) {
2416 // This rejected message has been seen by all the clients so
2419 // We need to watch this rejected message
2420 entry.setWatchSet(deviceWatchSet);
2425 * Check if this abort is live, if not then save it so we can kill it later.
2426 * update the last transaction number that was arbitrated on.
2428 private void processEntry(Abort entry) {
2431 if (entry.getTransactionSequenceNumber() != -1) {
2432 // update the transaction status if it was sent to the server
2433 TransactionStatus status = outstandingTransactionStatus.remove(entry.getTransactionSequenceNumber());
2434 if (status != null) {
2435 status.setStatus(TransactionStatus.StatusAborted);
2439 // Abort has not been seen by the client it is for yet so we need to keep track of it
2440 Abort previouslySeenAbort = liveAbortTable.put(entry.getAbortId(), entry);
2441 if (previouslySeenAbort != null) {
2442 previouslySeenAbort.setDead(); // Delete old version of the abort since we got a rescued newer version
2445 if (entry.getTransactionArbitrator() == localMachineId) {
2446 liveAbortsGeneratedByLocal.put(entry.getArbitratorLocalSequenceNumber(), entry);
2449 if ((entry.getSequenceNumber() != -1) && (lastMessageTable.get(entry.getTransactionMachineId()).getFirst() >= entry.getSequenceNumber())) {
2451 // The machine already saw this so it is dead
2453 liveAbortTable.remove(entry.getAbortId());
2455 if (entry.getTransactionArbitrator() == localMachineId) {
2456 liveAbortsGeneratedByLocal.remove(entry.getArbitratorLocalSequenceNumber());
2465 // Update the last arbitration data that we have seen so far
2466 if (lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(entry.getTransactionArbitrator()) != null) {
2468 long lastArbitrationSequenceNumber = lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(entry.getTransactionArbitrator());
2469 if (entry.getSequenceNumber() > lastArbitrationSequenceNumber) {
2471 lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.put(entry.getTransactionArbitrator(), entry.getSequenceNumber());
2474 // Never seen any data from this arbitrator so record the first one
2475 lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.put(entry.getTransactionArbitrator(), entry.getSequenceNumber());
2479 // Set dead a transaction if we can
2480 Transaction transactionToSetDead = liveTransactionByTransactionIdTable.remove(new Pair<Long, Long>(entry.getTransactionMachineId(), entry.getTransactionClientLocalSequenceNumber()));
2481 if (transactionToSetDead != null) {
2482 liveTransactionBySequenceNumberTable.remove(transactionToSetDead.getSequenceNumber());
2485 // Update the last transaction sequence number that the arbitrator arbitrated on
2486 Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(entry.getTransactionArbitrator());
2487 if ((lastTransactionNumber == null) || (lastTransactionNumber < entry.getTransactionSequenceNumber())) {
2490 if (entry.getTransactionSequenceNumber() != -1) {
2491 lastArbitratedTransactionNumberByArbitratorTable.put(entry.getTransactionArbitrator(), entry.getTransactionSequenceNumber());
2497 * Set dead the transaction part if that transaction is dead and keep track of all new parts
2499 private void processEntry(TransactionPart entry) {
2500 // Check if we have already seen this transaction and set it dead OR if it is not alive
2501 Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(entry.getArbitratorId());
2502 if ((lastTransactionNumber != null) && (lastTransactionNumber >= entry.getSequenceNumber())) {
2503 // This transaction is dead, it was already committed or aborted
2508 // This part is still alive
2509 Map<Pair<Long, Integer>, TransactionPart> transactionPart = newTransactionParts.get(entry.getMachineId());
2511 if (transactionPart == null) {
2512 // Dont have a table for this machine Id yet so make one
2513 transactionPart = new HashMap<Pair<Long, Integer>, TransactionPart>();
2514 newTransactionParts.put(entry.getMachineId(), transactionPart);
2517 // Update the part and set dead ones we have already seen (got a rescued version)
2518 TransactionPart previouslySeenPart = transactionPart.put(entry.getPartId(), entry);
2519 if (previouslySeenPart != null) {
2520 previouslySeenPart.setDead();
2525 * Process new commit entries and save them for future use. Delete duplicates
2527 private void processEntry(CommitPart entry) {
2530 // Update the last transaction that was updated if we can
2531 if (entry.getTransactionSequenceNumber() != -1) {
2532 Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(entry.getMachineId());
2534 // Update the last transaction sequence number that the arbitrator arbitrated on
2535 if ((lastTransactionNumber == null) || (lastTransactionNumber < entry.getTransactionSequenceNumber())) {
2536 lastArbitratedTransactionNumberByArbitratorTable.put(entry.getMachineId(), entry.getTransactionSequenceNumber());
2543 Map<Pair<Long, Integer>, CommitPart> commitPart = newCommitParts.get(entry.getMachineId());
2545 if (commitPart == null) {
2546 // Don't have a table for this machine Id yet so make one
2547 commitPart = new HashMap<Pair<Long, Integer>, CommitPart>();
2548 newCommitParts.put(entry.getMachineId(), commitPart);
2551 // Update the part and set dead ones we have already seen (got a rescued version)
2552 CommitPart previouslySeenPart = commitPart.put(entry.getPartId(), entry);
2553 if (previouslySeenPart != null) {
2554 previouslySeenPart.setDead();
2559 * Update the last message seen table. Update and set dead the appropriate RejectedMessages as clients see them.
2560 * Updates the live aborts, removes those that are dead and sets them dead.
2561 * Check that the last message seen is correct and that there is no mismatch of our own last message or that
2562 * other clients have not had a rollback on the last message.
2564 private void updateLastMessage(long machineId, long seqNum, Liveness liveness, boolean acceptUpdatesToLocal, HashSet<Long> machineSet) {
2566 // We have seen this machine ID
2567 machineSet.remove(machineId);
2569 // Get the set of rejected messages that this machine Id is has not seen yet
2570 HashSet<RejectedMessage> watchset = rejectedMessageWatchListTable.get(machineId);
2572 // If there is a rejected message that this machine Id has not seen yet
2573 if (watchset != null) {
2575 // Go through each rejected message that this machine Id has not seen yet
2576 for (Iterator<RejectedMessage> rmit = watchset.iterator(); rmit.hasNext(); ) {
2578 RejectedMessage rm = rmit.next();
2580 // If this machine Id has seen this rejected message...
2581 if (rm.getSequenceNumber() <= seqNum) {
2583 // Remove it from our watchlist
2586 // Decrement machines that need to see this notification
2587 rm.removeWatcher(machineId);
2592 // Set dead the abort
2593 for (Iterator<Map.Entry<Pair<Long, Long>, Abort>> i = liveAbortTable.entrySet().iterator(); i.hasNext();) {
2594 Abort abort = i.next().getValue();
2596 if ((abort.getTransactionMachineId() == machineId) && (abort.getSequenceNumber() <= seqNum)) {
2600 if (abort.getTransactionArbitrator() == localMachineId) {
2601 liveAbortsGeneratedByLocal.remove(abort.getArbitratorLocalSequenceNumber());
2608 if (machineId == localMachineId) {
2609 // Our own messages are immediately dead.
2610 if (liveness instanceof LastMessage) {
2611 ((LastMessage)liveness).setDead();
2612 } else if (liveness instanceof Slot) {
2613 ((Slot)liveness).setDead();
2615 throw new Error("Unrecognized type");
2619 // Get the old last message for this device
2620 Pair<Long, Liveness> lastMessageEntry = lastMessageTable.put(machineId, new Pair<Long, Liveness>(seqNum, liveness));
2621 if (lastMessageEntry == null) {
2622 // If no last message then there is nothing else to process
2626 long lastMessageSeqNum = lastMessageEntry.getFirst();
2627 Liveness lastEntry = lastMessageEntry.getSecond();
2629 // If it is not our machine Id since we already set ours to dead
2630 if (machineId != localMachineId) {
2631 if (lastEntry instanceof LastMessage) {
2632 ((LastMessage)lastEntry).setDead();
2633 } else if (lastEntry instanceof Slot) {
2634 ((Slot)lastEntry).setDead();
2636 throw new Error("Unrecognized type");
2640 // Make sure the server is not playing any games
2641 if (machineId == localMachineId) {
2643 if (hadPartialSendToServer) {
2644 // We were not making any updates and we had a machine mismatch
2645 if (lastMessageSeqNum > seqNum && !acceptUpdatesToLocal) {
2646 throw new Error("Server Error: Mismatch on local machine sequence number, needed at least: " + lastMessageSeqNum + " got: " + seqNum);
2650 // We were not making any updates and we had a machine mismatch
2651 if (lastMessageSeqNum != seqNum && !acceptUpdatesToLocal) {
2652 throw new Error("Server Error: Mismatch on local machine sequence number, needed: " + lastMessageSeqNum + " got: " + seqNum);
2656 if (lastMessageSeqNum > seqNum) {
2657 throw new Error("Server Error: Rollback on remote machine sequence number");
2663 * Add a rejected message entry to the watch set to keep track of which clients have seen that
2664 * rejected message entry and which have not.
2666 private void addWatchList(long machineId, RejectedMessage entry) {
2667 HashSet<RejectedMessage> entries = rejectedMessageWatchListTable.get(machineId);
2668 if (entries == null) {
2669 // There is no set for this machine ID yet so create one
2670 entries = new HashSet<RejectedMessage>();
2671 rejectedMessageWatchListTable.put(machineId, entries);
2677 * Check if the HMAC chain is not violated
2679 private void checkHMACChain(SlotIndexer indexer, Slot[] newSlots) {
2680 for (int i = 0; i < newSlots.length; i++) {
2681 Slot currSlot = newSlots[i];
2682 Slot prevSlot = indexer.getSlot(currSlot.getSequenceNumber() - 1);
2683 if (prevSlot != null &&
2684 !Arrays.equals(prevSlot.getHMAC(), currSlot.getPrevHMAC()))
2685 throw new Error("Server Error: Invalid HMAC Chain" + currSlot + " " + prevSlot);