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);
1447 updateExpectedSize();
1450 // If there is a gap, check to see if the server sent us everything.
1451 if (firstSeqNum != (sequenceNumber + 1)) {
1453 // Check the size of the slots that were sent down by the server.
1454 // Can only check the size if there was a gap
1455 checkNumSlots(newSlots.length);
1457 // Since there was a gap every machine must have pushed a slot or must have
1458 // a last message message. If not then the server is hiding slots
1459 if (!machineSet.isEmpty()) {
1460 throw new Error("Missing record for machines: " + machineSet);
1464 // Update the size of our local block chain.
1467 // Commit new to slots to the local block chain.
1468 for (Slot slot : newSlots) {
1470 // Insert this slot into our local block chain copy.
1471 buffer.putSlot(slot);
1473 // Keep track of how many slots are currently live (have live data in them).
1477 // Get the sequence number of the latest slot in the system
1478 sequenceNumber = newSlots[newSlots.length - 1].getSequenceNumber();
1480 updateLiveStateFromServer();
1482 // No Need to remember after we pulled from the server
1483 offlineTransactionsCommittedAndAtServer.clear();
1485 // This is invalidated now
1486 hadPartialSendToServer = false;
1489 private void updateLiveStateFromServer() {
1490 // Process the new transaction parts
1491 processNewTransactionParts();
1493 // Do arbitration on new transactions that were received
1494 arbitrateFromServer();
1496 // Update all the committed keys
1497 boolean didCommitOrSpeculate = updateCommittedTable();
1499 // Delete the transactions that are now dead
1500 updateLiveTransactionsAndStatus();
1503 didCommitOrSpeculate |= updateSpeculativeTable(didCommitOrSpeculate);
1504 updatePendingTransactionSpeculativeTable(didCommitOrSpeculate);
1507 private void updateLiveStateFromLocal() {
1508 // Update all the committed keys
1509 boolean didCommitOrSpeculate = updateCommittedTable();
1511 // Delete the transactions that are now dead
1512 updateLiveTransactionsAndStatus();
1515 didCommitOrSpeculate |= updateSpeculativeTable(didCommitOrSpeculate);
1516 updatePendingTransactionSpeculativeTable(didCommitOrSpeculate);
1519 private void initExpectedSize(long firstSequenceNumber, long numberOfSlots) {
1520 // if (didFindTableStatus) {
1523 long prevslots = firstSequenceNumber;
1526 if (didFindTableStatus) {
1527 // expectedsize = (prevslots < ((long) numberOfSlots)) ? (int) prevslots : expectedsize;
1528 // System.out.println("Here2: " + expectedsize + " " + numberOfSlots + " " + prevslots);
1531 expectedsize = (prevslots < ((long) numberOfSlots)) ? (int) prevslots : numberOfSlots;
1532 // System.out.println("Here: " + expectedsize);
1535 // System.out.println(numberOfSlots);
1537 didFindTableStatus = true;
1538 currMaxSize = numberOfSlots;
1541 private void updateExpectedSize() {
1544 if (expectedsize > currMaxSize) {
1545 expectedsize = currMaxSize;
1548 // System.out.println("" + expectedsize);
1554 * Check the size of the block chain to make sure there are enough slots sent back by the server.
1555 * This is only called when we have a gap between the slots that we have locally and the slots
1556 * sent by the server therefore in the slots sent by the server there will be at least 1 Table
1559 private void checkNumSlots(int numberOfSlots) {
1560 if (numberOfSlots != expectedsize) {
1561 throw new Error("Server Error: Server did not send all slots. Expected: " + expectedsize + " Received:" + numberOfSlots);
1565 private void updateCurrMaxSize(int newmaxsize) {
1566 currMaxSize = newmaxsize;
1571 * Update the size of of the local buffer if it is needed.
1573 private void commitNewMaxSize() {
1574 didFindTableStatus = false;
1576 // Resize the local slot buffer
1577 if (numberOfSlots != currMaxSize) {
1578 buffer.resize((int)currMaxSize);
1581 // Change the number of local slots to the new size
1582 numberOfSlots = (int)currMaxSize;
1584 // Recalculate the resize threshold since the size of the local buffer has changed
1585 setResizeThreshold();
1589 * Process the new transaction parts from this latest round of slots received from the server
1591 private void processNewTransactionParts() {
1593 if (newTransactionParts.size() == 0) {
1594 // Nothing new to process
1598 // Iterate through all the machine Ids that we received new parts for
1599 for (Long machineId : newTransactionParts.keySet()) {
1600 Map<Pair<Long, Integer>, TransactionPart> parts = newTransactionParts.get(machineId);
1602 // Iterate through all the parts for that machine Id
1603 for (Pair<Long, Integer> partId : parts.keySet()) {
1604 TransactionPart part = parts.get(partId);
1606 Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(part.getArbitratorId());
1607 if ((lastTransactionNumber != null) && (lastTransactionNumber >= part.getSequenceNumber())) {
1608 // Set dead the transaction part
1613 // Get the transaction object for that sequence number
1614 Transaction transaction = liveTransactionBySequenceNumberTable.get(part.getSequenceNumber());
1616 if (transaction == null) {
1617 // This is a new transaction that we dont have so make a new one
1618 transaction = new Transaction();
1620 // Insert this new transaction into the live tables
1621 liveTransactionBySequenceNumberTable.put(part.getSequenceNumber(), transaction);
1622 liveTransactionByTransactionIdTable.put(part.getTransactionId(), transaction);
1625 // Add that part to the transaction
1626 transaction.addPartDecode(part);
1630 // Clear all the new transaction parts in preparation for the next time the server sends slots
1631 newTransactionParts.clear();
1635 private long lastSeqNumArbOn = 0;
1637 private void arbitrateFromServer() {
1639 if (liveTransactionBySequenceNumberTable.size() == 0) {
1640 // Nothing to arbitrate on so move on
1644 // Get the transaction sequence numbers and sort from oldest to newest
1645 List<Long> transactionSequenceNumbers = new ArrayList<Long>(liveTransactionBySequenceNumberTable.keySet());
1646 Collections.sort(transactionSequenceNumbers);
1648 // Collection of key value pairs that are
1649 Map<IoTString, KeyValue> speculativeTableTmp = new HashMap<IoTString, KeyValue>();
1651 // The last transaction arbitrated on
1652 long lastTransactionCommitted = -1;
1653 Set<Abort> generatedAborts = new HashSet<Abort>();
1655 for (Long transactionSequenceNumber : transactionSequenceNumbers) {
1656 Transaction transaction = liveTransactionBySequenceNumberTable.get(transactionSequenceNumber);
1660 // Check if this machine arbitrates for this transaction if not then we cant arbitrate this transaction
1661 if (transaction.getArbitrator() != localMachineId) {
1665 if (transactionSequenceNumber < lastSeqNumArbOn) {
1669 if (offlineTransactionsCommittedAndAtServer.contains(transaction.getId())) {
1670 // We have seen this already locally so dont commit again
1675 if (!transaction.isComplete()) {
1676 // Will arbitrate in incorrect order if we continue so just break
1682 // update the largest transaction seen by arbitrator from server
1683 if (lastTransactionSeenFromMachineFromServer.get(transaction.getMachineId()) == null) {
1684 lastTransactionSeenFromMachineFromServer.put(transaction.getMachineId(), transaction.getClientLocalSequenceNumber());
1686 Long lastTransactionSeenFromMachine = lastTransactionSeenFromMachineFromServer.get(transaction.getMachineId());
1687 if (transaction.getClientLocalSequenceNumber() > lastTransactionSeenFromMachine) {
1688 lastTransactionSeenFromMachineFromServer.put(transaction.getMachineId(), transaction.getClientLocalSequenceNumber());
1692 if (transaction.evaluateGuard(committedKeyValueTable, speculativeTableTmp, null)) {
1693 // Guard evaluated as true
1695 // Update the local changes so we can make the commit
1696 for (KeyValue kv : transaction.getKeyValueUpdateSet()) {
1697 speculativeTableTmp.put(kv.getKey(), kv);
1700 // Update what the last transaction committed was for use in batch commit
1701 lastTransactionCommitted = transactionSequenceNumber;
1703 // Guard evaluated was false so create abort
1706 Abort newAbort = new Abort(null,
1707 transaction.getClientLocalSequenceNumber(),
1708 transaction.getSequenceNumber(),
1709 transaction.getMachineId(),
1710 transaction.getArbitrator(),
1711 localArbitrationSequenceNumber);
1712 localArbitrationSequenceNumber++;
1714 generatedAborts.add(newAbort);
1716 // Insert the abort so we can process
1717 processEntry(newAbort);
1720 lastSeqNumArbOn = transactionSequenceNumber;
1722 // liveTransactionBySequenceNumberTable.remove(transactionSequenceNumber);
1725 Commit newCommit = null;
1727 // If there is something to commit
1728 if (speculativeTableTmp.size() != 0) {
1730 // Create the commit and increment the commit sequence number
1731 newCommit = new Commit(localArbitrationSequenceNumber, localMachineId, lastTransactionCommitted);
1732 localArbitrationSequenceNumber++;
1734 // Add all the new keys to the commit
1735 for (KeyValue kv : speculativeTableTmp.values()) {
1736 newCommit.addKV(kv);
1739 // create the commit parts
1740 newCommit.createCommitParts();
1742 // Append all the commit parts to the end of the pending queue waiting for sending to the server
1744 // Insert the commit so we can process it
1745 for (CommitPart commitPart : newCommit.getParts().values()) {
1746 processEntry(commitPart);
1750 if ((newCommit != null) || (generatedAborts.size() > 0)) {
1751 ArbitrationRound arbitrationRound = new ArbitrationRound(newCommit, generatedAborts);
1752 pendingSendArbitrationRounds.add(arbitrationRound);
1754 if (compactArbitrationData()) {
1755 ArbitrationRound newArbitrationRound = pendingSendArbitrationRounds.get(pendingSendArbitrationRounds.size() - 1);
1756 if (newArbitrationRound.getCommit() != null) {
1757 for (CommitPart commitPart : newArbitrationRound.getCommit().getParts().values()) {
1758 processEntry(commitPart);
1765 private Pair<Boolean, Boolean> arbitrateOnLocalTransaction(Transaction transaction) {
1767 // Check if this machine arbitrates for this transaction if not then we cant arbitrate this transaction
1768 if (transaction.getArbitrator() != localMachineId) {
1769 return new Pair<Boolean, Boolean>(false, false);
1772 if (!transaction.isComplete()) {
1773 // Will arbitrate in incorrect order if we continue so just break
1775 return new Pair<Boolean, Boolean>(false, false);
1778 if (transaction.getMachineId() != localMachineId) {
1779 // dont do this check for local transactions
1780 if (lastTransactionSeenFromMachineFromServer.get(transaction.getMachineId()) != null) {
1781 if (lastTransactionSeenFromMachineFromServer.get(transaction.getMachineId()) > transaction.getClientLocalSequenceNumber()) {
1782 // We've have already seen this from the server
1783 return new Pair<Boolean, Boolean>(false, false);
1788 if (transaction.evaluateGuard(committedKeyValueTable, null, null)) {
1789 // Guard evaluated as true
1791 // Create the commit and increment the commit sequence number
1792 Commit newCommit = new Commit(localArbitrationSequenceNumber, localMachineId, -1);
1793 localArbitrationSequenceNumber++;
1795 // Update the local changes so we can make the commit
1796 for (KeyValue kv : transaction.getKeyValueUpdateSet()) {
1797 newCommit.addKV(kv);
1800 // create the commit parts
1801 newCommit.createCommitParts();
1803 // Append all the commit parts to the end of the pending queue waiting for sending to the server
1804 ArbitrationRound arbitrationRound = new ArbitrationRound(newCommit, new HashSet<Abort>());
1805 pendingSendArbitrationRounds.add(arbitrationRound);
1807 if (compactArbitrationData()) {
1808 ArbitrationRound newArbitrationRound = pendingSendArbitrationRounds.get(pendingSendArbitrationRounds.size() - 1);
1809 for (CommitPart commitPart : newArbitrationRound.getCommit().getParts().values()) {
1810 processEntry(commitPart);
1813 // Insert the commit so we can process it
1814 for (CommitPart commitPart : newCommit.getParts().values()) {
1815 processEntry(commitPart);
1819 if (transaction.getMachineId() == localMachineId) {
1820 TransactionStatus status = transaction.getTransactionStatus();
1821 if (status != null) {
1822 status.setStatus(TransactionStatus.StatusCommitted);
1826 updateLiveStateFromLocal();
1827 return new Pair<Boolean, Boolean>(true, true);
1830 if (transaction.getMachineId() == localMachineId) {
1831 // For locally created messages update the status
1833 // Guard evaluated was false so create abort
1834 TransactionStatus status = transaction.getTransactionStatus();
1835 if (status != null) {
1836 status.setStatus(TransactionStatus.StatusAborted);
1839 Set addAbortSet = new HashSet<Abort>();
1843 Abort newAbort = new Abort(null,
1844 transaction.getClientLocalSequenceNumber(),
1846 transaction.getMachineId(),
1847 transaction.getArbitrator(),
1848 localArbitrationSequenceNumber);
1849 localArbitrationSequenceNumber++;
1851 addAbortSet.add(newAbort);
1854 // Append all the commit parts to the end of the pending queue waiting for sending to the server
1855 ArbitrationRound arbitrationRound = new ArbitrationRound(null, addAbortSet);
1856 pendingSendArbitrationRounds.add(arbitrationRound);
1858 if (compactArbitrationData()) {
1859 ArbitrationRound newArbitrationRound = pendingSendArbitrationRounds.get(pendingSendArbitrationRounds.size() - 1);
1860 for (CommitPart commitPart : newArbitrationRound.getCommit().getParts().values()) {
1861 processEntry(commitPart);
1866 updateLiveStateFromLocal();
1867 return new Pair<Boolean, Boolean>(true, false);
1872 * 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
1874 private boolean compactArbitrationData() {
1876 if (pendingSendArbitrationRounds.size() < 2) {
1877 // Nothing to compact so do nothing
1881 ArbitrationRound lastRound = pendingSendArbitrationRounds.get(pendingSendArbitrationRounds.size() - 1);
1882 if (lastRound.didSendPart()) {
1886 boolean hadCommit = (lastRound.getCommit() == null);
1887 boolean gotNewCommit = false;
1889 int numberToDelete = 1;
1890 while (numberToDelete < pendingSendArbitrationRounds.size()) {
1891 ArbitrationRound round = pendingSendArbitrationRounds.get(pendingSendArbitrationRounds.size() - numberToDelete - 1);
1893 if (round.isFull() || round.didSendPart()) {
1894 // Stop since there is a part that cannot be compacted and we need to compact in order
1898 if (round.getCommit() == null) {
1900 // Try compacting aborts only
1901 int newSize = round.getCurrentSize() + lastRound.getAbortsCount();
1902 if (newSize > ArbitrationRound.MAX_PARTS) {
1903 // Cant compact since it would be too large
1906 lastRound.addAborts(round.getAborts());
1909 // Create a new larger commit
1910 Commit newCommit = Commit.merge(lastRound.getCommit(), round.getCommit(), localArbitrationSequenceNumber);
1911 localArbitrationSequenceNumber++;
1913 // Create the commit parts so that we can count them
1914 newCommit.createCommitParts();
1916 // Calculate the new size of the parts
1917 int newSize = newCommit.getNumberOfParts();
1918 newSize += lastRound.getAbortsCount();
1919 newSize += round.getAbortsCount();
1921 if (newSize > ArbitrationRound.MAX_PARTS) {
1922 // Cant compact since it would be too large
1926 // Set the new compacted part
1927 lastRound.setCommit(newCommit);
1928 lastRound.addAborts(round.getAborts());
1929 gotNewCommit = true;
1935 if (numberToDelete != 1) {
1936 // If there is a compaction
1938 // Delete the previous pieces that are now in the new compacted piece
1939 if (numberToDelete == pendingSendArbitrationRounds.size()) {
1940 pendingSendArbitrationRounds.clear();
1942 for (int i = 0; i < numberToDelete; i++) {
1943 pendingSendArbitrationRounds.remove(pendingSendArbitrationRounds.size() - 1);
1947 // Add the new compacted into the pending to send list
1948 pendingSendArbitrationRounds.add(lastRound);
1950 // Should reinsert into the commit processor
1951 if (hadCommit && gotNewCommit) {
1958 // private boolean compactArbitrationData() {
1963 * Update all the commits and the committed tables, sets dead the dead transactions
1965 private boolean updateCommittedTable() {
1967 if (newCommitParts.size() == 0) {
1968 // Nothing new to process
1972 // Iterate through all the machine Ids that we received new parts for
1973 for (Long machineId : newCommitParts.keySet()) {
1974 Map<Pair<Long, Integer>, CommitPart> parts = newCommitParts.get(machineId);
1976 // Iterate through all the parts for that machine Id
1977 for (Pair<Long, Integer> partId : parts.keySet()) {
1978 CommitPart part = parts.get(partId);
1980 // Get the transaction object for that sequence number
1981 Map<Long, Commit> commitForClientTable = liveCommitsTable.get(part.getMachineId());
1983 if (commitForClientTable == null) {
1984 // This is the first commit from this device
1985 commitForClientTable = new HashMap<Long, Commit>();
1986 liveCommitsTable.put(part.getMachineId(), commitForClientTable);
1989 Commit commit = commitForClientTable.get(part.getSequenceNumber());
1991 if (commit == null) {
1992 // This is a new commit that we dont have so make a new one
1993 commit = new Commit();
1995 // Insert this new commit into the live tables
1996 commitForClientTable.put(part.getSequenceNumber(), commit);
1999 // Add that part to the commit
2000 commit.addPartDecode(part);
2004 // Clear all the new commits parts in preparation for the next time the server sends slots
2005 newCommitParts.clear();
2007 // If we process a new commit keep track of it for future use
2008 boolean didProcessANewCommit = false;
2010 // Process the commits one by one
2011 for (Long arbitratorId : liveCommitsTable.keySet()) {
2013 // Get all the commits for a specific arbitrator
2014 Map<Long, Commit> commitForClientTable = liveCommitsTable.get(arbitratorId);
2016 // Sort the commits in order
2017 List<Long> commitSequenceNumbers = new ArrayList<Long>(commitForClientTable.keySet());
2018 Collections.sort(commitSequenceNumbers);
2020 // Get the last commit seen from this arbitrator
2021 long lastCommitSeenSequenceNumber = -1;
2022 if (lastCommitSeenSequenceNumberByArbitratorTable.get(arbitratorId) != null) {
2023 lastCommitSeenSequenceNumber = lastCommitSeenSequenceNumberByArbitratorTable.get(arbitratorId);
2026 // Go through each new commit one by one
2027 for (int i = 0; i < commitSequenceNumbers.size(); i++) {
2028 Long commitSequenceNumber = commitSequenceNumbers.get(i);
2029 Commit commit = commitForClientTable.get(commitSequenceNumber);
2031 // Special processing if a commit is not complete
2032 if (!commit.isComplete()) {
2033 if (i == (commitSequenceNumbers.size() - 1)) {
2034 // 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
2037 // This is a commit that was already dead but parts of it are still in the block chain (not flushed out yet).
2038 // Delete it and move on
2040 commitForClientTable.remove(commit.getSequenceNumber());
2045 // Update the last transaction that was updated if we can
2046 if (commit.getTransactionSequenceNumber() != -1) {
2047 Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(commit.getMachineId());
2049 // Update the last transaction sequence number that the arbitrator arbitrated on
2050 if ((lastTransactionNumber == null) || (lastTransactionNumber < commit.getTransactionSequenceNumber())) {
2051 lastArbitratedTransactionNumberByArbitratorTable.put(commit.getMachineId(), commit.getTransactionSequenceNumber());
2055 // Update the last arbitration data that we have seen so far
2056 if (lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(commit.getMachineId()) != null) {
2058 long lastArbitrationSequenceNumber = lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(commit.getMachineId());
2059 if (commit.getSequenceNumber() > lastArbitrationSequenceNumber) {
2061 lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.put(commit.getMachineId(), commit.getSequenceNumber());
2064 // Never seen any data from this arbitrator so record the first one
2065 lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.put(commit.getMachineId(), commit.getSequenceNumber());
2068 // We have already seen this commit before so need to do the full processing on this commit
2069 if (commit.getSequenceNumber() <= lastCommitSeenSequenceNumber) {
2071 // Update the last transaction that was updated if we can
2072 if (commit.getTransactionSequenceNumber() != -1) {
2073 Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(commit.getMachineId());
2075 // Update the last transaction sequence number that the arbitrator arbitrated on
2076 if ((lastTransactionNumber == null) || (lastTransactionNumber < commit.getTransactionSequenceNumber())) {
2077 lastArbitratedTransactionNumberByArbitratorTable.put(commit.getMachineId(), commit.getTransactionSequenceNumber());
2084 // If we got here then this is a brand new commit and needs full processing
2086 // Get what commits should be edited, these are the commits that have live values for their keys
2087 Set<Commit> commitsToEdit = new HashSet<Commit>();
2088 for (KeyValue kv : commit.getKeyValueUpdateSet()) {
2089 commitsToEdit.add(liveCommitsByKeyTable.get(kv.getKey()));
2091 commitsToEdit.remove(null); // remove null since it could be in this set
2093 // Update each previous commit that needs to be updated
2094 for (Commit previousCommit : commitsToEdit) {
2096 // Only bother with live commits (TODO: Maybe remove this check)
2097 if (previousCommit.isLive()) {
2099 // Update which keys in the old commits are still live
2100 for (KeyValue kv : commit.getKeyValueUpdateSet()) {
2101 previousCommit.invalidateKey(kv.getKey());
2104 // if the commit is now dead then remove it
2105 if (!previousCommit.isLive()) {
2106 commitForClientTable.remove(previousCommit);
2111 // Update the last seen sequence number from this arbitrator
2112 if (lastCommitSeenSequenceNumberByArbitratorTable.get(commit.getMachineId()) != null) {
2113 if (commit.getSequenceNumber() > lastCommitSeenSequenceNumberByArbitratorTable.get(commit.getMachineId())) {
2114 lastCommitSeenSequenceNumberByArbitratorTable.put(commit.getMachineId(), commit.getSequenceNumber());
2117 lastCommitSeenSequenceNumberByArbitratorTable.put(commit.getMachineId(), commit.getSequenceNumber());
2120 // We processed a new commit that we havent seen before
2121 didProcessANewCommit = true;
2123 // Update the committed table of keys and which commit is using which key
2124 for (KeyValue kv : commit.getKeyValueUpdateSet()) {
2125 committedKeyValueTable.put(kv.getKey(), kv);
2126 liveCommitsByKeyTable.put(kv.getKey(), commit);
2131 return didProcessANewCommit;
2135 * Create the speculative table from transactions that are still live and have come from the cloud
2137 private boolean updateSpeculativeTable(boolean didProcessNewCommits) {
2138 if (liveTransactionBySequenceNumberTable.keySet().size() == 0) {
2139 // There is nothing to speculate on
2143 // Create a list of the transaction sequence numbers and sort them from oldest to newest
2144 List<Long> transactionSequenceNumbersSorted = new ArrayList<Long>(liveTransactionBySequenceNumberTable.keySet());
2145 Collections.sort(transactionSequenceNumbersSorted);
2147 boolean hasGapInTransactionSequenceNumbers = transactionSequenceNumbersSorted.get(0) != oldestTransactionSequenceNumberSpeculatedOn;
2150 if (hasGapInTransactionSequenceNumbers || didProcessNewCommits) {
2151 // If there is a gap in the transaction sequence numbers then there was a commit or an abort of a transaction
2152 // OR there was a new commit (Could be from offline commit) so a redo the speculation from scratch
2154 // Start from scratch
2155 speculatedKeyValueTable.clear();
2156 lastTransactionSequenceNumberSpeculatedOn = -1;
2157 oldestTransactionSequenceNumberSpeculatedOn = -1;
2161 // Remember the front of the transaction list
2162 oldestTransactionSequenceNumberSpeculatedOn = transactionSequenceNumbersSorted.get(0);
2164 // Find where to start arbitration from
2165 int startIndex = transactionSequenceNumbersSorted.indexOf(lastTransactionSequenceNumberSpeculatedOn) + 1;
2167 if (startIndex >= transactionSequenceNumbersSorted.size()) {
2168 // Make sure we are not out of bounds
2169 return false; // did not speculate
2172 Set<Long> incompleteTransactionArbitrator = new HashSet<Long>();
2173 boolean didSkip = true;
2175 for (int i = startIndex; i < transactionSequenceNumbersSorted.size(); i++) {
2176 long transactionSequenceNumber = transactionSequenceNumbersSorted.get(i);
2177 Transaction transaction = liveTransactionBySequenceNumberTable.get(transactionSequenceNumber);
2179 if (!transaction.isComplete()) {
2180 // If there is an incomplete transaction then there is nothing we can do
2181 // add this transactions arbitrator to the list of arbitrators we should ignore
2182 incompleteTransactionArbitrator.add(transaction.getArbitrator());
2187 if (incompleteTransactionArbitrator.contains(transaction.getArbitrator())) {
2191 lastTransactionSequenceNumberSpeculatedOn = transactionSequenceNumber;
2193 if (transaction.evaluateGuard(committedKeyValueTable, speculatedKeyValueTable, null)) {
2194 // Guard evaluated to true so update the speculative table
2195 for (KeyValue kv : transaction.getKeyValueUpdateSet()) {
2196 speculatedKeyValueTable.put(kv.getKey(), kv);
2202 // Since there was a skip we need to redo the speculation next time around
2203 lastTransactionSequenceNumberSpeculatedOn = -1;
2204 oldestTransactionSequenceNumberSpeculatedOn = -1;
2207 // We did some speculation
2212 * Create the pending transaction speculative table from transactions that are still in the pending transaction buffer
2214 private void updatePendingTransactionSpeculativeTable(boolean didProcessNewCommitsOrSpeculate) {
2215 if (pendingTransactionQueue.size() == 0) {
2216 // There is nothing to speculate on
2221 if (didProcessNewCommitsOrSpeculate || (firstPendingTransaction != pendingTransactionQueue.get(0))) {
2222 // need to reset on the pending speculation
2223 lastPendingTransactionSpeculatedOn = null;
2224 firstPendingTransaction = pendingTransactionQueue.get(0);
2225 pendingTransactionSpeculatedKeyValueTable.clear();
2228 // Find where to start arbitration from
2229 int startIndex = pendingTransactionQueue.indexOf(firstPendingTransaction) + 1;
2231 if (startIndex >= pendingTransactionQueue.size()) {
2232 // Make sure we are not out of bounds
2236 for (int i = startIndex; i < pendingTransactionQueue.size(); i++) {
2237 Transaction transaction = pendingTransactionQueue.get(i);
2239 lastPendingTransactionSpeculatedOn = transaction;
2241 if (transaction.evaluateGuard(committedKeyValueTable, speculatedKeyValueTable, pendingTransactionSpeculatedKeyValueTable)) {
2242 // Guard evaluated to true so update the speculative table
2243 for (KeyValue kv : transaction.getKeyValueUpdateSet()) {
2244 pendingTransactionSpeculatedKeyValueTable.put(kv.getKey(), kv);
2251 * Set dead and remove from the live transaction tables the transactions that are dead
2253 private void updateLiveTransactionsAndStatus() {
2255 // Go through each of the transactions
2256 for (Iterator<Map.Entry<Long, Transaction>> iter = liveTransactionBySequenceNumberTable.entrySet().iterator(); iter.hasNext();) {
2257 Transaction transaction = iter.next().getValue();
2259 // Check if the transaction is dead
2260 Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(transaction.getArbitrator());
2261 if ((lastTransactionNumber != null) && (lastTransactionNumber >= transaction.getSequenceNumber())) {
2263 // Set dead the transaction
2264 transaction.setDead();
2266 // Remove the transaction from the live table
2268 liveTransactionByTransactionIdTable.remove(transaction.getId());
2272 // Go through each of the transactions
2273 for (Iterator<Map.Entry<Long, TransactionStatus>> iter = outstandingTransactionStatus.entrySet().iterator(); iter.hasNext();) {
2274 TransactionStatus status = iter.next().getValue();
2276 // Check if the transaction is dead
2277 Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(status.getTransactionArbitrator());
2278 if ((lastTransactionNumber != null) && (lastTransactionNumber >= status.getTransactionSequenceNumber())) {
2281 status.setStatus(TransactionStatus.StatusCommitted);
2290 * Process this slot, entry by entry. Also update the latest message sent by slot
2292 private void processSlot(SlotIndexer indexer, Slot slot, boolean acceptUpdatesToLocal, HashSet<Long> machineSet) {
2294 // Update the last message seen
2295 updateLastMessage(slot.getMachineID(), slot.getSequenceNumber(), slot, acceptUpdatesToLocal, machineSet);
2297 // Process each entry in the slot
2298 for (Entry entry : slot.getEntries()) {
2299 switch (entry.getType()) {
2301 case Entry.TypeCommitPart:
2302 processEntry((CommitPart)entry);
2305 case Entry.TypeAbort:
2306 processEntry((Abort)entry);
2309 case Entry.TypeTransactionPart:
2310 processEntry((TransactionPart)entry);
2313 case Entry.TypeNewKey:
2314 processEntry((NewKey)entry);
2317 case Entry.TypeLastMessage:
2318 processEntry((LastMessage)entry, machineSet);
2321 case Entry.TypeRejectedMessage:
2322 processEntry((RejectedMessage)entry, indexer);
2325 case Entry.TypeTableStatus:
2326 processEntry((TableStatus)entry, slot.getSequenceNumber());
2330 throw new Error("Unrecognized type: " + entry.getType());
2336 * Update the last message that was sent for a machine Id
2338 private void processEntry(LastMessage entry, HashSet<Long> machineSet) {
2339 // Update what the last message received by a machine was
2340 updateLastMessage(entry.getMachineID(), entry.getSequenceNumber(), entry, false, machineSet);
2344 * Add the new key to the arbitrators table and update the set of live new keys (in case of a rescued new key message)
2346 private void processEntry(NewKey entry) {
2348 // Update the arbitrator table with the new key information
2349 arbitratorTable.put(entry.getKey(), entry.getMachineID());
2351 // Update what the latest live new key is
2352 NewKey oldNewKey = liveNewKeyTable.put(entry.getKey(), entry);
2353 if (oldNewKey != null) {
2354 // Delete the old new key messages
2355 oldNewKey.setDead();
2360 * Process new table status entries and set dead the old ones as new ones come in.
2361 * keeps track of the largest and smallest table status seen in this current round
2362 * of updating the local copy of the block chain
2364 private void processEntry(TableStatus entry, long seq) {
2365 int newNumSlots = entry.getMaxSlots();
2366 updateCurrMaxSize(newNumSlots);
2368 initExpectedSize(seq, newNumSlots);
2370 if (liveTableStatus != null) {
2371 // We have a larger table status so the old table status is no longer alive
2372 liveTableStatus.setDead();
2375 // Make this new table status the latest alive table status
2376 liveTableStatus = entry;
2380 * Check old messages to see if there is a block chain violation. Also
2382 private void processEntry(RejectedMessage entry, SlotIndexer indexer) {
2383 long oldSeqNum = entry.getOldSeqNum();
2384 long newSeqNum = entry.getNewSeqNum();
2385 boolean isequal = entry.getEqual();
2386 long machineId = entry.getMachineID();
2387 long seq = entry.getSequenceNumber();
2390 // Check if we have messages that were supposed to be rejected in our local block chain
2391 for (long seqNum = oldSeqNum; seqNum <= newSeqNum; seqNum++) {
2394 Slot slot = indexer.getSlot(seqNum);
2397 // If we have this slot make sure that it was not supposed to be a rejected slot
2399 long slotMachineId = slot.getMachineID();
2400 if (isequal != (slotMachineId == machineId)) {
2401 throw new Error("Server Error: Trying to insert rejected message for slot " + seqNum);
2407 // Create a list of clients to watch until they see this rejected message entry.
2408 HashSet<Long> deviceWatchSet = new HashSet<Long>();
2409 for (Map.Entry<Long, Pair<Long, Liveness>> lastMessageEntry : lastMessageTable.entrySet()) {
2411 // Machine ID for the last message entry
2412 long lastMessageEntryMachineId = lastMessageEntry.getKey();
2414 // We've seen it, don't need to continue to watch. Our next
2415 // message will implicitly acknowledge it.
2416 if (lastMessageEntryMachineId == localMachineId) {
2420 Pair<Long, Liveness> lastMessageValue = lastMessageEntry.getValue();
2421 long entrySequenceNumber = lastMessageValue.getFirst();
2423 if (entrySequenceNumber < seq) {
2425 // Add this rejected message to the set of messages that this machine ID did not see yet
2426 addWatchList(lastMessageEntryMachineId, entry);
2428 // This client did not see this rejected message yet so add it to the watch set to monitor
2429 deviceWatchSet.add(lastMessageEntryMachineId);
2433 if (deviceWatchSet.isEmpty()) {
2434 // This rejected message has been seen by all the clients so
2437 // We need to watch this rejected message
2438 entry.setWatchSet(deviceWatchSet);
2443 * Check if this abort is live, if not then save it so we can kill it later.
2444 * update the last transaction number that was arbitrated on.
2446 private void processEntry(Abort entry) {
2449 if (entry.getTransactionSequenceNumber() != -1) {
2450 // update the transaction status if it was sent to the server
2451 TransactionStatus status = outstandingTransactionStatus.remove(entry.getTransactionSequenceNumber());
2452 if (status != null) {
2453 status.setStatus(TransactionStatus.StatusAborted);
2457 // Abort has not been seen by the client it is for yet so we need to keep track of it
2458 Abort previouslySeenAbort = liveAbortTable.put(entry.getAbortId(), entry);
2459 if (previouslySeenAbort != null) {
2460 previouslySeenAbort.setDead(); // Delete old version of the abort since we got a rescued newer version
2463 if (entry.getTransactionArbitrator() == localMachineId) {
2464 liveAbortsGeneratedByLocal.put(entry.getArbitratorLocalSequenceNumber(), entry);
2467 if ((entry.getSequenceNumber() != -1) && (lastMessageTable.get(entry.getTransactionMachineId()).getFirst() >= entry.getSequenceNumber())) {
2469 // The machine already saw this so it is dead
2471 liveAbortTable.remove(entry.getAbortId());
2473 if (entry.getTransactionArbitrator() == localMachineId) {
2474 liveAbortsGeneratedByLocal.remove(entry.getArbitratorLocalSequenceNumber());
2483 // Update the last arbitration data that we have seen so far
2484 if (lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(entry.getTransactionArbitrator()) != null) {
2486 long lastArbitrationSequenceNumber = lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(entry.getTransactionArbitrator());
2487 if (entry.getSequenceNumber() > lastArbitrationSequenceNumber) {
2489 lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.put(entry.getTransactionArbitrator(), entry.getSequenceNumber());
2492 // Never seen any data from this arbitrator so record the first one
2493 lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.put(entry.getTransactionArbitrator(), entry.getSequenceNumber());
2497 // Set dead a transaction if we can
2498 Transaction transactionToSetDead = liveTransactionByTransactionIdTable.remove(new Pair<Long, Long>(entry.getTransactionMachineId(), entry.getTransactionClientLocalSequenceNumber()));
2499 if (transactionToSetDead != null) {
2500 liveTransactionBySequenceNumberTable.remove(transactionToSetDead.getSequenceNumber());
2503 // Update the last transaction sequence number that the arbitrator arbitrated on
2504 Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(entry.getTransactionArbitrator());
2505 if ((lastTransactionNumber == null) || (lastTransactionNumber < entry.getTransactionSequenceNumber())) {
2508 if (entry.getTransactionSequenceNumber() != -1) {
2509 lastArbitratedTransactionNumberByArbitratorTable.put(entry.getTransactionArbitrator(), entry.getTransactionSequenceNumber());
2515 * Set dead the transaction part if that transaction is dead and keep track of all new parts
2517 private void processEntry(TransactionPart entry) {
2518 // Check if we have already seen this transaction and set it dead OR if it is not alive
2519 Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(entry.getArbitratorId());
2520 if ((lastTransactionNumber != null) && (lastTransactionNumber >= entry.getSequenceNumber())) {
2521 // This transaction is dead, it was already committed or aborted
2526 // This part is still alive
2527 Map<Pair<Long, Integer>, TransactionPart> transactionPart = newTransactionParts.get(entry.getMachineId());
2529 if (transactionPart == null) {
2530 // Dont have a table for this machine Id yet so make one
2531 transactionPart = new HashMap<Pair<Long, Integer>, TransactionPart>();
2532 newTransactionParts.put(entry.getMachineId(), transactionPart);
2535 // Update the part and set dead ones we have already seen (got a rescued version)
2536 TransactionPart previouslySeenPart = transactionPart.put(entry.getPartId(), entry);
2537 if (previouslySeenPart != null) {
2538 previouslySeenPart.setDead();
2543 * Process new commit entries and save them for future use. Delete duplicates
2545 private void processEntry(CommitPart entry) {
2548 // Update the last transaction that was updated if we can
2549 if (entry.getTransactionSequenceNumber() != -1) {
2550 Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(entry.getMachineId());
2552 // Update the last transaction sequence number that the arbitrator arbitrated on
2553 if ((lastTransactionNumber == null) || (lastTransactionNumber < entry.getTransactionSequenceNumber())) {
2554 lastArbitratedTransactionNumberByArbitratorTable.put(entry.getMachineId(), entry.getTransactionSequenceNumber());
2561 Map<Pair<Long, Integer>, CommitPart> commitPart = newCommitParts.get(entry.getMachineId());
2563 if (commitPart == null) {
2564 // Don't have a table for this machine Id yet so make one
2565 commitPart = new HashMap<Pair<Long, Integer>, CommitPart>();
2566 newCommitParts.put(entry.getMachineId(), commitPart);
2569 // Update the part and set dead ones we have already seen (got a rescued version)
2570 CommitPart previouslySeenPart = commitPart.put(entry.getPartId(), entry);
2571 if (previouslySeenPart != null) {
2572 previouslySeenPart.setDead();
2577 * Update the last message seen table. Update and set dead the appropriate RejectedMessages as clients see them.
2578 * Updates the live aborts, removes those that are dead and sets them dead.
2579 * Check that the last message seen is correct and that there is no mismatch of our own last message or that
2580 * other clients have not had a rollback on the last message.
2582 private void updateLastMessage(long machineId, long seqNum, Liveness liveness, boolean acceptUpdatesToLocal, HashSet<Long> machineSet) {
2584 // We have seen this machine ID
2585 machineSet.remove(machineId);
2587 // Get the set of rejected messages that this machine Id is has not seen yet
2588 HashSet<RejectedMessage> watchset = rejectedMessageWatchListTable.get(machineId);
2590 // If there is a rejected message that this machine Id has not seen yet
2591 if (watchset != null) {
2593 // Go through each rejected message that this machine Id has not seen yet
2594 for (Iterator<RejectedMessage> rmit = watchset.iterator(); rmit.hasNext(); ) {
2596 RejectedMessage rm = rmit.next();
2598 // If this machine Id has seen this rejected message...
2599 if (rm.getSequenceNumber() <= seqNum) {
2601 // Remove it from our watchlist
2604 // Decrement machines that need to see this notification
2605 rm.removeWatcher(machineId);
2610 // Set dead the abort
2611 for (Iterator<Map.Entry<Pair<Long, Long>, Abort>> i = liveAbortTable.entrySet().iterator(); i.hasNext();) {
2612 Abort abort = i.next().getValue();
2614 if ((abort.getTransactionMachineId() == machineId) && (abort.getSequenceNumber() <= seqNum)) {
2618 if (abort.getTransactionArbitrator() == localMachineId) {
2619 liveAbortsGeneratedByLocal.remove(abort.getArbitratorLocalSequenceNumber());
2626 if (machineId == localMachineId) {
2627 // Our own messages are immediately dead.
2628 if (liveness instanceof LastMessage) {
2629 ((LastMessage)liveness).setDead();
2630 } else if (liveness instanceof Slot) {
2631 ((Slot)liveness).setDead();
2633 throw new Error("Unrecognized type");
2637 // Get the old last message for this device
2638 Pair<Long, Liveness> lastMessageEntry = lastMessageTable.put(machineId, new Pair<Long, Liveness>(seqNum, liveness));
2639 if (lastMessageEntry == null) {
2640 // If no last message then there is nothing else to process
2644 long lastMessageSeqNum = lastMessageEntry.getFirst();
2645 Liveness lastEntry = lastMessageEntry.getSecond();
2647 // If it is not our machine Id since we already set ours to dead
2648 if (machineId != localMachineId) {
2649 if (lastEntry instanceof LastMessage) {
2650 ((LastMessage)lastEntry).setDead();
2651 } else if (lastEntry instanceof Slot) {
2652 ((Slot)lastEntry).setDead();
2654 throw new Error("Unrecognized type");
2658 // Make sure the server is not playing any games
2659 if (machineId == localMachineId) {
2661 if (hadPartialSendToServer) {
2662 // We were not making any updates and we had a machine mismatch
2663 if (lastMessageSeqNum > seqNum && !acceptUpdatesToLocal) {
2664 throw new Error("Server Error: Mismatch on local machine sequence number, needed at least: " + lastMessageSeqNum + " got: " + seqNum);
2668 // We were not making any updates and we had a machine mismatch
2669 if (lastMessageSeqNum != seqNum && !acceptUpdatesToLocal) {
2670 throw new Error("Server Error: Mismatch on local machine sequence number, needed: " + lastMessageSeqNum + " got: " + seqNum);
2674 if (lastMessageSeqNum > seqNum) {
2675 throw new Error("Server Error: Rollback on remote machine sequence number");
2681 * Add a rejected message entry to the watch set to keep track of which clients have seen that
2682 * rejected message entry and which have not.
2684 private void addWatchList(long machineId, RejectedMessage entry) {
2685 HashSet<RejectedMessage> entries = rejectedMessageWatchListTable.get(machineId);
2686 if (entries == null) {
2687 // There is no set for this machine ID yet so create one
2688 entries = new HashSet<RejectedMessage>();
2689 rejectedMessageWatchListTable.put(machineId, entries);
2695 * Check if the HMAC chain is not violated
2697 private void checkHMACChain(SlotIndexer indexer, Slot[] newSlots) {
2698 for (int i = 0; i < newSlots.length; i++) {
2699 Slot currSlot = newSlots[i];
2700 Slot prevSlot = indexer.getSlot(currSlot.getSequenceNumber() - 1);
2701 if (prevSlot != null &&
2702 !Arrays.equals(prevSlot.getHMAC(), currSlot.getPrevHMAC()))
2703 throw new Error("Server Error: Invalid HMAC Chain" + currSlot + " " + prevSlot);