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 {
26 static final int FREE_SLOTS = 10; // Number of slots that should be kept free
27 static final int SKIP_THRESHOLD = 10;
28 static final double RESIZE_MULTIPLE = 1.2;
29 static final double RESIZE_THRESHOLD = 0.75;
30 static final int REJECTED_THRESHOLD = 5;
33 private SlotBuffer buffer = null;
34 private CloudComm cloud = null;
35 private Random random = null;
36 private TableStatus liveTableStatus = null;
37 private PendingTransaction pendingTransactionBuilder = null; // Pending Transaction used in building a Pending Transaction
38 private Transaction lastPendingTransactionSpeculatedOn = null; // Last transaction that was speculated on from the pending transaction
39 private Transaction firstPendingTransaction = null; // first transaction in the pending transaction list
42 private int numberOfSlots = 0; // Number of slots stored in buffer
43 private int bufferResizeThreshold = 0; // Threshold on the number of live slots before a resize is needed
44 private long liveSlotCount = 0; // Number of currently live slots
45 private long oldestLiveSlotSequenceNumver = 0; // Smallest sequence number of the slot with a live entry
46 private long localMachineId = 0; // Machine ID of this client device
47 private long sequenceNumber = 0; // Largest sequence number a client has received
48 private int smallestTableStatusSeen = -1; // Smallest Table Status that was seen in the latest slots sent from the server
49 private int largestTableStatusSeen = -1; // Largest Table Status that was seen in the latest slots sent from the server
50 private long localTransactionSequenceNumber = 0; // Local sequence number counter for transactions
51 private long lastTransactionSequenceNumberSpeculatedOn = -1; // the last transaction that was speculated on
52 private long oldestTransactionSequenceNumberSpeculatedOn = -1; // the oldest transaction that was speculated on
53 private long localArbitrationSequenceNumber = 0;
54 private boolean hadPartialSendToServer = false;
55 private boolean attemptedToSendToServer = false;
58 private Map<IoTString, KeyValue> committedKeyValueTable = null; // Table of committed key value pairs
59 private Map<IoTString, KeyValue> speculatedKeyValueTable = null; // Table of speculated key value pairs, if there is a speculative value
60 private Map<IoTString, KeyValue> pendingTransactionSpeculatedKeyValueTable = null; // Table of speculated key value pairs, if there is a speculative value from the pending transactions
61 private Map<IoTString, NewKey> liveNewKeyTable = null; // Table of live new keys
62 private HashMap<Long, Pair<Long, Liveness>> lastMessageTable = null; // Last message sent by a client machine id -> (Seq Num, Slot or LastMessage);
63 private HashMap<Long, HashSet<RejectedMessage>> rejectedMessageWatchListTable = null; // Table of machine Ids and the set of rejected messages they have not seen yet
64 private Map<IoTString, Long> arbitratorTable = null; // Table of keys and their arbitrators
65 private Map<Pair<Long, Long>, Abort> liveAbortTable = null; // Table live abort messages
66 private Map<Long, Map<Pair<Long, Integer>, TransactionPart>> newTransactionParts = null; // transaction parts that are seen in this latest round of slots from the server
67 private Map<Long, Map<Pair<Long, Integer>, CommitPart>> newCommitParts = null; // commit parts that are seen in this latest round of slots from the server
68 private Map<Long, Long> lastArbitratedTransactionNumberByArbitratorTable = null; // Last transaction sequence number that an arbitrator arbitrated on
69 private Map<Long, Transaction> liveTransactionBySequenceNumberTable = null; // live transaction grouped by the sequence number
70 private Map<Pair<Long, Long>, Transaction> liveTransactionByTransactionIdTable = null; // live transaction grouped by the transaction ID
71 private Map<Long, Map<Long, Commit>> liveCommitsTable = null;
72 private Map<IoTString, Commit> liveCommitsByKeyTable = null;
73 private Map<Long, Long> lastCommitSeenSequenceNumberByArbitratorTable = null;
74 private Vector<Long> rejectedSlotList = null; // List of rejected slots that have yet to be sent to the server
75 private List<Transaction> pendingTransactionQueue = null;
76 private List<ArbitrationRound> pendingSendArbitrationRounds = null;
77 private List<Entry> pendingSendArbitrationEntriesToDelete = null;
78 private Map<Transaction, List<Integer>> transactionPartsSent = null;
79 private Map<Long, TransactionStatus> outstandingTransactionStatus = null;
80 private Map<Long, Abort> liveAbortsGeneratedByLocal = null;
81 private Set<Pair<Long, Long>> offlineTransactionsCommittedAndAtServer = null;
82 private Map<Long, Pair<String, Integer>> localCommunicationTable = null;
83 private Map<Long, Long> lastTransactionSeenFromMachineFromServer = null;
84 private Map<Long, Long> lastArbitrationDataLocalSequenceNumberSeenFromArbitrator = null;
90 public Table(String baseurl, String password, long _localMachineId, int listeningPort) {
91 localMachineId = _localMachineId;
92 cloud = new CloudComm(this, baseurl, password, listeningPort);
97 public Table(CloudComm _cloud, long _localMachineId) {
98 localMachineId = _localMachineId;
105 * Init all the stuff needed for for table usage
107 private void init() {
109 // Init helper objects
110 random = new Random();
111 buffer = new SlotBuffer();
114 oldestLiveSlotSequenceNumver = 1;
117 committedKeyValueTable = new HashMap<IoTString, KeyValue>();
118 speculatedKeyValueTable = new HashMap<IoTString, KeyValue>();
119 pendingTransactionSpeculatedKeyValueTable = new HashMap<IoTString, KeyValue>();
120 liveNewKeyTable = new HashMap<IoTString, NewKey>();
121 lastMessageTable = new HashMap<Long, Pair<Long, Liveness>>();
122 rejectedMessageWatchListTable = new HashMap<Long, HashSet<RejectedMessage>>();
123 arbitratorTable = new HashMap<IoTString, Long>();
124 liveAbortTable = new HashMap<Pair<Long, Long>, Abort>();
125 newTransactionParts = new HashMap<Long, Map<Pair<Long, Integer>, TransactionPart>>();
126 newCommitParts = new HashMap<Long, Map<Pair<Long, Integer>, CommitPart>>();
127 lastArbitratedTransactionNumberByArbitratorTable = new HashMap<Long, Long>();
128 liveTransactionBySequenceNumberTable = new HashMap<Long, Transaction>();
129 liveTransactionByTransactionIdTable = new HashMap<Pair<Long, Long>, Transaction>();
130 liveCommitsTable = new HashMap<Long, Map<Long, Commit>>();
131 liveCommitsByKeyTable = new HashMap<IoTString, Commit>();
132 lastCommitSeenSequenceNumberByArbitratorTable = new HashMap<Long, Long>();
133 rejectedSlotList = new Vector<Long>();
134 pendingTransactionQueue = new ArrayList<Transaction>();
135 pendingSendArbitrationEntriesToDelete = new ArrayList<Entry>();
136 transactionPartsSent = new HashMap<Transaction, List<Integer>>();
137 outstandingTransactionStatus = new HashMap<Long, TransactionStatus>();
138 liveAbortsGeneratedByLocal = new HashMap<Long, Abort>();
139 offlineTransactionsCommittedAndAtServer = new HashSet<Pair<Long, Long>>();
140 localCommunicationTable = new HashMap<Long, Pair<String, Integer>>();
141 lastTransactionSeenFromMachineFromServer = new HashMap<Long, Long>();
142 pendingSendArbitrationRounds = new ArrayList<ArbitrationRound>();
143 lastArbitrationDataLocalSequenceNumberSeenFromArbitrator = new HashMap<Long, Long>();
147 numberOfSlots = buffer.capacity();
148 setResizeThreshold();
151 // TODO: delete method
152 public synchronized void printSlots() {
153 long o = buffer.getOldestSeqNum();
154 long n = buffer.getNewestSeqNum();
156 int[] types = new int[10];
162 for (long i = o; i < (n + 1); i++) {
163 Slot s = buffer.getSlot(i);
165 Vector<Entry> entries = s.getEntries();
167 for (Entry e : entries) {
169 int type = e.getType();
170 types[type] = types[type] + 1;
179 for (int i = 0; i < 10; i++) {
180 System.out.println(i + " " + types[i]);
182 System.out.println("Live count: " + livec);
183 System.out.println("Dead count: " + deadc);
184 System.out.println("Old: " + o);
185 System.out.println("New: " + n);
186 System.out.println("Size: " + buffer.size());
188 // List<IoTString> strList = new ArrayList<IoTString>();
189 // for (int i = 0; i < 100; i++) {
190 // String keyA = "a" + i;
191 // String keyB = "b" + i;
192 // String keyC = "c" + i;
193 // String keyD = "d" + i;
195 // IoTString iKeyA = new IoTString(keyA);
196 // IoTString iKeyB = new IoTString(keyB);
197 // IoTString iKeyC = new IoTString(keyC);
198 // IoTString iKeyD = new IoTString(keyD);
200 // strList.add(iKeyA);
201 // strList.add(iKeyB);
202 // strList.add(iKeyC);
203 // strList.add(iKeyD);
207 // for (Long l : commitMap.keySet()) {
208 // for (Long l2 : commitMap.get(l).keySet()) {
209 // for (KeyValue kv : commitMap.get(l).get(l2).getkeyValueUpdateSet()) {
210 // strList.remove(kv.getKey());
211 // System.out.print(kv.getKey() + " ");
216 // System.out.println();
217 // System.out.println();
219 // for (IoTString s : strList) {
220 // System.out.print(s + " ");
222 // System.out.println();
223 // System.out.println(strList.size());
227 * Initialize the table by inserting a table status as the first entry into the table status
228 * also initialize the crypto stuff.
230 public synchronized void initTable() throws ServerException {
231 cloud.initSecurity();
233 // Create the first insertion into the block chain which is the table status
234 Slot s = new Slot(this, 1, localMachineId);
235 TableStatus status = new TableStatus(s, numberOfSlots);
237 Slot[] array = cloud.putSlot(s, numberOfSlots);
240 array = new Slot[] {s};
241 // update local block chain
242 validateAndUpdate(array, true);
243 } else if (array.length == 1) {
244 // in case we did push the slot BUT we failed to init it
245 validateAndUpdate(array, true);
247 throw new Error("Error on initialization");
252 * Rebuild the table from scratch by pulling the latest block chain from the server.
254 public synchronized void rebuild() throws ServerException {
255 // Just pull the latest slots from the server
256 Slot[] newslots = cloud.getSlots(sequenceNumber + 1);
257 validateAndUpdate(newslots, true);
260 // public String toString() {
261 // String retString = " Committed Table: \n";
262 // retString += "---------------------------\n";
263 // retString += commitedTable.toString();
265 // retString += "\n\n";
267 // retString += " Speculative Table: \n";
268 // retString += "---------------------------\n";
269 // retString += speculativeTable.toString();
274 public synchronized void addLocalCommunication(long arbitrator, String hostName, int portNumber) {
275 localCommunicationTable.put(arbitrator, new Pair<String, Integer>(hostName, portNumber));
278 public synchronized Long getArbitrator(IoTString key) {
279 return arbitratorTable.get(key);
282 public synchronized void close() {
286 public synchronized IoTString getCommitted(IoTString key) {
287 KeyValue kv = committedKeyValueTable.get(key);
290 return kv.getValue();
296 public synchronized IoTString getSpeculative(IoTString key) {
297 KeyValue kv = pendingTransactionSpeculatedKeyValueTable.get(key);
300 kv = speculatedKeyValueTable.get(key);
304 kv = committedKeyValueTable.get(key);
308 return kv.getValue();
314 public synchronized IoTString getCommittedAtomic(IoTString key) {
315 KeyValue kv = committedKeyValueTable.get(key);
317 if (arbitratorTable.get(key) == null) {
318 throw new Error("Key not Found.");
321 // Make sure new key value pair matches the current arbitrator
322 if (!pendingTransactionBuilder.checkArbitrator(arbitratorTable.get(key))) {
323 // TODO: Maybe not throw en error
324 throw new Error("Not all Key Values Match Arbitrator.");
328 pendingTransactionBuilder.addKVGuard(new KeyValue(key, kv.getValue()));
329 return kv.getValue();
331 pendingTransactionBuilder.addKVGuard(new KeyValue(key, null));
336 public synchronized IoTString getSpeculativeAtomic(IoTString key) {
337 if (arbitratorTable.get(key) == null) {
338 throw new Error("Key not Found.");
341 // Make sure new key value pair matches the current arbitrator
342 if (!pendingTransactionBuilder.checkArbitrator(arbitratorTable.get(key))) {
343 // TODO: Maybe not throw en error
344 throw new Error("Not all Key Values Match Arbitrator.");
347 KeyValue kv = pendingTransactionSpeculatedKeyValueTable.get(key);
350 kv = speculatedKeyValueTable.get(key);
354 kv = committedKeyValueTable.get(key);
358 pendingTransactionBuilder.addKVGuard(new KeyValue(key, kv.getValue()));
359 return kv.getValue();
361 pendingTransactionBuilder.addKVGuard(new KeyValue(key, null));
366 public synchronized boolean update() {
368 Slot[] newSlots = cloud.getSlots(sequenceNumber + 1);
369 validateAndUpdate(newSlots, false);
373 } catch (Exception e) {
374 // e.printStackTrace();
380 public synchronized boolean createNewKey(IoTString keyName, long machineId) throws ServerException {
382 if (arbitratorTable.get(keyName) != null) {
383 // There is already an arbitrator
387 NewKey newKey = new NewKey(null, keyName, machineId);
388 if (sendToServer(newKey)) {
389 // If successfully inserted
395 public synchronized void startTransaction() {
396 // Create a new transaction, invalidates any old pending transactions.
397 pendingTransactionBuilder = new PendingTransaction(localMachineId);
400 public synchronized void addKV(IoTString key, IoTString value) {
402 // Make sure it is a valid key
403 if (arbitratorTable.get(key) == null) {
404 throw new Error("Key not Found.");
407 // Make sure new key value pair matches the current arbitrator
408 if (!pendingTransactionBuilder.checkArbitrator(arbitratorTable.get(key))) {
409 // TODO: Maybe not throw en error
410 throw new Error("Not all Key Values Match Arbitrator.");
413 // Add the key value to this transaction
414 KeyValue kv = new KeyValue(key, value);
415 pendingTransactionBuilder.addKV(kv);
418 public synchronized TransactionStatus commitTransaction() {
420 if (pendingTransactionBuilder.getKVUpdates().size() == 0) {
421 // transaction with no updates will have no effect on the system
422 return new TransactionStatus(TransactionStatus.StatusNoEffect, -1);
425 // Set the local transaction sequence number and increment
426 pendingTransactionBuilder.setClientLocalSequenceNumber(localTransactionSequenceNumber);
427 localTransactionSequenceNumber++;
429 // Create the transaction status
430 TransactionStatus transactionStatus = new TransactionStatus(TransactionStatus.StatusPending, pendingTransactionBuilder.getArbitrator());
432 // Create the new transaction
433 Transaction newTransaction = pendingTransactionBuilder.createTransaction();
434 newTransaction.setTransactionStatus(transactionStatus);
436 if (pendingTransactionBuilder.getArbitrator() != localMachineId) {
437 // Add it to the queue and invalidate the builder for safety
438 pendingTransactionQueue.add(newTransaction);
440 arbitrateOnLocalTransaction(newTransaction);
441 updateLiveStateFromLocal();
444 pendingTransactionBuilder = new PendingTransaction(localMachineId);
448 } catch (ServerException e) {
450 Set<Long> arbitratorTriedAndFailed = new HashSet<Long>();
451 for (Iterator<Transaction> iter = pendingTransactionQueue.iterator(); iter.hasNext(); ) {
452 Transaction transaction = iter.next();
454 if (arbitratorTriedAndFailed.contains(transaction.getArbitrator())) {
455 // Already contacted this client so ignore all attempts to contact this client
456 // to preserve ordering for arbitrator
460 Pair<Boolean, Boolean> sendReturn = sendTransactionToLocal(transaction);
462 if (sendReturn.getFirst()) {
463 // Failed to contact over local
464 arbitratorTriedAndFailed.add(transaction.getArbitrator());
466 // Successful contact or should not contact
468 if (sendReturn.getSecond()) {
476 updateLiveStateFromLocal();
478 return transactionStatus;
482 * Get the machine ID for this client
484 public long getMachineId() {
485 return localMachineId;
489 * Decrement the number of live slots that we currently have
491 public void decrementLiveCount() {
496 * Recalculate the new resize threshold
498 private void setResizeThreshold() {
499 int resizeLower = (int) (RESIZE_THRESHOLD * numberOfSlots);
500 bufferResizeThreshold = resizeLower - 1 + random.nextInt(numberOfSlots - resizeLower);
503 private boolean sendToServer(NewKey newKey) throws ServerException {
506 // While we have stuff that needs inserting into the block chain
507 while ((pendingTransactionQueue.size() > 0) || (pendingSendArbitrationRounds.size() > 0) || (newKey != null)) {
510 Slot slot = new Slot(this, sequenceNumber + 1, localMachineId, buffer.getSlot(sequenceNumber).getHMAC());
512 // Try to fill the slot with data
513 ThreeTuple<Boolean, Integer, Boolean> fillSlotsReturn = fillSlot(slot, false, newKey);
514 boolean needsResize = fillSlotsReturn.getFirst();
515 int newSize = fillSlotsReturn.getSecond();
516 Boolean insertedNewKey = fillSlotsReturn.getThird();
519 // Reset which transaction to send
520 for (Transaction transaction : transactionPartsSent.keySet()) {
521 transaction.resetNextPartToSend();
523 // Set the transaction sequence number back to nothing
524 if (!transaction.didSendAPartToServer()) {
525 transaction.setSequenceNumber(-1);
529 // Clear the sent data since we are trying again
530 pendingSendArbitrationEntriesToDelete.clear();
531 transactionPartsSent.clear();
533 // We needed a resize so try again
534 fillSlot(slot, true, newKey);
537 // Try to send to the server
538 ThreeTuple<Boolean, Boolean, Slot[]> sendSlotsReturn = sendSlotsToServer(slot, newSize, newKey != null);
540 if (/*sendSlotsReturn.getSecond() || */sendSlotsReturn.getFirst()) {
541 // Did insert into the block chain
543 if (sendSlotsReturn.getFirst()) {
544 // This slot was what was inserted not a previous slot
546 // New Key was successfully inserted into the block chain so dont want to insert it again
550 // Remove the aborts and commit parts that were sent from the pending to send queue
551 for (Iterator<ArbitrationRound> iter = pendingSendArbitrationRounds.iterator(); iter.hasNext(); ) {
552 ArbitrationRound round = iter.next();
553 round.removeParts(pendingSendArbitrationEntriesToDelete);
555 if (round.isDoneSending()) {
556 // Sent all the parts
561 for (Transaction transaction : transactionPartsSent.keySet()) {
564 transaction.resetServerFailure();
567 // Update which transactions parts still need to be sent
568 transaction.removeSentParts(transactionPartsSent.get(transaction));
570 // Add the transaction status to the outstanding list
571 outstandingTransactionStatus.put(transaction.getSequenceNumber(), transaction.getTransactionStatus());
573 // Update the transaction status
574 transaction.getTransactionStatus().setStatus(TransactionStatus.StatusSentPartial);
576 // Check if all the transaction parts were successfully sent and if so then remove it from pending
577 if (transaction.didSendAllParts()) {
578 transaction.getTransactionStatus().setStatus(TransactionStatus.StatusSentFully);
579 pendingTransactionQueue.remove(transaction);
583 // Reset which transaction to send
584 for (Transaction transaction : transactionPartsSent.keySet()) {
585 transaction.resetNextPartToSend();
586 transaction.resetNextPartToSend();
588 // Set the transaction sequence number back to nothing
589 if (!transaction.didSendAPartToServer()) {
590 transaction.setSequenceNumber(-1);
595 // Clear the sent data in preparation for next send
596 pendingSendArbitrationEntriesToDelete.clear();
597 transactionPartsSent.clear();
599 if (sendSlotsReturn.getThird().length != 0) {
600 // insert into the local block chain
601 validateAndUpdate(sendSlotsReturn.getThird(), true);
604 } catch (ServerException e) {
606 System.out.println("Server Failure: " + e.getType());
609 if (e.getType() != ServerException.TypeInputTimeout) {
610 // e.printStackTrace();
612 // Nothing was able to be sent to the server so just clear these data structures
613 for (Transaction transaction : transactionPartsSent.keySet()) {
614 transaction.resetNextPartToSend();
616 // Set the transaction sequence number back to nothing
617 if (!transaction.didSendAPartToServer()) {
618 transaction.setSequenceNumber(-1);
622 // There was a partial send to the server
623 hadPartialSendToServer = true;
625 // Nothing was able to be sent to the server so just clear these data structures
626 for (Transaction transaction : transactionPartsSent.keySet()) {
627 transaction.resetNextPartToSend();
628 transaction.setServerFailure();
632 pendingSendArbitrationEntriesToDelete.clear();
633 transactionPartsSent.clear();
638 return newKey == null;
641 public synchronized boolean updateFromLocal(long machineId) {
642 Pair<String, Integer> localCommunicationInformation = localCommunicationTable.get(machineId);
643 if (localCommunicationInformation == null) {
644 // Cant talk to that device locally so do nothing
648 // Get the size of the send data
649 int sendDataSize = Integer.BYTES + Long.BYTES;
651 Long lastArbitrationDataLocalSequenceNumber = (long) - 1;
652 if (lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(machineId) != null) {
653 lastArbitrationDataLocalSequenceNumber = lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(machineId);
656 byte[] sendData = new byte[sendDataSize];
657 ByteBuffer bbEncode = ByteBuffer.wrap(sendData);
660 bbEncode.putLong(lastArbitrationDataLocalSequenceNumber);
664 byte[] returnData = cloud.sendLocalData(sendData, localCommunicationInformation.getFirst(), localCommunicationInformation.getSecond());
666 if (returnData == null) {
667 // Could not contact server
672 ByteBuffer bbDecode = ByteBuffer.wrap(returnData);
673 int numberOfEntries = bbDecode.getInt();
675 for (int i = 0; i < numberOfEntries; i++) {
676 byte type = bbDecode.get();
677 if (type == Entry.TypeAbort) {
678 Abort abort = (Abort)Abort.decode(null, bbDecode);
680 } else if (type == Entry.TypeCommitPart) {
681 CommitPart commitPart = (CommitPart)CommitPart.decode(null, bbDecode);
682 processEntry(commitPart);
686 updateLiveStateFromLocal();
691 private Pair<Boolean, Boolean> sendTransactionToLocal(Transaction transaction) {
693 // Get the devices local communications
694 Pair<String, Integer> localCommunicationInformation = localCommunicationTable.get(transaction.getArbitrator());
696 if (localCommunicationInformation == null) {
697 // Cant talk to that device locally so do nothing
698 return new Pair<Boolean, Boolean>(false, false);
701 // Get the size of the send data
702 int sendDataSize = Integer.BYTES + Long.BYTES;
703 for (TransactionPart part : transaction.getParts().values()) {
704 sendDataSize += part.getSize();
707 Long lastArbitrationDataLocalSequenceNumber = (long) - 1;
708 if (lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(transaction.getArbitrator()) != null) {
709 lastArbitrationDataLocalSequenceNumber = lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(transaction.getArbitrator());
712 // Make the send data size
713 byte[] sendData = new byte[sendDataSize];
714 ByteBuffer bbEncode = ByteBuffer.wrap(sendData);
717 bbEncode.putLong(lastArbitrationDataLocalSequenceNumber);
718 bbEncode.putInt(transaction.getParts().size());
719 for (TransactionPart part : transaction.getParts().values()) {
720 part.encode(bbEncode);
724 byte[] returnData = cloud.sendLocalData(sendData, localCommunicationInformation.getFirst(), localCommunicationInformation.getSecond());
726 if (returnData == null) {
727 // Could not contact server
728 return new Pair<Boolean, Boolean>(true, false);
732 ByteBuffer bbDecode = ByteBuffer.wrap(returnData);
733 boolean didCommit = bbDecode.get() == 1;
734 boolean couldArbitrate = bbDecode.get() == 1;
735 int numberOfEntries = bbDecode.getInt();
736 boolean foundAbort = false;
738 for (int i = 0; i < numberOfEntries; i++) {
739 byte type = bbDecode.get();
740 if (type == Entry.TypeAbort) {
741 Abort abort = (Abort)Abort.decode(null, bbDecode);
743 if ((abort.getTransactionMachineId() == localMachineId) && (abort.getTransactionClientLocalSequenceNumber() == transaction.getClientLocalSequenceNumber())) {
748 } else if (type == Entry.TypeCommitPart) {
749 CommitPart commitPart = (CommitPart)CommitPart.decode(null, bbDecode);
750 processEntry(commitPart);
754 updateLiveStateFromLocal();
756 if (couldArbitrate) {
757 TransactionStatus status = transaction.getTransactionStatus();
759 status.setStatus(TransactionStatus.StatusCommitted);
761 status.setStatus(TransactionStatus.StatusAborted);
764 TransactionStatus status = transaction.getTransactionStatus();
766 status.setStatus(TransactionStatus.StatusAborted);
768 status.setStatus(TransactionStatus.StatusCommitted);
772 return new Pair<Boolean, Boolean>(false, true);
775 public synchronized byte[] acceptDataFromLocal(byte[] data) {
777 ByteBuffer bbDecode = ByteBuffer.wrap(data);
778 long lastArbitratedSequenceNumberSeen = bbDecode.getLong();
779 int numberOfParts = bbDecode.getInt();
781 // If we did commit a transaction or not
782 boolean didCommit = false;
783 boolean couldArbitrate = false;
785 if (numberOfParts != 0) {
787 // decode the transaction
788 Transaction transaction = new Transaction();
789 for (int i = 0; i < numberOfParts; i++) {
791 TransactionPart newPart = (TransactionPart)TransactionPart.decode(null, bbDecode);
792 transaction.addPartDecode(newPart);
795 // Arbitrate on transaction and pull relevant return data
796 Pair<Boolean, Boolean> localArbitrateReturn = arbitrateOnLocalTransaction(transaction);
797 couldArbitrate = localArbitrateReturn.getFirst();
798 didCommit = localArbitrateReturn.getSecond();
800 updateLiveStateFromLocal();
802 // Transaction was sent to the server so keep track of it to prevent double commit
803 if (transaction.getSequenceNumber() != -1) {
804 offlineTransactionsCommittedAndAtServer.add(transaction.getId());
808 // The data to send back
809 int returnDataSize = 0;
810 List<Entry> unseenArbitrations = new ArrayList<Entry>();
812 // Get the aborts to send back
813 List<Long> abortLocalSequenceNumbers = new ArrayList<Long >(liveAbortsGeneratedByLocal.keySet());
814 Collections.sort(abortLocalSequenceNumbers);
815 for (Long localSequenceNumber : abortLocalSequenceNumbers) {
816 if (localSequenceNumber <= lastArbitratedSequenceNumberSeen) {
820 Abort abort = liveAbortsGeneratedByLocal.get(localSequenceNumber);
821 unseenArbitrations.add(abort);
822 returnDataSize += abort.getSize();
825 // Get the commits to send back
826 Map<Long, Commit> commitForClientTable = liveCommitsTable.get(localMachineId);
827 if (commitForClientTable != null) {
828 List<Long> commitLocalSequenceNumbers = new ArrayList<Long>(commitForClientTable.keySet());
829 Collections.sort(commitLocalSequenceNumbers);
831 for (Long localSequenceNumber : commitLocalSequenceNumbers) {
832 Commit commit = commitForClientTable.get(localSequenceNumber);
834 if (localSequenceNumber <= lastArbitratedSequenceNumberSeen) {
838 unseenArbitrations.addAll(commit.getParts().values());
840 for (CommitPart commitPart : commit.getParts().values()) {
841 returnDataSize += commitPart.getSize();
846 // Number of arbitration entries to decode
847 returnDataSize += 2 * Integer.BYTES;
849 // Boolean of did commit or not
850 if (numberOfParts != 0) {
851 returnDataSize += Byte.BYTES;
855 byte[] returnData = new byte[returnDataSize];
856 ByteBuffer bbEncode = ByteBuffer.wrap(returnData);
858 if (numberOfParts != 0) {
860 bbEncode.put((byte)1);
862 bbEncode.put((byte)0);
864 if (couldArbitrate) {
865 bbEncode.put((byte)1);
867 bbEncode.put((byte)0);
871 bbEncode.putInt(unseenArbitrations.size());
872 for (Entry entry : unseenArbitrations) {
873 entry.encode(bbEncode);
879 private ThreeTuple<Boolean, Boolean, Slot[]> sendSlotsToServer(Slot slot, int newSize, boolean isNewKey) throws ServerException {
881 boolean attemptedToSendToServerTmp = attemptedToSendToServer;
882 attemptedToSendToServer = true;
884 boolean inserted = false;
885 boolean lastTryInserted = false;
887 Slot[] array = cloud.putSlot(slot, newSize);
889 array = new Slot[] {slot};
890 rejectedSlotList.clear();
893 if (array.length == 0) {
894 throw new Error("Server Error: Did not send any slots");
897 // if (attemptedToSendToServerTmp) {
898 if (hadPartialSendToServer) {
900 boolean isInserted = false;
901 for (Slot s : array) {
902 if ((s.getSequenceNumber() == slot.getSequenceNumber()) && (s.getMachineID() == localMachineId)) {
908 for (Slot s : array) {
913 // Process each entry in the slot
914 for (Entry entry : s.getEntries()) {
916 if (entry.getType() == Entry.TypeLastMessage) {
917 LastMessage lastMessage = (LastMessage)entry;
919 if ((lastMessage.getMachineID() == localMachineId) && (lastMessage.getSequenceNumber() == slot.getSequenceNumber())) {
928 rejectedSlotList.add(slot.getSequenceNumber());
929 lastTryInserted = false;
931 lastTryInserted = true;
934 rejectedSlotList.add(slot.getSequenceNumber());
935 lastTryInserted = false;
939 return new ThreeTuple<Boolean, Boolean, Slot[]>(inserted, lastTryInserted, array);
943 * Returns false if a resize was needed
945 private ThreeTuple<Boolean, Integer, Boolean> fillSlot(Slot slot, boolean resize, NewKey newKeyEntry) {
947 if (liveSlotCount > bufferResizeThreshold) {
948 resize = true; //Resize is forced
952 newSize = (int) (numberOfSlots * RESIZE_MULTIPLE);
953 TableStatus status = new TableStatus(slot, newSize);
954 slot.addEntry(status);
957 // Fill with rejected slots first before doing anything else
958 doRejectedMessages(slot);
960 // Do mandatory rescue of entries
961 ThreeTuple<Boolean, Boolean, Long> mandatoryRescueReturn = doMandatoryResuce(slot, resize);
963 // Extract working variables
964 boolean needsResize = mandatoryRescueReturn.getFirst();
965 boolean seenLiveSlot = mandatoryRescueReturn.getSecond();
966 long currentRescueSequenceNumber = mandatoryRescueReturn.getThird();
968 if (needsResize && !resize) {
969 // We need to resize but we are not resizing so return false
970 return new ThreeTuple<Boolean, Integer, Boolean>(true, null, null);
973 boolean inserted = false;
974 if (newKeyEntry != null) {
975 newKeyEntry.setSlot(slot);
976 if (slot.hasSpace(newKeyEntry)) {
977 slot.addEntry(newKeyEntry);
982 // Clear the transactions, aborts and commits that were sent previously
983 transactionPartsSent.clear();
984 pendingSendArbitrationEntriesToDelete.clear();
986 for (ArbitrationRound round : pendingSendArbitrationRounds) {
987 boolean isFull = false;
988 round.generateParts();
989 List<Entry> parts = round.getParts();
991 // Insert pending arbitration data
992 for (Entry arbitrationData : parts) {
994 // If it is an abort then we need to set some information
995 if (arbitrationData instanceof Abort) {
996 ((Abort)arbitrationData).setSequenceNumber(slot.getSequenceNumber());
999 if (!slot.hasSpace(arbitrationData)) {
1000 // No space so cant do anything else with these data entries
1005 // Add to this current slot and add it to entries to delete
1006 slot.addEntry(arbitrationData);
1007 pendingSendArbitrationEntriesToDelete.add(arbitrationData);
1015 if (pendingTransactionQueue.size() > 0) {
1017 Transaction transaction = pendingTransactionQueue.get(0);
1019 // Set the transaction sequence number if it has yet to be inserted into the block chain
1020 if ((!transaction.didSendAPartToServer() && !transaction.getServerFailure()) || (transaction.getSequenceNumber() == -1)) {
1021 transaction.setSequenceNumber(slot.getSequenceNumber());
1025 TransactionPart part = transaction.getNextPartToSend();
1028 // Ran out of parts to send for this transaction so move on
1032 if (slot.hasSpace(part)) {
1033 slot.addEntry(part);
1034 List<Integer> partsSent = transactionPartsSent.get(transaction);
1035 if (partsSent == null) {
1036 partsSent = new ArrayList<Integer>();
1037 transactionPartsSent.put(transaction, partsSent);
1039 partsSent.add(part.getPartNumber());
1040 transactionPartsSent.put(transaction, partsSent);
1047 // Fill the remainder of the slot with rescue data
1048 doOptionalRescue(slot, seenLiveSlot, currentRescueSequenceNumber, resize);
1050 return new ThreeTuple<Boolean, Integer, Boolean>(false, newSize, inserted);
1053 private void doRejectedMessages(Slot s) {
1054 if (! rejectedSlotList.isEmpty()) {
1055 /* TODO: We should avoid generating a rejected message entry if
1056 * there is already a sufficient entry in the queue (e.g.,
1057 * equalsto value of true and same sequence number). */
1059 long old_seqn = rejectedSlotList.firstElement();
1060 if (rejectedSlotList.size() > REJECTED_THRESHOLD) {
1061 long new_seqn = rejectedSlotList.lastElement();
1062 RejectedMessage rm = new RejectedMessage(s, localMachineId, old_seqn, new_seqn, false);
1065 long prev_seqn = -1;
1067 /* Go through list of missing messages */
1068 for (; i < rejectedSlotList.size(); i++) {
1069 long curr_seqn = rejectedSlotList.get(i);
1070 Slot s_msg = buffer.getSlot(curr_seqn);
1073 prev_seqn = curr_seqn;
1075 /* Generate rejected message entry for missing messages */
1076 if (prev_seqn != -1) {
1077 RejectedMessage rm = new RejectedMessage(s, localMachineId, old_seqn, prev_seqn, false);
1080 /* Generate rejected message entries for present messages */
1081 for (; i < rejectedSlotList.size(); i++) {
1082 long curr_seqn = rejectedSlotList.get(i);
1083 Slot s_msg = buffer.getSlot(curr_seqn);
1084 long machineid = s_msg.getMachineID();
1085 RejectedMessage rm = new RejectedMessage(s, machineid, curr_seqn, curr_seqn, true);
1092 private ThreeTuple<Boolean, Boolean, Long> doMandatoryResuce(Slot slot, boolean resize) {
1093 long newestSequenceNumber = buffer.getNewestSeqNum();
1094 long oldestSequenceNumber = buffer.getOldestSeqNum();
1095 if (oldestLiveSlotSequenceNumver < oldestSequenceNumber) {
1096 oldestLiveSlotSequenceNumver = oldestSequenceNumber;
1099 long currentSequenceNumber = oldestLiveSlotSequenceNumver;
1100 boolean seenLiveSlot = false;
1101 long firstIfFull = newestSequenceNumber + 1 - numberOfSlots; // smallest seq number in the buffer if it is full
1102 long threshold = firstIfFull + FREE_SLOTS; // we want the buffer to be clear of live entries up to this point
1106 for (; currentSequenceNumber < threshold; currentSequenceNumber++) {
1107 Slot previousSlot = buffer.getSlot(currentSequenceNumber);
1108 // Push slot number forward
1109 if (! seenLiveSlot) {
1110 oldestLiveSlotSequenceNumver = currentSequenceNumber;
1113 if (!previousSlot.isLive()) {
1117 // We have seen a live slot
1118 seenLiveSlot = true;
1120 // Get all the live entries for a slot
1121 Vector<Entry> liveEntries = previousSlot.getLiveEntries(resize);
1123 // Iterate over all the live entries and try to rescue them
1124 for (Entry liveEntry : liveEntries) {
1125 if (slot.hasSpace(liveEntry)) {
1127 // Enough space to rescue the entry
1128 slot.addEntry(liveEntry);
1129 } else if (currentSequenceNumber == firstIfFull) {
1130 //if there's no space but the entry is about to fall off the queue
1131 System.out.println("B"); //?
1132 return new ThreeTuple<Boolean, Boolean, Long>(true, seenLiveSlot, currentSequenceNumber);
1139 return new ThreeTuple<Boolean, Boolean, Long>(false, seenLiveSlot, currentSequenceNumber);
1142 private void doOptionalRescue(Slot s, boolean seenliveslot, long seqn, boolean resize) {
1143 /* now go through live entries from least to greatest sequence number until
1144 * either all live slots added, or the slot doesn't have enough room
1145 * for SKIP_THRESHOLD consecutive entries*/
1147 long newestseqnum = buffer.getNewestSeqNum();
1149 for (; seqn <= newestseqnum; seqn++) {
1150 Slot prevslot = buffer.getSlot(seqn);
1151 //Push slot number forward
1153 oldestLiveSlotSequenceNumver = seqn;
1155 if (!prevslot.isLive())
1157 seenliveslot = true;
1158 Vector<Entry> liveentries = prevslot.getLiveEntries(resize);
1159 for (Entry liveentry : liveentries) {
1160 if (s.hasSpace(liveentry))
1161 s.addEntry(liveentry);
1164 if (skipcount > SKIP_THRESHOLD)
1172 * Checks for malicious activity and updates the local copy of the block chain.
1174 private void validateAndUpdate(Slot[] newSlots, boolean acceptUpdatesToLocal) {
1176 // The cloud communication layer has checked slot HMACs already before decoding
1177 if (newSlots.length == 0) {
1181 // Reset the table status declared sizes
1182 smallestTableStatusSeen = -1;
1183 largestTableStatusSeen = -1;
1186 // Make sure all slots are newer than the last largest slot this client has seen
1187 long firstSeqNum = newSlots[0].getSequenceNumber();
1188 if (firstSeqNum <= sequenceNumber) {
1189 throw new Error("Server Error: Sent older slots!");
1192 // Create an object that can access both new slots and slots in our local chain
1193 // without committing slots to our local chain
1194 SlotIndexer indexer = new SlotIndexer(newSlots, buffer);
1196 // Check that the HMAC chain is not broken
1197 checkHMACChain(indexer, newSlots);
1199 // Set to keep track of messages from clients
1200 HashSet<Long> machineSet = new HashSet<Long>(lastMessageTable.keySet());
1202 // Process each slots data
1203 for (Slot slot : newSlots) {
1204 processSlot(indexer, slot, acceptUpdatesToLocal, machineSet);
1207 // If there is a gap, check to see if the server sent us everything.
1208 if (firstSeqNum != (sequenceNumber + 1)) {
1210 // Check the size of the slots that were sent down by the server.
1211 // Can only check the size if there was a gap
1212 checkNumSlots(newSlots.length);
1214 // Since there was a gap every machine must have pushed a slot or must have
1215 // a last message message. If not then the server is hiding slots
1216 if (!machineSet.isEmpty()) {
1217 throw new Error("Missing record for machines: " + machineSet);
1221 // Update the size of our local block chain.
1224 // Commit new to slots to the local block chain.
1225 for (Slot slot : newSlots) {
1227 // Insert this slot into our local block chain copy.
1228 buffer.putSlot(slot);
1230 // Keep track of how many slots are currently live (have live data in them).
1234 // Get the sequence number of the latest slot in the system
1235 sequenceNumber = newSlots[newSlots.length - 1].getSequenceNumber();
1237 updateLiveStateFromServer();
1239 // No Need to remember after we pulled from the server
1240 offlineTransactionsCommittedAndAtServer.clear();
1242 // This is invalidated now
1243 hadPartialSendToServer = false;
1246 private void updateLiveStateFromServer() {
1247 // Process the new transaction parts
1248 processNewTransactionParts();
1250 // Do arbitration on new transactions that were received
1251 arbitrateFromServer();
1253 // Update all the committed keys
1254 boolean didCommitOrSpeculate = updateCommittedTable();
1256 // Delete the transactions that are now dead
1257 updateLiveTransactionsAndStatus();
1260 didCommitOrSpeculate |= updateSpeculativeTable(didCommitOrSpeculate);
1261 updatePendingTransactionSpeculativeTable(didCommitOrSpeculate);
1264 private void updateLiveStateFromLocal() {
1265 // Update all the committed keys
1266 boolean didCommitOrSpeculate = updateCommittedTable();
1268 // Delete the transactions that are now dead
1269 updateLiveTransactionsAndStatus();
1272 didCommitOrSpeculate |= updateSpeculativeTable(didCommitOrSpeculate);
1273 updatePendingTransactionSpeculativeTable(didCommitOrSpeculate);
1277 * Check the size of the block chain to make sure there are enough slots sent back by the server.
1278 * This is only called when we have a gap between the slots that we have locally and the slots
1279 * sent by the server therefore in the slots sent by the server there will be at least 1 Table
1282 private void checkNumSlots(int numberOfSlots) {
1284 // We only have 1 size so we must have this many slots
1285 if (largestTableStatusSeen == smallestTableStatusSeen) {
1286 if (numberOfSlots != smallestTableStatusSeen) {
1287 throw new Error("Server Error: Server did not send all slots. Expected: " + smallestTableStatusSeen + " Received:" + numberOfSlots);
1290 // We have more than 1
1291 if (numberOfSlots < smallestTableStatusSeen) {
1292 throw new Error("Server Error: Server did not send all slots. Expected at least: " + smallestTableStatusSeen + " Received:" + numberOfSlots);
1298 * Update the size of of the local buffer if it is needed.
1300 private void commitNewMaxSize() {
1302 int currMaxSize = 0;
1304 if (largestTableStatusSeen == -1) {
1305 // No table status seen so the current max size does not change
1306 currMaxSize = numberOfSlots;
1308 currMaxSize = largestTableStatusSeen;
1311 // Resize the local slot buffer
1312 if (numberOfSlots != currMaxSize) {
1313 buffer.resize(currMaxSize);
1316 // Change the number of local slots to the new size
1317 numberOfSlots = currMaxSize;
1319 // Recalculate the resize threshold since the size of the local buffer has changed
1320 setResizeThreshold();
1324 * Process the new transaction parts from this latest round of slots received from the server
1326 private void processNewTransactionParts() {
1328 if (newTransactionParts.size() == 0) {
1329 // Nothing new to process
1333 // Iterate through all the machine Ids that we received new parts for
1334 for (Long machineId : newTransactionParts.keySet()) {
1335 Map<Pair<Long, Integer>, TransactionPart> parts = newTransactionParts.get(machineId);
1337 // Iterate through all the parts for that machine Id
1338 for (Pair<Long, Integer> partId : parts.keySet()) {
1339 TransactionPart part = parts.get(partId);
1341 Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(part.getArbitratorId());
1342 if ((lastTransactionNumber != null) && (lastTransactionNumber >= part.getSequenceNumber())) {
1343 // Set dead the transaction part
1348 // Get the transaction object for that sequence number
1349 Transaction transaction = liveTransactionBySequenceNumberTable.get(part.getSequenceNumber());
1351 if (transaction == null) {
1352 // This is a new transaction that we dont have so make a new one
1353 transaction = new Transaction();
1355 // Insert this new transaction into the live tables
1356 liveTransactionBySequenceNumberTable.put(part.getSequenceNumber(), transaction);
1357 liveTransactionByTransactionIdTable.put(part.getTransactionId(), transaction);
1360 // Add that part to the transaction
1361 transaction.addPartDecode(part);
1365 // Clear all the new transaction parts in preparation for the next time the server sends slots
1366 newTransactionParts.clear();
1369 private void arbitrateFromServer() {
1371 if (liveTransactionBySequenceNumberTable.size() == 0) {
1372 // Nothing to arbitrate on so move on
1376 // Get the transaction sequence numbers and sort from oldest to newest
1377 List<Long> transactionSequenceNumbers = new ArrayList<Long>(liveTransactionBySequenceNumberTable.keySet());
1378 Collections.sort(transactionSequenceNumbers);
1380 // Collection of key value pairs that are
1381 Map<IoTString, KeyValue> speculativeTableTmp = new HashMap<IoTString, KeyValue>();
1383 // The last transaction arbitrated on
1384 long lastTransactionCommitted = -1;
1385 Set<Abort> generatedAborts = new HashSet<Abort>();
1387 for (Long transactionSequenceNumber : transactionSequenceNumbers) {
1388 Transaction transaction = liveTransactionBySequenceNumberTable.get(transactionSequenceNumber);
1390 // Check if this machine arbitrates for this transaction if not then we cant arbitrate this transaction
1391 if (transaction.getArbitrator() != localMachineId) {
1395 if (offlineTransactionsCommittedAndAtServer.contains(transaction.getId())) {
1396 // We have seen this already locally so dont commit again
1401 if (!transaction.isComplete()) {
1402 // Will arbitrate in incorrect order if we continue so just break
1407 // update the largest transaction seen by arbitrator from server
1408 if (lastTransactionSeenFromMachineFromServer.get(transaction.getMachineId()) == null) {
1409 lastTransactionSeenFromMachineFromServer.put(transaction.getMachineId(), transaction.getClientLocalSequenceNumber());
1411 Long lastTransactionSeenFromMachine = lastTransactionSeenFromMachineFromServer.get(transaction.getMachineId());
1412 if (transaction.getClientLocalSequenceNumber() > lastTransactionSeenFromMachine) {
1413 lastTransactionSeenFromMachineFromServer.put(transaction.getMachineId(), transaction.getClientLocalSequenceNumber());
1417 if (transaction.evaluateGuard(committedKeyValueTable, speculativeTableTmp, null)) {
1418 // Guard evaluated as true
1420 // Update the local changes so we can make the commit
1421 for (KeyValue kv : transaction.getKeyValueUpdateSet()) {
1422 speculativeTableTmp.put(kv.getKey(), kv);
1425 // Update what the last transaction committed was for use in batch commit
1426 lastTransactionCommitted = transaction.getSequenceNumber();
1428 // Guard evaluated was false so create abort
1431 Abort newAbort = new Abort(null,
1432 transaction.getClientLocalSequenceNumber(),
1433 transaction.getSequenceNumber(),
1434 transaction.getMachineId(),
1435 transaction.getArbitrator(),
1436 localArbitrationSequenceNumber);
1437 localArbitrationSequenceNumber++;
1439 generatedAborts.add(newAbort);
1441 // Insert the abort so we can process
1442 processEntry(newAbort);
1446 Commit newCommit = null;
1448 // If there is something to commit
1449 if (speculativeTableTmp.size() != 0) {
1451 // Create the commit and increment the commit sequence number
1452 newCommit = new Commit(localArbitrationSequenceNumber, localMachineId, lastTransactionCommitted);
1453 localArbitrationSequenceNumber++;
1455 // Add all the new keys to the commit
1456 for (KeyValue kv : speculativeTableTmp.values()) {
1457 newCommit.addKV(kv);
1460 // create the commit parts
1461 newCommit.createCommitParts();
1463 // Append all the commit parts to the end of the pending queue waiting for sending to the server
1465 // Insert the commit so we can process it
1466 for (CommitPart commitPart : newCommit.getParts().values()) {
1467 processEntry(commitPart);
1471 if ((newCommit != null) || (generatedAborts.size() > 0)) {
1472 ArbitrationRound arbitrationRound = new ArbitrationRound(newCommit, generatedAborts);
1473 pendingSendArbitrationRounds.add(arbitrationRound);
1475 if (compactArbitrationData()) {
1476 ArbitrationRound newArbitrationRound = pendingSendArbitrationRounds.get(pendingSendArbitrationRounds.size() - 1);
1477 if (newArbitrationRound.getCommit() != null) {
1478 for (CommitPart commitPart : newArbitrationRound.getCommit().getParts().values()) {
1479 processEntry(commitPart);
1486 private Pair<Boolean, Boolean> arbitrateOnLocalTransaction(Transaction transaction) {
1488 // Check if this machine arbitrates for this transaction if not then we cant arbitrate this transaction
1489 if (transaction.getArbitrator() != localMachineId) {
1490 return new Pair<Boolean, Boolean>(false, false);
1493 if (!transaction.isComplete()) {
1494 // Will arbitrate in incorrect order if we continue so just break
1496 return new Pair<Boolean, Boolean>(false, false);
1499 if (transaction.getMachineId() != localMachineId) {
1500 // dont do this check for local transactions
1501 if (lastTransactionSeenFromMachineFromServer.get(transaction.getMachineId()) != null) {
1502 if (lastTransactionSeenFromMachineFromServer.get(transaction.getMachineId()) > transaction.getClientLocalSequenceNumber()) {
1503 // We've have already seen this from the server
1504 return new Pair<Boolean, Boolean>(false, false);
1509 if (transaction.evaluateGuard(committedKeyValueTable, null, null)) {
1510 // Guard evaluated as true
1512 // Create the commit and increment the commit sequence number
1513 Commit newCommit = new Commit(localArbitrationSequenceNumber, localMachineId, -1);
1514 localArbitrationSequenceNumber++;
1516 // Update the local changes so we can make the commit
1517 for (KeyValue kv : transaction.getKeyValueUpdateSet()) {
1518 newCommit.addKV(kv);
1521 // create the commit parts
1522 newCommit.createCommitParts();
1524 // Append all the commit parts to the end of the pending queue waiting for sending to the server
1525 ArbitrationRound arbitrationRound = new ArbitrationRound(newCommit, new HashSet<Abort>());
1526 pendingSendArbitrationRounds.add(arbitrationRound);
1528 if (compactArbitrationData()) {
1529 ArbitrationRound newArbitrationRound = pendingSendArbitrationRounds.get(pendingSendArbitrationRounds.size() - 1);
1530 for (CommitPart commitPart : newArbitrationRound.getCommit().getParts().values()) {
1531 processEntry(commitPart);
1534 // Insert the commit so we can process it
1535 for (CommitPart commitPart : newCommit.getParts().values()) {
1536 processEntry(commitPart);
1540 if (transaction.getMachineId() == localMachineId) {
1541 TransactionStatus status = transaction.getTransactionStatus();
1542 if (status != null) {
1543 status.setStatus(TransactionStatus.StatusCommitted);
1547 updateLiveStateFromLocal();
1548 return new Pair<Boolean, Boolean>(true, true);
1551 if (transaction.getMachineId() == localMachineId) {
1552 // For locally created messages update the status
1554 // Guard evaluated was false so create abort
1555 TransactionStatus status = transaction.getTransactionStatus();
1556 if (status != null) {
1557 status.setStatus(TransactionStatus.StatusAborted);
1561 Set addAbortSet = new HashSet<Abort>();
1565 Abort newAbort = new Abort(null,
1566 transaction.getClientLocalSequenceNumber(),
1568 transaction.getMachineId(),
1569 transaction.getArbitrator(),
1570 localArbitrationSequenceNumber);
1571 localArbitrationSequenceNumber++;
1573 addAbortSet.add(newAbort);
1576 // Append all the commit parts to the end of the pending queue waiting for sending to the server
1577 ArbitrationRound arbitrationRound = new ArbitrationRound(null, addAbortSet);
1578 pendingSendArbitrationRounds.add(arbitrationRound);
1580 if (compactArbitrationData()) {
1581 ArbitrationRound newArbitrationRound = pendingSendArbitrationRounds.get(pendingSendArbitrationRounds.size() - 1);
1582 for (CommitPart commitPart : newArbitrationRound.getCommit().getParts().values()) {
1583 processEntry(commitPart);
1588 updateLiveStateFromLocal();
1589 return new Pair<Boolean, Boolean>(true, false);
1594 * 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
1596 private boolean compactArbitrationData() {
1598 if (pendingSendArbitrationRounds.size() < 2) {
1599 // Nothing to compact so do nothing
1603 ArbitrationRound lastRound = pendingSendArbitrationRounds.get(pendingSendArbitrationRounds.size() - 1);
1604 if (lastRound.didSendPart()) {
1608 boolean hadCommit = (lastRound.getCommit() == null);
1609 boolean gotNewCommit = false;
1611 int numberToDelete = 1;
1612 while (numberToDelete < pendingSendArbitrationRounds.size()) {
1613 ArbitrationRound round = pendingSendArbitrationRounds.get(pendingSendArbitrationRounds.size() - numberToDelete - 1);
1615 if (round.isFull() || round.didSendPart()) {
1616 // Stop since there is a part that cannot be compacted and we need to compact in order
1620 if (round.getCommit() == null) {
1622 // Try compacting aborts only
1623 int newSize = round.getCurrentSize() + lastRound.getAbortsCount();
1624 if (newSize > ArbitrationRound.MAX_PARTS) {
1625 // Cant compact since it would be too large
1628 lastRound.addAborts(round.getAborts());
1631 // Create a new larger commit
1632 Commit newCommit = Commit.merge(lastRound.getCommit(), round.getCommit(), localArbitrationSequenceNumber);
1633 localArbitrationSequenceNumber++;
1635 // Create the commit parts so that we can count them
1636 newCommit.createCommitParts();
1638 // Calculate the new size of the parts
1639 int newSize = newCommit.getNumberOfParts();
1640 newSize += lastRound.getAbortsCount();
1641 newSize += round.getAbortsCount();
1643 if (newSize > ArbitrationRound.MAX_PARTS) {
1644 // Cant compact since it would be too large
1648 // Set the new compacted part
1649 lastRound.setCommit(newCommit);
1650 lastRound.addAborts(round.getAborts());
1651 gotNewCommit = true;
1657 if (numberToDelete != 1) {
1658 // If there is a compaction
1660 // Delete the previous pieces that are now in the new compacted piece
1661 if (numberToDelete == pendingSendArbitrationRounds.size()) {
1662 pendingSendArbitrationRounds.clear();
1664 for (int i = 0; i < numberToDelete; i++) {
1665 pendingSendArbitrationRounds.remove(pendingSendArbitrationRounds.size() - 1);
1669 // Add the new compacted into the pending to send list
1670 pendingSendArbitrationRounds.add(lastRound);
1672 // Should reinsert into the commit processor
1673 if (hadCommit && gotNewCommit) {
1680 // private boolean compactArbitrationData() {
1685 * Update all the commits and the committed tables, sets dead the dead transactions
1687 private boolean updateCommittedTable() {
1689 if (newCommitParts.size() == 0) {
1690 // Nothing new to process
1694 // Iterate through all the machine Ids that we received new parts for
1695 for (Long machineId : newCommitParts.keySet()) {
1696 Map<Pair<Long, Integer>, CommitPart> parts = newCommitParts.get(machineId);
1698 // Iterate through all the parts for that machine Id
1699 for (Pair<Long, Integer> partId : parts.keySet()) {
1700 CommitPart part = parts.get(partId);
1702 // Get the transaction object for that sequence number
1703 Map<Long, Commit> commitForClientTable = liveCommitsTable.get(part.getMachineId());
1705 if (commitForClientTable == null) {
1706 // This is the first commit from this device
1707 commitForClientTable = new HashMap<Long, Commit>();
1708 liveCommitsTable.put(part.getMachineId(), commitForClientTable);
1711 Commit commit = commitForClientTable.get(part.getSequenceNumber());
1713 if (commit == null) {
1714 // This is a new commit that we dont have so make a new one
1715 commit = new Commit();
1717 // Insert this new commit into the live tables
1718 commitForClientTable.put(part.getSequenceNumber(), commit);
1721 // Add that part to the commit
1722 commit.addPartDecode(part);
1726 // Clear all the new commits parts in preparation for the next time the server sends slots
1727 newCommitParts.clear();
1729 // If we process a new commit keep track of it for future use
1730 boolean didProcessANewCommit = false;
1732 // Process the commits one by one
1733 for (Long arbitratorId : liveCommitsTable.keySet()) {
1735 // Get all the commits for a specific arbitrator
1736 Map<Long, Commit> commitForClientTable = liveCommitsTable.get(arbitratorId);
1738 // Sort the commits in order
1739 List<Long> commitSequenceNumbers = new ArrayList<Long>(commitForClientTable.keySet());
1740 Collections.sort(commitSequenceNumbers);
1742 // Get the last commit seen from this arbitrator
1743 long lastCommitSeenSequenceNumber = -1;
1744 if (lastCommitSeenSequenceNumberByArbitratorTable.get(arbitratorId) != null) {
1745 lastCommitSeenSequenceNumber = lastCommitSeenSequenceNumberByArbitratorTable.get(arbitratorId);
1748 // Go through each new commit one by one
1749 for (int i = 0; i < commitSequenceNumbers.size(); i++) {
1750 Long commitSequenceNumber = commitSequenceNumbers.get(i);
1751 Commit commit = commitForClientTable.get(commitSequenceNumber);
1753 // Special processing if a commit is not complete
1754 if (!commit.isComplete()) {
1755 if (i == (commitSequenceNumbers.size() - 1)) {
1756 // 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
1759 // This is a commit that was already dead but parts of it are still in the block chain (not flushed out yet).
1760 // Delete it and move on
1762 commitForClientTable.remove(commit.getSequenceNumber());
1767 // Update the last arbitration data that we have seen so far
1768 if (lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(commit.getMachineId()) != null) {
1770 long lastArbitrationSequenceNumber = lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(commit.getMachineId());
1771 if (commit.getSequenceNumber() > lastArbitrationSequenceNumber) {
1773 lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.put(commit.getMachineId(), commit.getSequenceNumber());
1776 // Never seen any data from this arbitrator so record the first one
1777 lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.put(commit.getMachineId(), commit.getSequenceNumber());
1780 // We have already seen this commit before so need to do the full processing on this commit
1781 if (commit.getSequenceNumber() <= lastCommitSeenSequenceNumber) {
1783 // Update the last transaction that was updated if we can
1784 if (commit.getTransactionSequenceNumber() != -1) {
1785 Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(commit.getMachineId());
1787 // Update the last transaction sequence number that the arbitrator arbitrated on
1788 if ((lastTransactionNumber == null) || (lastTransactionNumber < commit.getTransactionSequenceNumber())) {
1789 lastArbitratedTransactionNumberByArbitratorTable.put(commit.getMachineId(), commit.getTransactionSequenceNumber());
1796 // If we got here then this is a brand new commit and needs full processing
1798 // Get what commits should be edited, these are the commits that have live values for their keys
1799 Set<Commit> commitsToEdit = new HashSet<Commit>();
1800 for (KeyValue kv : commit.getKeyValueUpdateSet()) {
1801 commitsToEdit.add(liveCommitsByKeyTable.get(kv.getKey()));
1803 commitsToEdit.remove(null); // remove null since it could be in this set
1805 // Update each previous commit that needs to be updated
1806 for (Commit previousCommit : commitsToEdit) {
1808 // Only bother with live commits (TODO: Maybe remove this check)
1809 if (previousCommit.isLive()) {
1811 // Update which keys in the old commits are still live
1812 for (KeyValue kv : commit.getKeyValueUpdateSet()) {
1813 previousCommit.invalidateKey(kv.getKey());
1816 // if the commit is now dead then remove it
1817 if (!previousCommit.isLive()) {
1818 commitForClientTable.remove(previousCommit);
1823 // Update the last seen sequence number from this arbitrator
1824 if (lastCommitSeenSequenceNumberByArbitratorTable.get(commit.getMachineId()) != null) {
1825 if (commit.getSequenceNumber() > lastCommitSeenSequenceNumberByArbitratorTable.get(commit.getMachineId())) {
1826 lastCommitSeenSequenceNumberByArbitratorTable.put(commit.getMachineId(), commit.getSequenceNumber());
1829 lastCommitSeenSequenceNumberByArbitratorTable.put(commit.getMachineId(), commit.getSequenceNumber());
1834 // Update the last transaction that was updated if we can
1835 if (commit.getTransactionSequenceNumber() != -1) {
1836 Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(commit.getMachineId());
1838 // Update the last transaction sequence number that the arbitrator arbitrated on
1839 if ((lastTransactionNumber == null) || (lastTransactionNumber < commit.getTransactionSequenceNumber())) {
1840 lastArbitratedTransactionNumberByArbitratorTable.put(commit.getMachineId(), commit.getTransactionSequenceNumber());
1844 // We processed a new commit that we havent seen before
1845 didProcessANewCommit = true;
1849 // Update the committed table of keys and which commit is using which key
1850 for (KeyValue kv : commit.getKeyValueUpdateSet()) {
1851 committedKeyValueTable.put(kv.getKey(), kv);
1852 liveCommitsByKeyTable.put(kv.getKey(), commit);
1857 return didProcessANewCommit;
1861 * Create the speculative table from transactions that are still live and have come from the cloud
1863 private boolean updateSpeculativeTable(boolean didProcessNewCommits) {
1864 if (liveTransactionBySequenceNumberTable.keySet().size() == 0) {
1865 // There is nothing to speculate on
1869 // Create a list of the transaction sequence numbers and sort them from oldest to newest
1870 List<Long> transactionSequenceNumbersSorted = new ArrayList<Long>(liveTransactionBySequenceNumberTable.keySet());
1871 Collections.sort(transactionSequenceNumbersSorted);
1873 boolean hasGapInTransactionSequenceNumbers = transactionSequenceNumbersSorted.get(0) != oldestTransactionSequenceNumberSpeculatedOn;
1876 if (hasGapInTransactionSequenceNumbers || didProcessNewCommits) {
1877 // If there is a gap in the transaction sequence numbers then there was a commit or an abort of a transaction
1878 // OR there was a new commit (Could be from offline commit) so a redo the speculation from scratch
1880 // Start from scratch
1881 speculatedKeyValueTable.clear();
1882 lastTransactionSequenceNumberSpeculatedOn = -1;
1883 oldestTransactionSequenceNumberSpeculatedOn = -1;
1887 // Remember the front of the transaction list
1888 oldestTransactionSequenceNumberSpeculatedOn = transactionSequenceNumbersSorted.get(0);
1890 // Find where to start arbitration from
1891 int startIndex = transactionSequenceNumbersSorted.indexOf(lastTransactionSequenceNumberSpeculatedOn) + 1;
1893 if (startIndex >= transactionSequenceNumbersSorted.size()) {
1894 // Make sure we are not out of bounds
1895 return false; // did not speculate
1898 Set<Long> incompleteTransactionArbitrator = new HashSet<Long>();
1899 boolean didSkip = true;
1901 for (int i = startIndex; i < transactionSequenceNumbersSorted.size(); i++) {
1902 long transactionSequenceNumber = transactionSequenceNumbersSorted.get(i);
1903 Transaction transaction = liveTransactionBySequenceNumberTable.get(transactionSequenceNumber);
1905 if (!transaction.isComplete()) {
1906 // If there is an incomplete transaction then there is nothing we can do
1907 // add this transactions arbitrator to the list of arbitrators we should ignore
1908 incompleteTransactionArbitrator.add(transaction.getArbitrator());
1913 if (incompleteTransactionArbitrator.contains(transaction.getArbitrator())) {
1917 lastTransactionSequenceNumberSpeculatedOn = transactionSequenceNumber;
1919 if (transaction.evaluateGuard(committedKeyValueTable, speculatedKeyValueTable, null)) {
1920 // Guard evaluated to true so update the speculative table
1921 for (KeyValue kv : transaction.getKeyValueUpdateSet()) {
1922 speculatedKeyValueTable.put(kv.getKey(), kv);
1928 // Since there was a skip we need to redo the speculation next time around
1929 lastTransactionSequenceNumberSpeculatedOn = -1;
1930 oldestTransactionSequenceNumberSpeculatedOn = -1;
1933 // We did some speculation
1938 * Create the pending transaction speculative table from transactions that are still in the pending transaction buffer
1940 private void updatePendingTransactionSpeculativeTable(boolean didProcessNewCommitsOrSpeculate) {
1941 if (pendingTransactionQueue.size() == 0) {
1942 // There is nothing to speculate on
1947 if (didProcessNewCommitsOrSpeculate || (firstPendingTransaction != pendingTransactionQueue.get(0))) {
1948 // need to reset on the pending speculation
1949 lastPendingTransactionSpeculatedOn = null;
1950 firstPendingTransaction = pendingTransactionQueue.get(0);
1951 pendingTransactionSpeculatedKeyValueTable.clear();
1954 // Find where to start arbitration from
1955 int startIndex = pendingTransactionQueue.indexOf(firstPendingTransaction) + 1;
1957 if (startIndex >= pendingTransactionQueue.size()) {
1958 // Make sure we are not out of bounds
1962 for (int i = startIndex; i < pendingTransactionQueue.size(); i++) {
1963 Transaction transaction = pendingTransactionQueue.get(i);
1965 lastPendingTransactionSpeculatedOn = transaction;
1967 if (transaction.evaluateGuard(committedKeyValueTable, speculatedKeyValueTable, pendingTransactionSpeculatedKeyValueTable)) {
1968 // Guard evaluated to true so update the speculative table
1969 for (KeyValue kv : transaction.getKeyValueUpdateSet()) {
1970 pendingTransactionSpeculatedKeyValueTable.put(kv.getKey(), kv);
1977 * Set dead and remove from the live transaction tables the transactions that are dead
1979 private void updateLiveTransactionsAndStatus() {
1981 // Go through each of the transactions
1982 for (Iterator<Map.Entry<Long, Transaction>> iter = liveTransactionBySequenceNumberTable.entrySet().iterator(); iter.hasNext();) {
1983 Transaction transaction = iter.next().getValue();
1985 // Check if the transaction is dead
1986 Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(transaction.getArbitrator());
1987 if ((lastTransactionNumber != null) && (lastTransactionNumber >= transaction.getSequenceNumber())) {
1989 // Set dead the transaction
1990 transaction.setDead();
1992 // Remove the transaction from the live table
1994 liveTransactionByTransactionIdTable.remove(transaction.getId());
1998 // Go through each of the transactions
1999 for (Iterator<Map.Entry<Long, TransactionStatus>> iter = outstandingTransactionStatus.entrySet().iterator(); iter.hasNext();) {
2000 TransactionStatus status = iter.next().getValue();
2002 // Check if the transaction is dead
2003 Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(status.getTransactionArbitrator());
2004 if ((lastTransactionNumber != null) && (lastTransactionNumber >= status.getTransactionSequenceNumber())) {
2007 status.setStatus(TransactionStatus.StatusCommitted);
2016 * Process this slot, entry by entry. Also update the latest message sent by slot
2018 private void processSlot(SlotIndexer indexer, Slot slot, boolean acceptUpdatesToLocal, HashSet<Long> machineSet) {
2020 // Update the last message seen
2021 updateLastMessage(slot.getMachineID(), slot.getSequenceNumber(), slot, acceptUpdatesToLocal, machineSet);
2023 // Process each entry in the slot
2024 for (Entry entry : slot.getEntries()) {
2025 switch (entry.getType()) {
2027 case Entry.TypeCommitPart:
2028 processEntry((CommitPart)entry);
2031 case Entry.TypeAbort:
2032 processEntry((Abort)entry);
2035 case Entry.TypeTransactionPart:
2036 processEntry((TransactionPart)entry);
2039 case Entry.TypeNewKey:
2040 processEntry((NewKey)entry);
2043 case Entry.TypeLastMessage:
2044 processEntry((LastMessage)entry, machineSet);
2047 case Entry.TypeRejectedMessage:
2048 processEntry((RejectedMessage)entry, indexer);
2051 case Entry.TypeTableStatus:
2052 processEntry((TableStatus)entry);
2056 throw new Error("Unrecognized type: " + entry.getType());
2062 * Update the last message that was sent for a machine Id
2064 private void processEntry(LastMessage entry, HashSet<Long> machineSet) {
2065 // Update what the last message received by a machine was
2066 updateLastMessage(entry.getMachineID(), entry.getSequenceNumber(), entry, false, machineSet);
2070 * Add the new key to the arbitrators table and update the set of live new keys (in case of a rescued new key message)
2072 private void processEntry(NewKey entry) {
2074 // Update the arbitrator table with the new key information
2075 arbitratorTable.put(entry.getKey(), entry.getMachineID());
2077 // Update what the latest live new key is
2078 NewKey oldNewKey = liveNewKeyTable.put(entry.getKey(), entry);
2079 if (oldNewKey != null) {
2080 // Delete the old new key messages
2081 oldNewKey.setDead();
2086 * Process new table status entries and set dead the old ones as new ones come in.
2087 * keeps track of the largest and smallest table status seen in this current round
2088 * of updating the local copy of the block chain
2090 private void processEntry(TableStatus entry) {
2091 int newNumSlots = entry.getMaxSlots();
2093 if (liveTableStatus != null) {
2094 // We have a larger table status so the old table status is no longer alive
2095 liveTableStatus.setDead();
2098 // Make this new table status the latest alive table status
2099 liveTableStatus = entry;
2101 if ((smallestTableStatusSeen == -1) || (newNumSlots < smallestTableStatusSeen)) {
2102 smallestTableStatusSeen = newNumSlots;
2105 if ((largestTableStatusSeen == -1) || (newNumSlots > largestTableStatusSeen)) {
2106 largestTableStatusSeen = newNumSlots;
2111 * Check old messages to see if there is a block chain violation. Also
2113 private void processEntry(RejectedMessage entry, SlotIndexer indexer) {
2114 long oldSeqNum = entry.getOldSeqNum();
2115 long newSeqNum = entry.getNewSeqNum();
2116 boolean isequal = entry.getEqual();
2117 long machineId = entry.getMachineID();
2120 // Check if we have messages that were supposed to be rejected in our local block chain
2121 for (long seqNum = oldSeqNum; seqNum <= newSeqNum; seqNum++) {
2124 Slot slot = indexer.getSlot(seqNum);
2127 // If we have this slot make sure that it was not supposed to be a rejected slot
2129 long slotMachineId = slot.getMachineID();
2130 if (isequal != (slotMachineId == machineId)) {
2131 throw new Error("Server Error: Trying to insert rejected message for slot " + seqNum);
2137 // Create a list of clients to watch until they see this rejected message entry.
2138 HashSet<Long> deviceWatchSet = new HashSet<Long>();
2139 for (Map.Entry<Long, Pair<Long, Liveness>> lastMessageEntry : lastMessageTable.entrySet()) {
2141 // Machine ID for the last message entry
2142 long lastMessageEntryMachineId = lastMessageEntry.getKey();
2144 // We've seen it, don't need to continue to watch. Our next
2145 // message will implicitly acknowledge it.
2146 if (lastMessageEntryMachineId == localMachineId) {
2150 Pair<Long, Liveness> lastMessageValue = lastMessageEntry.getValue();
2151 long entrySequenceNumber = lastMessageValue.getFirst();
2153 if (entrySequenceNumber < newSeqNum) {
2155 // Add this rejected message to the set of messages that this machine ID did not see yet
2156 addWatchList(lastMessageEntryMachineId, entry);
2158 // This client did not see this rejected message yet so add it to the watch set to monitor
2159 deviceWatchSet.add(lastMessageEntryMachineId);
2163 if (deviceWatchSet.isEmpty()) {
2164 // This rejected message has been seen by all the clients so
2167 // We need to watch this rejected message
2168 entry.setWatchSet(deviceWatchSet);
2173 * Check if this abort is live, if not then save it so we can kill it later.
2174 * update the last transaction number that was arbitrated on.
2176 private void processEntry(Abort entry) {
2179 if (entry.getTransactionSequenceNumber() != -1) {
2180 // update the transaction status if it was sent to the server
2181 TransactionStatus status = outstandingTransactionStatus.remove(entry.getTransactionSequenceNumber());
2182 if (status != null) {
2183 status.setStatus(TransactionStatus.StatusAborted);
2187 // Abort has not been seen by the client it is for yet so we need to keep track of it
2188 Abort previouslySeenAbort = liveAbortTable.put(entry.getAbortId(), entry);
2189 if (previouslySeenAbort != null) {
2190 previouslySeenAbort.setDead(); // Delete old version of the abort since we got a rescued newer version
2193 if (entry.getTransactionArbitrator() == localMachineId) {
2194 liveAbortsGeneratedByLocal.put(entry.getArbitratorLocalSequenceNumber(), entry);
2197 if ((entry.getSequenceNumber() != -1) && (lastMessageTable.get(entry.getTransactionMachineId()).getFirst() >= entry.getSequenceNumber())) {
2199 // The machine already saw this so it is dead
2201 liveAbortTable.remove(entry.getAbortId());
2203 if (entry.getTransactionArbitrator() == localMachineId) {
2204 liveAbortsGeneratedByLocal.remove(entry.getArbitratorLocalSequenceNumber());
2213 // Update the last arbitration data that we have seen so far
2214 if (lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(entry.getTransactionArbitrator()) != null) {
2216 long lastArbitrationSequenceNumber = lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(entry.getTransactionArbitrator());
2217 if (entry.getSequenceNumber() > lastArbitrationSequenceNumber) {
2219 lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.put(entry.getTransactionArbitrator(), entry.getSequenceNumber());
2222 // Never seen any data from this arbitrator so record the first one
2223 lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.put(entry.getTransactionArbitrator(), entry.getSequenceNumber());
2227 // Set dead a transaction if we can
2228 Transaction transactionToSetDead = liveTransactionByTransactionIdTable.remove(new Pair<Long, Long>(entry.getTransactionMachineId(), entry.getTransactionClientLocalSequenceNumber()));
2229 if (transactionToSetDead != null) {
2230 liveTransactionBySequenceNumberTable.remove(transactionToSetDead.getSequenceNumber());
2233 // Update the last transaction sequence number that the arbitrator arbitrated on
2234 Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(entry.getTransactionArbitrator());
2235 if ((lastTransactionNumber == null) || (lastTransactionNumber < entry.getTransactionSequenceNumber())) {
2238 if (entry.getTransactionSequenceNumber() != -1) {
2239 lastArbitratedTransactionNumberByArbitratorTable.put(entry.getTransactionArbitrator(), entry.getTransactionSequenceNumber());
2245 * Set dead the transaction part if that transaction is dead and keep track of all new parts
2247 private void processEntry(TransactionPart entry) {
2248 // Check if we have already seen this transaction and set it dead OR if it is not alive
2249 Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(entry.getArbitratorId());
2250 if ((lastTransactionNumber != null) && (lastTransactionNumber >= entry.getSequenceNumber())) {
2251 // This transaction is dead, it was already committed or aborted
2256 // This part is still alive
2257 Map<Pair<Long, Integer>, TransactionPart> transactionPart = newTransactionParts.get(entry.getMachineId());
2259 if (transactionPart == null) {
2260 // Dont have a table for this machine Id yet so make one
2261 transactionPart = new HashMap<Pair<Long, Integer>, TransactionPart>();
2262 newTransactionParts.put(entry.getMachineId(), transactionPart);
2265 // Update the part and set dead ones we have already seen (got a rescued version)
2266 TransactionPart previouslySeenPart = transactionPart.put(entry.getPartId(), entry);
2267 if (previouslySeenPart != null) {
2268 previouslySeenPart.setDead();
2273 * Process new commit entries and save them for future use. Delete duplicates
2275 private void processEntry(CommitPart entry) {
2276 Map<Pair<Long, Integer>, CommitPart> commitPart = newCommitParts.get(entry.getMachineId());
2278 if (commitPart == null) {
2279 // Don't have a table for this machine Id yet so make one
2280 commitPart = new HashMap<Pair<Long, Integer>, CommitPart>();
2281 newCommitParts.put(entry.getMachineId(), commitPart);
2284 // Update the part and set dead ones we have already seen (got a rescued version)
2285 CommitPart previouslySeenPart = commitPart.put(entry.getPartId(), entry);
2286 if (previouslySeenPart != null) {
2287 previouslySeenPart.setDead();
2292 * Update the last message seen table. Update and set dead the appropriate RejectedMessages as clients see them.
2293 * Updates the live aborts, removes those that are dead and sets them dead.
2294 * Check that the last message seen is correct and that there is no mismatch of our own last message or that
2295 * other clients have not had a rollback on the last message.
2297 private void updateLastMessage(long machineId, long seqNum, Liveness liveness, boolean acceptUpdatesToLocal, HashSet<Long> machineSet) {
2299 // We have seen this machine ID
2300 machineSet.remove(machineId);
2302 // Get the set of rejected messages that this machine Id is has not seen yet
2303 HashSet<RejectedMessage> watchset = rejectedMessageWatchListTable.get(machineId);
2305 // If there is a rejected message that this machine Id has not seen yet
2306 if (watchset != null) {
2308 // Go through each rejected message that this machine Id has not seen yet
2309 for (Iterator<RejectedMessage> rmit = watchset.iterator(); rmit.hasNext(); ) {
2311 RejectedMessage rm = rmit.next();
2313 // If this machine Id has seen this rejected message...
2314 if (rm.getNewSeqNum() <= seqNum) {
2316 // Remove it from our watchlist
2319 // Decrement machines that need to see this notification
2320 rm.removeWatcher(machineId);
2325 // Set dead the abort
2326 for (Iterator<Map.Entry<Pair<Long, Long>, Abort>> i = liveAbortTable.entrySet().iterator(); i.hasNext();) {
2327 Abort abort = i.next().getValue();
2329 if ((abort.getTransactionMachineId() == machineId) && (abort.getSequenceNumber() <= seqNum)) {
2333 if (abort.getTransactionArbitrator() == localMachineId) {
2334 liveAbortsGeneratedByLocal.remove(abort.getArbitratorLocalSequenceNumber());
2341 if (machineId == localMachineId) {
2342 // Our own messages are immediately dead.
2343 if (liveness instanceof LastMessage) {
2344 ((LastMessage)liveness).setDead();
2345 } else if (liveness instanceof Slot) {
2346 ((Slot)liveness).setDead();
2348 throw new Error("Unrecognized type");
2352 // Get the old last message for this device
2353 Pair<Long, Liveness> lastMessageEntry = lastMessageTable.put(machineId, new Pair<Long, Liveness>(seqNum, liveness));
2354 if (lastMessageEntry == null) {
2355 // If no last message then there is nothing else to process
2359 long lastMessageSeqNum = lastMessageEntry.getFirst();
2360 Liveness lastEntry = lastMessageEntry.getSecond();
2362 // If it is not our machine Id since we already set ours to dead
2363 if (machineId != localMachineId) {
2364 if (lastEntry instanceof LastMessage) {
2365 ((LastMessage)lastEntry).setDead();
2366 } else if (lastEntry instanceof Slot) {
2367 ((Slot)lastEntry).setDead();
2369 throw new Error("Unrecognized type");
2373 // Make sure the server is not playing any games
2374 if (machineId == localMachineId) {
2376 if (hadPartialSendToServer) {
2377 // We were not making any updates and we had a machine mismatch
2378 if (lastMessageSeqNum > seqNum && !acceptUpdatesToLocal) {
2379 throw new Error("Server Error: Mismatch on local machine sequence number, needed at least: " + lastMessageSeqNum + " got: " + seqNum);
2383 // We were not making any updates and we had a machine mismatch
2384 if (lastMessageSeqNum != seqNum && !acceptUpdatesToLocal) {
2385 throw new Error("Server Error: Mismatch on local machine sequence number, needed: " + lastMessageSeqNum + " got: " + seqNum);
2389 if (lastMessageSeqNum > seqNum) {
2390 throw new Error("Server Error: Rollback on remote machine sequence number");
2396 * Add a rejected message entry to the watch set to keep track of which clients have seen that
2397 * rejected message entry and which have not.
2399 private void addWatchList(long machineId, RejectedMessage entry) {
2400 HashSet<RejectedMessage> entries = rejectedMessageWatchListTable.get(machineId);
2401 if (entries == null) {
2402 // There is no set for this machine ID yet so create one
2403 entries = new HashSet<RejectedMessage>();
2404 rejectedMessageWatchListTable.put(machineId, entries);
2410 * Check if the HMAC chain is not violated
2412 private void checkHMACChain(SlotIndexer indexer, Slot[] newSlots) {
2413 for (int i = 0; i < newSlots.length; i++) {
2414 Slot currSlot = newSlots[i];
2415 Slot prevSlot = indexer.getSlot(currSlot.getSequenceNumber() - 1);
2416 if (prevSlot != null &&
2417 !Arrays.equals(prevSlot.getHMAC(), currSlot.getPrevHMAC()))
2418 throw new Error("Server Error: Invalid HMAC Chain" + currSlot + " " + prevSlot);