735d15021228c29019f5606ae43d8a49240304f1
[iotcloud.git] / version2 / src / java / iotcloud / Table.java
1 package iotcloud;
2
3 import java.util.Iterator;
4 import java.util.Random;
5 import java.util.Arrays;
6 import java.util.Map;
7 import java.util.Set;
8 import java.util.List;
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;
15
16 /**
17  * IoTTable data structure.  Provides client interface.
18  * @author Brian Demsky
19  * @version 1.0
20  */
21
22 final public class Table {
23
24         /* Constants */
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;
30
31         /* Helper Objects */
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
39
40         /* Variables */
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;
58
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;
65
66
67         /* Data Structures  */
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;
95
96
97         public Table(String baseurl, String password, long _localMachineId, int listeningPort) {
98                 localMachineId = _localMachineId;
99                 cloud = new CloudComm(this, baseurl, password, listeningPort);
100
101                 init();
102         }
103
104         public Table(CloudComm _cloud, long _localMachineId) {
105                 localMachineId = _localMachineId;
106                 cloud = _cloud;
107
108                 init();
109         }
110
111         /**
112          * Init all the stuff needed for for table usage
113          */
114         private void init() {
115
116                 // Init helper objects
117                 random = new Random();
118                 buffer = new SlotBuffer();
119
120                 // Set Variables
121                 oldestLiveSlotSequenceNumver = 1;
122
123                 // init data structs
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>();
151
152
153                 // Other init stuff
154                 numberOfSlots = buffer.capacity();
155                 setResizeThreshold();
156         }
157
158         // TODO: delete method
159         public synchronized void printSlots() {
160                 long o = buffer.getOldestSeqNum();
161                 long n = buffer.getNewestSeqNum();
162
163                 int[] types = new int[10];
164
165                 int num = 0;
166
167                 int livec = 0;
168                 int deadc = 0;
169                 for (long i = o; i < (n + 1); i++) {
170                         Slot s = buffer.getSlot(i);
171
172                         Vector<Entry> entries = s.getEntries();
173
174                         for (Entry e : entries) {
175                                 if (e.isLive()) {
176                                         int type = e.getType();
177                                         types[type] = types[type] + 1;
178                                         num++;
179                                         livec++;
180                                 } else {
181                                         deadc++;
182                                 }
183                         }
184                 }
185
186                 for (int i = 0; i < 10; i++) {
187                         System.out.println(i + "    " + types[i]);
188                 }
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());
197
198                 for (Long k : lastArbitratedTransactionNumberByArbitratorTable.keySet()) {
199                         System.out.println(k + ": " + lastArbitratedTransactionNumberByArbitratorTable.get(k));
200                 }
201
202
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 + " ");
207                                 }
208                                 System.out.print("|| ");
209                         }
210                         System.out.println();
211                 }
212
213         }
214
215         /**
216          * Initialize the table by inserting a table status as the first entry into the table status
217          * also initialize the crypto stuff.
218          */
219         public synchronized void initTable() throws ServerException {
220                 cloud.initSecurity();
221
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);
225                 s.addEntry(status);
226                 Slot[] array = cloud.putSlot(s, numberOfSlots);
227
228                 if (array == null) {
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);
235                 } else {
236                         throw new Error("Error on initialization");
237                 }
238         }
239
240         /**
241          * Rebuild the table from scratch by pulling the latest block chain from the server.
242          */
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);
247         }
248
249         // public String toString() {
250         //      String retString = " Committed Table: \n";
251         //      retString += "---------------------------\n";
252         //      retString += commitedTable.toString();
253
254         //      retString += "\n\n";
255
256         //      retString += " Speculative Table: \n";
257         //      retString += "---------------------------\n";
258         //      retString += speculativeTable.toString();
259
260         //      return retString;
261         // }
262
263         public synchronized void addLocalCommunication(long arbitrator, String hostName, int portNumber) {
264                 localCommunicationTable.put(arbitrator, new Pair<String, Integer>(hostName, portNumber));
265         }
266
267         public synchronized Long getArbitrator(IoTString key) {
268                 return arbitratorTable.get(key);
269         }
270
271         public synchronized void close() {
272                 cloud.close();
273         }
274
275         public synchronized IoTString getCommitted(IoTString key)  {
276                 KeyValue kv = committedKeyValueTable.get(key);
277
278                 if (kv != null) {
279                         return kv.getValue();
280                 } else {
281                         return null;
282                 }
283         }
284
285         public synchronized IoTString getSpeculative(IoTString key) {
286                 KeyValue kv = pendingTransactionSpeculatedKeyValueTable.get(key);
287
288                 if (kv == null) {
289                         kv = speculatedKeyValueTable.get(key);
290                 }
291
292                 if (kv == null) {
293                         kv = committedKeyValueTable.get(key);
294                 }
295
296                 if (kv != null) {
297                         return kv.getValue();
298                 } else {
299                         return null;
300                 }
301         }
302
303         public synchronized IoTString getCommittedAtomic(IoTString key) {
304                 KeyValue kv = committedKeyValueTable.get(key);
305
306                 if (arbitratorTable.get(key) == null) {
307                         throw new Error("Key not Found.");
308                 }
309
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.");
314                 }
315
316                 if (kv != null) {
317                         pendingTransactionBuilder.addKVGuard(new KeyValue(key, kv.getValue()));
318                         return kv.getValue();
319                 } else {
320                         pendingTransactionBuilder.addKVGuard(new KeyValue(key, null));
321                         return null;
322                 }
323         }
324
325         public synchronized IoTString getSpeculativeAtomic(IoTString key) {
326                 if (arbitratorTable.get(key) == null) {
327                         throw new Error("Key not Found.");
328                 }
329
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.");
334                 }
335
336                 KeyValue kv = pendingTransactionSpeculatedKeyValueTable.get(key);
337
338                 if (kv == null) {
339                         kv = speculatedKeyValueTable.get(key);
340                 }
341
342                 if (kv == null) {
343                         kv = committedKeyValueTable.get(key);
344                 }
345
346                 if (kv != null) {
347                         pendingTransactionBuilder.addKVGuard(new KeyValue(key, kv.getValue()));
348                         return kv.getValue();
349                 } else {
350                         pendingTransactionBuilder.addKVGuard(new KeyValue(key, null));
351                         return null;
352                 }
353         }
354
355         public synchronized boolean update()  {
356                 try {
357                         Slot[] newSlots = cloud.getSlots(sequenceNumber + 1);
358                         validateAndUpdate(newSlots, false);
359                         sendToServer(null);
360
361
362                         updateLiveTransactionsAndStatus();
363
364                         return true;
365                 } catch (Exception e) {
366                         // e.printStackTrace();
367
368                         for (Long m : localCommunicationTable.keySet()) {
369                                 updateFromLocal(m);
370                         }
371                 }
372
373                 return false;
374         }
375
376         public synchronized boolean createNewKey(IoTString keyName, long machineId) throws ServerException {
377                 while (true) {
378                         if (arbitratorTable.get(keyName) != null) {
379                                 // There is already an arbitrator
380                                 return false;
381                         }
382
383                         NewKey newKey = new NewKey(null, keyName, machineId);
384                         if (sendToServer(newKey)) {
385                                 // If successfully inserted
386                                 return true;
387                         }
388                 }
389         }
390
391         public synchronized void startTransaction() {
392                 // Create a new transaction, invalidates any old pending transactions.
393                 pendingTransactionBuilder = new PendingTransaction(localMachineId);
394         }
395
396         public synchronized void addKV(IoTString key, IoTString value) {
397
398                 // Make sure it is a valid key
399                 if (arbitratorTable.get(key) == null) {
400                         throw new Error("Key not Found.");
401                 }
402
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.");
407                 }
408
409                 // Add the key value to this transaction
410                 KeyValue kv = new KeyValue(key, value);
411                 pendingTransactionBuilder.addKV(kv);
412         }
413
414         public synchronized TransactionStatus commitTransaction() {
415
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);
419                 }
420
421                 // Set the local transaction sequence number and increment
422                 pendingTransactionBuilder.setClientLocalSequenceNumber(localTransactionSequenceNumber);
423                 localTransactionSequenceNumber++;
424
425                 // Create the transaction status
426                 TransactionStatus transactionStatus = new TransactionStatus(TransactionStatus.StatusPending, pendingTransactionBuilder.getArbitrator());
427
428                 // Create the new transaction
429                 Transaction newTransaction = pendingTransactionBuilder.createTransaction();
430                 newTransaction.setTransactionStatus(transactionStatus);
431
432                 if (pendingTransactionBuilder.getArbitrator() != localMachineId) {
433                         // Add it to the queue and invalidate the builder for safety
434                         pendingTransactionQueue.add(newTransaction);
435                 } else {
436                         arbitrateOnLocalTransaction(newTransaction);
437                         updateLiveStateFromLocal();
438                 }
439
440                 pendingTransactionBuilder = new PendingTransaction(localMachineId);
441
442                 try {
443                         sendToServer(null);
444                 } catch (ServerException e) {
445
446                         Set<Long> arbitratorTriedAndFailed = new HashSet<Long>();
447                         for (Iterator<Transaction> iter = pendingTransactionQueue.iterator(); iter.hasNext(); ) {
448                                 Transaction transaction = iter.next();
449
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
453                                         continue;
454                                 }
455
456                                 Pair<Boolean, Boolean> sendReturn = sendTransactionToLocal(transaction);
457
458                                 if (sendReturn.getFirst()) {
459                                         // Failed to contact over local
460                                         arbitratorTriedAndFailed.add(transaction.getArbitrator());
461                                 } else {
462                                         // Successful contact or should not contact
463
464                                         if (sendReturn.getSecond()) {
465                                                 // did arbitrate
466                                                 iter.remove();
467                                         }
468                                 }
469                         }
470                 }
471
472                 updateLiveStateFromLocal();
473
474                 return transactionStatus;
475         }
476
477         /**
478          * Get the machine ID for this client
479          */
480         public long getMachineId() {
481                 return localMachineId;
482         }
483
484         /**
485          * Decrement the number of live slots that we currently have
486          */
487         public void decrementLiveCount() {
488                 liveSlotCount--;
489         }
490
491         /**
492          * Recalculate the new resize threshold
493          */
494         private void setResizeThreshold() {
495                 int resizeLower = (int) (RESIZE_THRESHOLD * numberOfSlots);
496                 bufferResizeThreshold = resizeLower - 1 + random.nextInt(numberOfSlots - resizeLower);
497         }
498
499
500         boolean lastInsertedNewKey = false;
501
502         private boolean sendToServer(NewKey newKey) throws ServerException {
503
504                 boolean fromRetry = false;
505
506                 try {
507                         if (hadPartialSendToServer) {
508                                 Slot[] newSlots = cloud.getSlots(sequenceNumber + 1);
509                                 if (newSlots.length == 0) {
510                                         fromRetry = true;
511                                         ThreeTuple<Boolean, Boolean, Slot[]> sendSlotsReturn = sendSlotsToServer(lastSlotAttemptedToSend, lastNewSize, lastIsNewKey);
512
513                                         if (sendSlotsReturn.getFirst()) {
514                                                 if (newKey != null) {
515                                                         if (lastInsertedNewKey && (lastNewKey.getKey() == newKey.getKey()) && (lastNewKey.getMachineID() == newKey.getMachineID())) {
516                                                                 newKey = null;
517                                                         }
518                                                 }
519
520                                                 for (Transaction transaction : lastTransactionPartsSent.keySet()) {
521                                                         transaction.resetServerFailure();
522
523                                                         // Update which transactions parts still need to be sent
524                                                         transaction.removeSentParts(lastTransactionPartsSent.get(transaction));
525
526                                                         // Add the transaction status to the outstanding list
527                                                         outstandingTransactionStatus.put(transaction.getSequenceNumber(), transaction.getTransactionStatus());
528
529                                                         // Update the transaction status
530                                                         transaction.getTransactionStatus().setStatus(TransactionStatus.StatusSentPartial);
531
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);
536                                                         }
537                                                 }
538                                         } else {
539
540                                                 newSlots = sendSlotsReturn.getThird();
541
542                                                 boolean isInserted = false;
543                                                 for (Slot s : newSlots) {
544                                                         if ((s.getSequenceNumber() == lastSlotAttemptedToSend.getSequenceNumber()) && (s.getMachineID() == localMachineId)) {
545                                                                 isInserted = true;
546                                                                 break;
547                                                         }
548                                                 }
549
550                                                 for (Slot s : newSlots) {
551                                                         if (isInserted) {
552                                                                 break;
553                                                         }
554
555                                                         // Process each entry in the slot
556                                                         for (Entry entry : s.getEntries()) {
557
558                                                                 if (entry.getType() == Entry.TypeLastMessage) {
559                                                                         LastMessage lastMessage = (LastMessage)entry;
560                                                                         if ((lastMessage.getMachineID() == localMachineId) && (lastMessage.getSequenceNumber() == lastSlotAttemptedToSend.getSequenceNumber())) {
561                                                                                 isInserted = true;
562                                                                                 break;
563                                                                         }
564                                                                 }
565                                                         }
566                                                 }
567
568                                                 if (isInserted) {
569                                                         if (newKey != null) {
570                                                                 if (lastInsertedNewKey && (lastNewKey.getKey() == newKey.getKey()) && (lastNewKey.getMachineID() == newKey.getMachineID())) {
571                                                                         newKey = null;
572                                                                 }
573                                                         }
574
575                                                         for (Transaction transaction : lastTransactionPartsSent.keySet()) {
576                                                                 transaction.resetServerFailure();
577
578                                                                 // Update which transactions parts still need to be sent
579                                                                 transaction.removeSentParts(lastTransactionPartsSent.get(transaction));
580
581                                                                 // Add the transaction status to the outstanding list
582                                                                 outstandingTransactionStatus.put(transaction.getSequenceNumber(), transaction.getTransactionStatus());
583
584                                                                 // Update the transaction status
585                                                                 transaction.getTransactionStatus().setStatus(TransactionStatus.StatusSentPartial);
586
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);
591                                                                 } else {
592                                                                         transaction.resetServerFailure();
593                                                                         // Set the transaction sequence number back to nothing
594                                                                         if (!transaction.didSendAPartToServer()) {
595                                                                                 transaction.setSequenceNumber(-1);
596                                                                         }
597                                                                 }
598                                                         }
599                                                 }
600                                         }
601
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);
607                                                 }
608                                         }
609
610                                         if (sendSlotsReturn.getThird().length != 0) {
611                                                 // insert into the local block chain
612                                                 validateAndUpdate(sendSlotsReturn.getThird(), true);
613                                         }
614                                         // continue;
615                                 } else {
616                                         boolean isInserted = false;
617                                         for (Slot s : newSlots) {
618                                                 if ((s.getSequenceNumber() == lastSlotAttemptedToSend.getSequenceNumber()) && (s.getMachineID() == localMachineId)) {
619                                                         isInserted = true;
620                                                         break;
621                                                 }
622                                         }
623
624                                         for (Slot s : newSlots) {
625                                                 if (isInserted) {
626                                                         break;
627                                                 }
628
629                                                 // Process each entry in the slot
630                                                 for (Entry entry : s.getEntries()) {
631
632                                                         if (entry.getType() == Entry.TypeLastMessage) {
633                                                                 LastMessage lastMessage = (LastMessage)entry;
634                                                                 if ((lastMessage.getMachineID() == localMachineId) && (lastMessage.getSequenceNumber() == lastSlotAttemptedToSend.getSequenceNumber())) {
635                                                                         isInserted = true;
636                                                                         break;
637                                                                 }
638                                                         }
639                                                 }
640                                         }
641
642                                         if (isInserted) {
643                                                 if (newKey != null) {
644                                                         if (lastInsertedNewKey && (lastNewKey.getKey() == newKey.getKey()) && (lastNewKey.getMachineID() == newKey.getMachineID())) {
645                                                                 newKey = null;
646                                                         }
647                                                 }
648
649                                                 for (Transaction transaction : lastTransactionPartsSent.keySet()) {
650                                                         transaction.resetServerFailure();
651
652                                                         // Update which transactions parts still need to be sent
653                                                         transaction.removeSentParts(lastTransactionPartsSent.get(transaction));
654
655                                                         // Add the transaction status to the outstanding list
656                                                         outstandingTransactionStatus.put(transaction.getSequenceNumber(), transaction.getTransactionStatus());
657
658                                                         // Update the transaction status
659                                                         transaction.getTransactionStatus().setStatus(TransactionStatus.StatusSentPartial);
660
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);
665                                                         } else {
666                                                                 transaction.resetServerFailure();
667                                                                 // Set the transaction sequence number back to nothing
668                                                                 if (!transaction.didSendAPartToServer()) {
669                                                                         transaction.setSequenceNumber(-1);
670                                                                 }
671                                                         }
672                                                 }
673                                         } else {
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);
679                                                         }
680                                                 }
681                                         }
682
683                                         // insert into the local block chain
684                                         validateAndUpdate(newSlots, true);
685                                 }
686                         }
687                 } catch (ServerException e) {
688                         throw e;
689                 }
690
691
692                 try {
693                         // While we have stuff that needs inserting into the block chain
694                         while ((pendingTransactionQueue.size() > 0) || (pendingSendArbitrationRounds.size() > 0) || (newKey != null)) {
695                                 fromRetry = false;
696
697                                 if (hadPartialSendToServer) {
698                                         throw new Error("Should Be error free");
699                                 }
700
701
702
703                                 // If there is a new key with same name then end
704                                 if ((newKey != null) && (arbitratorTable.get(newKey.getKey()) != null)) {
705                                         return false;
706                                 }
707
708                                 // Create the slot
709                                 Slot slot = new Slot(this, sequenceNumber + 1, localMachineId, buffer.getSlot(sequenceNumber).getHMAC());
710
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();
716
717                                 if (needsResize) {
718                                         // Reset which transaction to send
719                                         for (Transaction transaction : transactionPartsSent.keySet()) {
720                                                 transaction.resetNextPartToSend();
721
722                                                 // Set the transaction sequence number back to nothing
723                                                 if (!transaction.didSendAPartToServer() && !transaction.getServerFailure()) {
724                                                         transaction.setSequenceNumber(-1);
725                                                 }
726                                         }
727
728                                         // Clear the sent data since we are trying again
729                                         pendingSendArbitrationEntriesToDelete.clear();
730                                         transactionPartsSent.clear();
731
732                                         // We needed a resize so try again
733                                         fillSlot(slot, true, newKey);
734                                 }
735
736                                 lastSlotAttemptedToSend = slot;
737                                 lastIsNewKey = (newKey != null);
738                                 lastInsertedNewKey = insertedNewKey;
739                                 lastNewSize = newSize;
740                                 lastNewKey = newKey;
741                                 lastTransactionPartsSent = new HashMap<Transaction, List<Integer>>(transactionPartsSent);
742                                 lastPendingSendArbitrationEntriesToDelete = new ArrayList<Entry>(pendingSendArbitrationEntriesToDelete);
743
744
745                                 ThreeTuple<Boolean, Boolean, Slot[]> sendSlotsReturn = sendSlotsToServer(slot, newSize, newKey != null);
746
747                                 if (sendSlotsReturn.getFirst()) {
748
749                                         // Did insert into the block chain
750
751                                         if (insertedNewKey) {
752                                                 // This slot was what was inserted not a previous slot
753
754                                                 // New Key was successfully inserted into the block chain so dont want to insert it again
755                                                 newKey = null;
756                                         }
757
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);
762
763                                                 if (round.isDoneSending()) {
764                                                         // Sent all the parts
765                                                         iter.remove();
766                                                 }
767                                         }
768
769                                         for (Transaction transaction : transactionPartsSent.keySet()) {
770                                                 transaction.resetServerFailure();
771
772                                                 // Update which transactions parts still need to be sent
773                                                 transaction.removeSentParts(transactionPartsSent.get(transaction));
774
775                                                 // Add the transaction status to the outstanding list
776                                                 outstandingTransactionStatus.put(transaction.getSequenceNumber(), transaction.getTransactionStatus());
777
778                                                 // Update the transaction status
779                                                 transaction.getTransactionStatus().setStatus(TransactionStatus.StatusSentPartial);
780
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);
785                                                 }
786                                         }
787                                 } else {
788
789                                         // if (!sendSlotsReturn.getSecond()) {
790                                         //      for (Transaction transaction : lastTransactionPartsSent.keySet()) {
791                                         //              transaction.resetServerFailure();
792                                         //      }
793                                         // } else {
794                                         //      for (Transaction transaction : lastTransactionPartsSent.keySet()) {
795                                         //              transaction.resetServerFailure();
796
797                                         //              // Update which transactions parts still need to be sent
798                                         //              transaction.removeSentParts(transactionPartsSent.get(transaction));
799
800                                         //              // Add the transaction status to the outstanding list
801                                         //              outstandingTransactionStatus.put(transaction.getSequenceNumber(), transaction.getTransactionStatus());
802
803                                         //              // Update the transaction status
804                                         //              transaction.getTransactionStatus().setStatus(TransactionStatus.StatusSentPartial);
805
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);
810
811                                         //                      for (KeyValue kv : transaction.getKeyValueUpdateSet()) {
812                                         //                              System.out.println("Sent: " + kv + "  from: " + localMachineId + "   Slot:" + lastSlotAttemptedToSend.getSequenceNumber() + "  Claimed:" + transaction.getSequenceNumber());
813                                         //                      }
814                                         //              }
815                                         //      }
816                                         // }
817
818                                         // Reset which transaction to send
819                                         for (Transaction transaction : transactionPartsSent.keySet()) {
820                                                 transaction.resetNextPartToSend();
821                                                 // transaction.resetNextPartToSend();
822
823                                                 // Set the transaction sequence number back to nothing
824                                                 if (!transaction.didSendAPartToServer() && !transaction.getServerFailure()) {
825                                                         transaction.setSequenceNumber(-1);
826                                                 }
827                                         }
828                                 }
829
830                                 // Clear the sent data in preparation for next send
831                                 pendingSendArbitrationEntriesToDelete.clear();
832                                 transactionPartsSent.clear();
833
834                                 if (sendSlotsReturn.getThird().length != 0) {
835                                         // insert into the local block chain
836                                         validateAndUpdate(sendSlotsReturn.getThird(), true);
837                                 }
838                         }
839
840                 } catch (ServerException e) {
841
842                         if (e.getType() != ServerException.TypeInputTimeout) {
843                                 // e.printStackTrace();
844
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();
848
849                                         // Set the transaction sequence number back to nothing
850                                         if (!transaction.didSendAPartToServer() && !transaction.getServerFailure()) {
851                                                 transaction.setSequenceNumber(-1);
852                                         }
853                                 }
854                         } else {
855                                 // There was a partial send to the server
856                                 hadPartialSendToServer = true;
857
858
859                                 // if (!fromRetry) {
860                                 //      lastTransactionPartsSent = new HashMap<Transaction, List<Integer>>(transactionPartsSent);
861                                 //      lastPendingSendArbitrationEntriesToDelete = new ArrayList<Entry>(pendingSendArbitrationEntriesToDelete);
862                                 // }
863
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();
868                                 }
869                         }
870
871                         pendingSendArbitrationEntriesToDelete.clear();
872                         transactionPartsSent.clear();
873
874                         throw e;
875                 }
876
877                 return newKey == null;
878         }
879
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
884                         return false;
885                 }
886
887                 // Get the size of the send data
888                 int sendDataSize = Integer.BYTES + Long.BYTES;
889
890                 Long lastArbitrationDataLocalSequenceNumber = (long) - 1;
891                 if (lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(machineId) != null) {
892                         lastArbitrationDataLocalSequenceNumber = lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(machineId);
893                 }
894
895                 byte[] sendData = new byte[sendDataSize];
896                 ByteBuffer bbEncode = ByteBuffer.wrap(sendData);
897
898                 // Encode the data
899                 bbEncode.putLong(lastArbitrationDataLocalSequenceNumber);
900                 bbEncode.putInt(0);
901
902                 // Send by local
903                 byte[] returnData = cloud.sendLocalData(sendData, localCommunicationInformation.getFirst(), localCommunicationInformation.getSecond());
904
905                 if (returnData == null) {
906                         // Could not contact server
907                         return false;
908                 }
909
910                 // Decode the data
911                 ByteBuffer bbDecode = ByteBuffer.wrap(returnData);
912                 int numberOfEntries = bbDecode.getInt();
913
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);
918                                 processEntry(abort);
919                         } else if (type == Entry.TypeCommitPart) {
920                                 CommitPart commitPart = (CommitPart)CommitPart.decode(null, bbDecode);
921                                 processEntry(commitPart);
922                         }
923                 }
924
925                 updateLiveStateFromLocal();
926
927                 return true;
928         }
929
930         private Pair<Boolean, Boolean> sendTransactionToLocal(Transaction transaction) {
931
932                 // Get the devices local communications
933                 Pair<String, Integer> localCommunicationInformation = localCommunicationTable.get(transaction.getArbitrator());
934
935                 if (localCommunicationInformation == null) {
936                         // Cant talk to that device locally so do nothing
937                         return new Pair<Boolean, Boolean>(true, false);
938                 }
939
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();
944                 }
945
946                 Long lastArbitrationDataLocalSequenceNumber = (long) - 1;
947                 if (lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(transaction.getArbitrator()) != null) {
948                         lastArbitrationDataLocalSequenceNumber = lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(transaction.getArbitrator());
949                 }
950
951                 // Make the send data size
952                 byte[] sendData = new byte[sendDataSize];
953                 ByteBuffer bbEncode = ByteBuffer.wrap(sendData);
954
955                 // Encode the data
956                 bbEncode.putLong(lastArbitrationDataLocalSequenceNumber);
957                 bbEncode.putInt(transaction.getParts().size());
958                 for (TransactionPart part : transaction.getParts().values()) {
959                         part.encode(bbEncode);
960                 }
961
962
963                 // Send by local
964                 byte[] returnData = cloud.sendLocalData(sendData, localCommunicationInformation.getFirst(), localCommunicationInformation.getSecond());
965
966                 if (returnData == null) {
967                         // Could not contact server
968                         return new Pair<Boolean, Boolean>(true, false);
969                 }
970
971                 // Decode the data
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;
977
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);
982
983                                 if ((abort.getTransactionMachineId() == localMachineId) && (abort.getTransactionClientLocalSequenceNumber() == transaction.getClientLocalSequenceNumber())) {
984                                         foundAbort = true;
985                                 }
986
987                                 processEntry(abort);
988                         } else if (type == Entry.TypeCommitPart) {
989                                 CommitPart commitPart = (CommitPart)CommitPart.decode(null, bbDecode);
990                                 processEntry(commitPart);
991                         }
992                 }
993
994                 updateLiveStateFromLocal();
995
996                 if (couldArbitrate) {
997                         TransactionStatus status =  transaction.getTransactionStatus();
998                         if (didCommit) {
999                                 status.setStatus(TransactionStatus.StatusCommitted);
1000                         } else {
1001                                 status.setStatus(TransactionStatus.StatusAborted);
1002                         }
1003                 } else {
1004                         TransactionStatus status =  transaction.getTransactionStatus();
1005                         if (foundAbort) {
1006                                 status.setStatus(TransactionStatus.StatusAborted);
1007                         } else {
1008                                 status.setStatus(TransactionStatus.StatusCommitted);
1009                         }
1010                 }
1011
1012                 return new Pair<Boolean, Boolean>(false, true);
1013         }
1014
1015         public synchronized byte[] acceptDataFromLocal(byte[] data) {
1016
1017                 // Decode the data
1018                 ByteBuffer bbDecode = ByteBuffer.wrap(data);
1019                 long lastArbitratedSequenceNumberSeen = bbDecode.getLong();
1020                 int numberOfParts = bbDecode.getInt();
1021
1022                 // If we did commit a transaction or not
1023                 boolean didCommit = false;
1024                 boolean couldArbitrate = false;
1025
1026                 if (numberOfParts != 0) {
1027
1028                         // decode the transaction
1029                         Transaction transaction = new Transaction();
1030                         for (int i = 0; i < numberOfParts; i++) {
1031                                 bbDecode.get();
1032                                 TransactionPart newPart = (TransactionPart)TransactionPart.decode(null, bbDecode);
1033                                 transaction.addPartDecode(newPart);
1034                         }
1035
1036                         // Arbitrate on transaction and pull relevant return data
1037                         Pair<Boolean, Boolean> localArbitrateReturn = arbitrateOnLocalTransaction(transaction);
1038                         couldArbitrate = localArbitrateReturn.getFirst();
1039                         didCommit = localArbitrateReturn.getSecond();
1040
1041                         updateLiveStateFromLocal();
1042
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());
1046                         }
1047                 }
1048
1049                 // The data to send back
1050                 int returnDataSize = 0;
1051                 List<Entry> unseenArbitrations = new ArrayList<Entry>();
1052
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) {
1058                                 continue;
1059                         }
1060
1061                         Abort abort = liveAbortsGeneratedByLocal.get(localSequenceNumber);
1062                         unseenArbitrations.add(abort);
1063                         returnDataSize += abort.getSize();
1064                 }
1065
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);
1071
1072                         for (Long localSequenceNumber : commitLocalSequenceNumbers) {
1073                                 Commit commit = commitForClientTable.get(localSequenceNumber);
1074
1075                                 if (localSequenceNumber <= lastArbitratedSequenceNumberSeen) {
1076                                         continue;
1077                                 }
1078
1079                                 unseenArbitrations.addAll(commit.getParts().values());
1080
1081                                 for (CommitPart commitPart : commit.getParts().values()) {
1082                                         returnDataSize += commitPart.getSize();
1083                                 }
1084                         }
1085                 }
1086
1087                 // Number of arbitration entries to decode
1088                 returnDataSize += 2 * Integer.BYTES;
1089
1090                 // Boolean of did commit or not
1091                 if (numberOfParts != 0) {
1092                         returnDataSize += Byte.BYTES;
1093                 }
1094
1095                 // Data to send Back
1096                 byte[] returnData = new byte[returnDataSize];
1097                 ByteBuffer bbEncode = ByteBuffer.wrap(returnData);
1098
1099                 if (numberOfParts != 0) {
1100                         if (didCommit) {
1101                                 bbEncode.put((byte)1);
1102                         } else {
1103                                 bbEncode.put((byte)0);
1104                         }
1105                         if (couldArbitrate) {
1106                                 bbEncode.put((byte)1);
1107                         } else {
1108                                 bbEncode.put((byte)0);
1109                         }
1110                 }
1111
1112                 bbEncode.putInt(unseenArbitrations.size());
1113                 for (Entry entry : unseenArbitrations) {
1114                         entry.encode(bbEncode);
1115                 }
1116
1117                 return returnData;
1118         }
1119
1120         private ThreeTuple<Boolean, Boolean, Slot[]> sendSlotsToServer(Slot slot, int newSize, boolean isNewKey)  throws ServerException {
1121
1122                 boolean attemptedToSendToServerTmp = attemptedToSendToServer;
1123                 attemptedToSendToServer = true;
1124
1125                 boolean inserted = false;
1126                 boolean lastTryInserted = false;
1127
1128                 Slot[] array = cloud.putSlot(slot, newSize);
1129                 if (array == null) {
1130                         array = new Slot[] {slot};
1131                         rejectedSlotList.clear();
1132                         inserted = true;
1133                 }       else {
1134                         if (array.length == 0) {
1135                                 throw new Error("Server Error: Did not send any slots");
1136                         }
1137
1138                         // if (attemptedToSendToServerTmp) {
1139                         if (hadPartialSendToServer) {
1140
1141                                 boolean isInserted = false;
1142                                 for (Slot s : array) {
1143                                         if ((s.getSequenceNumber() == slot.getSequenceNumber()) && (s.getMachineID() == localMachineId)) {
1144                                                 isInserted = true;
1145                                                 break;
1146                                         }
1147                                 }
1148
1149                                 for (Slot s : array) {
1150                                         if (isInserted) {
1151                                                 break;
1152                                         }
1153
1154                                         // Process each entry in the slot
1155                                         for (Entry entry : s.getEntries()) {
1156
1157                                                 if (entry.getType() == Entry.TypeLastMessage) {
1158                                                         LastMessage lastMessage = (LastMessage)entry;
1159
1160                                                         if ((lastMessage.getMachineID() == localMachineId) && (lastMessage.getSequenceNumber() == slot.getSequenceNumber())) {
1161                                                                 isInserted = true;
1162                                                                 break;
1163                                                         }
1164                                                 }
1165                                         }
1166                                 }
1167
1168                                 if (!isInserted) {
1169                                         rejectedSlotList.add(slot.getSequenceNumber());
1170                                         lastTryInserted = false;
1171                                 } else {
1172                                         lastTryInserted = true;
1173                                 }
1174                         } else {
1175                                 rejectedSlotList.add(slot.getSequenceNumber());
1176                                 lastTryInserted = false;
1177                         }
1178                 }
1179
1180                 return new ThreeTuple<Boolean, Boolean, Slot[]>(inserted, lastTryInserted, array);
1181         }
1182
1183         /**
1184          * Returns false if a resize was needed
1185          */
1186         private ThreeTuple<Boolean, Integer, Boolean> fillSlot(Slot slot, boolean resize, NewKey newKeyEntry) {
1187                 int newSize = 0;
1188                 if (liveSlotCount > bufferResizeThreshold) {
1189                         resize = true; //Resize is forced
1190                 }
1191
1192                 if (resize) {
1193                         newSize = (int) (numberOfSlots * RESIZE_MULTIPLE);
1194                         TableStatus status = new TableStatus(slot, newSize);
1195                         slot.addEntry(status);
1196                 }
1197
1198                 // Fill with rejected slots first before doing anything else
1199                 doRejectedMessages(slot);
1200
1201                 // Do mandatory rescue of entries
1202                 ThreeTuple<Boolean, Boolean, Long> mandatoryRescueReturn = doMandatoryResuce(slot, resize);
1203
1204                 // Extract working variables
1205                 boolean needsResize = mandatoryRescueReturn.getFirst();
1206                 boolean seenLiveSlot = mandatoryRescueReturn.getSecond();
1207                 long currentRescueSequenceNumber = mandatoryRescueReturn.getThird();
1208
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);
1212                 }
1213
1214                 boolean inserted = false;
1215                 if (newKeyEntry != null) {
1216                         newKeyEntry.setSlot(slot);
1217                         if (slot.hasSpace(newKeyEntry)) {
1218                                 slot.addEntry(newKeyEntry);
1219                                 inserted = true;
1220                         }
1221                 }
1222
1223                 // Clear the transactions, aborts and commits that were sent previously
1224                 transactionPartsSent.clear();
1225                 pendingSendArbitrationEntriesToDelete.clear();
1226
1227                 for (ArbitrationRound round : pendingSendArbitrationRounds) {
1228                         boolean isFull = false;
1229                         round.generateParts();
1230                         List<Entry> parts = round.getParts();
1231
1232                         // Insert pending arbitration data
1233                         for (Entry arbitrationData : parts) {
1234
1235                                 // If it is an abort then we need to set some information
1236                                 if (arbitrationData instanceof Abort) {
1237                                         ((Abort)arbitrationData).setSequenceNumber(slot.getSequenceNumber());
1238                                 }
1239
1240                                 if (!slot.hasSpace(arbitrationData)) {
1241                                         // No space so cant do anything else with these data entries
1242                                         isFull = true;
1243                                         break;
1244                                 }
1245
1246                                 // Add to this current slot and add it to entries to delete
1247                                 slot.addEntry(arbitrationData);
1248                                 pendingSendArbitrationEntriesToDelete.add(arbitrationData);
1249                         }
1250
1251                         if (isFull) {
1252                                 break;
1253                         }
1254                 }
1255
1256                 if (pendingTransactionQueue.size() > 0) {
1257
1258                         Transaction transaction = pendingTransactionQueue.get(0);
1259
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());
1263                         // }
1264
1265                         if ((!transaction.didSendAPartToServer()) || (transaction.getSequenceNumber() == -1)) {
1266                                 transaction.setSequenceNumber(slot.getSequenceNumber());
1267                         }
1268
1269
1270                         while (true) {
1271                                 TransactionPart part = transaction.getNextPartToSend();
1272
1273                                 if (part == null) {
1274                                         // Ran out of parts to send for this transaction so move on
1275                                         break;
1276                                 }
1277
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);
1284                                         }
1285                                         partsSent.add(part.getPartNumber());
1286                                         transactionPartsSent.put(transaction, partsSent);
1287                                 } else {
1288                                         break;
1289                                 }
1290                         }
1291                 }
1292
1293                 // Fill the remainder of the slot with rescue data
1294                 doOptionalRescue(slot, seenLiveSlot, currentRescueSequenceNumber, resize);
1295
1296                 return new ThreeTuple<Boolean, Integer, Boolean>(false, newSize, inserted);
1297         }
1298
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).  */
1304
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);
1309                                 s.addEntry(rm);
1310                         } else {
1311                                 long prev_seqn = -1;
1312                                 int i = 0;
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);
1317                                         if (s_msg != null)
1318                                                 break;
1319                                         prev_seqn = curr_seqn;
1320                                 }
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);
1324                                         s.addEntry(rm);
1325                                 }
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);
1332                                         s.addEntry(rm);
1333                                 }
1334                         }
1335                 }
1336         }
1337
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;
1343                 }
1344
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
1349
1350
1351                 // Mandatory Rescue
1352                 for (; currentSequenceNumber < threshold; currentSequenceNumber++) {
1353                         Slot previousSlot = buffer.getSlot(currentSequenceNumber);
1354                         // Push slot number forward
1355                         if (! seenLiveSlot) {
1356                                 oldestLiveSlotSequenceNumver = currentSequenceNumber;
1357                         }
1358
1359                         if (!previousSlot.isLive()) {
1360                                 continue;
1361                         }
1362
1363                         // We have seen a live slot
1364                         seenLiveSlot = true;
1365
1366                         // Get all the live entries for a slot
1367                         Vector<Entry> liveEntries = previousSlot.getLiveEntries(resize);
1368
1369                         // Iterate over all the live entries and try to rescue them
1370                         for (Entry liveEntry : liveEntries) {
1371                                 if (slot.hasSpace(liveEntry)) {
1372
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);
1379
1380                                 }
1381                         }
1382                 }
1383
1384                 // Did not resize
1385                 return new ThreeTuple<Boolean, Boolean, Long>(false, seenLiveSlot, currentSequenceNumber);
1386         }
1387
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*/
1392                 int skipcount = 0;
1393                 long newestseqnum = buffer.getNewestSeqNum();
1394                 search:
1395                 for (; seqn <= newestseqnum; seqn++) {
1396                         Slot prevslot = buffer.getSlot(seqn);
1397                         //Push slot number forward
1398                         if (!seenliveslot)
1399                                 oldestLiveSlotSequenceNumver = seqn;
1400
1401                         if (!prevslot.isLive())
1402                                 continue;
1403                         seenliveslot = true;
1404                         Vector<Entry> liveentries = prevslot.getLiveEntries(resize);
1405                         for (Entry liveentry : liveentries) {
1406                                 if (s.hasSpace(liveentry))
1407                                         s.addEntry(liveentry);
1408                                 else {
1409                                         skipcount++;
1410                                         if (skipcount > SKIP_THRESHOLD)
1411                                                 break search;
1412                                 }
1413                         }
1414                 }
1415         }
1416
1417         /**
1418          * Checks for malicious activity and updates the local copy of the block chain.
1419          */
1420         private void validateAndUpdate(Slot[] newSlots, boolean acceptUpdatesToLocal) {
1421
1422                 // The cloud communication layer has checked slot HMACs already before decoding
1423                 if (newSlots.length == 0) {
1424                         return;
1425                 }
1426
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!");
1431                 }
1432
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);
1436
1437                 // Check that the HMAC chain is not broken
1438                 checkHMACChain(indexer, newSlots);
1439
1440                 // Set to keep track of messages from clients
1441                 HashSet<Long> machineSet = new HashSet<Long>(lastMessageTable.keySet());
1442
1443                 // Process each slots data
1444                 for (Slot slot : newSlots) {
1445                         processSlot(indexer, slot, acceptUpdatesToLocal, machineSet);
1446
1447                         updateExpectedSize();
1448                 }
1449
1450                 // If there is a gap, check to see if the server sent us everything.
1451                 if (firstSeqNum != (sequenceNumber + 1)) {
1452
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);
1456
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);
1461                         }
1462                 }
1463
1464                 // Update the size of our local block chain.
1465                 commitNewMaxSize();
1466
1467                 // Commit new to slots to the local block chain.
1468                 for (Slot slot : newSlots) {
1469
1470                         // Insert this slot into our local block chain copy.
1471                         buffer.putSlot(slot);
1472
1473                         // Keep track of how many slots are currently live (have live data in them).
1474                         liveSlotCount++;
1475                 }
1476
1477                 // Get the sequence number of the latest slot in the system
1478                 sequenceNumber = newSlots[newSlots.length - 1].getSequenceNumber();
1479
1480                 updateLiveStateFromServer();
1481
1482                 // No Need to remember after we pulled from the server
1483                 offlineTransactionsCommittedAndAtServer.clear();
1484
1485                 // This is invalidated now
1486                 hadPartialSendToServer = false;
1487         }
1488
1489         private void updateLiveStateFromServer() {
1490                 // Process the new transaction parts
1491                 processNewTransactionParts();
1492
1493                 // Do arbitration on new transactions that were received
1494                 arbitrateFromServer();
1495
1496                 // Update all the committed keys
1497                 boolean didCommitOrSpeculate = updateCommittedTable();
1498
1499                 // Delete the transactions that are now dead
1500                 updateLiveTransactionsAndStatus();
1501
1502                 // Do speculations
1503                 didCommitOrSpeculate |= updateSpeculativeTable(didCommitOrSpeculate);
1504                 updatePendingTransactionSpeculativeTable(didCommitOrSpeculate);
1505         }
1506
1507         private void updateLiveStateFromLocal() {
1508                 // Update all the committed keys
1509                 boolean didCommitOrSpeculate = updateCommittedTable();
1510
1511                 // Delete the transactions that are now dead
1512                 updateLiveTransactionsAndStatus();
1513
1514                 // Do speculations
1515                 didCommitOrSpeculate |= updateSpeculativeTable(didCommitOrSpeculate);
1516                 updatePendingTransactionSpeculativeTable(didCommitOrSpeculate);
1517         }
1518
1519         private void initExpectedSize(long firstSequenceNumber, long numberOfSlots) {
1520                 // if (didFindTableStatus) {
1521                 // return;
1522                 // }
1523                 long prevslots = firstSequenceNumber;
1524
1525
1526                 if (didFindTableStatus) {
1527                         expectedsize = (prevslots < ((long) numberOfSlots)) ? (int) prevslots : expectedsize;
1528                 } else {
1529                         expectedsize = (prevslots < ((long) numberOfSlots)) ? (int) prevslots : numberOfSlots;
1530                 }
1531                 
1532                 didFindTableStatus = true;
1533                 currMaxSize = numberOfSlots;
1534         }
1535
1536         private void updateExpectedSize() {
1537                 expectedsize++;
1538
1539                 if (expectedsize > currMaxSize) {
1540                         expectedsize = currMaxSize;
1541                 }
1542         }
1543
1544
1545         /**
1546          * Check the size of the block chain to make sure there are enough slots sent back by the server.
1547          * This is only called when we have a gap between the slots that we have locally and the slots
1548          * sent by the server therefore in the slots sent by the server there will be at least 1 Table
1549          * status message
1550          */
1551         private void checkNumSlots(int numberOfSlots) {
1552                 if (numberOfSlots != expectedsize) {
1553                         throw new Error("Server Error: Server did not send all slots.  Expected: " + expectedsize + " Received:" + numberOfSlots);
1554                 }
1555         }
1556
1557         private void updateCurrMaxSize(int newmaxsize) {
1558                 currMaxSize = newmaxsize;
1559         }
1560
1561
1562         /**
1563          * Update the size of of the local buffer if it is needed.
1564          */
1565         private void commitNewMaxSize() {
1566                 didFindTableStatus = false;
1567
1568                 // Resize the local slot buffer
1569                 if (numberOfSlots != currMaxSize) {
1570                         buffer.resize((int)currMaxSize);
1571                 }
1572
1573                 // Change the number of local slots to the new size
1574                 numberOfSlots = (int)currMaxSize;
1575
1576                 // Recalculate the resize threshold since the size of the local buffer has changed
1577                 setResizeThreshold();
1578         }
1579
1580         /**
1581          * Process the new transaction parts from this latest round of slots received from the server
1582          */
1583         private void processNewTransactionParts() {
1584
1585                 if (newTransactionParts.size() == 0) {
1586                         // Nothing new to process
1587                         return;
1588                 }
1589
1590                 // Iterate through all the machine Ids that we received new parts for
1591                 for (Long machineId : newTransactionParts.keySet()) {
1592                         Map<Pair<Long, Integer>, TransactionPart> parts = newTransactionParts.get(machineId);
1593
1594                         // Iterate through all the parts for that machine Id
1595                         for (Pair<Long, Integer> partId : parts.keySet()) {
1596                                 TransactionPart part = parts.get(partId);
1597
1598                                 Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(part.getArbitratorId());
1599                                 if ((lastTransactionNumber != null) && (lastTransactionNumber >= part.getSequenceNumber())) {
1600                                         // Set dead the transaction part
1601                                         part.setDead();
1602                                         continue;
1603                                 }
1604
1605                                 // Get the transaction object for that sequence number
1606                                 Transaction transaction = liveTransactionBySequenceNumberTable.get(part.getSequenceNumber());
1607
1608                                 if (transaction == null) {
1609                                         // This is a new transaction that we dont have so make a new one
1610                                         transaction = new Transaction();
1611
1612                                         // Insert this new transaction into the live tables
1613                                         liveTransactionBySequenceNumberTable.put(part.getSequenceNumber(), transaction);
1614                                         liveTransactionByTransactionIdTable.put(part.getTransactionId(), transaction);
1615                                 }
1616
1617                                 // Add that part to the transaction
1618                                 transaction.addPartDecode(part);
1619                         }
1620                 }
1621
1622                 // Clear all the new transaction parts in preparation for the next time the server sends slots
1623                 newTransactionParts.clear();
1624         }
1625
1626
1627         private long lastSeqNumArbOn = 0;
1628
1629         private void arbitrateFromServer() {
1630
1631                 if (liveTransactionBySequenceNumberTable.size() == 0) {
1632                         // Nothing to arbitrate on so move on
1633                         return;
1634                 }
1635
1636                 // Get the transaction sequence numbers and sort from oldest to newest
1637                 List<Long> transactionSequenceNumbers = new ArrayList<Long>(liveTransactionBySequenceNumberTable.keySet());
1638                 Collections.sort(transactionSequenceNumbers);
1639
1640                 // Collection of key value pairs that are
1641                 Map<IoTString, KeyValue> speculativeTableTmp = new HashMap<IoTString, KeyValue>();
1642
1643                 // The last transaction arbitrated on
1644                 long lastTransactionCommitted = -1;
1645                 Set<Abort> generatedAborts = new HashSet<Abort>();
1646
1647                 for (Long transactionSequenceNumber : transactionSequenceNumbers) {
1648                         Transaction transaction = liveTransactionBySequenceNumberTable.get(transactionSequenceNumber);
1649
1650
1651
1652                         // Check if this machine arbitrates for this transaction if not then we cant arbitrate this transaction
1653                         if (transaction.getArbitrator() != localMachineId) {
1654                                 continue;
1655                         }
1656
1657                         if (transactionSequenceNumber < lastSeqNumArbOn) {
1658                                 continue;
1659                         }
1660
1661                         if (offlineTransactionsCommittedAndAtServer.contains(transaction.getId())) {
1662                                 // We have seen this already locally so dont commit again
1663                                 continue;
1664                         }
1665
1666
1667                         if (!transaction.isComplete()) {
1668                                 // Will arbitrate in incorrect order if we continue so just break
1669                                 // Most likely this
1670                                 break;
1671                         }
1672
1673
1674                         // update the largest transaction seen by arbitrator from server
1675                         if (lastTransactionSeenFromMachineFromServer.get(transaction.getMachineId()) == null) {
1676                                 lastTransactionSeenFromMachineFromServer.put(transaction.getMachineId(), transaction.getClientLocalSequenceNumber());
1677                         } else {
1678                                 Long lastTransactionSeenFromMachine = lastTransactionSeenFromMachineFromServer.get(transaction.getMachineId());
1679                                 if (transaction.getClientLocalSequenceNumber() > lastTransactionSeenFromMachine) {
1680                                         lastTransactionSeenFromMachineFromServer.put(transaction.getMachineId(), transaction.getClientLocalSequenceNumber());
1681                                 }
1682                         }
1683
1684                         if (transaction.evaluateGuard(committedKeyValueTable, speculativeTableTmp, null)) {
1685                                 // Guard evaluated as true
1686
1687                                 // Update the local changes so we can make the commit
1688                                 for (KeyValue kv : transaction.getKeyValueUpdateSet()) {
1689                                         speculativeTableTmp.put(kv.getKey(), kv);
1690                                 }
1691
1692                                 // Update what the last transaction committed was for use in batch commit
1693                                 lastTransactionCommitted = transactionSequenceNumber;
1694                         } else {
1695                                 // Guard evaluated was false so create abort
1696
1697                                 // Create the abort
1698                                 Abort newAbort = new Abort(null,
1699                                                            transaction.getClientLocalSequenceNumber(),
1700                                                            transaction.getSequenceNumber(),
1701                                                            transaction.getMachineId(),
1702                                                            transaction.getArbitrator(),
1703                                                            localArbitrationSequenceNumber);
1704                                 localArbitrationSequenceNumber++;
1705
1706                                 generatedAborts.add(newAbort);
1707
1708                                 // Insert the abort so we can process
1709                                 processEntry(newAbort);
1710                         }
1711
1712                         lastSeqNumArbOn = transactionSequenceNumber;
1713
1714                         // liveTransactionBySequenceNumberTable.remove(transactionSequenceNumber);
1715                 }
1716
1717                 Commit newCommit = null;
1718
1719                 // If there is something to commit
1720                 if (speculativeTableTmp.size() != 0) {
1721
1722                         // Create the commit and increment the commit sequence number
1723                         newCommit = new Commit(localArbitrationSequenceNumber, localMachineId, lastTransactionCommitted);
1724                         localArbitrationSequenceNumber++;
1725
1726                         // Add all the new keys to the commit
1727                         for (KeyValue kv : speculativeTableTmp.values()) {
1728                                 newCommit.addKV(kv);
1729                         }
1730
1731                         // create the commit parts
1732                         newCommit.createCommitParts();
1733
1734                         // Append all the commit parts to the end of the pending queue waiting for sending to the server
1735
1736                         // Insert the commit so we can process it
1737                         for (CommitPart commitPart : newCommit.getParts().values()) {
1738                                 processEntry(commitPart);
1739                         }
1740                 }
1741
1742                 if ((newCommit != null) || (generatedAborts.size() > 0)) {
1743                         ArbitrationRound arbitrationRound = new ArbitrationRound(newCommit, generatedAborts);
1744                         pendingSendArbitrationRounds.add(arbitrationRound);
1745
1746                         if (compactArbitrationData()) {
1747                                 ArbitrationRound newArbitrationRound = pendingSendArbitrationRounds.get(pendingSendArbitrationRounds.size() - 1);
1748                                 if (newArbitrationRound.getCommit() != null) {
1749                                         for (CommitPart commitPart : newArbitrationRound.getCommit().getParts().values()) {
1750                                                 processEntry(commitPart);
1751                                         }
1752                                 }
1753                         }
1754                 }
1755         }
1756
1757         private Pair<Boolean, Boolean> arbitrateOnLocalTransaction(Transaction transaction) {
1758
1759                 // Check if this machine arbitrates for this transaction if not then we cant arbitrate this transaction
1760                 if (transaction.getArbitrator() != localMachineId) {
1761                         return new Pair<Boolean, Boolean>(false, false);
1762                 }
1763
1764                 if (!transaction.isComplete()) {
1765                         // Will arbitrate in incorrect order if we continue so just break
1766                         // Most likely this
1767                         return new Pair<Boolean, Boolean>(false, false);
1768                 }
1769
1770                 if (transaction.getMachineId() != localMachineId) {
1771                         // dont do this check for local transactions
1772                         if (lastTransactionSeenFromMachineFromServer.get(transaction.getMachineId()) != null) {
1773                                 if (lastTransactionSeenFromMachineFromServer.get(transaction.getMachineId()) > transaction.getClientLocalSequenceNumber()) {
1774                                         // We've have already seen this from the server
1775                                         return new Pair<Boolean, Boolean>(false, false);
1776                                 }
1777                         }
1778                 }
1779
1780                 if (transaction.evaluateGuard(committedKeyValueTable, null, null)) {
1781                         // Guard evaluated as true
1782
1783                         // Create the commit and increment the commit sequence number
1784                         Commit newCommit = new Commit(localArbitrationSequenceNumber, localMachineId, -1);
1785                         localArbitrationSequenceNumber++;
1786
1787                         // Update the local changes so we can make the commit
1788                         for (KeyValue kv : transaction.getKeyValueUpdateSet()) {
1789                                 newCommit.addKV(kv);
1790                         }
1791
1792                         // create the commit parts
1793                         newCommit.createCommitParts();
1794
1795                         // Append all the commit parts to the end of the pending queue waiting for sending to the server
1796                         ArbitrationRound arbitrationRound = new ArbitrationRound(newCommit, new HashSet<Abort>());
1797                         pendingSendArbitrationRounds.add(arbitrationRound);
1798
1799                         if (compactArbitrationData()) {
1800                                 ArbitrationRound newArbitrationRound = pendingSendArbitrationRounds.get(pendingSendArbitrationRounds.size() - 1);
1801                                 for (CommitPart commitPart : newArbitrationRound.getCommit().getParts().values()) {
1802                                         processEntry(commitPart);
1803                                 }
1804                         } else {
1805                                 // Insert the commit so we can process it
1806                                 for (CommitPart commitPart : newCommit.getParts().values()) {
1807                                         processEntry(commitPart);
1808                                 }
1809                         }
1810
1811                         if (transaction.getMachineId() == localMachineId) {
1812                                 TransactionStatus status = transaction.getTransactionStatus();
1813                                 if (status != null) {
1814                                         status.setStatus(TransactionStatus.StatusCommitted);
1815                                 }
1816                         }
1817
1818                         updateLiveStateFromLocal();
1819                         return new Pair<Boolean, Boolean>(true, true);
1820                 } else {
1821
1822                         if (transaction.getMachineId() == localMachineId) {
1823                                 // For locally created messages update the status
1824
1825                                 // Guard evaluated was false so create abort
1826                                 TransactionStatus status = transaction.getTransactionStatus();
1827                                 if (status != null) {
1828                                         status.setStatus(TransactionStatus.StatusAborted);
1829                                 }
1830                         } else {
1831                                 Set addAbortSet = new HashSet<Abort>();
1832
1833
1834                                 // Create the abort
1835                                 Abort newAbort = new Abort(null,
1836                                                            transaction.getClientLocalSequenceNumber(),
1837                                                            -1,
1838                                                            transaction.getMachineId(),
1839                                                            transaction.getArbitrator(),
1840                                                            localArbitrationSequenceNumber);
1841                                 localArbitrationSequenceNumber++;
1842
1843                                 addAbortSet.add(newAbort);
1844
1845
1846                                 // Append all the commit parts to the end of the pending queue waiting for sending to the server
1847                                 ArbitrationRound arbitrationRound = new ArbitrationRound(null, addAbortSet);
1848                                 pendingSendArbitrationRounds.add(arbitrationRound);
1849
1850                                 if (compactArbitrationData()) {
1851                                         ArbitrationRound newArbitrationRound = pendingSendArbitrationRounds.get(pendingSendArbitrationRounds.size() - 1);
1852                                         for (CommitPart commitPart : newArbitrationRound.getCommit().getParts().values()) {
1853                                                 processEntry(commitPart);
1854                                         }
1855                                 }
1856                         }
1857
1858                         updateLiveStateFromLocal();
1859                         return new Pair<Boolean, Boolean>(true, false);
1860                 }
1861         }
1862
1863         /**
1864          * 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
1865          */
1866         private boolean compactArbitrationData() {
1867
1868                 if (pendingSendArbitrationRounds.size() < 2) {
1869                         // Nothing to compact so do nothing
1870                         return false;
1871                 }
1872
1873                 ArbitrationRound lastRound = pendingSendArbitrationRounds.get(pendingSendArbitrationRounds.size() - 1);
1874                 if (lastRound.didSendPart()) {
1875                         return false;
1876                 }
1877
1878                 boolean hadCommit = (lastRound.getCommit() == null);
1879                 boolean gotNewCommit = false;
1880
1881                 int numberToDelete = 1;
1882                 while (numberToDelete < pendingSendArbitrationRounds.size()) {
1883                         ArbitrationRound round = pendingSendArbitrationRounds.get(pendingSendArbitrationRounds.size() - numberToDelete - 1);
1884
1885                         if (round.isFull() || round.didSendPart()) {
1886                                 // Stop since there is a part that cannot be compacted and we need to compact in order
1887                                 break;
1888                         }
1889
1890                         if (round.getCommit() == null) {
1891
1892                                 // Try compacting aborts only
1893                                 int newSize = round.getCurrentSize() + lastRound.getAbortsCount();
1894                                 if (newSize > ArbitrationRound.MAX_PARTS) {
1895                                         // Cant compact since it would be too large
1896                                         break;
1897                                 }
1898                                 lastRound.addAborts(round.getAborts());
1899                         } else {
1900
1901                                 // Create a new larger commit
1902                                 Commit newCommit = Commit.merge(lastRound.getCommit(), round.getCommit(), localArbitrationSequenceNumber);
1903                                 localArbitrationSequenceNumber++;
1904
1905                                 // Create the commit parts so that we can count them
1906                                 newCommit.createCommitParts();
1907
1908                                 // Calculate the new size of the parts
1909                                 int newSize = newCommit.getNumberOfParts();
1910                                 newSize += lastRound.getAbortsCount();
1911                                 newSize += round.getAbortsCount();
1912
1913                                 if (newSize > ArbitrationRound.MAX_PARTS) {
1914                                         // Cant compact since it would be too large
1915                                         break;
1916                                 }
1917
1918                                 // Set the new compacted part
1919                                 lastRound.setCommit(newCommit);
1920                                 lastRound.addAborts(round.getAborts());
1921                                 gotNewCommit = true;
1922                         }
1923
1924                         numberToDelete++;
1925                 }
1926
1927                 if (numberToDelete != 1) {
1928                         // If there is a compaction
1929
1930                         // Delete the previous pieces that are now in the new compacted piece
1931                         if (numberToDelete == pendingSendArbitrationRounds.size()) {
1932                                 pendingSendArbitrationRounds.clear();
1933                         } else {
1934                                 for (int i = 0; i < numberToDelete; i++) {
1935                                         pendingSendArbitrationRounds.remove(pendingSendArbitrationRounds.size() - 1);
1936                                 }
1937                         }
1938
1939                         // Add the new compacted into the pending to send list
1940                         pendingSendArbitrationRounds.add(lastRound);
1941
1942                         // Should reinsert into the commit processor
1943                         if (hadCommit && gotNewCommit) {
1944                                 return true;
1945                         }
1946                 }
1947
1948                 return false;
1949         }
1950         // private boolean compactArbitrationData() {
1951         //      return false;
1952         // }
1953
1954         /**
1955          * Update all the commits and the committed tables, sets dead the dead transactions
1956          */
1957         private boolean updateCommittedTable() {
1958
1959                 if (newCommitParts.size() == 0) {
1960                         // Nothing new to process
1961                         return false;
1962                 }
1963
1964                 // Iterate through all the machine Ids that we received new parts for
1965                 for (Long machineId : newCommitParts.keySet()) {
1966                         Map<Pair<Long, Integer>, CommitPart> parts = newCommitParts.get(machineId);
1967
1968                         // Iterate through all the parts for that machine Id
1969                         for (Pair<Long, Integer> partId : parts.keySet()) {
1970                                 CommitPart part = parts.get(partId);
1971
1972                                 // Get the transaction object for that sequence number
1973                                 Map<Long, Commit> commitForClientTable = liveCommitsTable.get(part.getMachineId());
1974
1975                                 if (commitForClientTable == null) {
1976                                         // This is the first commit from this device
1977                                         commitForClientTable = new HashMap<Long, Commit>();
1978                                         liveCommitsTable.put(part.getMachineId(), commitForClientTable);
1979                                 }
1980
1981                                 Commit commit = commitForClientTable.get(part.getSequenceNumber());
1982
1983                                 if (commit == null) {
1984                                         // This is a new commit that we dont have so make a new one
1985                                         commit = new Commit();
1986
1987                                         // Insert this new commit into the live tables
1988                                         commitForClientTable.put(part.getSequenceNumber(), commit);
1989                                 }
1990
1991                                 // Add that part to the commit
1992                                 commit.addPartDecode(part);
1993                         }
1994                 }
1995
1996                 // Clear all the new commits parts in preparation for the next time the server sends slots
1997                 newCommitParts.clear();
1998
1999                 // If we process a new commit keep track of it for future use
2000                 boolean didProcessANewCommit = false;
2001
2002                 // Process the commits one by one
2003                 for (Long arbitratorId : liveCommitsTable.keySet()) {
2004
2005                         // Get all the commits for a specific arbitrator
2006                         Map<Long, Commit> commitForClientTable = liveCommitsTable.get(arbitratorId);
2007
2008                         // Sort the commits in order
2009                         List<Long> commitSequenceNumbers = new ArrayList<Long>(commitForClientTable.keySet());
2010                         Collections.sort(commitSequenceNumbers);
2011
2012                         // Get the last commit seen from this arbitrator
2013                         long lastCommitSeenSequenceNumber = -1;
2014                         if (lastCommitSeenSequenceNumberByArbitratorTable.get(arbitratorId) != null) {
2015                                 lastCommitSeenSequenceNumber = lastCommitSeenSequenceNumberByArbitratorTable.get(arbitratorId);
2016                         }
2017
2018                         // Go through each new commit one by one
2019                         for (int i = 0; i < commitSequenceNumbers.size(); i++) {
2020                                 Long commitSequenceNumber = commitSequenceNumbers.get(i);
2021                                 Commit commit = commitForClientTable.get(commitSequenceNumber);
2022
2023                                 // Special processing if a commit is not complete
2024                                 if (!commit.isComplete()) {
2025                                         if (i == (commitSequenceNumbers.size() - 1)) {
2026                                                 // 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
2027                                                 break;
2028                                         } else {
2029                                                 // This is a commit that was already dead but parts of it are still in the block chain (not flushed out yet).
2030                                                 // Delete it and move on
2031                                                 commit.setDead();
2032                                                 commitForClientTable.remove(commit.getSequenceNumber());
2033                                                 continue;
2034                                         }
2035                                 }
2036
2037                                 // Update the last transaction that was updated if we can
2038                                 if (commit.getTransactionSequenceNumber() != -1) {
2039                                         Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(commit.getMachineId());
2040
2041                                         // Update the last transaction sequence number that the arbitrator arbitrated on
2042                                         if ((lastTransactionNumber == null) || (lastTransactionNumber < commit.getTransactionSequenceNumber())) {
2043                                                 lastArbitratedTransactionNumberByArbitratorTable.put(commit.getMachineId(), commit.getTransactionSequenceNumber());
2044                                         }
2045                                 }
2046
2047                                 // Update the last arbitration data that we have seen so far
2048                                 if (lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(commit.getMachineId()) != null) {
2049
2050                                         long lastArbitrationSequenceNumber = lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(commit.getMachineId());
2051                                         if (commit.getSequenceNumber() > lastArbitrationSequenceNumber) {
2052                                                 // Is larger
2053                                                 lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.put(commit.getMachineId(), commit.getSequenceNumber());
2054                                         }
2055                                 } else {
2056                                         // Never seen any data from this arbitrator so record the first one
2057                                         lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.put(commit.getMachineId(), commit.getSequenceNumber());
2058                                 }
2059
2060                                 // We have already seen this commit before so need to do the full processing on this commit
2061                                 if (commit.getSequenceNumber() <= lastCommitSeenSequenceNumber) {
2062
2063                                         // Update the last transaction that was updated if we can
2064                                         if (commit.getTransactionSequenceNumber() != -1) {
2065                                                 Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(commit.getMachineId());
2066
2067                                                 // Update the last transaction sequence number that the arbitrator arbitrated on
2068                                                 if ((lastTransactionNumber == null) || (lastTransactionNumber < commit.getTransactionSequenceNumber())) {
2069                                                         lastArbitratedTransactionNumberByArbitratorTable.put(commit.getMachineId(), commit.getTransactionSequenceNumber());
2070                                                 }
2071                                         }
2072
2073                                         continue;
2074                                 }
2075
2076                                 // If we got here then this is a brand new commit and needs full processing
2077
2078                                 // Get what commits should be edited, these are the commits that have live values for their keys
2079                                 Set<Commit> commitsToEdit = new HashSet<Commit>();
2080                                 for (KeyValue kv : commit.getKeyValueUpdateSet()) {
2081                                         commitsToEdit.add(liveCommitsByKeyTable.get(kv.getKey()));
2082                                 }
2083                                 commitsToEdit.remove(null); // remove null since it could be in this set
2084
2085                                 // Update each previous commit that needs to be updated
2086                                 for (Commit previousCommit : commitsToEdit) {
2087
2088                                         // Only bother with live commits (TODO: Maybe remove this check)
2089                                         if (previousCommit.isLive()) {
2090
2091                                                 // Update which keys in the old commits are still live
2092                                                 for (KeyValue kv : commit.getKeyValueUpdateSet()) {
2093                                                         previousCommit.invalidateKey(kv.getKey());
2094                                                 }
2095
2096                                                 // if the commit is now dead then remove it
2097                                                 if (!previousCommit.isLive()) {
2098                                                         commitForClientTable.remove(previousCommit);
2099                                                 }
2100                                         }
2101                                 }
2102
2103                                 // Update the last seen sequence number from this arbitrator
2104                                 if (lastCommitSeenSequenceNumberByArbitratorTable.get(commit.getMachineId()) != null) {
2105                                         if (commit.getSequenceNumber() > lastCommitSeenSequenceNumberByArbitratorTable.get(commit.getMachineId())) {
2106                                                 lastCommitSeenSequenceNumberByArbitratorTable.put(commit.getMachineId(), commit.getSequenceNumber());
2107                                         }
2108                                 } else {
2109                                         lastCommitSeenSequenceNumberByArbitratorTable.put(commit.getMachineId(), commit.getSequenceNumber());
2110                                 }
2111
2112                                 // We processed a new commit that we havent seen before
2113                                 didProcessANewCommit = true;
2114
2115                                 // Update the committed table of keys and which commit is using which key
2116                                 for (KeyValue kv : commit.getKeyValueUpdateSet()) {
2117                                         committedKeyValueTable.put(kv.getKey(), kv);
2118                                         liveCommitsByKeyTable.put(kv.getKey(), commit);
2119                                 }
2120                         }
2121                 }
2122
2123                 return didProcessANewCommit;
2124         }
2125
2126         /**
2127          * Create the speculative table from transactions that are still live and have come from the cloud
2128          */
2129         private boolean updateSpeculativeTable(boolean didProcessNewCommits) {
2130                 if (liveTransactionBySequenceNumberTable.keySet().size() == 0) {
2131                         // There is nothing to speculate on
2132                         return false;
2133                 }
2134
2135                 // Create a list of the transaction sequence numbers and sort them from oldest to newest
2136                 List<Long> transactionSequenceNumbersSorted = new ArrayList<Long>(liveTransactionBySequenceNumberTable.keySet());
2137                 Collections.sort(transactionSequenceNumbersSorted);
2138
2139                 boolean hasGapInTransactionSequenceNumbers = transactionSequenceNumbersSorted.get(0) != oldestTransactionSequenceNumberSpeculatedOn;
2140
2141
2142                 if (hasGapInTransactionSequenceNumbers || didProcessNewCommits) {
2143                         // If there is a gap in the transaction sequence numbers then there was a commit or an abort of a transaction
2144                         // OR there was a new commit (Could be from offline commit) so a redo the speculation from scratch
2145
2146                         // Start from scratch
2147                         speculatedKeyValueTable.clear();
2148                         lastTransactionSequenceNumberSpeculatedOn = -1;
2149                         oldestTransactionSequenceNumberSpeculatedOn = -1;
2150
2151                 }
2152
2153                 // Remember the front of the transaction list
2154                 oldestTransactionSequenceNumberSpeculatedOn = transactionSequenceNumbersSorted.get(0);
2155
2156                 // Find where to start arbitration from
2157                 int startIndex = transactionSequenceNumbersSorted.indexOf(lastTransactionSequenceNumberSpeculatedOn) + 1;
2158
2159                 if (startIndex >= transactionSequenceNumbersSorted.size()) {
2160                         // Make sure we are not out of bounds
2161                         return false; // did not speculate
2162                 }
2163
2164                 Set<Long> incompleteTransactionArbitrator = new HashSet<Long>();
2165                 boolean didSkip = true;
2166
2167                 for (int i = startIndex; i < transactionSequenceNumbersSorted.size(); i++) {
2168                         long transactionSequenceNumber = transactionSequenceNumbersSorted.get(i);
2169                         Transaction transaction = liveTransactionBySequenceNumberTable.get(transactionSequenceNumber);
2170
2171                         if (!transaction.isComplete()) {
2172                                 // If there is an incomplete transaction then there is nothing we can do
2173                                 // add this transactions arbitrator to the list of arbitrators we should ignore
2174                                 incompleteTransactionArbitrator.add(transaction.getArbitrator());
2175                                 didSkip = true;
2176                                 continue;
2177                         }
2178
2179                         if (incompleteTransactionArbitrator.contains(transaction.getArbitrator())) {
2180                                 continue;
2181                         }
2182
2183                         lastTransactionSequenceNumberSpeculatedOn = transactionSequenceNumber;
2184
2185                         if (transaction.evaluateGuard(committedKeyValueTable, speculatedKeyValueTable, null)) {
2186                                 // Guard evaluated to true so update the speculative table
2187                                 for (KeyValue kv : transaction.getKeyValueUpdateSet()) {
2188                                         speculatedKeyValueTable.put(kv.getKey(), kv);
2189                                 }
2190                         }
2191                 }
2192
2193                 if (didSkip) {
2194                         // Since there was a skip we need to redo the speculation next time around
2195                         lastTransactionSequenceNumberSpeculatedOn = -1;
2196                         oldestTransactionSequenceNumberSpeculatedOn = -1;
2197                 }
2198
2199                 // We did some speculation
2200                 return true;
2201         }
2202
2203         /**
2204          * Create the pending transaction speculative table from transactions that are still in the pending transaction buffer
2205          */
2206         private void updatePendingTransactionSpeculativeTable(boolean didProcessNewCommitsOrSpeculate) {
2207                 if (pendingTransactionQueue.size() == 0) {
2208                         // There is nothing to speculate on
2209                         return;
2210                 }
2211
2212
2213                 if (didProcessNewCommitsOrSpeculate || (firstPendingTransaction != pendingTransactionQueue.get(0))) {
2214                         // need to reset on the pending speculation
2215                         lastPendingTransactionSpeculatedOn = null;
2216                         firstPendingTransaction = pendingTransactionQueue.get(0);
2217                         pendingTransactionSpeculatedKeyValueTable.clear();
2218                 }
2219
2220                 // Find where to start arbitration from
2221                 int startIndex = pendingTransactionQueue.indexOf(firstPendingTransaction) + 1;
2222
2223                 if (startIndex >= pendingTransactionQueue.size()) {
2224                         // Make sure we are not out of bounds
2225                         return;
2226                 }
2227
2228                 for (int i = startIndex; i < pendingTransactionQueue.size(); i++) {
2229                         Transaction transaction = pendingTransactionQueue.get(i);
2230
2231                         lastPendingTransactionSpeculatedOn = transaction;
2232
2233                         if (transaction.evaluateGuard(committedKeyValueTable, speculatedKeyValueTable, pendingTransactionSpeculatedKeyValueTable)) {
2234                                 // Guard evaluated to true so update the speculative table
2235                                 for (KeyValue kv : transaction.getKeyValueUpdateSet()) {
2236                                         pendingTransactionSpeculatedKeyValueTable.put(kv.getKey(), kv);
2237                                 }
2238                         }
2239                 }
2240         }
2241
2242         /**
2243          * Set dead and remove from the live transaction tables the transactions that are dead
2244          */
2245         private void updateLiveTransactionsAndStatus() {
2246
2247                 // Go through each of the transactions
2248                 for (Iterator<Map.Entry<Long, Transaction>> iter = liveTransactionBySequenceNumberTable.entrySet().iterator(); iter.hasNext();) {
2249                         Transaction transaction = iter.next().getValue();
2250
2251                         // Check if the transaction is dead
2252                         Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(transaction.getArbitrator());
2253                         if ((lastTransactionNumber != null) && (lastTransactionNumber >= transaction.getSequenceNumber())) {
2254
2255                                 // Set dead the transaction
2256                                 transaction.setDead();
2257
2258                                 // Remove the transaction from the live table
2259                                 iter.remove();
2260                                 liveTransactionByTransactionIdTable.remove(transaction.getId());
2261                         }
2262                 }
2263
2264                 // Go through each of the transactions
2265                 for (Iterator<Map.Entry<Long, TransactionStatus>> iter = outstandingTransactionStatus.entrySet().iterator(); iter.hasNext();) {
2266                         TransactionStatus status = iter.next().getValue();
2267
2268                         // Check if the transaction is dead
2269                         Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(status.getTransactionArbitrator());
2270                         if ((lastTransactionNumber != null) && (lastTransactionNumber >= status.getTransactionSequenceNumber())) {
2271
2272                                 // Set committed
2273                                 status.setStatus(TransactionStatus.StatusCommitted);
2274
2275                                 // Remove
2276                                 iter.remove();
2277                         }
2278                 }
2279         }
2280
2281         /**
2282          * Process this slot, entry by entry.  Also update the latest message sent by slot
2283          */
2284         private void processSlot(SlotIndexer indexer, Slot slot, boolean acceptUpdatesToLocal, HashSet<Long> machineSet) {
2285
2286                 // Update the last message seen
2287                 updateLastMessage(slot.getMachineID(), slot.getSequenceNumber(), slot, acceptUpdatesToLocal, machineSet);
2288
2289                 // Process each entry in the slot
2290                 for (Entry entry : slot.getEntries()) {
2291                         switch (entry.getType()) {
2292
2293                         case Entry.TypeCommitPart:
2294                                 processEntry((CommitPart)entry);
2295                                 break;
2296
2297                         case Entry.TypeAbort:
2298                                 processEntry((Abort)entry);
2299                                 break;
2300
2301                         case Entry.TypeTransactionPart:
2302                                 processEntry((TransactionPart)entry);
2303                                 break;
2304
2305                         case Entry.TypeNewKey:
2306                                 processEntry((NewKey)entry);
2307                                 break;
2308
2309                         case Entry.TypeLastMessage:
2310                                 processEntry((LastMessage)entry, machineSet);
2311                                 break;
2312
2313                         case Entry.TypeRejectedMessage:
2314                                 processEntry((RejectedMessage)entry, indexer);
2315                                 break;
2316
2317                         case Entry.TypeTableStatus:
2318                                 processEntry((TableStatus)entry, slot.getSequenceNumber());
2319                                 break;
2320
2321                         default:
2322                                 throw new Error("Unrecognized type: " + entry.getType());
2323                         }
2324                 }
2325         }
2326
2327         /**
2328          * Update the last message that was sent for a machine Id
2329          */
2330         private void processEntry(LastMessage entry, HashSet<Long> machineSet) {
2331                 // Update what the last message received by a machine was
2332                 updateLastMessage(entry.getMachineID(), entry.getSequenceNumber(), entry, false, machineSet);
2333         }
2334
2335         /**
2336          * Add the new key to the arbitrators table and update the set of live new keys (in case of a rescued new key message)
2337          */
2338         private void processEntry(NewKey entry) {
2339
2340                 // Update the arbitrator table with the new key information
2341                 arbitratorTable.put(entry.getKey(), entry.getMachineID());
2342
2343                 // Update what the latest live new key is
2344                 NewKey oldNewKey = liveNewKeyTable.put(entry.getKey(), entry);
2345                 if (oldNewKey != null) {
2346                         // Delete the old new key messages
2347                         oldNewKey.setDead();
2348                 }
2349         }
2350
2351         /**
2352          * Process new table status entries and set dead the old ones as new ones come in.
2353          * keeps track of the largest and smallest table status seen in this current round
2354          * of updating the local copy of the block chain
2355          */
2356         private void processEntry(TableStatus entry, long seq) {
2357                 int newNumSlots = entry.getMaxSlots();
2358                 updateCurrMaxSize(newNumSlots);
2359
2360                 initExpectedSize(seq, newNumSlots);
2361
2362                 if (liveTableStatus != null) {
2363                         // We have a larger table status so the old table status is no longer alive
2364                         liveTableStatus.setDead();
2365                 }
2366
2367                 // Make this new table status the latest alive table status
2368                 liveTableStatus = entry;
2369         }
2370
2371         /**
2372          * Check old messages to see if there is a block chain violation. Also
2373          */
2374         private void processEntry(RejectedMessage entry, SlotIndexer indexer) {
2375                 long oldSeqNum = entry.getOldSeqNum();
2376                 long newSeqNum = entry.getNewSeqNum();
2377                 boolean isequal = entry.getEqual();
2378                 long machineId = entry.getMachineID();
2379                 long seq = entry.getSequenceNumber();
2380
2381
2382                 // Check if we have messages that were supposed to be rejected in our local block chain
2383                 for (long seqNum = oldSeqNum; seqNum <= newSeqNum; seqNum++) {
2384
2385                         // Get the slot
2386                         Slot slot = indexer.getSlot(seqNum);
2387
2388                         if (slot != null) {
2389                                 // If we have this slot make sure that it was not supposed to be a rejected slot
2390
2391                                 long slotMachineId = slot.getMachineID();
2392                                 if (isequal != (slotMachineId == machineId)) {
2393                                         throw new Error("Server Error: Trying to insert rejected message for slot " + seqNum);
2394                                 }
2395                         }
2396                 }
2397
2398
2399                 // Create a list of clients to watch until they see this rejected message entry.
2400                 HashSet<Long> deviceWatchSet = new HashSet<Long>();
2401                 for (Map.Entry<Long, Pair<Long, Liveness>> lastMessageEntry : lastMessageTable.entrySet()) {
2402
2403                         // Machine ID for the last message entry
2404                         long lastMessageEntryMachineId = lastMessageEntry.getKey();
2405
2406                         // We've seen it, don't need to continue to watch.  Our next
2407                         // message will implicitly acknowledge it.
2408                         if (lastMessageEntryMachineId == localMachineId) {
2409                                 continue;
2410                         }
2411
2412                         Pair<Long, Liveness> lastMessageValue = lastMessageEntry.getValue();
2413                         long entrySequenceNumber = lastMessageValue.getFirst();
2414
2415                         if (entrySequenceNumber < seq) {
2416
2417                                 // Add this rejected message to the set of messages that this machine ID did not see yet
2418                                 addWatchList(lastMessageEntryMachineId, entry);
2419
2420                                 // This client did not see this rejected message yet so add it to the watch set to monitor
2421                                 deviceWatchSet.add(lastMessageEntryMachineId);
2422                         }
2423                 }
2424
2425                 if (deviceWatchSet.isEmpty()) {
2426                         // This rejected message has been seen by all the clients so
2427                         entry.setDead();
2428                 } else {
2429                         // We need to watch this rejected message
2430                         entry.setWatchSet(deviceWatchSet);
2431                 }
2432         }
2433
2434         /**
2435          * Check if this abort is live, if not then save it so we can kill it later.
2436          * update the last transaction number that was arbitrated on.
2437          */
2438         private void processEntry(Abort entry) {
2439
2440
2441                 if (entry.getTransactionSequenceNumber() != -1) {
2442                         // update the transaction status if it was sent to the server
2443                         TransactionStatus status = outstandingTransactionStatus.remove(entry.getTransactionSequenceNumber());
2444                         if (status != null) {
2445                                 status.setStatus(TransactionStatus.StatusAborted);
2446                         }
2447                 }
2448
2449                 // Abort has not been seen by the client it is for yet so we need to keep track of it
2450                 Abort previouslySeenAbort = liveAbortTable.put(entry.getAbortId(), entry);
2451                 if (previouslySeenAbort != null) {
2452                         previouslySeenAbort.setDead(); // Delete old version of the abort since we got a rescued newer version
2453                 }
2454
2455                 if (entry.getTransactionArbitrator() == localMachineId) {
2456                         liveAbortsGeneratedByLocal.put(entry.getArbitratorLocalSequenceNumber(), entry);
2457                 }
2458
2459                 if ((entry.getSequenceNumber() != -1) && (lastMessageTable.get(entry.getTransactionMachineId()).getFirst() >= entry.getSequenceNumber())) {
2460
2461                         // The machine already saw this so it is dead
2462                         entry.setDead();
2463                         liveAbortTable.remove(entry.getAbortId());
2464
2465                         if (entry.getTransactionArbitrator() == localMachineId) {
2466                                 liveAbortsGeneratedByLocal.remove(entry.getArbitratorLocalSequenceNumber());
2467                         }
2468
2469                         return;
2470                 }
2471
2472
2473
2474
2475                 // Update the last arbitration data that we have seen so far
2476                 if (lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(entry.getTransactionArbitrator()) != null) {
2477
2478                         long lastArbitrationSequenceNumber = lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(entry.getTransactionArbitrator());
2479                         if (entry.getSequenceNumber() > lastArbitrationSequenceNumber) {
2480                                 // Is larger
2481                                 lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.put(entry.getTransactionArbitrator(), entry.getSequenceNumber());
2482                         }
2483                 } else {
2484                         // Never seen any data from this arbitrator so record the first one
2485                         lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.put(entry.getTransactionArbitrator(), entry.getSequenceNumber());
2486                 }
2487
2488
2489                 // Set dead a transaction if we can
2490                 Transaction transactionToSetDead = liveTransactionByTransactionIdTable.remove(new Pair<Long, Long>(entry.getTransactionMachineId(), entry.getTransactionClientLocalSequenceNumber()));
2491                 if (transactionToSetDead != null) {
2492                         liveTransactionBySequenceNumberTable.remove(transactionToSetDead.getSequenceNumber());
2493                 }
2494
2495                 // Update the last transaction sequence number that the arbitrator arbitrated on
2496                 Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(entry.getTransactionArbitrator());
2497                 if ((lastTransactionNumber == null) || (lastTransactionNumber < entry.getTransactionSequenceNumber())) {
2498
2499                         // Is a valid one
2500                         if (entry.getTransactionSequenceNumber() != -1) {
2501                                 lastArbitratedTransactionNumberByArbitratorTable.put(entry.getTransactionArbitrator(), entry.getTransactionSequenceNumber());
2502                         }
2503                 }
2504         }
2505
2506         /**
2507          * Set dead the transaction part if that transaction is dead and keep track of all new parts
2508          */
2509         private void processEntry(TransactionPart entry) {
2510                 // Check if we have already seen this transaction and set it dead OR if it is not alive
2511                 Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(entry.getArbitratorId());
2512                 if ((lastTransactionNumber != null) && (lastTransactionNumber >= entry.getSequenceNumber())) {
2513                         // This transaction is dead, it was already committed or aborted
2514                         entry.setDead();
2515                         return;
2516                 }
2517
2518                 // This part is still alive
2519                 Map<Pair<Long, Integer>, TransactionPart> transactionPart = newTransactionParts.get(entry.getMachineId());
2520
2521                 if (transactionPart == null) {
2522                         // Dont have a table for this machine Id yet so make one
2523                         transactionPart = new HashMap<Pair<Long, Integer>, TransactionPart>();
2524                         newTransactionParts.put(entry.getMachineId(), transactionPart);
2525                 }
2526
2527                 // Update the part and set dead ones we have already seen (got a rescued version)
2528                 TransactionPart previouslySeenPart = transactionPart.put(entry.getPartId(), entry);
2529                 if (previouslySeenPart != null) {
2530                         previouslySeenPart.setDead();
2531                 }
2532         }
2533
2534         /**
2535          * Process new commit entries and save them for future use.  Delete duplicates
2536          */
2537         private void processEntry(CommitPart entry) {
2538
2539
2540                 // Update the last transaction that was updated if we can
2541                 if (entry.getTransactionSequenceNumber() != -1) {
2542                         Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(entry.getMachineId());
2543
2544                         // Update the last transaction sequence number that the arbitrator arbitrated on
2545                         if ((lastTransactionNumber == null) || (lastTransactionNumber < entry.getTransactionSequenceNumber())) {
2546                                 lastArbitratedTransactionNumberByArbitratorTable.put(entry.getMachineId(), entry.getTransactionSequenceNumber());
2547                         }
2548                 }
2549
2550
2551
2552
2553                 Map<Pair<Long, Integer>, CommitPart> commitPart = newCommitParts.get(entry.getMachineId());
2554
2555                 if (commitPart == null) {
2556                         // Don't have a table for this machine Id yet so make one
2557                         commitPart = new HashMap<Pair<Long, Integer>, CommitPart>();
2558                         newCommitParts.put(entry.getMachineId(), commitPart);
2559                 }
2560
2561                 // Update the part and set dead ones we have already seen (got a rescued version)
2562                 CommitPart previouslySeenPart = commitPart.put(entry.getPartId(), entry);
2563                 if (previouslySeenPart != null) {
2564                         previouslySeenPart.setDead();
2565                 }
2566         }
2567
2568         /**
2569          * Update the last message seen table.  Update and set dead the appropriate RejectedMessages as clients see them.
2570          * Updates the live aborts, removes those that are dead and sets them dead.
2571          * Check that the last message seen is correct and that there is no mismatch of our own last message or that
2572          * other clients have not had a rollback on the last message.
2573          */
2574         private void updateLastMessage(long machineId, long seqNum, Liveness liveness, boolean acceptUpdatesToLocal, HashSet<Long> machineSet) {
2575
2576                 // We have seen this machine ID
2577                 machineSet.remove(machineId);
2578
2579                 // Get the set of rejected messages that this machine Id is has not seen yet
2580                 HashSet<RejectedMessage> watchset = rejectedMessageWatchListTable.get(machineId);
2581
2582                 // If there is a rejected message that this machine Id has not seen yet
2583                 if (watchset != null) {
2584
2585                         // Go through each rejected message that this machine Id has not seen yet
2586                         for (Iterator<RejectedMessage> rmit = watchset.iterator(); rmit.hasNext(); ) {
2587
2588                                 RejectedMessage rm = rmit.next();
2589
2590                                 // If this machine Id has seen this rejected message...
2591                                 if (rm.getSequenceNumber() <= seqNum) {
2592
2593                                         // Remove it from our watchlist
2594                                         rmit.remove();
2595
2596                                         // Decrement machines that need to see this notification
2597                                         rm.removeWatcher(machineId);
2598                                 }
2599                         }
2600                 }
2601
2602                 // Set dead the abort
2603                 for (Iterator<Map.Entry<Pair<Long, Long>, Abort>> i = liveAbortTable.entrySet().iterator(); i.hasNext();) {
2604                         Abort abort = i.next().getValue();
2605
2606                         if ((abort.getTransactionMachineId() == machineId) && (abort.getSequenceNumber() <= seqNum)) {
2607                                 abort.setDead();
2608                                 i.remove();
2609
2610                                 if (abort.getTransactionArbitrator() == localMachineId) {
2611                                         liveAbortsGeneratedByLocal.remove(abort.getArbitratorLocalSequenceNumber());
2612                                 }
2613                         }
2614                 }
2615
2616
2617
2618                 if (machineId == localMachineId) {
2619                         // Our own messages are immediately dead.
2620                         if (liveness instanceof LastMessage) {
2621                                 ((LastMessage)liveness).setDead();
2622                         } else if (liveness instanceof Slot) {
2623                                 ((Slot)liveness).setDead();
2624                         } else {
2625                                 throw new Error("Unrecognized type");
2626                         }
2627                 }
2628
2629                 // Get the old last message for this device
2630                 Pair<Long, Liveness> lastMessageEntry = lastMessageTable.put(machineId, new Pair<Long, Liveness>(seqNum, liveness));
2631                 if (lastMessageEntry == null) {
2632                         // If no last message then there is nothing else to process
2633                         return;
2634                 }
2635
2636                 long lastMessageSeqNum = lastMessageEntry.getFirst();
2637                 Liveness lastEntry = lastMessageEntry.getSecond();
2638
2639                 // If it is not our machine Id since we already set ours to dead
2640                 if (machineId != localMachineId) {
2641                         if (lastEntry instanceof LastMessage) {
2642                                 ((LastMessage)lastEntry).setDead();
2643                         } else if (lastEntry instanceof Slot) {
2644                                 ((Slot)lastEntry).setDead();
2645                         } else {
2646                                 throw new Error("Unrecognized type");
2647                         }
2648                 }
2649
2650                 // Make sure the server is not playing any games
2651                 if (machineId == localMachineId) {
2652
2653                         if (hadPartialSendToServer) {
2654                                 // We were not making any updates and we had a machine mismatch
2655                                 if (lastMessageSeqNum > seqNum && !acceptUpdatesToLocal) {
2656                                         throw new Error("Server Error: Mismatch on local machine sequence number, needed at least: " +  lastMessageSeqNum  + " got: " + seqNum);
2657                                 }
2658
2659                         } else {
2660                                 // We were not making any updates and we had a machine mismatch
2661                                 if (lastMessageSeqNum != seqNum && !acceptUpdatesToLocal) {
2662                                         throw new Error("Server Error: Mismatch on local machine sequence number, needed: " +  lastMessageSeqNum + " got: " + seqNum);
2663                                 }
2664                         }
2665                 } else {
2666                         if (lastMessageSeqNum > seqNum) {
2667                                 throw new Error("Server Error: Rollback on remote machine sequence number");
2668                         }
2669                 }
2670         }
2671
2672         /**
2673          * Add a rejected message entry to the watch set to keep track of which clients have seen that
2674          * rejected message entry and which have not.
2675          */
2676         private void addWatchList(long machineId, RejectedMessage entry) {
2677                 HashSet<RejectedMessage> entries = rejectedMessageWatchListTable.get(machineId);
2678                 if (entries == null) {
2679                         // There is no set for this machine ID yet so create one
2680                         entries = new HashSet<RejectedMessage>();
2681                         rejectedMessageWatchListTable.put(machineId, entries);
2682                 }
2683                 entries.add(entry);
2684         }
2685
2686         /**
2687          * Check if the HMAC chain is not violated
2688          */
2689         private void checkHMACChain(SlotIndexer indexer, Slot[] newSlots) {
2690                 for (int i = 0; i < newSlots.length; i++) {
2691                         Slot currSlot = newSlots[i];
2692                         Slot prevSlot = indexer.getSlot(currSlot.getSequenceNumber() - 1);
2693                         if (prevSlot != null &&
2694                                 !Arrays.equals(prevSlot.getHMAC(), currSlot.getPrevHMAC()))
2695                                 throw new Error("Server Error: Invalid HMAC Chain" + currSlot + " " + prevSlot);
2696                 }
2697         }
2698 }