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 = 2; // Number of slots that should be kept free // 10
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];
174 for (long i = o; i < (n + 1); i++) {
175 Slot s = buffer.getSlot(i);
182 Vector<Entry> entries = s.getEntries();
184 for (Entry e : entries) {
186 int type = e.getType();
190 RejectedMessage rej = (RejectedMessage)e;
193 System.out.println(rej.getMachineID());
197 types[type] = types[type] + 1;
206 for (int i = 0; i < 10; i++) {
207 System.out.println(i + " " + types[i]);
209 System.out.println("Live count: " + livec);
210 System.out.println("Live Slot count: " + liveslo);
212 System.out.println("Dead count: " + deadc);
213 System.out.println("Old: " + o);
214 System.out.println("New: " + n);
215 System.out.println("Size: " + buffer.size());
216 // System.out.println("Commits: " + liveCommitsTable.size());
217 System.out.println("pendingTrans: " + pendingTransactionQueue.size());
218 System.out.println("Trans Status Out: " + outstandingTransactionStatus.size());
220 for (Long k : lastArbitratedTransactionNumberByArbitratorTable.keySet()) {
221 System.out.println(k + ": " + lastArbitratedTransactionNumberByArbitratorTable.get(k));
225 for (Long a : liveCommitsTable.keySet()) {
226 for (Long b : liveCommitsTable.get(a).keySet()) {
227 for (KeyValue kv : liveCommitsTable.get(a).get(b).getKeyValueUpdateSet()) {
228 System.out.print(kv + " ");
230 System.out.print("|| ");
232 System.out.println();
238 * Initialize the table by inserting a table status as the first entry into the table status
239 * also initialize the crypto stuff.
241 public synchronized void initTable() throws ServerException {
242 cloud.initSecurity();
244 // Create the first insertion into the block chain which is the table status
245 Slot s = new Slot(this, 1, localMachineId);
246 TableStatus status = new TableStatus(s, numberOfSlots);
248 Slot[] array = cloud.putSlot(s, numberOfSlots);
251 array = new Slot[] {s};
252 // update local block chain
253 validateAndUpdate(array, true);
254 } else if (array.length == 1) {
255 // in case we did push the slot BUT we failed to init it
256 validateAndUpdate(array, true);
258 throw new Error("Error on initialization");
263 * Rebuild the table from scratch by pulling the latest block chain from the server.
265 public synchronized void rebuild() throws ServerException {
266 // Just pull the latest slots from the server
267 Slot[] newslots = cloud.getSlots(sequenceNumber + 1);
268 validateAndUpdate(newslots, true);
270 updateLiveTransactionsAndStatus();
274 // public String toString() {
275 // String retString = " Committed Table: \n";
276 // retString += "---------------------------\n";
277 // retString += commitedTable.toString();
279 // retString += "\n\n";
281 // retString += " Speculative Table: \n";
282 // retString += "---------------------------\n";
283 // retString += speculativeTable.toString();
288 public synchronized void addLocalCommunication(long arbitrator, String hostName, int portNumber) {
289 localCommunicationTable.put(arbitrator, new Pair<String, Integer>(hostName, portNumber));
292 public synchronized Long getArbitrator(IoTString key) {
293 return arbitratorTable.get(key);
296 public synchronized void close() {
300 public synchronized IoTString getCommitted(IoTString key) {
301 KeyValue kv = committedKeyValueTable.get(key);
304 return kv.getValue();
310 public synchronized IoTString getSpeculative(IoTString key) {
311 KeyValue kv = pendingTransactionSpeculatedKeyValueTable.get(key);
314 kv = speculatedKeyValueTable.get(key);
318 kv = committedKeyValueTable.get(key);
322 return kv.getValue();
328 public synchronized IoTString getCommittedAtomic(IoTString key) {
329 KeyValue kv = committedKeyValueTable.get(key);
331 if (arbitratorTable.get(key) == null) {
332 throw new Error("Key not Found.");
335 // Make sure new key value pair matches the current arbitrator
336 if (!pendingTransactionBuilder.checkArbitrator(arbitratorTable.get(key))) {
337 // TODO: Maybe not throw en error
338 throw new Error("Not all Key Values Match Arbitrator.");
342 pendingTransactionBuilder.addKVGuard(new KeyValue(key, kv.getValue()));
343 return kv.getValue();
345 pendingTransactionBuilder.addKVGuard(new KeyValue(key, null));
350 public synchronized IoTString getSpeculativeAtomic(IoTString key) {
351 if (arbitratorTable.get(key) == null) {
352 throw new Error("Key not Found.");
355 // Make sure new key value pair matches the current arbitrator
356 if (!pendingTransactionBuilder.checkArbitrator(arbitratorTable.get(key))) {
357 // TODO: Maybe not throw en error
358 throw new Error("Not all Key Values Match Arbitrator.");
361 KeyValue kv = pendingTransactionSpeculatedKeyValueTable.get(key);
364 kv = speculatedKeyValueTable.get(key);
368 kv = committedKeyValueTable.get(key);
372 pendingTransactionBuilder.addKVGuard(new KeyValue(key, kv.getValue()));
373 return kv.getValue();
375 pendingTransactionBuilder.addKVGuard(new KeyValue(key, null));
380 public synchronized boolean update() {
382 Slot[] newSlots = cloud.getSlots(sequenceNumber + 1);
383 validateAndUpdate(newSlots, false);
387 updateLiveTransactionsAndStatus();
390 } catch (Exception e) {
391 // e.printStackTrace();
393 for (Long m : localCommunicationTable.keySet()) {
401 public synchronized boolean createNewKey(IoTString keyName, long machineId) throws ServerException {
403 if (arbitratorTable.get(keyName) != null) {
404 // There is already an arbitrator
408 NewKey newKey = new NewKey(null, keyName, machineId);
410 if (sendToServer(newKey)) {
411 // If successfully inserted
417 public synchronized void startTransaction() {
418 // Create a new transaction, invalidates any old pending transactions.
419 pendingTransactionBuilder = new PendingTransaction(localMachineId);
422 public synchronized void addKV(IoTString key, IoTString value) {
424 // Make sure it is a valid key
425 if (arbitratorTable.get(key) == null) {
426 throw new Error("Key not Found.");
429 // Make sure new key value pair matches the current arbitrator
430 if (!pendingTransactionBuilder.checkArbitrator(arbitratorTable.get(key))) {
431 // TODO: Maybe not throw en error
432 throw new Error("Not all Key Values Match Arbitrator.");
435 // Add the key value to this transaction
436 KeyValue kv = new KeyValue(key, value);
437 pendingTransactionBuilder.addKV(kv);
440 public synchronized TransactionStatus commitTransaction() {
442 if (pendingTransactionBuilder.getKVUpdates().size() == 0) {
443 // transaction with no updates will have no effect on the system
444 return new TransactionStatus(TransactionStatus.StatusNoEffect, -1);
447 // Set the local transaction sequence number and increment
448 pendingTransactionBuilder.setClientLocalSequenceNumber(localTransactionSequenceNumber);
449 localTransactionSequenceNumber++;
451 // Create the transaction status
452 TransactionStatus transactionStatus = new TransactionStatus(TransactionStatus.StatusPending, pendingTransactionBuilder.getArbitrator());
454 // Create the new transaction
455 Transaction newTransaction = pendingTransactionBuilder.createTransaction();
456 newTransaction.setTransactionStatus(transactionStatus);
458 if (pendingTransactionBuilder.getArbitrator() != localMachineId) {
459 // Add it to the queue and invalidate the builder for safety
460 pendingTransactionQueue.add(newTransaction);
462 arbitrateOnLocalTransaction(newTransaction);
463 updateLiveStateFromLocal();
466 pendingTransactionBuilder = new PendingTransaction(localMachineId);
470 } catch (ServerException e) {
472 Set<Long> arbitratorTriedAndFailed = new HashSet<Long>();
473 for (Iterator<Transaction> iter = pendingTransactionQueue.iterator(); iter.hasNext(); ) {
474 Transaction transaction = iter.next();
476 if (arbitratorTriedAndFailed.contains(transaction.getArbitrator())) {
477 // Already contacted this client so ignore all attempts to contact this client
478 // to preserve ordering for arbitrator
482 Pair<Boolean, Boolean> sendReturn = sendTransactionToLocal(transaction);
484 if (sendReturn.getFirst()) {
485 // Failed to contact over local
486 arbitratorTriedAndFailed.add(transaction.getArbitrator());
488 // Successful contact or should not contact
490 if (sendReturn.getSecond()) {
498 updateLiveStateFromLocal();
500 return transactionStatus;
504 * Get the machine ID for this client
506 public long getMachineId() {
507 return localMachineId;
511 * Decrement the number of live slots that we currently have
513 public void decrementLiveCount() {
518 * Recalculate the new resize threshold
520 private void setResizeThreshold() {
521 int resizeLower = (int) (RESIZE_THRESHOLD * numberOfSlots);
522 bufferResizeThreshold = resizeLower - 1 + random.nextInt(numberOfSlots - resizeLower);
526 boolean lastInsertedNewKey = false;
528 private boolean sendToServer(NewKey newKey) throws ServerException {
530 boolean fromRetry = false;
533 if (hadPartialSendToServer) {
534 Slot[] newSlots = cloud.getSlots(sequenceNumber + 1);
535 if (newSlots.length == 0) {
537 ThreeTuple<Boolean, Boolean, Slot[]> sendSlotsReturn = sendSlotsToServer(lastSlotAttemptedToSend, lastNewSize, lastIsNewKey);
539 if (sendSlotsReturn.getFirst()) {
540 if (newKey != null) {
541 if (lastInsertedNewKey && (lastNewKey.getKey() == newKey.getKey()) && (lastNewKey.getMachineID() == newKey.getMachineID())) {
546 for (Transaction transaction : lastTransactionPartsSent.keySet()) {
547 transaction.resetServerFailure();
549 // Update which transactions parts still need to be sent
550 transaction.removeSentParts(lastTransactionPartsSent.get(transaction));
552 // Add the transaction status to the outstanding list
553 outstandingTransactionStatus.put(transaction.getSequenceNumber(), transaction.getTransactionStatus());
555 // Update the transaction status
556 transaction.getTransactionStatus().setStatus(TransactionStatus.StatusSentPartial);
558 // Check if all the transaction parts were successfully sent and if so then remove it from pending
559 if (transaction.didSendAllParts()) {
560 transaction.getTransactionStatus().setStatus(TransactionStatus.StatusSentFully);
561 pendingTransactionQueue.remove(transaction);
566 newSlots = sendSlotsReturn.getThird();
568 boolean isInserted = false;
569 for (Slot s : newSlots) {
570 if ((s.getSequenceNumber() == lastSlotAttemptedToSend.getSequenceNumber()) && (s.getMachineID() == localMachineId)) {
576 for (Slot s : newSlots) {
581 // Process each entry in the slot
582 for (Entry entry : s.getEntries()) {
584 if (entry.getType() == Entry.TypeLastMessage) {
585 LastMessage lastMessage = (LastMessage)entry;
586 if ((lastMessage.getMachineID() == localMachineId) && (lastMessage.getSequenceNumber() == lastSlotAttemptedToSend.getSequenceNumber())) {
595 if (newKey != null) {
596 if (lastInsertedNewKey && (lastNewKey.getKey() == newKey.getKey()) && (lastNewKey.getMachineID() == newKey.getMachineID())) {
601 for (Transaction transaction : lastTransactionPartsSent.keySet()) {
602 transaction.resetServerFailure();
604 // Update which transactions parts still need to be sent
605 transaction.removeSentParts(lastTransactionPartsSent.get(transaction));
607 // Add the transaction status to the outstanding list
608 outstandingTransactionStatus.put(transaction.getSequenceNumber(), transaction.getTransactionStatus());
610 // Update the transaction status
611 transaction.getTransactionStatus().setStatus(TransactionStatus.StatusSentPartial);
613 // Check if all the transaction parts were successfully sent and if so then remove it from pending
614 if (transaction.didSendAllParts()) {
615 transaction.getTransactionStatus().setStatus(TransactionStatus.StatusSentFully);
616 pendingTransactionQueue.remove(transaction);
618 transaction.resetServerFailure();
619 // Set the transaction sequence number back to nothing
620 if (!transaction.didSendAPartToServer()) {
621 transaction.setSequenceNumber(-1);
628 for (Transaction transaction : lastTransactionPartsSent.keySet()) {
629 transaction.resetServerFailure();
630 // Set the transaction sequence number back to nothing
631 if (!transaction.didSendAPartToServer()) {
632 transaction.setSequenceNumber(-1);
636 if (sendSlotsReturn.getThird().length != 0) {
637 // insert into the local block chain
638 validateAndUpdate(sendSlotsReturn.getThird(), true);
642 boolean isInserted = false;
643 for (Slot s : newSlots) {
644 if ((s.getSequenceNumber() == lastSlotAttemptedToSend.getSequenceNumber()) && (s.getMachineID() == localMachineId)) {
650 for (Slot s : newSlots) {
655 // Process each entry in the slot
656 for (Entry entry : s.getEntries()) {
658 if (entry.getType() == Entry.TypeLastMessage) {
659 LastMessage lastMessage = (LastMessage)entry;
660 if ((lastMessage.getMachineID() == localMachineId) && (lastMessage.getSequenceNumber() == lastSlotAttemptedToSend.getSequenceNumber())) {
669 if (newKey != null) {
670 if (lastInsertedNewKey && (lastNewKey.getKey() == newKey.getKey()) && (lastNewKey.getMachineID() == newKey.getMachineID())) {
675 for (Transaction transaction : lastTransactionPartsSent.keySet()) {
676 transaction.resetServerFailure();
678 // Update which transactions parts still need to be sent
679 transaction.removeSentParts(lastTransactionPartsSent.get(transaction));
681 // Add the transaction status to the outstanding list
682 outstandingTransactionStatus.put(transaction.getSequenceNumber(), transaction.getTransactionStatus());
684 // Update the transaction status
685 transaction.getTransactionStatus().setStatus(TransactionStatus.StatusSentPartial);
687 // Check if all the transaction parts were successfully sent and if so then remove it from pending
688 if (transaction.didSendAllParts()) {
689 transaction.getTransactionStatus().setStatus(TransactionStatus.StatusSentFully);
690 pendingTransactionQueue.remove(transaction);
692 transaction.resetServerFailure();
693 // Set the transaction sequence number back to nothing
694 if (!transaction.didSendAPartToServer()) {
695 transaction.setSequenceNumber(-1);
700 for (Transaction transaction : lastTransactionPartsSent.keySet()) {
701 transaction.resetServerFailure();
702 // Set the transaction sequence number back to nothing
703 if (!transaction.didSendAPartToServer()) {
704 transaction.setSequenceNumber(-1);
709 // insert into the local block chain
710 validateAndUpdate(newSlots, true);
713 } catch (ServerException e) {
720 // While we have stuff that needs inserting into the block chain
721 while ((pendingTransactionQueue.size() > 0) || (pendingSendArbitrationRounds.size() > 0) || (newKey != null)) {
726 if (hadPartialSendToServer) {
727 throw new Error("Should Be error free");
732 // If there is a new key with same name then end
733 if ((newKey != null) && (arbitratorTable.get(newKey.getKey()) != null)) {
738 Slot slot = new Slot(this, sequenceNumber + 1, localMachineId, buffer.getSlot(sequenceNumber).getHMAC());
740 // Try to fill the slot with data
741 ThreeTuple<Boolean, Integer, Boolean> fillSlotsReturn = fillSlot(slot, false, newKey);
742 boolean needsResize = fillSlotsReturn.getFirst();
743 int newSize = fillSlotsReturn.getSecond();
744 Boolean insertedNewKey = fillSlotsReturn.getThird();
747 // Reset which transaction to send
748 for (Transaction transaction : transactionPartsSent.keySet()) {
749 transaction.resetNextPartToSend();
751 // Set the transaction sequence number back to nothing
752 if (!transaction.didSendAPartToServer() && !transaction.getServerFailure()) {
753 transaction.setSequenceNumber(-1);
757 // Clear the sent data since we are trying again
758 pendingSendArbitrationEntriesToDelete.clear();
759 transactionPartsSent.clear();
761 // We needed a resize so try again
762 fillSlot(slot, true, newKey);
765 lastSlotAttemptedToSend = slot;
766 lastIsNewKey = (newKey != null);
767 lastInsertedNewKey = insertedNewKey;
768 lastNewSize = newSize;
770 lastTransactionPartsSent = new HashMap<Transaction, List<Integer>>(transactionPartsSent);
771 lastPendingSendArbitrationEntriesToDelete = new ArrayList<Entry>(pendingSendArbitrationEntriesToDelete);
774 ThreeTuple<Boolean, Boolean, Slot[]> sendSlotsReturn = sendSlotsToServer(slot, newSize, newKey != null);
776 if (sendSlotsReturn.getFirst()) {
778 // Did insert into the block chain
780 if (insertedNewKey) {
781 // This slot was what was inserted not a previous slot
783 // New Key was successfully inserted into the block chain so dont want to insert it again
787 // Remove the aborts and commit parts that were sent from the pending to send queue
788 for (Iterator<ArbitrationRound> iter = pendingSendArbitrationRounds.iterator(); iter.hasNext(); ) {
789 ArbitrationRound round = iter.next();
790 round.removeParts(pendingSendArbitrationEntriesToDelete);
792 if (round.isDoneSending()) {
793 // Sent all the parts
798 for (Transaction transaction : transactionPartsSent.keySet()) {
799 transaction.resetServerFailure();
801 // Update which transactions parts still need to be sent
802 transaction.removeSentParts(transactionPartsSent.get(transaction));
804 // Add the transaction status to the outstanding list
805 outstandingTransactionStatus.put(transaction.getSequenceNumber(), transaction.getTransactionStatus());
807 // Update the transaction status
808 transaction.getTransactionStatus().setStatus(TransactionStatus.StatusSentPartial);
810 // Check if all the transaction parts were successfully sent and if so then remove it from pending
811 if (transaction.didSendAllParts()) {
812 transaction.getTransactionStatus().setStatus(TransactionStatus.StatusSentFully);
813 pendingTransactionQueue.remove(transaction);
818 // if (!sendSlotsReturn.getSecond()) {
819 // for (Transaction transaction : lastTransactionPartsSent.keySet()) {
820 // transaction.resetServerFailure();
823 // for (Transaction transaction : lastTransactionPartsSent.keySet()) {
824 // transaction.resetServerFailure();
826 // // Update which transactions parts still need to be sent
827 // transaction.removeSentParts(transactionPartsSent.get(transaction));
829 // // Add the transaction status to the outstanding list
830 // outstandingTransactionStatus.put(transaction.getSequenceNumber(), transaction.getTransactionStatus());
832 // // Update the transaction status
833 // transaction.getTransactionStatus().setStatus(TransactionStatus.StatusSentPartial);
835 // // Check if all the transaction parts were successfully sent and if so then remove it from pending
836 // if (transaction.didSendAllParts()) {
837 // transaction.getTransactionStatus().setStatus(TransactionStatus.StatusSentFully);
838 // pendingTransactionQueue.remove(transaction);
840 // for (KeyValue kv : transaction.getKeyValueUpdateSet()) {
841 // System.out.println("Sent: " + kv + " from: " + localMachineId + " Slot:" + lastSlotAttemptedToSend.getSequenceNumber() + " Claimed:" + transaction.getSequenceNumber());
847 // Reset which transaction to send
848 for (Transaction transaction : transactionPartsSent.keySet()) {
849 transaction.resetNextPartToSend();
850 // transaction.resetNextPartToSend();
852 // Set the transaction sequence number back to nothing
853 if (!transaction.didSendAPartToServer() && !transaction.getServerFailure()) {
854 transaction.setSequenceNumber(-1);
859 // Clear the sent data in preparation for next send
860 pendingSendArbitrationEntriesToDelete.clear();
861 transactionPartsSent.clear();
863 if (sendSlotsReturn.getThird().length != 0) {
864 // insert into the local block chain
865 validateAndUpdate(sendSlotsReturn.getThird(), true);
869 } catch (ServerException e) {
871 if (e.getType() != ServerException.TypeInputTimeout) {
872 // e.printStackTrace();
874 // Nothing was able to be sent to the server so just clear these data structures
875 for (Transaction transaction : transactionPartsSent.keySet()) {
876 transaction.resetNextPartToSend();
878 // Set the transaction sequence number back to nothing
879 if (!transaction.didSendAPartToServer() && !transaction.getServerFailure()) {
880 transaction.setSequenceNumber(-1);
884 // There was a partial send to the server
885 hadPartialSendToServer = true;
889 // lastTransactionPartsSent = new HashMap<Transaction, List<Integer>>(transactionPartsSent);
890 // lastPendingSendArbitrationEntriesToDelete = new ArrayList<Entry>(pendingSendArbitrationEntriesToDelete);
893 // Nothing was able to be sent to the server so just clear these data structures
894 for (Transaction transaction : transactionPartsSent.keySet()) {
895 transaction.resetNextPartToSend();
896 transaction.setServerFailure();
900 pendingSendArbitrationEntriesToDelete.clear();
901 transactionPartsSent.clear();
906 return newKey == null;
909 private synchronized boolean updateFromLocal(long machineId) {
910 Pair<String, Integer> localCommunicationInformation = localCommunicationTable.get(machineId);
911 if (localCommunicationInformation == null) {
912 // Cant talk to that device locally so do nothing
916 // Get the size of the send data
917 int sendDataSize = Integer.BYTES + Long.BYTES;
919 Long lastArbitrationDataLocalSequenceNumber = (long) - 1;
920 if (lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(machineId) != null) {
921 lastArbitrationDataLocalSequenceNumber = lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(machineId);
924 byte[] sendData = new byte[sendDataSize];
925 ByteBuffer bbEncode = ByteBuffer.wrap(sendData);
928 bbEncode.putLong(lastArbitrationDataLocalSequenceNumber);
932 byte[] returnData = cloud.sendLocalData(sendData, localCommunicationInformation.getFirst(), localCommunicationInformation.getSecond());
934 if (returnData == null) {
935 // Could not contact server
940 ByteBuffer bbDecode = ByteBuffer.wrap(returnData);
941 int numberOfEntries = bbDecode.getInt();
943 for (int i = 0; i < numberOfEntries; i++) {
944 byte type = bbDecode.get();
945 if (type == Entry.TypeAbort) {
946 Abort abort = (Abort)Abort.decode(null, bbDecode);
948 } else if (type == Entry.TypeCommitPart) {
949 CommitPart commitPart = (CommitPart)CommitPart.decode(null, bbDecode);
950 processEntry(commitPart);
954 updateLiveStateFromLocal();
959 private Pair<Boolean, Boolean> sendTransactionToLocal(Transaction transaction) {
961 // Get the devices local communications
962 Pair<String, Integer> localCommunicationInformation = localCommunicationTable.get(transaction.getArbitrator());
964 if (localCommunicationInformation == null) {
965 // Cant talk to that device locally so do nothing
966 return new Pair<Boolean, Boolean>(true, false);
969 // Get the size of the send data
970 int sendDataSize = Integer.BYTES + Long.BYTES;
971 for (TransactionPart part : transaction.getParts().values()) {
972 sendDataSize += part.getSize();
975 Long lastArbitrationDataLocalSequenceNumber = (long) - 1;
976 if (lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(transaction.getArbitrator()) != null) {
977 lastArbitrationDataLocalSequenceNumber = lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(transaction.getArbitrator());
980 // Make the send data size
981 byte[] sendData = new byte[sendDataSize];
982 ByteBuffer bbEncode = ByteBuffer.wrap(sendData);
985 bbEncode.putLong(lastArbitrationDataLocalSequenceNumber);
986 bbEncode.putInt(transaction.getParts().size());
987 for (TransactionPart part : transaction.getParts().values()) {
988 part.encode(bbEncode);
993 byte[] returnData = cloud.sendLocalData(sendData, localCommunicationInformation.getFirst(), localCommunicationInformation.getSecond());
995 if (returnData == null) {
996 // Could not contact server
997 return new Pair<Boolean, Boolean>(true, false);
1001 ByteBuffer bbDecode = ByteBuffer.wrap(returnData);
1002 boolean didCommit = bbDecode.get() == 1;
1003 boolean couldArbitrate = bbDecode.get() == 1;
1004 int numberOfEntries = bbDecode.getInt();
1005 boolean foundAbort = false;
1007 for (int i = 0; i < numberOfEntries; i++) {
1008 byte type = bbDecode.get();
1009 if (type == Entry.TypeAbort) {
1010 Abort abort = (Abort)Abort.decode(null, bbDecode);
1012 if ((abort.getTransactionMachineId() == localMachineId) && (abort.getTransactionClientLocalSequenceNumber() == transaction.getClientLocalSequenceNumber())) {
1016 processEntry(abort);
1017 } else if (type == Entry.TypeCommitPart) {
1018 CommitPart commitPart = (CommitPart)CommitPart.decode(null, bbDecode);
1019 processEntry(commitPart);
1023 updateLiveStateFromLocal();
1025 if (couldArbitrate) {
1026 TransactionStatus status = transaction.getTransactionStatus();
1028 status.setStatus(TransactionStatus.StatusCommitted);
1030 status.setStatus(TransactionStatus.StatusAborted);
1033 TransactionStatus status = transaction.getTransactionStatus();
1035 status.setStatus(TransactionStatus.StatusAborted);
1037 status.setStatus(TransactionStatus.StatusCommitted);
1041 return new Pair<Boolean, Boolean>(false, true);
1044 public synchronized byte[] acceptDataFromLocal(byte[] data) {
1047 ByteBuffer bbDecode = ByteBuffer.wrap(data);
1048 long lastArbitratedSequenceNumberSeen = bbDecode.getLong();
1049 int numberOfParts = bbDecode.getInt();
1051 // If we did commit a transaction or not
1052 boolean didCommit = false;
1053 boolean couldArbitrate = false;
1055 if (numberOfParts != 0) {
1057 // decode the transaction
1058 Transaction transaction = new Transaction();
1059 for (int i = 0; i < numberOfParts; i++) {
1061 TransactionPart newPart = (TransactionPart)TransactionPart.decode(null, bbDecode);
1062 transaction.addPartDecode(newPart);
1065 // Arbitrate on transaction and pull relevant return data
1066 Pair<Boolean, Boolean> localArbitrateReturn = arbitrateOnLocalTransaction(transaction);
1067 couldArbitrate = localArbitrateReturn.getFirst();
1068 didCommit = localArbitrateReturn.getSecond();
1070 updateLiveStateFromLocal();
1072 // Transaction was sent to the server so keep track of it to prevent double commit
1073 if (transaction.getSequenceNumber() != -1) {
1074 offlineTransactionsCommittedAndAtServer.add(transaction.getId());
1078 // The data to send back
1079 int returnDataSize = 0;
1080 List<Entry> unseenArbitrations = new ArrayList<Entry>();
1082 // Get the aborts to send back
1083 List<Long> abortLocalSequenceNumbers = new ArrayList<Long >(liveAbortsGeneratedByLocal.keySet());
1084 Collections.sort(abortLocalSequenceNumbers);
1085 for (Long localSequenceNumber : abortLocalSequenceNumbers) {
1086 if (localSequenceNumber <= lastArbitratedSequenceNumberSeen) {
1090 Abort abort = liveAbortsGeneratedByLocal.get(localSequenceNumber);
1091 unseenArbitrations.add(abort);
1092 returnDataSize += abort.getSize();
1095 // Get the commits to send back
1096 Map<Long, Commit> commitForClientTable = liveCommitsTable.get(localMachineId);
1097 if (commitForClientTable != null) {
1098 List<Long> commitLocalSequenceNumbers = new ArrayList<Long>(commitForClientTable.keySet());
1099 Collections.sort(commitLocalSequenceNumbers);
1101 for (Long localSequenceNumber : commitLocalSequenceNumbers) {
1102 Commit commit = commitForClientTable.get(localSequenceNumber);
1104 if (localSequenceNumber <= lastArbitratedSequenceNumberSeen) {
1108 unseenArbitrations.addAll(commit.getParts().values());
1110 for (CommitPart commitPart : commit.getParts().values()) {
1111 returnDataSize += commitPart.getSize();
1116 // Number of arbitration entries to decode
1117 returnDataSize += 2 * Integer.BYTES;
1119 // Boolean of did commit or not
1120 if (numberOfParts != 0) {
1121 returnDataSize += Byte.BYTES;
1124 // Data to send Back
1125 byte[] returnData = new byte[returnDataSize];
1126 ByteBuffer bbEncode = ByteBuffer.wrap(returnData);
1128 if (numberOfParts != 0) {
1130 bbEncode.put((byte)1);
1132 bbEncode.put((byte)0);
1134 if (couldArbitrate) {
1135 bbEncode.put((byte)1);
1137 bbEncode.put((byte)0);
1141 bbEncode.putInt(unseenArbitrations.size());
1142 for (Entry entry : unseenArbitrations) {
1143 entry.encode(bbEncode);
1149 private ThreeTuple<Boolean, Boolean, Slot[]> sendSlotsToServer(Slot slot, int newSize, boolean isNewKey) throws ServerException {
1151 boolean attemptedToSendToServerTmp = attemptedToSendToServer;
1152 attemptedToSendToServer = true;
1154 boolean inserted = false;
1155 boolean lastTryInserted = false;
1157 Slot[] array = cloud.putSlot(slot, newSize);
1158 if (array == null) {
1159 array = new Slot[] {slot};
1160 rejectedSlotList.clear();
1163 if (array.length == 0) {
1164 throw new Error("Server Error: Did not send any slots");
1167 // if (attemptedToSendToServerTmp) {
1168 if (hadPartialSendToServer) {
1170 boolean isInserted = false;
1171 for (Slot s : array) {
1172 if ((s.getSequenceNumber() == slot.getSequenceNumber()) && (s.getMachineID() == localMachineId)) {
1178 for (Slot s : array) {
1183 // Process each entry in the slot
1184 for (Entry entry : s.getEntries()) {
1186 if (entry.getType() == Entry.TypeLastMessage) {
1187 LastMessage lastMessage = (LastMessage)entry;
1189 if ((lastMessage.getMachineID() == localMachineId) && (lastMessage.getSequenceNumber() == slot.getSequenceNumber())) {
1198 rejectedSlotList.add(slot.getSequenceNumber());
1199 lastTryInserted = false;
1201 lastTryInserted = true;
1204 rejectedSlotList.add(slot.getSequenceNumber());
1205 lastTryInserted = false;
1209 return new ThreeTuple<Boolean, Boolean, Slot[]>(inserted, lastTryInserted, array);
1213 * Returns false if a resize was needed
1215 private ThreeTuple<Boolean, Integer, Boolean> fillSlot(Slot slot, boolean resize, NewKey newKeyEntry) {
1219 if (liveSlotCount > bufferResizeThreshold) {
1220 resize = true; //Resize is forced
1225 newSize = (int) (numberOfSlots * RESIZE_MULTIPLE);
1226 TableStatus status = new TableStatus(slot, newSize);
1227 slot.addEntry(status);
1230 // Fill with rejected slots first before doing anything else
1231 doRejectedMessages(slot);
1233 // Do mandatory rescue of entries
1234 ThreeTuple<Boolean, Boolean, Long> mandatoryRescueReturn = doMandatoryResuce(slot, resize);
1236 // Extract working variables
1237 boolean needsResize = mandatoryRescueReturn.getFirst();
1238 boolean seenLiveSlot = mandatoryRescueReturn.getSecond();
1239 long currentRescueSequenceNumber = mandatoryRescueReturn.getThird();
1241 if (needsResize && !resize) {
1242 // We need to resize but we are not resizing so return false
1243 return new ThreeTuple<Boolean, Integer, Boolean>(true, null, null);
1246 boolean inserted = false;
1247 if (newKeyEntry != null) {
1248 newKeyEntry.setSlot(slot);
1249 if (slot.hasSpace(newKeyEntry)) {
1251 slot.addEntry(newKeyEntry);
1256 // Clear the transactions, aborts and commits that were sent previously
1257 transactionPartsSent.clear();
1258 pendingSendArbitrationEntriesToDelete.clear();
1260 for (ArbitrationRound round : pendingSendArbitrationRounds) {
1261 boolean isFull = false;
1262 round.generateParts();
1263 List<Entry> parts = round.getParts();
1265 // Insert pending arbitration data
1266 for (Entry arbitrationData : parts) {
1268 // If it is an abort then we need to set some information
1269 if (arbitrationData instanceof Abort) {
1270 ((Abort)arbitrationData).setSequenceNumber(slot.getSequenceNumber());
1273 if (!slot.hasSpace(arbitrationData)) {
1274 // No space so cant do anything else with these data entries
1279 // Add to this current slot and add it to entries to delete
1280 slot.addEntry(arbitrationData);
1281 pendingSendArbitrationEntriesToDelete.add(arbitrationData);
1289 if (pendingTransactionQueue.size() > 0) {
1291 Transaction transaction = pendingTransactionQueue.get(0);
1293 // Set the transaction sequence number if it has yet to be inserted into the block chain
1294 // if ((!transaction.didSendAPartToServer() && !transaction.getServerFailure()) || (transaction.getSequenceNumber() == -1)) {
1295 // transaction.setSequenceNumber(slot.getSequenceNumber());
1298 if ((!transaction.didSendAPartToServer()) || (transaction.getSequenceNumber() == -1)) {
1299 transaction.setSequenceNumber(slot.getSequenceNumber());
1304 TransactionPart part = transaction.getNextPartToSend();
1307 // Ran out of parts to send for this transaction so move on
1311 if (slot.hasSpace(part)) {
1312 slot.addEntry(part);
1313 List<Integer> partsSent = transactionPartsSent.get(transaction);
1314 if (partsSent == null) {
1315 partsSent = new ArrayList<Integer>();
1316 transactionPartsSent.put(transaction, partsSent);
1318 partsSent.add(part.getPartNumber());
1319 transactionPartsSent.put(transaction, partsSent);
1326 // Fill the remainder of the slot with rescue data
1327 doOptionalRescue(slot, seenLiveSlot, currentRescueSequenceNumber, resize);
1329 return new ThreeTuple<Boolean, Integer, Boolean>(false, newSize, inserted);
1332 private void doRejectedMessages(Slot s) {
1333 if (! rejectedSlotList.isEmpty()) {
1334 /* TODO: We should avoid generating a rejected message entry if
1335 * there is already a sufficient entry in the queue (e.g.,
1336 * equalsto value of true and same sequence number). */
1338 long old_seqn = rejectedSlotList.firstElement();
1339 if (rejectedSlotList.size() > REJECTED_THRESHOLD) {
1340 long new_seqn = rejectedSlotList.lastElement();
1341 RejectedMessage rm = new RejectedMessage(s, s.getSequenceNumber(), localMachineId, old_seqn, new_seqn, false);
1344 long prev_seqn = -1;
1346 /* Go through list of missing messages */
1347 for (; i < rejectedSlotList.size(); i++) {
1348 long curr_seqn = rejectedSlotList.get(i);
1349 Slot s_msg = buffer.getSlot(curr_seqn);
1352 prev_seqn = curr_seqn;
1354 /* Generate rejected message entry for missing messages */
1355 if (prev_seqn != -1) {
1356 RejectedMessage rm = new RejectedMessage(s, s.getSequenceNumber(), localMachineId, old_seqn, prev_seqn, false);
1359 /* Generate rejected message entries for present messages */
1360 for (; i < rejectedSlotList.size(); i++) {
1361 long curr_seqn = rejectedSlotList.get(i);
1362 Slot s_msg = buffer.getSlot(curr_seqn);
1363 long machineid = s_msg.getMachineID();
1364 RejectedMessage rm = new RejectedMessage(s, s.getSequenceNumber(), machineid, curr_seqn, curr_seqn, true);
1371 private ThreeTuple<Boolean, Boolean, Long> doMandatoryResuce(Slot slot, boolean resize) {
1372 long newestSequenceNumber = buffer.getNewestSeqNum();
1373 long oldestSequenceNumber = buffer.getOldestSeqNum();
1374 if (oldestLiveSlotSequenceNumver < oldestSequenceNumber) {
1375 oldestLiveSlotSequenceNumver = oldestSequenceNumber;
1378 long currentSequenceNumber = oldestLiveSlotSequenceNumver;
1379 boolean seenLiveSlot = false;
1380 long firstIfFull = newestSequenceNumber + 1 - numberOfSlots; // smallest seq number in the buffer if it is full
1381 long threshold = firstIfFull + FREE_SLOTS; // we want the buffer to be clear of live entries up to this point
1385 for (; currentSequenceNumber < threshold; currentSequenceNumber++) {
1386 Slot previousSlot = buffer.getSlot(currentSequenceNumber);
1387 // Push slot number forward
1388 if (! seenLiveSlot) {
1389 oldestLiveSlotSequenceNumver = currentSequenceNumber;
1392 if (!previousSlot.isLive()) {
1396 // We have seen a live slot
1397 seenLiveSlot = true;
1399 // Get all the live entries for a slot
1400 Vector<Entry> liveEntries = previousSlot.getLiveEntries(resize);
1402 // Iterate over all the live entries and try to rescue them
1403 for (Entry liveEntry : liveEntries) {
1404 if (slot.hasSpace(liveEntry)) {
1406 // Enough space to rescue the entry
1407 slot.addEntry(liveEntry);
1408 } else if (currentSequenceNumber == firstIfFull) {
1409 //if there's no space but the entry is about to fall off the queue
1410 System.out.println("B"); //?
1411 return new ThreeTuple<Boolean, Boolean, Long>(true, seenLiveSlot, currentSequenceNumber);
1418 return new ThreeTuple<Boolean, Boolean, Long>(false, seenLiveSlot, currentSequenceNumber);
1421 private void doOptionalRescue(Slot s, boolean seenliveslot, long seqn, boolean resize) {
1422 /* now go through live entries from least to greatest sequence number until
1423 * either all live slots added, or the slot doesn't have enough room
1424 * for SKIP_THRESHOLD consecutive entries*/
1426 long newestseqnum = buffer.getNewestSeqNum();
1428 for (; seqn <= newestseqnum; seqn++) {
1429 Slot prevslot = buffer.getSlot(seqn);
1430 //Push slot number forward
1432 oldestLiveSlotSequenceNumver = seqn;
1434 if (!prevslot.isLive())
1436 seenliveslot = true;
1437 Vector<Entry> liveentries = prevslot.getLiveEntries(resize);
1438 for (Entry liveentry : liveentries) {
1439 if (s.hasSpace(liveentry))
1440 s.addEntry(liveentry);
1443 if (skipcount > SKIP_THRESHOLD)
1451 * Checks for malicious activity and updates the local copy of the block chain.
1453 private void validateAndUpdate(Slot[] newSlots, boolean acceptUpdatesToLocal) {
1455 // The cloud communication layer has checked slot HMACs already before decoding
1456 if (newSlots.length == 0) {
1460 // Make sure all slots are newer than the last largest slot this client has seen
1461 long firstSeqNum = newSlots[0].getSequenceNumber();
1462 if (firstSeqNum <= sequenceNumber) {
1463 throw new Error("Server Error: Sent older slots!");
1466 // Create an object that can access both new slots and slots in our local chain
1467 // without committing slots to our local chain
1468 SlotIndexer indexer = new SlotIndexer(newSlots, buffer);
1470 // Check that the HMAC chain is not broken
1471 checkHMACChain(indexer, newSlots);
1473 // Set to keep track of messages from clients
1474 HashSet<Long> machineSet = new HashSet<Long>(lastMessageTable.keySet());
1476 // Process each slots data
1477 for (Slot slot : newSlots) {
1478 processSlot(indexer, slot, acceptUpdatesToLocal, machineSet);
1480 updateExpectedSize();
1483 // If there is a gap, check to see if the server sent us everything.
1484 if (firstSeqNum != (sequenceNumber + 1)) {
1486 // Check the size of the slots that were sent down by the server.
1487 // Can only check the size if there was a gap
1488 checkNumSlots(newSlots.length);
1490 // Since there was a gap every machine must have pushed a slot or must have
1491 // a last message message. If not then the server is hiding slots
1492 if (!machineSet.isEmpty()) {
1493 throw new Error("Missing record for machines: " + machineSet);
1497 // Update the size of our local block chain.
1500 // Commit new to slots to the local block chain.
1501 for (Slot slot : newSlots) {
1503 // Insert this slot into our local block chain copy.
1504 buffer.putSlot(slot);
1506 // Keep track of how many slots are currently live (have live data in them).
1510 // Get the sequence number of the latest slot in the system
1511 sequenceNumber = newSlots[newSlots.length - 1].getSequenceNumber();
1513 updateLiveStateFromServer();
1515 // No Need to remember after we pulled from the server
1516 offlineTransactionsCommittedAndAtServer.clear();
1518 // This is invalidated now
1519 hadPartialSendToServer = false;
1522 private void updateLiveStateFromServer() {
1523 // Process the new transaction parts
1524 processNewTransactionParts();
1526 // Do arbitration on new transactions that were received
1527 arbitrateFromServer();
1529 // Update all the committed keys
1530 boolean didCommitOrSpeculate = updateCommittedTable();
1532 // Delete the transactions that are now dead
1533 updateLiveTransactionsAndStatus();
1536 didCommitOrSpeculate |= updateSpeculativeTable(didCommitOrSpeculate);
1537 updatePendingTransactionSpeculativeTable(didCommitOrSpeculate);
1540 private void updateLiveStateFromLocal() {
1541 // Update all the committed keys
1542 boolean didCommitOrSpeculate = updateCommittedTable();
1544 // Delete the transactions that are now dead
1545 updateLiveTransactionsAndStatus();
1548 didCommitOrSpeculate |= updateSpeculativeTable(didCommitOrSpeculate);
1549 updatePendingTransactionSpeculativeTable(didCommitOrSpeculate);
1552 private void initExpectedSize(long firstSequenceNumber, long numberOfSlots) {
1553 // if (didFindTableStatus) {
1556 long prevslots = firstSequenceNumber;
1559 if (didFindTableStatus) {
1560 // expectedsize = (prevslots < ((long) numberOfSlots)) ? (int) prevslots : expectedsize;
1561 // System.out.println("Here2: " + expectedsize + " " + numberOfSlots + " " + prevslots);
1564 expectedsize = (prevslots < ((long) numberOfSlots)) ? (int) prevslots : numberOfSlots;
1565 // System.out.println("Here: " + expectedsize);
1568 // System.out.println(numberOfSlots);
1570 didFindTableStatus = true;
1571 currMaxSize = numberOfSlots;
1574 private void updateExpectedSize() {
1577 if (expectedsize > currMaxSize) {
1578 expectedsize = currMaxSize;
1584 * Check the size of the block chain to make sure there are enough slots sent back by the server.
1585 * This is only called when we have a gap between the slots that we have locally and the slots
1586 * sent by the server therefore in the slots sent by the server there will be at least 1 Table
1589 private void checkNumSlots(int numberOfSlots) {
1590 if (numberOfSlots != expectedsize) {
1591 throw new Error("Server Error: Server did not send all slots. Expected: " + expectedsize + " Received:" + numberOfSlots);
1595 private void updateCurrMaxSize(int newmaxsize) {
1596 currMaxSize = newmaxsize;
1601 * Update the size of of the local buffer if it is needed.
1603 private void commitNewMaxSize() {
1604 didFindTableStatus = false;
1606 // Resize the local slot buffer
1607 if (numberOfSlots != currMaxSize) {
1608 buffer.resize((int)currMaxSize);
1611 // Change the number of local slots to the new size
1612 numberOfSlots = (int)currMaxSize;
1615 // Recalculate the resize threshold since the size of the local buffer has changed
1616 setResizeThreshold();
1620 * Process the new transaction parts from this latest round of slots received from the server
1622 private void processNewTransactionParts() {
1624 if (newTransactionParts.size() == 0) {
1625 // Nothing new to process
1629 // Iterate through all the machine Ids that we received new parts for
1630 for (Long machineId : newTransactionParts.keySet()) {
1631 Map<Pair<Long, Integer>, TransactionPart> parts = newTransactionParts.get(machineId);
1633 // Iterate through all the parts for that machine Id
1634 for (Pair<Long, Integer> partId : parts.keySet()) {
1635 TransactionPart part = parts.get(partId);
1637 Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(part.getArbitratorId());
1638 if ((lastTransactionNumber != null) && (lastTransactionNumber >= part.getSequenceNumber())) {
1639 // Set dead the transaction part
1644 // Get the transaction object for that sequence number
1645 Transaction transaction = liveTransactionBySequenceNumberTable.get(part.getSequenceNumber());
1647 if (transaction == null) {
1648 // This is a new transaction that we dont have so make a new one
1649 transaction = new Transaction();
1651 // Insert this new transaction into the live tables
1652 liveTransactionBySequenceNumberTable.put(part.getSequenceNumber(), transaction);
1653 liveTransactionByTransactionIdTable.put(part.getTransactionId(), transaction);
1656 // Add that part to the transaction
1657 transaction.addPartDecode(part);
1661 // Clear all the new transaction parts in preparation for the next time the server sends slots
1662 newTransactionParts.clear();
1666 private long lastSeqNumArbOn = 0;
1668 private void arbitrateFromServer() {
1670 if (liveTransactionBySequenceNumberTable.size() == 0) {
1671 // Nothing to arbitrate on so move on
1675 // Get the transaction sequence numbers and sort from oldest to newest
1676 List<Long> transactionSequenceNumbers = new ArrayList<Long>(liveTransactionBySequenceNumberTable.keySet());
1677 Collections.sort(transactionSequenceNumbers);
1679 // Collection of key value pairs that are
1680 Map<IoTString, KeyValue> speculativeTableTmp = new HashMap<IoTString, KeyValue>();
1682 // The last transaction arbitrated on
1683 long lastTransactionCommitted = -1;
1684 Set<Abort> generatedAborts = new HashSet<Abort>();
1686 for (Long transactionSequenceNumber : transactionSequenceNumbers) {
1687 Transaction transaction = liveTransactionBySequenceNumberTable.get(transactionSequenceNumber);
1691 // Check if this machine arbitrates for this transaction if not then we cant arbitrate this transaction
1692 if (transaction.getArbitrator() != localMachineId) {
1696 if (transactionSequenceNumber < lastSeqNumArbOn) {
1700 if (offlineTransactionsCommittedAndAtServer.contains(transaction.getId())) {
1701 // We have seen this already locally so dont commit again
1706 if (!transaction.isComplete()) {
1707 // Will arbitrate in incorrect order if we continue so just break
1713 // update the largest transaction seen by arbitrator from server
1714 if (lastTransactionSeenFromMachineFromServer.get(transaction.getMachineId()) == null) {
1715 lastTransactionSeenFromMachineFromServer.put(transaction.getMachineId(), transaction.getClientLocalSequenceNumber());
1717 Long lastTransactionSeenFromMachine = lastTransactionSeenFromMachineFromServer.get(transaction.getMachineId());
1718 if (transaction.getClientLocalSequenceNumber() > lastTransactionSeenFromMachine) {
1719 lastTransactionSeenFromMachineFromServer.put(transaction.getMachineId(), transaction.getClientLocalSequenceNumber());
1723 if (transaction.evaluateGuard(committedKeyValueTable, speculativeTableTmp, null)) {
1724 // Guard evaluated as true
1726 // Update the local changes so we can make the commit
1727 for (KeyValue kv : transaction.getKeyValueUpdateSet()) {
1728 speculativeTableTmp.put(kv.getKey(), kv);
1731 // Update what the last transaction committed was for use in batch commit
1732 lastTransactionCommitted = transactionSequenceNumber;
1734 // Guard evaluated was false so create abort
1737 Abort newAbort = new Abort(null,
1738 transaction.getClientLocalSequenceNumber(),
1739 transaction.getSequenceNumber(),
1740 transaction.getMachineId(),
1741 transaction.getArbitrator(),
1742 localArbitrationSequenceNumber);
1743 localArbitrationSequenceNumber++;
1745 generatedAborts.add(newAbort);
1747 // Insert the abort so we can process
1748 processEntry(newAbort);
1751 lastSeqNumArbOn = transactionSequenceNumber;
1753 // liveTransactionBySequenceNumberTable.remove(transactionSequenceNumber);
1756 Commit newCommit = null;
1758 // If there is something to commit
1759 if (speculativeTableTmp.size() != 0) {
1761 // Create the commit and increment the commit sequence number
1762 newCommit = new Commit(localArbitrationSequenceNumber, localMachineId, lastTransactionCommitted);
1763 localArbitrationSequenceNumber++;
1765 // Add all the new keys to the commit
1766 for (KeyValue kv : speculativeTableTmp.values()) {
1767 newCommit.addKV(kv);
1770 // create the commit parts
1771 newCommit.createCommitParts();
1773 // Append all the commit parts to the end of the pending queue waiting for sending to the server
1775 // Insert the commit so we can process it
1776 for (CommitPart commitPart : newCommit.getParts().values()) {
1777 processEntry(commitPart);
1781 if ((newCommit != null) || (generatedAborts.size() > 0)) {
1782 ArbitrationRound arbitrationRound = new ArbitrationRound(newCommit, generatedAborts);
1783 pendingSendArbitrationRounds.add(arbitrationRound);
1785 if (compactArbitrationData()) {
1786 ArbitrationRound newArbitrationRound = pendingSendArbitrationRounds.get(pendingSendArbitrationRounds.size() - 1);
1787 if (newArbitrationRound.getCommit() != null) {
1788 for (CommitPart commitPart : newArbitrationRound.getCommit().getParts().values()) {
1789 processEntry(commitPart);
1796 private Pair<Boolean, Boolean> arbitrateOnLocalTransaction(Transaction transaction) {
1798 // Check if this machine arbitrates for this transaction if not then we cant arbitrate this transaction
1799 if (transaction.getArbitrator() != localMachineId) {
1800 return new Pair<Boolean, Boolean>(false, false);
1803 if (!transaction.isComplete()) {
1804 // Will arbitrate in incorrect order if we continue so just break
1806 return new Pair<Boolean, Boolean>(false, false);
1809 if (transaction.getMachineId() != localMachineId) {
1810 // dont do this check for local transactions
1811 if (lastTransactionSeenFromMachineFromServer.get(transaction.getMachineId()) != null) {
1812 if (lastTransactionSeenFromMachineFromServer.get(transaction.getMachineId()) > transaction.getClientLocalSequenceNumber()) {
1813 // We've have already seen this from the server
1814 return new Pair<Boolean, Boolean>(false, false);
1819 if (transaction.evaluateGuard(committedKeyValueTable, null, null)) {
1820 // Guard evaluated as true
1822 // Create the commit and increment the commit sequence number
1823 Commit newCommit = new Commit(localArbitrationSequenceNumber, localMachineId, -1);
1824 localArbitrationSequenceNumber++;
1826 // Update the local changes so we can make the commit
1827 for (KeyValue kv : transaction.getKeyValueUpdateSet()) {
1828 newCommit.addKV(kv);
1831 // create the commit parts
1832 newCommit.createCommitParts();
1834 // Append all the commit parts to the end of the pending queue waiting for sending to the server
1835 ArbitrationRound arbitrationRound = new ArbitrationRound(newCommit, new HashSet<Abort>());
1836 pendingSendArbitrationRounds.add(arbitrationRound);
1838 if (compactArbitrationData()) {
1839 ArbitrationRound newArbitrationRound = pendingSendArbitrationRounds.get(pendingSendArbitrationRounds.size() - 1);
1840 for (CommitPart commitPart : newArbitrationRound.getCommit().getParts().values()) {
1841 processEntry(commitPart);
1844 // Insert the commit so we can process it
1845 for (CommitPart commitPart : newCommit.getParts().values()) {
1846 processEntry(commitPart);
1850 if (transaction.getMachineId() == localMachineId) {
1851 TransactionStatus status = transaction.getTransactionStatus();
1852 if (status != null) {
1853 status.setStatus(TransactionStatus.StatusCommitted);
1857 updateLiveStateFromLocal();
1858 return new Pair<Boolean, Boolean>(true, true);
1861 if (transaction.getMachineId() == localMachineId) {
1862 // For locally created messages update the status
1864 // Guard evaluated was false so create abort
1865 TransactionStatus status = transaction.getTransactionStatus();
1866 if (status != null) {
1867 status.setStatus(TransactionStatus.StatusAborted);
1870 Set addAbortSet = new HashSet<Abort>();
1874 Abort newAbort = new Abort(null,
1875 transaction.getClientLocalSequenceNumber(),
1877 transaction.getMachineId(),
1878 transaction.getArbitrator(),
1879 localArbitrationSequenceNumber);
1880 localArbitrationSequenceNumber++;
1882 addAbortSet.add(newAbort);
1885 // Append all the commit parts to the end of the pending queue waiting for sending to the server
1886 ArbitrationRound arbitrationRound = new ArbitrationRound(null, addAbortSet);
1887 pendingSendArbitrationRounds.add(arbitrationRound);
1889 if (compactArbitrationData()) {
1890 ArbitrationRound newArbitrationRound = pendingSendArbitrationRounds.get(pendingSendArbitrationRounds.size() - 1);
1891 for (CommitPart commitPart : newArbitrationRound.getCommit().getParts().values()) {
1892 processEntry(commitPart);
1897 updateLiveStateFromLocal();
1898 return new Pair<Boolean, Boolean>(true, false);
1903 * 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
1905 private boolean compactArbitrationData() {
1907 if (pendingSendArbitrationRounds.size() < 2) {
1908 // Nothing to compact so do nothing
1912 ArbitrationRound lastRound = pendingSendArbitrationRounds.get(pendingSendArbitrationRounds.size() - 1);
1913 if (lastRound.didSendPart()) {
1917 boolean hadCommit = (lastRound.getCommit() == null);
1918 boolean gotNewCommit = false;
1920 int numberToDelete = 1;
1921 while (numberToDelete < pendingSendArbitrationRounds.size()) {
1922 ArbitrationRound round = pendingSendArbitrationRounds.get(pendingSendArbitrationRounds.size() - numberToDelete - 1);
1924 if (round.isFull() || round.didSendPart()) {
1925 // Stop since there is a part that cannot be compacted and we need to compact in order
1929 if (round.getCommit() == null) {
1931 // Try compacting aborts only
1932 int newSize = round.getCurrentSize() + lastRound.getAbortsCount();
1933 if (newSize > ArbitrationRound.MAX_PARTS) {
1934 // Cant compact since it would be too large
1937 lastRound.addAborts(round.getAborts());
1940 // Create a new larger commit
1941 Commit newCommit = Commit.merge(lastRound.getCommit(), round.getCommit(), localArbitrationSequenceNumber);
1942 localArbitrationSequenceNumber++;
1944 // Create the commit parts so that we can count them
1945 newCommit.createCommitParts();
1947 // Calculate the new size of the parts
1948 int newSize = newCommit.getNumberOfParts();
1949 newSize += lastRound.getAbortsCount();
1950 newSize += round.getAbortsCount();
1952 if (newSize > ArbitrationRound.MAX_PARTS) {
1953 // Cant compact since it would be too large
1957 // Set the new compacted part
1958 lastRound.setCommit(newCommit);
1959 lastRound.addAborts(round.getAborts());
1960 gotNewCommit = true;
1966 if (numberToDelete != 1) {
1967 // If there is a compaction
1969 // Delete the previous pieces that are now in the new compacted piece
1970 if (numberToDelete == pendingSendArbitrationRounds.size()) {
1971 pendingSendArbitrationRounds.clear();
1973 for (int i = 0; i < numberToDelete; i++) {
1974 pendingSendArbitrationRounds.remove(pendingSendArbitrationRounds.size() - 1);
1978 // Add the new compacted into the pending to send list
1979 pendingSendArbitrationRounds.add(lastRound);
1981 // Should reinsert into the commit processor
1982 if (hadCommit && gotNewCommit) {
1989 // private boolean compactArbitrationData() {
1994 * Update all the commits and the committed tables, sets dead the dead transactions
1996 private boolean updateCommittedTable() {
1998 if (newCommitParts.size() == 0) {
1999 // Nothing new to process
2003 // Iterate through all the machine Ids that we received new parts for
2004 for (Long machineId : newCommitParts.keySet()) {
2005 Map<Pair<Long, Integer>, CommitPart> parts = newCommitParts.get(machineId);
2007 // Iterate through all the parts for that machine Id
2008 for (Pair<Long, Integer> partId : parts.keySet()) {
2009 CommitPart part = parts.get(partId);
2011 // Get the transaction object for that sequence number
2012 Map<Long, Commit> commitForClientTable = liveCommitsTable.get(part.getMachineId());
2014 if (commitForClientTable == null) {
2015 // This is the first commit from this device
2016 commitForClientTable = new HashMap<Long, Commit>();
2017 liveCommitsTable.put(part.getMachineId(), commitForClientTable);
2020 Commit commit = commitForClientTable.get(part.getSequenceNumber());
2022 if (commit == null) {
2023 // This is a new commit that we dont have so make a new one
2024 commit = new Commit();
2026 // Insert this new commit into the live tables
2027 commitForClientTable.put(part.getSequenceNumber(), commit);
2030 // Add that part to the commit
2031 commit.addPartDecode(part);
2035 // Clear all the new commits parts in preparation for the next time the server sends slots
2036 newCommitParts.clear();
2038 // If we process a new commit keep track of it for future use
2039 boolean didProcessANewCommit = false;
2041 // Process the commits one by one
2042 for (Long arbitratorId : liveCommitsTable.keySet()) {
2044 // Get all the commits for a specific arbitrator
2045 Map<Long, Commit> commitForClientTable = liveCommitsTable.get(arbitratorId);
2047 // Sort the commits in order
2048 List<Long> commitSequenceNumbers = new ArrayList<Long>(commitForClientTable.keySet());
2049 Collections.sort(commitSequenceNumbers);
2051 // Get the last commit seen from this arbitrator
2052 long lastCommitSeenSequenceNumber = -1;
2053 if (lastCommitSeenSequenceNumberByArbitratorTable.get(arbitratorId) != null) {
2054 lastCommitSeenSequenceNumber = lastCommitSeenSequenceNumberByArbitratorTable.get(arbitratorId);
2057 // Go through each new commit one by one
2058 for (int i = 0; i < commitSequenceNumbers.size(); i++) {
2059 Long commitSequenceNumber = commitSequenceNumbers.get(i);
2060 Commit commit = commitForClientTable.get(commitSequenceNumber);
2062 // Special processing if a commit is not complete
2063 if (!commit.isComplete()) {
2064 if (i == (commitSequenceNumbers.size() - 1)) {
2065 // 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
2068 // This is a commit that was already dead but parts of it are still in the block chain (not flushed out yet).
2069 // Delete it and move on
2071 commitForClientTable.remove(commit.getSequenceNumber());
2076 // Update the last transaction that was updated if we can
2077 if (commit.getTransactionSequenceNumber() != -1) {
2078 Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(commit.getMachineId());
2080 // Update the last transaction sequence number that the arbitrator arbitrated on
2081 if ((lastTransactionNumber == null) || (lastTransactionNumber < commit.getTransactionSequenceNumber())) {
2082 lastArbitratedTransactionNumberByArbitratorTable.put(commit.getMachineId(), commit.getTransactionSequenceNumber());
2086 // Update the last arbitration data that we have seen so far
2087 if (lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(commit.getMachineId()) != null) {
2089 long lastArbitrationSequenceNumber = lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(commit.getMachineId());
2090 if (commit.getSequenceNumber() > lastArbitrationSequenceNumber) {
2092 lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.put(commit.getMachineId(), commit.getSequenceNumber());
2095 // Never seen any data from this arbitrator so record the first one
2096 lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.put(commit.getMachineId(), commit.getSequenceNumber());
2099 // We have already seen this commit before so need to do the full processing on this commit
2100 if (commit.getSequenceNumber() <= lastCommitSeenSequenceNumber) {
2102 // Update the last transaction that was updated if we can
2103 if (commit.getTransactionSequenceNumber() != -1) {
2104 Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(commit.getMachineId());
2106 // Update the last transaction sequence number that the arbitrator arbitrated on
2107 if ((lastTransactionNumber == null) || (lastTransactionNumber < commit.getTransactionSequenceNumber())) {
2108 lastArbitratedTransactionNumberByArbitratorTable.put(commit.getMachineId(), commit.getTransactionSequenceNumber());
2115 // If we got here then this is a brand new commit and needs full processing
2117 // Get what commits should be edited, these are the commits that have live values for their keys
2118 Set<Commit> commitsToEdit = new HashSet<Commit>();
2119 for (KeyValue kv : commit.getKeyValueUpdateSet()) {
2120 commitsToEdit.add(liveCommitsByKeyTable.get(kv.getKey()));
2122 commitsToEdit.remove(null); // remove null since it could be in this set
2124 // Update each previous commit that needs to be updated
2125 for (Commit previousCommit : commitsToEdit) {
2127 // Only bother with live commits (TODO: Maybe remove this check)
2128 if (previousCommit.isLive()) {
2130 // Update which keys in the old commits are still live
2131 for (KeyValue kv : commit.getKeyValueUpdateSet()) {
2132 previousCommit.invalidateKey(kv.getKey());
2135 // if the commit is now dead then remove it
2136 if (!previousCommit.isLive()) {
2137 commitForClientTable.remove(previousCommit);
2142 // Update the last seen sequence number from this arbitrator
2143 if (lastCommitSeenSequenceNumberByArbitratorTable.get(commit.getMachineId()) != null) {
2144 if (commit.getSequenceNumber() > lastCommitSeenSequenceNumberByArbitratorTable.get(commit.getMachineId())) {
2145 lastCommitSeenSequenceNumberByArbitratorTable.put(commit.getMachineId(), commit.getSequenceNumber());
2148 lastCommitSeenSequenceNumberByArbitratorTable.put(commit.getMachineId(), commit.getSequenceNumber());
2151 // We processed a new commit that we havent seen before
2152 didProcessANewCommit = true;
2154 // Update the committed table of keys and which commit is using which key
2155 for (KeyValue kv : commit.getKeyValueUpdateSet()) {
2156 committedKeyValueTable.put(kv.getKey(), kv);
2157 liveCommitsByKeyTable.put(kv.getKey(), commit);
2162 return didProcessANewCommit;
2166 * Create the speculative table from transactions that are still live and have come from the cloud
2168 private boolean updateSpeculativeTable(boolean didProcessNewCommits) {
2169 if (liveTransactionBySequenceNumberTable.keySet().size() == 0) {
2170 // There is nothing to speculate on
2174 // Create a list of the transaction sequence numbers and sort them from oldest to newest
2175 List<Long> transactionSequenceNumbersSorted = new ArrayList<Long>(liveTransactionBySequenceNumberTable.keySet());
2176 Collections.sort(transactionSequenceNumbersSorted);
2178 boolean hasGapInTransactionSequenceNumbers = transactionSequenceNumbersSorted.get(0) != oldestTransactionSequenceNumberSpeculatedOn;
2181 if (hasGapInTransactionSequenceNumbers || didProcessNewCommits) {
2182 // If there is a gap in the transaction sequence numbers then there was a commit or an abort of a transaction
2183 // OR there was a new commit (Could be from offline commit) so a redo the speculation from scratch
2185 // Start from scratch
2186 speculatedKeyValueTable.clear();
2187 lastTransactionSequenceNumberSpeculatedOn = -1;
2188 oldestTransactionSequenceNumberSpeculatedOn = -1;
2192 // Remember the front of the transaction list
2193 oldestTransactionSequenceNumberSpeculatedOn = transactionSequenceNumbersSorted.get(0);
2195 // Find where to start arbitration from
2196 int startIndex = transactionSequenceNumbersSorted.indexOf(lastTransactionSequenceNumberSpeculatedOn) + 1;
2198 if (startIndex >= transactionSequenceNumbersSorted.size()) {
2199 // Make sure we are not out of bounds
2200 return false; // did not speculate
2203 Set<Long> incompleteTransactionArbitrator = new HashSet<Long>();
2204 boolean didSkip = true;
2206 for (int i = startIndex; i < transactionSequenceNumbersSorted.size(); i++) {
2207 long transactionSequenceNumber = transactionSequenceNumbersSorted.get(i);
2208 Transaction transaction = liveTransactionBySequenceNumberTable.get(transactionSequenceNumber);
2210 if (!transaction.isComplete()) {
2211 // If there is an incomplete transaction then there is nothing we can do
2212 // add this transactions arbitrator to the list of arbitrators we should ignore
2213 incompleteTransactionArbitrator.add(transaction.getArbitrator());
2218 if (incompleteTransactionArbitrator.contains(transaction.getArbitrator())) {
2222 lastTransactionSequenceNumberSpeculatedOn = transactionSequenceNumber;
2224 if (transaction.evaluateGuard(committedKeyValueTable, speculatedKeyValueTable, null)) {
2225 // Guard evaluated to true so update the speculative table
2226 for (KeyValue kv : transaction.getKeyValueUpdateSet()) {
2227 speculatedKeyValueTable.put(kv.getKey(), kv);
2233 // Since there was a skip we need to redo the speculation next time around
2234 lastTransactionSequenceNumberSpeculatedOn = -1;
2235 oldestTransactionSequenceNumberSpeculatedOn = -1;
2238 // We did some speculation
2243 * Create the pending transaction speculative table from transactions that are still in the pending transaction buffer
2245 private void updatePendingTransactionSpeculativeTable(boolean didProcessNewCommitsOrSpeculate) {
2246 if (pendingTransactionQueue.size() == 0) {
2247 // There is nothing to speculate on
2252 if (didProcessNewCommitsOrSpeculate || (firstPendingTransaction != pendingTransactionQueue.get(0))) {
2253 // need to reset on the pending speculation
2254 lastPendingTransactionSpeculatedOn = null;
2255 firstPendingTransaction = pendingTransactionQueue.get(0);
2256 pendingTransactionSpeculatedKeyValueTable.clear();
2259 // Find where to start arbitration from
2260 int startIndex = pendingTransactionQueue.indexOf(firstPendingTransaction) + 1;
2262 if (startIndex >= pendingTransactionQueue.size()) {
2263 // Make sure we are not out of bounds
2267 for (int i = startIndex; i < pendingTransactionQueue.size(); i++) {
2268 Transaction transaction = pendingTransactionQueue.get(i);
2270 lastPendingTransactionSpeculatedOn = transaction;
2272 if (transaction.evaluateGuard(committedKeyValueTable, speculatedKeyValueTable, pendingTransactionSpeculatedKeyValueTable)) {
2273 // Guard evaluated to true so update the speculative table
2274 for (KeyValue kv : transaction.getKeyValueUpdateSet()) {
2275 pendingTransactionSpeculatedKeyValueTable.put(kv.getKey(), kv);
2282 * Set dead and remove from the live transaction tables the transactions that are dead
2284 private void updateLiveTransactionsAndStatus() {
2286 // Go through each of the transactions
2287 for (Iterator<Map.Entry<Long, Transaction>> iter = liveTransactionBySequenceNumberTable.entrySet().iterator(); iter.hasNext();) {
2288 Transaction transaction = iter.next().getValue();
2290 // Check if the transaction is dead
2291 Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(transaction.getArbitrator());
2292 if ((lastTransactionNumber != null) && (lastTransactionNumber >= transaction.getSequenceNumber())) {
2294 // Set dead the transaction
2295 transaction.setDead();
2297 // Remove the transaction from the live table
2299 liveTransactionByTransactionIdTable.remove(transaction.getId());
2303 // Go through each of the transactions
2304 for (Iterator<Map.Entry<Long, TransactionStatus>> iter = outstandingTransactionStatus.entrySet().iterator(); iter.hasNext();) {
2305 TransactionStatus status = iter.next().getValue();
2307 // Check if the transaction is dead
2308 Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(status.getTransactionArbitrator());
2309 if ((lastTransactionNumber != null) && (lastTransactionNumber >= status.getTransactionSequenceNumber())) {
2312 status.setStatus(TransactionStatus.StatusCommitted);
2321 * Process this slot, entry by entry. Also update the latest message sent by slot
2323 private void processSlot(SlotIndexer indexer, Slot slot, boolean acceptUpdatesToLocal, HashSet<Long> machineSet) {
2325 // Update the last message seen
2326 updateLastMessage(slot.getMachineID(), slot.getSequenceNumber(), slot, acceptUpdatesToLocal, machineSet);
2328 // Process each entry in the slot
2329 for (Entry entry : slot.getEntries()) {
2330 switch (entry.getType()) {
2332 case Entry.TypeCommitPart:
2333 processEntry((CommitPart)entry);
2336 case Entry.TypeAbort:
2337 processEntry((Abort)entry);
2340 case Entry.TypeTransactionPart:
2341 processEntry((TransactionPart)entry);
2344 case Entry.TypeNewKey:
2345 processEntry((NewKey)entry);
2348 case Entry.TypeLastMessage:
2349 processEntry((LastMessage)entry, machineSet);
2352 case Entry.TypeRejectedMessage:
2353 processEntry((RejectedMessage)entry, indexer);
2356 case Entry.TypeTableStatus:
2357 processEntry((TableStatus)entry, slot.getSequenceNumber());
2361 throw new Error("Unrecognized type: " + entry.getType());
2367 * Update the last message that was sent for a machine Id
2369 private void processEntry(LastMessage entry, HashSet<Long> machineSet) {
2370 // Update what the last message received by a machine was
2371 updateLastMessage(entry.getMachineID(), entry.getSequenceNumber(), entry, false, machineSet);
2375 * Add the new key to the arbitrators table and update the set of live new keys (in case of a rescued new key message)
2377 private void processEntry(NewKey entry) {
2379 // Update the arbitrator table with the new key information
2380 arbitratorTable.put(entry.getKey(), entry.getMachineID());
2382 // Update what the latest live new key is
2383 NewKey oldNewKey = liveNewKeyTable.put(entry.getKey(), entry);
2384 if (oldNewKey != null) {
2385 // Delete the old new key messages
2386 oldNewKey.setDead();
2391 * Process new table status entries and set dead the old ones as new ones come in.
2392 * keeps track of the largest and smallest table status seen in this current round
2393 * of updating the local copy of the block chain
2395 private void processEntry(TableStatus entry, long seq) {
2396 int newNumSlots = entry.getMaxSlots();
2397 updateCurrMaxSize(newNumSlots);
2399 initExpectedSize(seq, newNumSlots);
2401 if (liveTableStatus != null) {
2402 // We have a larger table status so the old table status is no longer alive
2403 liveTableStatus.setDead();
2406 // Make this new table status the latest alive table status
2407 liveTableStatus = entry;
2411 * Check old messages to see if there is a block chain violation. Also
2413 private void processEntry(RejectedMessage entry, SlotIndexer indexer) {
2414 long oldSeqNum = entry.getOldSeqNum();
2415 long newSeqNum = entry.getNewSeqNum();
2416 boolean isequal = entry.getEqual();
2417 long machineId = entry.getMachineID();
2418 long seq = entry.getSequenceNumber();
2421 // Check if we have messages that were supposed to be rejected in our local block chain
2422 for (long seqNum = oldSeqNum; seqNum <= newSeqNum; seqNum++) {
2425 Slot slot = indexer.getSlot(seqNum);
2428 // If we have this slot make sure that it was not supposed to be a rejected slot
2430 long slotMachineId = slot.getMachineID();
2431 if (isequal != (slotMachineId == machineId)) {
2432 throw new Error("Server Error: Trying to insert rejected message for slot " + seqNum);
2438 // Create a list of clients to watch until they see this rejected message entry.
2439 HashSet<Long> deviceWatchSet = new HashSet<Long>();
2440 for (Map.Entry<Long, Pair<Long, Liveness>> lastMessageEntry : lastMessageTable.entrySet()) {
2442 // Machine ID for the last message entry
2443 long lastMessageEntryMachineId = lastMessageEntry.getKey();
2445 // We've seen it, don't need to continue to watch. Our next
2446 // message will implicitly acknowledge it.
2447 if (lastMessageEntryMachineId == localMachineId) {
2451 Pair<Long, Liveness> lastMessageValue = lastMessageEntry.getValue();
2452 long entrySequenceNumber = lastMessageValue.getFirst();
2454 if (entrySequenceNumber < seq) {
2456 // Add this rejected message to the set of messages that this machine ID did not see yet
2457 addWatchList(lastMessageEntryMachineId, entry);
2459 // This client did not see this rejected message yet so add it to the watch set to monitor
2460 deviceWatchSet.add(lastMessageEntryMachineId);
2464 if (deviceWatchSet.isEmpty()) {
2465 // This rejected message has been seen by all the clients so
2468 // We need to watch this rejected message
2469 entry.setWatchSet(deviceWatchSet);
2474 * Check if this abort is live, if not then save it so we can kill it later.
2475 * update the last transaction number that was arbitrated on.
2477 private void processEntry(Abort entry) {
2480 if (entry.getTransactionSequenceNumber() != -1) {
2481 // update the transaction status if it was sent to the server
2482 TransactionStatus status = outstandingTransactionStatus.remove(entry.getTransactionSequenceNumber());
2483 if (status != null) {
2484 status.setStatus(TransactionStatus.StatusAborted);
2488 // Abort has not been seen by the client it is for yet so we need to keep track of it
2489 Abort previouslySeenAbort = liveAbortTable.put(entry.getAbortId(), entry);
2490 if (previouslySeenAbort != null) {
2491 previouslySeenAbort.setDead(); // Delete old version of the abort since we got a rescued newer version
2494 if (entry.getTransactionArbitrator() == localMachineId) {
2495 liveAbortsGeneratedByLocal.put(entry.getArbitratorLocalSequenceNumber(), entry);
2498 if ((entry.getSequenceNumber() != -1) && (lastMessageTable.get(entry.getTransactionMachineId()).getFirst() >= entry.getSequenceNumber())) {
2500 // The machine already saw this so it is dead
2502 liveAbortTable.remove(entry.getAbortId());
2504 if (entry.getTransactionArbitrator() == localMachineId) {
2505 liveAbortsGeneratedByLocal.remove(entry.getArbitratorLocalSequenceNumber());
2514 // Update the last arbitration data that we have seen so far
2515 if (lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(entry.getTransactionArbitrator()) != null) {
2517 long lastArbitrationSequenceNumber = lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(entry.getTransactionArbitrator());
2518 if (entry.getSequenceNumber() > lastArbitrationSequenceNumber) {
2520 lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.put(entry.getTransactionArbitrator(), entry.getSequenceNumber());
2523 // Never seen any data from this arbitrator so record the first one
2524 lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.put(entry.getTransactionArbitrator(), entry.getSequenceNumber());
2528 // Set dead a transaction if we can
2529 Transaction transactionToSetDead = liveTransactionByTransactionIdTable.remove(new Pair<Long, Long>(entry.getTransactionMachineId(), entry.getTransactionClientLocalSequenceNumber()));
2530 if (transactionToSetDead != null) {
2531 liveTransactionBySequenceNumberTable.remove(transactionToSetDead.getSequenceNumber());
2534 // Update the last transaction sequence number that the arbitrator arbitrated on
2535 Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(entry.getTransactionArbitrator());
2536 if ((lastTransactionNumber == null) || (lastTransactionNumber < entry.getTransactionSequenceNumber())) {
2539 if (entry.getTransactionSequenceNumber() != -1) {
2540 lastArbitratedTransactionNumberByArbitratorTable.put(entry.getTransactionArbitrator(), entry.getTransactionSequenceNumber());
2546 * Set dead the transaction part if that transaction is dead and keep track of all new parts
2548 private void processEntry(TransactionPart entry) {
2549 // Check if we have already seen this transaction and set it dead OR if it is not alive
2550 Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(entry.getArbitratorId());
2551 if ((lastTransactionNumber != null) && (lastTransactionNumber >= entry.getSequenceNumber())) {
2552 // This transaction is dead, it was already committed or aborted
2557 // This part is still alive
2558 Map<Pair<Long, Integer>, TransactionPart> transactionPart = newTransactionParts.get(entry.getMachineId());
2560 if (transactionPart == null) {
2561 // Dont have a table for this machine Id yet so make one
2562 transactionPart = new HashMap<Pair<Long, Integer>, TransactionPart>();
2563 newTransactionParts.put(entry.getMachineId(), transactionPart);
2566 // Update the part and set dead ones we have already seen (got a rescued version)
2567 TransactionPart previouslySeenPart = transactionPart.put(entry.getPartId(), entry);
2568 if (previouslySeenPart != null) {
2569 previouslySeenPart.setDead();
2574 * Process new commit entries and save them for future use. Delete duplicates
2576 private void processEntry(CommitPart entry) {
2579 // Update the last transaction that was updated if we can
2580 if (entry.getTransactionSequenceNumber() != -1) {
2581 Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(entry.getMachineId());
2583 // Update the last transaction sequence number that the arbitrator arbitrated on
2584 if ((lastTransactionNumber == null) || (lastTransactionNumber < entry.getTransactionSequenceNumber())) {
2585 lastArbitratedTransactionNumberByArbitratorTable.put(entry.getMachineId(), entry.getTransactionSequenceNumber());
2592 Map<Pair<Long, Integer>, CommitPart> commitPart = newCommitParts.get(entry.getMachineId());
2594 if (commitPart == null) {
2595 // Don't have a table for this machine Id yet so make one
2596 commitPart = new HashMap<Pair<Long, Integer>, CommitPart>();
2597 newCommitParts.put(entry.getMachineId(), commitPart);
2600 // Update the part and set dead ones we have already seen (got a rescued version)
2601 CommitPart previouslySeenPart = commitPart.put(entry.getPartId(), entry);
2602 if (previouslySeenPart != null) {
2603 previouslySeenPart.setDead();
2608 * Update the last message seen table. Update and set dead the appropriate RejectedMessages as clients see them.
2609 * Updates the live aborts, removes those that are dead and sets them dead.
2610 * Check that the last message seen is correct and that there is no mismatch of our own last message or that
2611 * other clients have not had a rollback on the last message.
2613 private void updateLastMessage(long machineId, long seqNum, Liveness liveness, boolean acceptUpdatesToLocal, HashSet<Long> machineSet) {
2615 // We have seen this machine ID
2616 machineSet.remove(machineId);
2618 // Get the set of rejected messages that this machine Id is has not seen yet
2619 HashSet<RejectedMessage> watchset = rejectedMessageWatchListTable.get(machineId);
2621 // If there is a rejected message that this machine Id has not seen yet
2622 if (watchset != null) {
2624 // Go through each rejected message that this machine Id has not seen yet
2625 for (Iterator<RejectedMessage> rmit = watchset.iterator(); rmit.hasNext(); ) {
2627 RejectedMessage rm = rmit.next();
2629 // If this machine Id has seen this rejected message...
2630 if (rm.getSequenceNumber() <= seqNum) {
2632 // Remove it from our watchlist
2635 // Decrement machines that need to see this notification
2636 rm.removeWatcher(machineId);
2641 // Set dead the abort
2642 for (Iterator<Map.Entry<Pair<Long, Long>, Abort>> i = liveAbortTable.entrySet().iterator(); i.hasNext();) {
2643 Abort abort = i.next().getValue();
2645 if ((abort.getTransactionMachineId() == machineId) && (abort.getSequenceNumber() <= seqNum)) {
2649 if (abort.getTransactionArbitrator() == localMachineId) {
2650 liveAbortsGeneratedByLocal.remove(abort.getArbitratorLocalSequenceNumber());
2657 if (machineId == localMachineId) {
2658 // Our own messages are immediately dead.
2659 if (liveness instanceof LastMessage) {
2660 ((LastMessage)liveness).setDead();
2661 } else if (liveness instanceof Slot) {
2662 ((Slot)liveness).setDead();
2664 throw new Error("Unrecognized type");
2668 // Get the old last message for this device
2669 Pair<Long, Liveness> lastMessageEntry = lastMessageTable.put(machineId, new Pair<Long, Liveness>(seqNum, liveness));
2670 if (lastMessageEntry == null) {
2671 // If no last message then there is nothing else to process
2675 long lastMessageSeqNum = lastMessageEntry.getFirst();
2676 Liveness lastEntry = lastMessageEntry.getSecond();
2678 // If it is not our machine Id since we already set ours to dead
2679 if (machineId != localMachineId) {
2680 if (lastEntry instanceof LastMessage) {
2681 ((LastMessage)lastEntry).setDead();
2682 } else if (lastEntry instanceof Slot) {
2683 ((Slot)lastEntry).setDead();
2685 throw new Error("Unrecognized type");
2689 // Make sure the server is not playing any games
2690 if (machineId == localMachineId) {
2692 if (hadPartialSendToServer) {
2693 // We were not making any updates and we had a machine mismatch
2694 if (lastMessageSeqNum > seqNum && !acceptUpdatesToLocal) {
2695 throw new Error("Server Error: Mismatch on local machine sequence number, needed at least: " + lastMessageSeqNum + " got: " + seqNum);
2699 // We were not making any updates and we had a machine mismatch
2700 if (lastMessageSeqNum != seqNum && !acceptUpdatesToLocal) {
2701 throw new Error("Server Error: Mismatch on local machine sequence number, needed: " + lastMessageSeqNum + " got: " + seqNum);
2705 if (lastMessageSeqNum > seqNum) {
2706 throw new Error("Server Error: Rollback on remote machine sequence number");
2712 * Add a rejected message entry to the watch set to keep track of which clients have seen that
2713 * rejected message entry and which have not.
2715 private void addWatchList(long machineId, RejectedMessage entry) {
2716 HashSet<RejectedMessage> entries = rejectedMessageWatchListTable.get(machineId);
2717 if (entries == null) {
2718 // There is no set for this machine ID yet so create one
2719 entries = new HashSet<RejectedMessage>();
2720 rejectedMessageWatchListTable.put(machineId, entries);
2726 * Check if the HMAC chain is not violated
2728 private void checkHMACChain(SlotIndexer indexer, Slot[] newSlots) {
2729 for (int i = 0; i < newSlots.length; i++) {
2730 Slot currSlot = newSlots[i];
2731 Slot prevSlot = indexer.getSlot(currSlot.getSequenceNumber() - 1);
2732 if (prevSlot != null &&
2733 !Arrays.equals(prevSlot.getHMAC(), currSlot.getPrevHMAC()))
2734 throw new Error("Server Error: Invalid HMAC Chain" + currSlot + " " + prevSlot);