TOMLayer.java 84.0 KB
Newer Older
1
/**
P
pjsousa@gmail.com 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
 * Copyright (c) 2007-2009 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags
 * 
 * This file is part of SMaRt.
 * 
 * SMaRt is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * SMaRt is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with SMaRt.  If not, see <http://www.gnu.org/licenses/>.
 */

package navigators.smart.tom.core;

21 22 23
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
P
pjsousa@gmail.com 已提交
24 25 26
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
B
bessani@gmail.com 已提交
27
import java.io.Serializable;
P
pjsousa@gmail.com 已提交
28
import java.security.MessageDigest;
B
bessani@gmail.com 已提交
29 30
import java.security.PrivateKey;
import java.security.Signature;
P
pjsousa@gmail.com 已提交
31
import java.security.SignedObject;
32
import java.util.Arrays;
P
pjsousa@gmail.com 已提交
33 34 35 36 37 38 39
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
40 41
import java.util.Timer;
import java.util.TimerTask;
P
pjsousa@gmail.com 已提交
42 43
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
44
import java.util.logging.Level;
45

P
pjsousa@gmail.com 已提交
46
import navigators.smart.clientsmanagement.ClientsManager;
47
import navigators.smart.clientsmanagement.RequestList;
P
pjsousa@gmail.com 已提交
48 49 50
import navigators.smart.communication.ServerCommunicationSystem;
import navigators.smart.communication.client.RequestReceiver;
import navigators.smart.paxosatwar.Consensus;
51
import navigators.smart.paxosatwar.executionmanager.RoundValuePair;
P
pjsousa@gmail.com 已提交
52 53 54 55 56
import navigators.smart.paxosatwar.executionmanager.Execution;
import navigators.smart.paxosatwar.executionmanager.ExecutionManager;
import navigators.smart.paxosatwar.executionmanager.LeaderModule;
import navigators.smart.paxosatwar.executionmanager.Round;
import navigators.smart.paxosatwar.roles.Acceptor;
57
import navigators.smart.reconfiguration.ReconfigurationManager;
58
import navigators.smart.statemanagment.SMMessage;
59
import navigators.smart.statemanagment.StateLog;
60 61
import navigators.smart.statemanagment.StateManager;
import navigators.smart.statemanagment.TransferableState;
P
pjsousa@gmail.com 已提交
62 63 64 65 66 67 68 69 70 71 72 73
import navigators.smart.tom.TOMRequestReceiver;
import navigators.smart.tom.core.messages.TOMMessage;
import navigators.smart.tom.core.timer.RTInfo;
import navigators.smart.tom.core.timer.RequestsTimer;
import navigators.smart.tom.core.timer.messages.ForwardedMessage;
import navigators.smart.tom.core.timer.messages.RTCollect;
import navigators.smart.tom.core.timer.messages.RTLeaderChange;
import navigators.smart.tom.core.timer.messages.RTMessage;
import navigators.smart.tom.util.BatchBuilder;
import navigators.smart.tom.util.BatchReader;
import navigators.smart.tom.util.Logger;
import navigators.smart.tom.util.TOMUtil;
74 75 76 77
import navigators.smart.tom.leaderchange.LCMessage;
import navigators.smart.tom.leaderchange.CollectData;
import navigators.smart.tom.leaderchange.LCManager;
import navigators.smart.tom.leaderchange.LastEidData;
P
pjsousa@gmail.com 已提交
78 79 80 81 82 83 84 85 86 87 88 89 90


/**
 * This class implements a thread that uses the PaW algorithm to provide the application
 * a layer of total ordered messages
 */
public final class TOMLayer extends Thread implements RequestReceiver {

    //other components used by the TOMLayer (they are never changed)
    public ExecutionManager execManager; // Execution manager
    public LeaderModule lm; // Leader module
    public Acceptor acceptor; // Acceptor role of the PaW algorithm
    private ServerCommunicationSystem communication; // Communication system between replicas
91
    //private OutOfContextMessageThread ot; // Thread which manages messages that do not belong to the current execution
P
pjsousa@gmail.com 已提交
92
    private DeliveryThread dt; // Thread which delivers total ordered messages to the appication
93
    
P
pjsousa@gmail.com 已提交
94 95 96 97 98 99 100 101 102 103 104 105
    /** Manage timers for pending requests */
    public RequestsTimer requestsTimer;
    /** Store requests received but still not ordered */
    public ClientsManager clientsManager;
    /** The id of the consensus being executed (or -1 if there is none) */
    private int inExecution = -1;
    private int lastExecuted = -1;
    private Map<Integer, RTInfo> timeoutInfo = new HashMap<Integer, RTInfo>();
    private ReentrantLock lockTI = new ReentrantLock();
    private TOMRequestReceiver receiver;
    //the next two are used to generate message digests
    private MessageDigest md;
B
bessani@gmail.com 已提交
106
    private Signature engine;
P
pjsousa@gmail.com 已提交
107 108

    //the next two are used to generate non-deterministic data in a deterministic way (by the leader)
109
    private BatchBuilder bb = new BatchBuilder();
P
pjsousa@gmail.com 已提交
110 111 112 113 114 115 116 117 118 119
    private long lastTimestamp = 0;

    /* The locks and conditions used to wait upon creating a propose */
    private ReentrantLock leaderLock = new ReentrantLock();
    private Condition iAmLeader = leaderLock.newCondition();
    private ReentrantLock messagesLock = new ReentrantLock();
    private Condition haveMessages = messagesLock.newCondition();
    private ReentrantLock proposeLock = new ReentrantLock();
    private Condition canPropose = proposeLock.newCondition();

120 121 122 123 124
    /*** ISTO E CODIGO DO JOAO, RELACIONADO COM A TROCA DE LIDER */

    private LCManager lcManager;
    /*************************************************************/

P
pjsousa@gmail.com 已提交
125 126 127 128 129 130
    /* flag that indicates that the lader changed between the last propose and
    this propose. This flag is changed on updateLeader (to true) and decided
    (to false) and used in run.*/
    private boolean leaderChanged = true;


B
bessani@gmail.com 已提交
131
    private PrivateKey prk;
132 133 134
    
    private ReconfigurationManager reconfManager;
    
P
pjsousa@gmail.com 已提交
135 136 137 138 139 140 141 142 143 144 145 146 147 148
    /**
     * Creates a new instance of TOMulticastLayer
     * @param manager Execution manager
     * @param receiver Object that receives requests from clients
     * @param lm Leader module
     * @param a Acceptor role of the PaW algorithm
     * @param cs Communication system between replicas
     * @param conf TOM configuration
     */
    public TOMLayer(ExecutionManager manager,
            TOMRequestReceiver receiver,
            LeaderModule lm,
            Acceptor a,
            ServerCommunicationSystem cs,
B
bessani@gmail.com 已提交
149
            ReconfigurationManager recManager) {
P
pjsousa@gmail.com 已提交
150 151 152 153 154 155 156 157

        super("TOM Layer");

        this.execManager = manager;
        this.receiver = receiver;
        this.lm = lm;
        this.acceptor = a;
        this.communication = cs;
158
        this.reconfManager = recManager;
P
pjsousa@gmail.com 已提交
159 160

        //do not create a timer manager if the timeout is 0
B
bessani@gmail.com 已提交
161
        if (reconfManager.getStaticConf().getRequestTimeout() == 0){
P
pjsousa@gmail.com 已提交
162 163
            this.requestsTimer = null;
        }
164
        else this.requestsTimer = new RequestsTimer(this, reconfManager.getStaticConf().getRequestTimeout()); // Create requests timers manager (a thread)
P
pjsousa@gmail.com 已提交
165

166
        this.clientsManager = new ClientsManager(reconfManager, requestsTimer); // Create clients manager
P
pjsousa@gmail.com 已提交
167 168 169 170 171 172

        try {
            this.md = MessageDigest.getInstance("MD5"); // TODO: nao devia ser antes SHA?
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
173

B
bessani@gmail.com 已提交
174 175 176 177 178 179 180
        try {
            this.engine = Signature.getInstance("SHA1withRSA");
        } catch (Exception e) {
            e.printStackTrace();
        }

        this.prk = reconfManager.getStaticConf().getRSAPrivateKey();
P
pjsousa@gmail.com 已提交
181

B
bessani@gmail.com 已提交
182 183 184
        /*** ISTO E CODIGO DO JOAO, RELACIONADO COM A TROCA DE LIDER */
        this.lcManager = new LCManager(this,recManager, md);
        /*************************************************************/
P
pjsousa@gmail.com 已提交
185

186
        this.dt = new DeliveryThread(this, receiver, this.reconfManager); // Create delivery thread
P
pjsousa@gmail.com 已提交
187
        this.dt.start();
188

189
        /** ISTO E CODIGO DO JOAO, PARA TRATAR DOS CHECKPOINTS E TRANSFERENCIA DE ESTADO*/
B
bessani@gmail.com 已提交
190
        this.stateManager = new StateManager(this.reconfManager);
191
        /*******************************************************/
P
pjsousa@gmail.com 已提交
192 193
    }

194
    ReentrantLock hashLock = new ReentrantLock();
B
bessani@gmail.com 已提交
195

P
pjsousa@gmail.com 已提交
196 197 198 199 200 201
    /**
     * Computes an hash for a TOM message
     * @param message
     * @return Hash for teh specified TOM message
     */
    public final byte[] computeHash(byte[] data) {
202 203
        byte[] ret = null;
        hashLock.lock();
B
bessani@gmail.com 已提交
204
        ret = md.digest(data);
205 206 207
        hashLock.unlock();

        return ret;
B
bessani@gmail.com 已提交
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
    }

    public SignedObject sign(Serializable obj) {
        try {
            return new SignedObject(obj, prk, engine);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Verifies the signature of a signed object
     * @param so Signed object to be verified
     * @param sender Replica id that supposably signed this object
     * @return True if the signature is valid, false otherwise
     */
    public boolean verifySignature(SignedObject so, int sender) {
        try {
            return so.verify(reconfManager.getStaticConf().getRSAPublicKey(sender), engine);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
P
pjsousa@gmail.com 已提交
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
    }

    /**
     * Retrieve Communication system between replicas
     * @return Communication system between replicas
     */
    public ServerCommunicationSystem getCommunication() {
        return this.communication;
    }

    public void imAmTheLeader() {
        leaderLock.lock();
        iAmLeader.signal();
        leaderLock.unlock();
    }

    /**
     * Sets which consensus was the last to be executed
     * @param last ID of the consensus which was last to be executed
     */
B
bessani@gmail.com 已提交
252
    public void setLastExec(int last) {
P
pjsousa@gmail.com 已提交
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
        this.lastExecuted = last;
    }

    /**
     * Gets the ID of the consensus which was established as the last executed
     * @return ID of the consensus which was established as the last executed
     */
    public int getLastExec() {
        return this.lastExecuted;
    }

    /**
     * Sets which consensus is being executed at the moment
     *
     * @param inEx ID of the consensus being executed at the moment
     */
    public void setInExec(int inEx) {
        Logger.println("(TOMLayer.setInExec) modifying inExec from " + this.inExecution + " to " + inEx);

        proposeLock.lock();
        this.inExecution = inEx;
274 275 276 277 278
        if (inEx == -1
        /** ISTO E CODIGO DO JOAO, PARA TRATAR DA TRANSFERENCIA DE ESTADO */
            && !isRetrievingState()
        /******************************************************************/
        ) {
P
pjsousa@gmail.com 已提交
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
            canPropose.signalAll();
        }
        proposeLock.unlock();
    }

    /**
     * This method blocks until the PaW algorithm is finished
     */
    public void waitForPaxosToFinish() {
        proposeLock.lock();
        canPropose.awaitUninterruptibly();
        proposeLock.unlock();
    }

    /**
     * Gets the ID of the consensus currently beign executed
     *
     * @return ID of the consensus currently beign executed (if no consensus ir executing, -1 is returned)
     */
    public int getInExec() {
        return this.inExecution;
    }

    /**
     * This method is invoked by the comunication system to deliver a request.
     * It assumes that the communication system delivers the message in FIFO
     * order.
     *
     * @param msg The request being received
     */
B
bessani@gmail.com 已提交
309
    @Override
P
pjsousa@gmail.com 已提交
310 311 312 313 314 315 316 317 318
    public void requestReceived(TOMMessage msg) {
        /**********************************************************/
        /********************MALICIOUS CODE************************/
        /**********************************************************/
        //first server always ignores messages from the first client (with n=4)
        /*
        if (conf.getProcessId() == 0 && msg.getSender() == 4) {
        return;
        }
B
bessani@gmail.com 已提交
319
      */
P
pjsousa@gmail.com 已提交
320 321 322
        /**********************************************************/
        /**********************************************************/
        /**********************************************************/
B
bessani@gmail.com 已提交
323

324
        // check if this request is valid and add it to the client' pending requests list
B
bessani@gmail.com 已提交
325 326 327
        boolean readOnly = msg.getReqType() == ReconfigurationManager.TOM_READONLY_REQUEST;
        if (clientsManager.requestReceived(msg, true, !readOnly, communication)) {
            if (readOnly) {
P
pjsousa@gmail.com 已提交
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
                receiver.receiveMessage(msg);
            } else {
                messagesLock.lock();
                haveMessages.signal();
                messagesLock.unlock();
            }
        } else {
            Logger.println("(TOMLayer.requestReceive) the received TOMMessage " + msg + " was discarded.");
        }

    }

    /**
     * Creates a value to be proposed to the acceptors. Invoked if this replica is the leader
     * @return A value to be proposed to the acceptors
     */
    private byte[] createPropose(Consensus cons) {
        // Retrieve a set of pending requests from the clients manager
346
        RequestList pendingRequests = clientsManager.getPendingRequests();
P
pjsousa@gmail.com 已提交
347 348

        int numberOfMessages = pendingRequests.size(); // number of messages retrieved
349 350 351
        //******* EDUARDO BEGIN **************//
        int numberOfNonces = this.reconfManager.getStaticConf().getNumberOfNonces(); // ammount of nonces to be generated
        //******* EDUARDO END **************//
B
bessani@gmail.com 已提交
352 353 354 355

        //for benchmarking
        cons.firstMessageProposed = pendingRequests.getFirst();
        cons.firstMessageProposed.consensusStartTime = System.nanoTime();
P
pjsousa@gmail.com 已提交
356
        cons.batchSize = numberOfMessages;
B
bessani@gmail.com 已提交
357

P
pjsousa@gmail.com 已提交
358 359 360 361 362 363 364
        /*
        // These instructions are used only for benchmarking
        stConsensusBatch.store(numberOfMessages);
        if (stConsensusBatch.getCount() % BENCHMARK_PERIOD == 0) {
            System.out.println("#Media de batch dos ultimos " + BENCHMARK_PERIOD + " consensos: " + stConsensusBatch.getAverage(true));
            stConsensusBatch.reset();
        }
B
bessani@gmail.com 已提交
365
      */
P
pjsousa@gmail.com 已提交
366 367 368
        Logger.println("(TOMLayer.run) creating a PROPOSE with " + numberOfMessages + " msgs");

        int totalMessageSize = 0; //total size of the messages being batched
B
bessani@gmail.com 已提交
369

P
pjsousa@gmail.com 已提交
370 371 372 373 374 375 376 377 378 379 380 381 382 383
        byte[][] messages = new byte[numberOfMessages][]; //bytes of the message (or its hash)
        byte[][] signatures = new byte[numberOfMessages][]; //bytes of the message (or its hash)

        // Fill the array of bytes for the messages/signatures being batched
        int i = 0;
        for (Iterator<TOMMessage> li = pendingRequests.iterator(); li.hasNext(); i++) {
            TOMMessage msg = li.next();
            //Logger.println("(TOMLayer.run) adding req " + msg + " to PROPOSE");
            messages[i] = msg.serializedMessage;
            signatures[i] = msg.serializedMessageSignature;

            totalMessageSize += messages[i].length;
        }

384
        // return the batch
385 386
        return bb.createBatch(System.currentTimeMillis(), numberOfNonces, numberOfMessages, totalMessageSize, 
                this.reconfManager.getStaticConf().getUseSignatures() == 1, messages, signatures,this.reconfManager);
387
    }
P
pjsousa@gmail.com 已提交
388 389 390 391 392 393 394 395 396 397 398 399 400



    /**
     * This is the main code for this thread. It basically waits until this replica becomes the leader,
     * and when so, proposes a value to the other acceptors
     */
    @Override
    public void run() {
        /*
        Storage st = new Storage(BENCHMARK_PERIOD/2);
        long start=-1;
        int counter =0;
B
bessani@gmail.com 已提交
401
      */
402 403 404 405
        /**********ISTO E CODIGO MARTELADO, PARA FAZER AVALIACOES **************/
        long initialTime = -1;
        long currentTime = -1;
        /***********************************************************************/
P
pjsousa@gmail.com 已提交
406
        while (true) {
407 408
            /**********ISTO E CODIGO MARTELADO, PARA FAZER AVALIACOES **************/
            //System.out.println(currentTime);
B
bessani@gmail.com 已提交
409
            if (initialTime > -1) currentTime = System.nanoTime() - initialTime;
410
            /***********************************************************************/
P
pjsousa@gmail.com 已提交
411 412 413 414
            Logger.println("(TOMLayer.run) Running."); // TODO: isto n podia passar para fora do ciclo?

            // blocks until this replica learns to be the leader for the current round of the current consensus
            leaderLock.lock();
415
            Logger.println("(TOMLayer.run) Next leader for eid=" + (getLastExec() + 1) + ": " + lm.getCurrentLeader());
416 417
            
            //******* EDUARDO BEGIN **************//
418
            if (/*lm.getLeader(getLastExec() + 1, 0)*/ lm.getCurrentLeader() != this.reconfManager.getStaticConf().getProcessId()) {
P
pjsousa@gmail.com 已提交
419
                iAmLeader.awaitUninterruptibly();
420
                waitForPaxosToFinish();
P
pjsousa@gmail.com 已提交
421
            }
422 423
            //******* EDUARDO END **************//
            
P
pjsousa@gmail.com 已提交
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
            leaderLock.unlock();
            Logger.println("(TOMLayer.run) I'm the leader.");

            // blocks until there are requests to be processed/ordered
            messagesLock.lock();
            if (!clientsManager.havePendingRequests()) {
                haveMessages.awaitUninterruptibly();
            }
            messagesLock.unlock();
            Logger.println("(TOMLayer.run) There are messages to be ordered.");

            // blocks until the current consensus finishes
            proposeLock.lock();
            if (getInExec() != -1 && !leaderChanged) { //there is some consensus running and the leader not changed
                Logger.println("(TOMLayer.run) Waiting that consensus " + getInExec() + " terminates.");
                canPropose.awaitUninterruptibly();
            }
            proposeLock.unlock();

            Logger.println("(TOMLayer.run) I can try to propose.");
444
                //******* EDUARDO BEGIN **************//
445
            if ((lm.getCurrentLeader() == this.reconfManager.getStaticConf().getProcessId()) && //I'm the leader
446
                    //******* EDUARDO END **************//
P
pjsousa@gmail.com 已提交
447 448 449 450 451
                    (clientsManager.havePendingRequests()) && //there are messages to be ordered
                    (getInExec() == -1 || leaderChanged)) { //there is no consensus in execution

                leaderChanged = false;

452
                /**********ISTO E CODIGO MARTELADO, PARA FAZER AVALIACOES **************/
453
                boolean temp = false;
454
                if (initialTime == -1) {
B
bessani@gmail.com 已提交
455
                    initialTime = System.nanoTime();
456 457
                    currentTime = 0;
                }
458 459 460 461
                else if ((this.reconfManager.getStaticConf().getProcessId() == 0) /*&& (currentTime >= 5000)*/) {
                        //System.exit(0);
                        //temp = true;
                        //if ((getLastExec() + 1) >= 200) temp = true;
B
bessani@gmail.com 已提交
462
                        //System.out.println("Isto ta assim: " + (getLastExec() + 1));
463
                }
464 465
                /***********************************************************************/

P
pjsousa@gmail.com 已提交
466 467 468 469 470 471 472 473
                // Sets the current execution
                int execId = getLastExec() + 1;
                setInExec(execId);

                //Logger.println("(TOMLayer.run) Waiting for acceptor semaphore to be released.");
                Execution exec = execManager.getExecution(execId);
                //Logger.println("(TOMLayer.run) Acceptor semaphore acquired");

474
                execManager.getProposer().startExecution(execId,createPropose(exec.getLearner()));
475
                if (temp) System.exit(0);
P
pjsousa@gmail.com 已提交
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
            }
        }
    }

    /**
     * Called by the current consensus's execution, to notify the TOM layer that a value was decided
     * @param cons The decided consensus
     */
    public void decided(Consensus cons) {
        this.dt.delivery(cons); // Delivers the consensus to the delivery thread
    }

    /**
     * Verify if the value being proposed for a round is valid. It verifies the
     * client signature of all batch requests.
     *
     * TODO: verify timestamps and nonces
     *
     * @param round the Round for which this value is being proposed
     * @param proposedValue the value being proposed
     * @return
     */
498
    public TOMMessage[] checkProposedValue(byte[] proposedValue) {
P
pjsousa@gmail.com 已提交
499
        Logger.println("(TOMLayer.isProposedValueValid) starting");
500

501 502
        BatchReader batchReader = new BatchReader(proposedValue, 
                this.reconfManager.getStaticConf().getUseSignatures() == 1);
P
pjsousa@gmail.com 已提交
503

504
        TOMMessage[] requests = null;
P
pjsousa@gmail.com 已提交
505

506 507 508
        try {
            //deserialize the message
            //TODO: verify Timestamps and Nonces
509
            requests = batchReader.deserialiseRequests(this.reconfManager);
P
pjsousa@gmail.com 已提交
510

511
            for (int i = 0; i < requests.length; i++) {
B
bessani@gmail.com 已提交
512 513 514 515 516 517
                //notifies the client manager that this request was received and get
                //the result of its validation
                if (!clientsManager.requestReceived(requests[i], false)) {
                    clientsManager.getClientsLock().unlock();
                    Logger.println("(TOMLayer.isProposedValueValid) finished, return=false");
                    System.out.println("failure in deserialize batch");
518 519 520 521 522 523
                    return null;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            clientsManager.getClientsLock().unlock();
B
bessani@gmail.com 已提交
524
            Logger.println("(TOMLayer.isProposedValueValid) finished, return=false");
525
            return null;
P
pjsousa@gmail.com 已提交
526 527
        }
        //clientsManager.getClientsLock().unlock();
528 529
        if (Logger.debug) {
            Logger.println("(TOMLayer.isProposedValueValid) finished, return=true");
P
pjsousa@gmail.com 已提交
530
        }
531
//        round.deserializedPropValue = requests;
P
pjsousa@gmail.com 已提交
532

533
        return requests;
P
pjsousa@gmail.com 已提交
534
    }
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
//    /**
//     * TODO: este metodo nao e usado. Pode desaparecer?
//     * @param br
//     * @return
//     */
//    public final boolean verifyTimestampAndNonces(BatchReader br) {
//        long timestamp = br.getTimestamp();
//
//        if (conf.canVerifyTimestamps()) {
//            //br.ufsc.das.util.tom.Logger.println("(TOMLayer.verifyTimestampAndNonces) verifying timestamp "+timestamp+">"+lastTimestamp+"?");
//            if (timestamp > lastTimestamp) {
//                lastTimestamp = timestamp;
//            } else {
//                System.err.println("########################################################");
//                System.err.println("- timestamp received " + timestamp + " <= " + lastTimestamp);
//                System.err.println("- maybe the proposer have a non-synchronized clock");
//                System.err.println("########################################################");
//                return false;
//            }
//        }
//
//        return br.getNumberOfNonces() == conf.getNumberOfNonces();
//    }
P
pjsousa@gmail.com 已提交
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572

    /**
     * Invoked when a timeout for a TOM message is triggered.
     *
     * @param reqId Request ID of the message to which the timeout is related to
     * @return True if the request is still pending and the timeout was not triggered before, false otherwise
     */
    public boolean requestTimeout(List<TOMMessage> requestList) {
        List<byte[][]> serializedRequestList = new LinkedList<byte[][]>();

        //verify if the request is still pending
        for (Iterator<TOMMessage> i = requestList.listIterator(); i.hasNext();) {
            TOMMessage request = i.next();
            if (clientsManager.isPending(request.getId())) {
                RTInfo rti = getTimeoutInfo(request.getId());
573
                if (!rti.isTimeout(this.reconfManager.getStaticConf().getProcessId())) {
P
pjsousa@gmail.com 已提交
574 575
                    serializedRequestList.add(
                            new byte[][]{request.serializedMessage, request.serializedMessageSignature});
576
                    timeout(this.reconfManager.getStaticConf().getProcessId(), request, rti);
P
pjsousa@gmail.com 已提交
577 578 579 580 581 582 583 584 585 586 587 588 589 590
                    Logger.println("(TOMLayer.requestTimeout) Must send timeout for reqId=" + request.getId());
                }
            }
        }

        if (!requestList.isEmpty()) {
            sendTimeoutMessage(serializedRequestList);
            return true;
        } else {
            return false;
        }
    }

    public void forwardRequestToLeader(TOMMessage request) {
591
        int leaderId = lm.getCurrentLeader();
B
bessani@gmail.com 已提交
592
        System.out.println("(TOMLayer.forwardRequestToLeader) forwarding " + request + " to " + leaderId);
593 594 595 596 597
        
            //******* EDUARDO BEGIN **************//
        communication.send(new int[]{leaderId}, 
                new ForwardedMessage(this.reconfManager.getStaticConf().getProcessId(), request));
            //******* EDUARDO END **************//
P
pjsousa@gmail.com 已提交
598 599 600 601 602 603 604 605
    }

    /**
     * Sends a RT-TIMEOUT message to other processes.
     *
     * @param request the message that caused the timeout
     */
    public void sendTimeoutMessage(List<byte[][]> serializedRequestList) {
606
        System.out.println("Estou a ser invocado!!");
607 608
        //******* EDUARDO BEGIN **************//
        communication.send(this.reconfManager.getCurrentViewOtherAcceptors(),
609
                new RTMessage(TOMUtil.STOP, -1, this.reconfManager.getStaticConf().getProcessId(), serializedRequestList));
610
       //******* EDUARDO END **************//
P
pjsousa@gmail.com 已提交
611 612 613 614 615 616 617 618 619
    }

    /**
     * Sends a RT-COLLECT message to other processes
     * TODO: Se se o novo leader for este processo, nao e enviada nenhuma mensagem. Isto estara bem feito?
     * @param reqId ID of the message which triggered the timeout
     * @param collect Proof for the timeout
     */
    public void sendCollectMessage(int reqId, RTCollect collect) {
620
            //******* EDUARDO BEGIN **************//
621
        RTMessage rtm = new RTMessage(TOMUtil.SYNC, reqId,
B
bessani@gmail.com 已提交
622
                this.reconfManager.getStaticConf().getProcessId(), sign(collect));
P
pjsousa@gmail.com 已提交
623

624
        if (collect.getNewLeader() == this.reconfManager.getStaticConf().getProcessId()) {
P
pjsousa@gmail.com 已提交
625
            RTInfo rti = getTimeoutInfo(reqId);
626 627
            collect((SignedObject) rtm.getContent(), this.reconfManager.getStaticConf().getProcessId(), rti);
            //******* EDUARDO END **************//
P
pjsousa@gmail.com 已提交
628 629 630 631 632
        } else {
            int[] target = {collect.getNewLeader()};
            this.communication.send(target, rtm);
        }

633
        
P
pjsousa@gmail.com 已提交
634 635 636 637 638 639 640 641 642 643
    }

    /**
     * Sends a RT-LEADER message to other processes. It also updates the leader
     *
     * @param reqId ID of the message which triggered the timeout
     * @param timeout Timeout number
     * @param rtLC Proofs for the leader change
     */
    public void sendNewLeaderMessage(int reqId, RTLeaderChange rtLC) {
644 645
        
         //******* EDUARDO BEGIN **************//
646
        RTMessage rtm = new RTMessage(TOMUtil.CATCH_UP, reqId, this.reconfManager.getStaticConf().getProcessId(), rtLC);
P
pjsousa@gmail.com 已提交
647 648 649
        //br.ufsc.das.util.Logger.println("Atualizando leader para "+rtLC.newLeader+" a partir de "+rtLC.start);
        updateLeader(reqId, rtLC.start, rtLC.newLeader);

650 651
        communication.send(this.reconfManager.getCurrentViewOtherAcceptors(), rtm);
        //******* EDUARDO END **************//
P
pjsousa@gmail.com 已提交
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
    }

    /**
     * Updates the leader of the PaW algorithm. This is triggered upon a timeout
     * for a pending message.
     *
     * @param reqId ID of the message which triggered the timeout
     * @param start Consensus where the new leader belongs
     * @param newLeader Replica ID of the new leader
     * @param timeout Timeout number
     */
    private void updateLeader(int reqId, int start, int newLeader) {
        lm.addLeaderInfo(start, 0, newLeader); // update the leader
        leaderChanged = true;

        leaderLock.lock(); // Signal the TOMlayer thread, if this replica is the leader
668 669
        //******* EDUARDO BEGIN **************//
        if (lm.getLeader(getLastExec() + 1, 0) == this.reconfManager.getStaticConf().getProcessId()) {
P
pjsousa@gmail.com 已提交
670 671
            iAmLeader.signal();
        }
672
        //******* EDUARDO END **************//
P
pjsousa@gmail.com 已提交
673 674 675 676 677 678 679 680 681 682 683 684 685 686
        leaderLock.unlock();

        removeTimeoutInfo(reqId); // remove timeout infos
        //requestsTimer.startTimer(clientsManager.getPending(reqId)); // restarts the timer
        execManager.restart(); // restarts the execution manager
    }

    /**
     * This method is invoked when the comunication system needs to deliver a message related to timeouts
     * for a pending TOM message
     * @param msg The timeout related message being delivered
     */
    public void deliverTimeoutRequest(RTMessage msg) {
        switch (msg.getRTType()) {
687
            case TOMUtil.STOP:
P
pjsousa@gmail.com 已提交
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
                 {
                    Logger.println("(TOMLayer.deliverTimeoutRequest) receiving timeout message from " + msg.getSender());
                    List<byte[][]> serializedRequestList = (List<byte[][]>) msg.getContent();

                    for (Iterator<byte[][]> i = serializedRequestList.iterator(); i.hasNext();) {
                        byte[][] serializedRequest = i.next();

                        if (serializedRequest == null || serializedRequest.length != 2) {
                            return;
                        }

                        TOMMessage request;

                        //deserialize the message
                        try {
                            DataInputStream ois = new DataInputStream(
                                    new ByteArrayInputStream(serializedRequest[0]));
                            request = new TOMMessage();
706
                            request.rExternal(ois);
P
pjsousa@gmail.com 已提交
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
                        } catch (Exception e) {
                            e.printStackTrace();
                            clientsManager.getClientsLock().unlock();
                            Logger.println("(TOMLayer.deliverTimeoutRequest) invalid request.");
                            return;
                        }

                        request.serializedMessage = serializedRequest[0];
                        request.serializedMessageSignature = serializedRequest[1];

                        if (clientsManager.requestReceived(request, false)) { //Is this a pending message?
                            RTInfo rti = getTimeoutInfo(request.getId());
                            timeout(msg.getSender(), request, rti);
                        }
                    }
                }
                break;
724
            case TOMUtil.SYNC:
P
pjsousa@gmail.com 已提交
725 726 727
                 {
                    Logger.println("(TOMLayer.deliverTimeoutRequest) receiving collect for message " + msg.getReqId() + " from " + msg.getSender());
                    SignedObject so = (SignedObject) msg.getContent();
B
bessani@gmail.com 已提交
728
                    if (verifySignature(so, msg.getSender())) { // valid signature?
P
pjsousa@gmail.com 已提交
729 730 731 732 733 734
                        try {
                            RTCollect rtc = (RTCollect) so.getObject();
                            int reqId = rtc.getReqId();

                            int nl = chooseNewLeader();

735 736 737
                            //******* EDUARDO BEGIN **************//
                            if (nl == this.reconfManager.getStaticConf().getProcessId() && nl == rtc.getNewLeader()) { // If this is process the new leader?
                            //******* EDUARDO END **************//
P
pjsousa@gmail.com 已提交
738 739 740 741 742 743 744 745 746 747 748
                                RTInfo rti = getTimeoutInfo(reqId);
                                collect(so, msg.getSender(), rti);
                            }
                        } catch (ClassNotFoundException cnfe) {
                            cnfe.printStackTrace(System.err);
                        } catch (IOException ioe) {
                            ioe.printStackTrace(System.err);
                        }
                    }
                }
                break;
749
            case TOMUtil.CATCH_UP:
P
pjsousa@gmail.com 已提交
750 751 752 753 754
                 {
                    Logger.println("1 recebendo newLeader de " + msg.getSender());
                    RTLeaderChange rtLC = (RTLeaderChange) msg.getContent();
                    RTCollect[] rtc = getValid(msg.getReqId(), rtLC.proof);

755
                    if (rtLC.isAGoodStartLeader(rtc, this.reconfManager.getCurrentViewF())) { // Is it a legitm and valid leader?
P
pjsousa@gmail.com 已提交
756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
                        Logger.println("Atualizando leader para " + rtLC.newLeader + " a partir de " + rtLC.start);
                        updateLeader(msg.getReqId(), rtLC.start, rtLC.newLeader);
                    //FALTA... eliminar dados referentes a consensos maiores q start.
                    }
                }
                break;
        }
    }

    /**
     * Retrieves the timeout information for a given timeout. If the timeout
     * info does not exist, we create one.
     *
     * @param reqId ID of the message which triggered the timeout
     * @return The timeout information
     */
    public RTInfo getTimeoutInfo(int reqId) {
        lockTI.lock();
        RTInfo ti = timeoutInfo.get(reqId);
        if (ti == null) {
776
            ti = new RTInfo(this.reconfManager, reqId, this);
P
pjsousa@gmail.com 已提交
777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806
            timeoutInfo.put(reqId, ti);
        }
        lockTI.unlock();
        return ti;
    }

    /**
     * Removes the timeout information for a given timeout.
     *
     * @param reqId ID of the message which triggered the timeout
     * @return The timeout information
     */
    private void removeTimeoutInfo(int reqId) {
        lockTI.lock();
        timeoutInfo.remove(reqId);
        lockTI.unlock();
    }

    /**
     * Invoked by the TOM layer to notify that a  timeout ocurred in a replica, and to
     * compute the necessary tasks
     * @param a Replica ID where this timeout occurred
     * @param request the request that provoked the timeout
     * @param rti the timeout info for this request
     */
    public void timeout(int acceptor, TOMMessage request, RTInfo rti) {
        rti.setTimeout(acceptor);

        int reqId = rti.getRequestId();

807 808 809 810 811 812
        //******* EDUARDO BEGIN **************//
        if (rti.countTimeouts() > reconfManager.getQuorumF() && 
                !rti.isTimeout(reconfManager.getStaticConf().getProcessId())) {
            rti.setTimeout(reconfManager.getStaticConf().getProcessId());
        //******* EDUARDO END **************//
            
P
pjsousa@gmail.com 已提交
813 814 815 816 817 818 819 820 821 822 823 824
            List<byte[][]> serializedRequestList = new LinkedList<byte[][]>();
            serializedRequestList.add(
                    new byte[][]{request.serializedMessage, request.serializedMessageSignature});

            sendTimeoutMessage(serializedRequestList);
        /*
        if (requestsTimer != null) {
        requestsTimer.startTimer(clientsManager.getPending(reqId));
        }
         */
        }

825 826 827
        //******* EDUARDO BEGIN **************//
        if (rti.countTimeouts() > reconfManager.getQuorumStrong() && !rti.isCollected()) {
        //******* EDUARDO END **************//
P
pjsousa@gmail.com 已提交
828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
            rti.setCollected();
            /*
            requestsTimer.stopTimer(clientsManager.getPending(reqId));
             */
            execManager.stop();

            int newLeader = chooseNewLeader();

            int last = -1;
            if (getInExec() != -1) {
                last = getInExec();
            } else {
                last = getLastExec();
            }

            Logger.println("(TOMLayer.timeout) sending COLLECT to " + newLeader +
                    " for " + reqId + " with last execution = " + last);
            sendCollectMessage(reqId, new RTCollect(newLeader, last, reqId));
        }
    }

    /**
     * Invoked by the TOM layer when a collect message is received, and to
     * compute the necessary tasks
     * @param c Proof from the replica that sent the message
     * @param a ID of the replica which sent the message
     */
    public void collect(SignedObject c, int a, RTInfo rti) {
        Logger.println("COLLECT 1");
        rti.setCollect(a, c);

859 860 861
        //******* EDUARDO BEGIN **************//
        if (rti.countCollect() > 2 * reconfManager.getCurrentViewF() && !rti.isNewLeaderSent()) {
        //******* EDUARDO END **************//
P
pjsousa@gmail.com 已提交
862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878
            rti.setNewLeaderSent();
            Logger.println("COLLECT 2");

            SignedObject collect[] = rti.getCollect();

            RTCollect[] rtc = new RTCollect[collect.length];
            for (int i = 0; i < collect.length; i++) {
                if (collect[i] != null) {
                    try {
                        rtc[i] = (RTCollect) collect[i].getObject();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            Logger.println("COLLECT 3");
879
            //******* EDUARDO BEGIN **************//
P
pjsousa@gmail.com 已提交
880
            RTInfo.NextLeaderAndConsensusInfo nextLeaderCons =
881 882
                    rti.getStartLeader(rtc, reconfManager.getCurrentViewF());
            //******* EDUARDO END **************//
P
pjsousa@gmail.com 已提交
883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
            RTLeaderChange rtLC = new RTLeaderChange(collect, nextLeaderCons.leader,
                    nextLeaderCons.cons);

            sendNewLeaderMessage(rti.getRequestId(), rtLC);
        }
    }

    private int chooseNewLeader() {
        int lastRoundNumber = 0; //the number of the last round successfully executed

        Execution lastExec = execManager.getExecution(getLastExec());
        if (lastExec != null) {
            Round lastRound = lastExec.getDecisionRound();
            if (lastRound != null) {
                lastRoundNumber = lastRound.getNumber();
            }
        }

901 902 903 904 905 906 907 908
        
        //******* EDUARDO BEGIN **************//
        int pos = reconfManager.getCurrentViewPos(lm.getLeader(getLastExec(), lastRoundNumber));
        
        return this.reconfManager.getCurrentViewProcesses()[(pos + 1) % reconfManager.getCurrentViewN()];
        
        //return (lm.getLeader(getLastExec(), lastRoundNumber) + 1) % reconfManager.getCurrentViewN();
        //******* EDUARDO END **************//
P
pjsousa@gmail.com 已提交
909 910 911 912 913 914 915 916 917 918 919 920 921 922
    }

    /**
     * Gets an array of valid RTCollect proofs
     *
     * @param reqId ID of the message which triggered the timeout
     * @param timeout Timeout number
     * @param proof Array of signed objects containing the proofs to be verified
     * @return The sub-set of proofs that are valid
     */
    private RTCollect[] getValid(int reqId, SignedObject[] proof) {
        Collection<RTCollect> valid = new HashSet<RTCollect>();
        try {
            for (int i = 0; i < proof.length; i++) {
B
bessani@gmail.com 已提交
923
                if (proof[i] != null && verifySignature(proof[i], i)) { // is the signature valid?
P
pjsousa@gmail.com 已提交
924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939
                    RTCollect rtc = (RTCollect) proof[i].getObject();
                    // Does this proof refers to the specified message id and timeout?
                    if (rtc != null && rtc.getReqId() == reqId) {
                        valid.add(rtc);
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }

        return valid.toArray(new RTCollect[0]); // return the valid proofs ans an array
    }

    /** ISTO E CODIGO DO JOAO, PARA TRATAR DOS CHECKPOINTS */
940
    private StateManager stateManager = null;
941
    private ReentrantLock lockState = new ReentrantLock();
942 943
    private ReentrantLock lockTimer = new ReentrantLock();
    private Timer stateTimer = null;
944

945
    public void saveState(byte[] state, int lastEid, int decisionRound, int leader) {
946 947 948 949 950

        StateLog log = stateManager.getLog();

        lockState.lock();

951 952
        Logger.println("(TOMLayer.saveState) Saving state of EID " + lastEid + ", round " + decisionRound + " and leader " + leader);

953
        log.newCheckpoint(state, computeHash(state));
954 955
        log.setLastEid(-1);
        log.setLastCheckpointEid(lastEid);
956 957
        log.setLastCheckpointRound(decisionRound);
        log.setLastCheckpointLeader(leader);
958

959
        /************************* TESTE *************************
960
        System.out.println("[TOMLayer.saveState]");
961 962 963
        int value = 0;
        for (int i = 0; i < 4; i++) {
            int shift = (4 - 1 - i) * 8;
964
            value += (log.getState()[i] & 0x000000FF) << shift;
965
        }
966
        System.out.println("//////////////////CHECKPOINT//////////////////////");
967
        System.out.println("Estado: " + value);
968 969
        System.out.println("Checkpoint: " + log.getLastCheckpointEid());
        System.out.println("Ultimo EID: " + log.getLastEid());
970
        System.out.println("//////////////////////////////////////////////////");
971
        System.out.println("[/TOMLayer.saveState]");
972
        /************************* TESTE *************************/
973 974
        
        lockState.unlock();
975 976

        Logger.println("(TOMLayer.saveState) Finished saving state of EID " + lastEid + ", round " + decisionRound + " and leader " + leader);
P
pjsousa@gmail.com 已提交
977
    }
978
    public void saveBatch(byte[] batch, int lastEid, int decisionRound, int leader) {
979 980 981 982

        StateLog log = stateManager.getLog();

        lockState.lock();
983 984 985

        Logger.println("(TOMLayer.saveBatch) Saving batch of EID " + lastEid + ", round " + decisionRound + " and leader " + leader);

986
        log.addMessageBatch(batch, decisionRound, leader);
987
        log.setLastEid(lastEid);
988 989

        /************************* TESTE *************************
990
        System.out.println("[TOMLayer.saveBatch]");
991
        byte[][] batches = log.getMessageBatches();
992 993 994 995 996 997 998
        int count = 0;
        for (int i = 0; i < batches.length; i++)
            if (batches[i] != null) count++;

        System.out.println("//////////////////////BATCH///////////////////////");
        //System.out.println("Total batches (according to StateManager): " + stateManager.getLog().getNumBatches());
        System.out.println("Total batches (actually counted by this code): " + count);
999
        System.out.println("Ultimo EID: " + log.getLastEid());
1000 1001
        //System.out.println("Espaco restante para armazenar batches: " + (stateManager.getLog().getMessageBatches().length - count));
        System.out.println("//////////////////////////////////////////////////");
1002
        System.out.println("[/TOMLayer.saveBatch]");
1003 1004
        /************************* TESTE *************************/

1005
        lockState.unlock();
1006 1007

        Logger.println("(TOMLayer.saveBatch) Finished saving batch of EID " + lastEid + ", round " + decisionRound + " and leader " + leader);
1008 1009 1010 1011 1012
    }

    /** ISTO E CODIGO DO JOAO, PARA TRATAR DA TRANSFERENCIA DE ESTADO */
    
    public void requestState(int me, int[] otherAcceptors, int sender, int eid) {
1013

1014
        /************************* TESTE *************************
1015
        System.out.println("[TOMLayer.requestState]");
1016 1017
        System.out.println("Mensagem adiantada! (eid " + eid + " vindo de " + sender + ") ");
        /************************* TESTE *************************/
1018 1019 1020
        //******* EDUARDO BEGIN **************//
        if (reconfManager.getStaticConf().isStateTransferEnabled()) {
        //******* EDUARDO END **************//
1021

1022
            Logger.println("(TOMLayer.requestState) The state transfer protocol is enabled");
1023

1024
            if (stateManager.getWaiting() == -1) {
1025

1026 1027
                Logger.println("(TOMLayer.requestState) I'm not waiting for any state, so I will keep record of this message");
                stateManager.addEID(sender, eid);
1028

1029
                /************************* TESTE *************************
1030 1031
                System.out.println("Nao estou a espera");
                System.out.println("Numero de mensagens recebidas para este EID de replicas diferentes: " + stateManager.moreThenF_EIDs(eid));
1032
                /************************* TESTE *************************/
1033

1034 1035
                if (stateManager.getLastEID() < eid && stateManager.moreThenF_EIDs(eid)) {

1036
                    Logger.println("(TOMLayer.requestState) I have now more than " + reconfManager.getCurrentViewF() + " messages for EID " + eid + " which are beyond EID " + stateManager.getLastEID());
1037 1038 1039
                    /************************* TESTE *************************
                    System.out.println("Recebi mais de " + conf.getF() + " mensagens para eid " + eid + " que sao posteriores a " + stateManager.getLastEID());
                    /************************* TESTE *************************/
1040

1041
                    requestsTimer.clearAll();
1042 1043 1044
                    stateManager.setLastEID(eid);
                    stateManager.setWaiting(eid - 1);
                    //stateManager.emptyReplicas(eid);// isto causa uma excepcao
1045

1046 1047
                    SMMessage smsg = new SMMessage(me, eid - 1, TOMUtil.SM_REQUEST, stateManager.getReplica(), null);
                    communication.send(otherAcceptors, smsg);
1048

1049
                    Logger.println("(TOMLayer.requestState) I just sent a request to the other replicas for the state up to EID " + (eid - 1));
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069

                    TimerTask stateTask =  new TimerTask() {
                        public void run() {

                        lockTimer.lock();

                        Logger.println("(TimerTask.run) Timeout for the replica that was supposed to send the complete state. Changing desired replica.");
                        System.out.println("Timeout no timer do estado!");

                        stateManager.setWaiting(-1);
                        stateManager.changeReplica();
                        stateManager.emptyStates();
                        stateManager.setReplicaState(null);

                        lockTimer.unlock();
                        }
                    };

                    Timer stateTimer = new Timer("state timer");
                    stateTimer.schedule(stateTask,1500);
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
                    /************************* TESTE *************************

                    System.out.println("Enviei um pedido!");
                    System.out.println("Quem envia: " + smsg.getSender());
                    System.out.println("Que tipo: " + smsg.getType());
                    System.out.println("Que EID: " + smsg.getEid());
                    System.out.println("Ultimo EID: " + stateManager.getLastEID());
                    System.out.println("A espera do EID: " + stateManager.getWaiting());
                    /************************* TESTE *************************/
                }
1080
            }
1081
        }
1082 1083 1084 1085 1086 1087 1088 1089
        else {
            System.out.println("##################################################################################");
            System.out.println("- Ahead-of-time message discarded");
            System.out.println("- If many messages of the same consensus are discarded, the replica can halt!");
            System.out.println("- Try to increase the 'system.paxos.highMarc' configuration parameter.");
            System.out.println("- Last consensus executed: " + lastExecuted);
            System.out.println("##################################################################################");
        }
1090
        /************************* TESTE *************************
1091 1092
        System.out.println("[/TOMLayer.requestState]");
        /************************* TESTE *************************/
1093 1094 1095
    }

    public void SMRequestDeliver(SMMessage msg) {
1096

1097 1098 1099
        //******* EDUARDO BEGIN **************//
        if (reconfManager.getStaticConf().isStateTransferEnabled()) {
        //******* EDUARDO END **************//
1100

1101 1102 1103
            Logger.println("(TOMLayer.SMRequestDeliver) The state transfer protocol is enabled");
            
            lockState.lock();
1104

1105 1106 1107 1108 1109 1110 1111 1112
            Logger.println("(TOMLayer.SMRequestDeliver) I received a state request for EID " + msg.getEid() + " from replica " + msg.getSender());
            /************************* TESTE *************************
            System.out.println("[TOMLayer.SMRequestDeliver]");
            System.out.println("Recebi um pedido de estado!");
            System.out.println("Estado pedido: " + msg.getEid());
            System.out.println("Checkpoint q eu tenho: " + stateManager.getLog().getLastCheckpointEid());
            System.out.println("Ultimo eid q recebi no log: " + stateManager.getLog().getLastEid());
            /************************* TESTE *************************/
1113

1114
            boolean sendState = msg.getReplica() == reconfManager.getStaticConf().getProcessId();
1115
            if (sendState) Logger.println("(TOMLayer.SMRequestDeliver) I should be the one sending the state");
1116

1117
            TransferableState state = stateManager.getLog().getTransferableState(msg.getEid(), sendState);
1118

1119
            lockState.unlock();
1120

1121 1122 1123 1124 1125 1126 1127
            if (state == null) {
                Logger.println("(TOMLayer.SMRequestDeliver) I don't have the state requested :-(");
               /************************* TESTE *************************
               System.out.println("Nao tenho o estado pedido!");
               /************************* TESTE *************************/
              state = new TransferableState();
            }
1128
        
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
            /************************* TESTE *************************
            else {

                for (int eid = state.getLastCheckpointEid() + 1; eid <= state.getLastEid(); eid++) {
                    byte[] batch = state.getMessageBatch(eid).batch;

                    if (batch == null) System.out.println("isto esta nulo!!!");
                    else System.out.println("isto nao esta nulo");
                
                    BatchReader batchReader = new BatchReader(batch,reconfManager.getStaticConf().getUseSignatures() == 1);
                    TOMMessage[] requests = batchReader.deserialiseRequests(reconfManager);
                    System.out.println("tudo correu bem");
                }
            }
            /************************* TESTE *************************/

1145
            /** CODIGO MALICIOSO, PARA FORCAR A REPLICA ATRASADA A PEDIR O ESTADO A OUTRA DAS REPLICAS */
1146 1147
            //byte[] badState = {127};
            //if (sendState && reconfManager.getStaticConf().getProcessId() == 0) state.setState(badState);
1148
            /*******************************************************************************************/
1149

1150
            int[] targets = { msg.getSender() };
1151 1152
            SMMessage smsg = new SMMessage(reconfManager.getStaticConf().getProcessId(), 
                    msg.getEid(), TOMUtil.SM_REPLY, -1, state);
1153 1154 1155

            // malicious code, to force the replica not to send the state
            //if (reconfManager.getStaticConf().getProcessId() != 0 || !sendState)
1156
            communication.send(targets, smsg);
1157

1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
            Logger.println("(TOMLayer.SMRequestDeliver) I sent the state for checkpoint " + state.getLastCheckpointEid() + " with batches until EID " + state.getLastEid());
            /************************* TESTE *************************
            System.out.println("Quem envia: " + smsg.getSender());
            System.out.println("Que tipo: " + smsg.getType());
            System.out.println("Que EID: " + smsg.getEid());
            //System.exit(0);
            /************************* TESTE *************************/
            /************************* TESTE *************************
            System.out.println("[/TOMLayer.SMRequestDeliver]");
            /************************* TESTE *************************/
        }
1169 1170 1171 1172
    }

    public void SMReplyDeliver(SMMessage msg) {

1173
        /************************* TESTE *************************
1174
        System.out.println("[TOMLayer.SMReplyDeliver]");
1175
        System.out.println("Recebi uma resposta de uma replica!");
1176 1177 1178
        System.out.println("[reply] Esta resposta tem o estado? " + msg.getState().hasState());
        System.out.println("[reply] EID do ultimo checkpoint: " + msg.getState().getLastCheckpointEid());
        System.out.println("[reply] EID do ultimo batch recebido: " + msg.getState().getLastEid());
1179
        if (msg.getState().getMessageBatches() != null)
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
            System.out.println("[reply] Numero de batches: " + msg.getState().getMessageBatches().length);
        else System.out.println("[reply] Nao ha batches");
        if (msg.getState().getState() != null) {
            System.out.println("[reply] Tamanho do estado em bytes: " + msg.getState().getState().length);

            int value = 0;
            for (int i = 0; i < 4; i++) {
                int shift = (4 - 1 - i) * 8;
                value += (msg.getState().getState()[i] & 0x000000FF) << shift;
            }
            System.out.println("[reply] Valor do estado: " + value);
        }
        else System.out.println("[reply] Nao ha estado");
1193
        /************************* TESTE *************************/
1194
        //******* EDUARDO BEGIN **************//
1195 1196

        lockTimer.lock();
1197 1198
        if (reconfManager.getStaticConf().isStateTransferEnabled()) {
        //******* EDUARDO END **************//
1199

1200 1201
            Logger.println("(TOMLayer.SMReplyDeliver) The state transfer protocol is enabled");
            Logger.println("(TOMLayer.SMReplyDeliver) I received a state reply for EID " + msg.getEid() + " from replica " + msg.getSender());
1202

1203
            if (stateManager.getWaiting() != -1 && msg.getEid() == stateManager.getWaiting()) {
1204

1205 1206 1207 1208
                /************************* TESTE *************************
                System.out.println("A resposta e referente ao eid que estou a espera! (" + msg.getEid() + ")");
                /************************* TESTE *************************/
                Logger.println("(TOMLayer.SMReplyDeliver) The reply is for the EID that I want!");
1209
            
1210 1211 1212
                if (msg.getSender() == stateManager.getReplica() && msg.getState().getState() != null) {
                    Logger.println("(TOMLayer.SMReplyDeliver) I received the state, from the replica that I was expecting");
                    stateManager.setReplicaState(msg.getState().getState());
1213
                    if (stateTimer != null) stateTimer.cancel();
1214
                }
1215

1216
                stateManager.addState(msg.getSender(),msg.getState());
1217

1218
                if (stateManager.moreThanF_Replies()) {
1219

1220
                    Logger.println("(TOMLayer.SMReplyDeliver) I have at least " + reconfManager.getCurrentViewF() + " replies!");
1221
                    /************************* TESTE *************************
1222
                    System.out.println("Ja tenho mais que " + reconfManager.getQuorumF() + " respostas iguais!");
1223
                    /************************* TESTE *************************/
1224

1225
                    TransferableState state = stateManager.getValidHash();
1226

1227 1228 1229 1230 1231 1232
                    int haveState = 0;
                    if (stateManager.getReplicaState() != null) {
                        byte[] hash = null;
                        hash = computeHash(stateManager.getReplicaState());
                        if (state != null) {
                            if (Arrays.equals(hash, state.getStateHash())) haveState = 1;
1233 1234
                            else if (stateManager.getNumValidHashes() > reconfManager.getCurrentViewF()) haveState = -1;

1235
                        }
1236 1237
                    }

1238
                    if (state != null && haveState == 1) {
1239

1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
                        /************************* TESTE *************************
                        System.out.println("As respostas desse estado são validas!");

                        System.out.println("[state] Esta resposta tem o estado? " + state.hasState());
                        System.out.println("[state] EID do ultimo checkpoint: " + state.getLastCheckpointEid());
                        System.out.println("[state] EID do ultimo batch recebido: " + state.getLastEid());
                        if (state.getMessageBatches() != null)
                            System.out.println("[state] Numero de batches: " + state.getMessageBatches().length);
                        else System.out.println("[state] Nao ha batches");
                        if (state.getState() != null) {
                            System.out.println("[state] Tamanho do estado em bytes: " + state.getState().length);

                            int value = 0;
                            for (int i = 0; i < 4; i++) {
                                int shift = (4 - 1 - i) * 8;
                                value += (state.getState()[i] & 0x000000FF) << shift;
                            }
                            System.out.println("[state] Valor do estado: " + value);
1258
                        }
1259
                        else System.out.println("[state] Nao ha estado");
1260

1261 1262
                        //System.exit(0);
                        /************************* TESTE *************************/
1263

1264
                        Logger.println("(TOMLayer.SMReplyDeliver) The state of those replies is good!");
1265

1266
                        state.setState(stateManager.getReplicaState());
1267
                    
1268
                        lockState.lock();
1269

1270
                        stateManager.getLog().update(state);
1271

1272 1273 1274 1275 1276 1277 1278
                        /************************* TESTE *************************
                        System.out.println("[log] Estado pedido: " + msg.getEid());
                        System.out.println("[log] EID do ultimo checkpoint: " + stateManager.getLog().getLastCheckpointEid());
                        System.out.println("[log] EID do ultimo batch recebido: " + stateManager.getLog().getLastEid());
                        System.out.println("[log] Numero de batches: " + stateManager.getLog().getNumBatches());
                        if (stateManager.getLog().getState() != null) {
                            System.out.println("[log] Tamanho do estado em bytes: " + stateManager.getLog().getState().length);
1279
                    
1280 1281 1282 1283 1284 1285
                            int value = 0;
                            for (int i = 0; i < 4; i++) {
                                int shift = (4 - 1 - i) * 8;
                                value += (stateManager.getLog().getState()[i] & 0x000000FF) << shift;
                            }
                            System.out.println("[log] Valor do estado: " + value);
1286
                        }
1287 1288
                        //System.exit(0);
                        /************************* TESTE *************************/
1289

1290
                        lockState.unlock();
1291

1292 1293
                        //System.out.println("Desbloqueei o lock para o log do estado");
                        dt.deliverLock();
1294

1295
                        //System.out.println("Bloqueei o lock entre esta thread e a delivery thread");
1296

1297
                        //ot.OutOfContextLock();
1298

1299
                        //System.out.println("Bloqueei o lock entre esta thread e a out of context thread");
1300

1301
                        stateManager.setWaiting(-1);
1302

1303
                        //System.out.println("Ja nao estou a espera de nenhum estado, e vou actualizar-me");
1304

1305
                        dt.update(state);
1306
                        processOutOfContext();
1307

1308
                        dt.canDeliver();
1309

1310
                        //ot.OutOfContextUnlock();
1311
                        dt.deliverUnlock();
1312
                    
1313 1314
                        stateManager.emptyStates();
                        stateManager.setReplicaState(null);
1315

1316 1317
                        System.out.println("Actualizei o estado!");

1318 1319 1320 1321 1322 1323
                    //******* EDUARDO BEGIN **************//
                    } else if (state == null && (reconfManager.getCurrentViewN() / 2) < stateManager.getReplies()) {
                    //******* EDUARDO END **************//
                        
                        Logger.println("(TOMLayer.SMReplyDeliver) I have more than " + 
                                (reconfManager.getCurrentViewN() / 2) + " messages that are no good!");
1324 1325 1326 1327
                        /************************* TESTE *************************
                        System.out.println("Tenho mais de 2F respostas que nao servem para nada!");
                        //System.exit(0);
                        /************************* TESTE *************************/
1328

1329 1330 1331
                        stateManager.setWaiting(-1);
                        stateManager.emptyStates();
                        stateManager.setReplicaState(null);
1332 1333

                        if (stateTimer != null) stateTimer.cancel();
1334
                    } else if (haveState == -1) {
1335

1336
                        Logger.println("(TOMLayer.SMReplyDeliver) The replica from which I expected the state, sent one which doesn't match the hash of the others, or it never sent it at all");
1337

1338 1339 1340 1341
                        stateManager.setWaiting(-1);
                        stateManager.changeReplica();
                        stateManager.emptyStates();
                        stateManager.setReplicaState(null);
1342 1343

                        if (stateTimer != null) stateTimer.cancel();
1344
                    }
1345 1346 1347
                }
            }
        }
1348
        lockTimer.unlock();
1349
        /************************* TESTE *************************
1350 1351
        System.out.println("[/TOMLayer.SMReplyDeliver]");
        /************************* TESTE *************************/
P
pjsousa@gmail.com 已提交
1352
    }
1353 1354

    public boolean isRetrievingState() {
1355
        //lockTimer.lock();
1356
        boolean result =  stateManager != null && stateManager.getWaiting() != -1;
1357
        //lockTimer.unlock();
1358 1359

        return result;
1360
    }
1361 1362

    public void setNoExec() {
1363
        Logger.println("(TOMLayer.setNoExec) modifying inExec from " + this.inExecution + " to " + -1);
1364 1365 1366 1367 1368 1369 1370 1371

        proposeLock.lock();
        this.inExecution = -1;
        //ot.addUpdate();
        canPropose.signalAll();
        proposeLock.unlock();
    }

P
pjsousa@gmail.com 已提交
1372
    /********************************************************/
1373 1374 1375 1376

    public void processOutOfContext() {
        while (true) {
            int nextExecution = getLastExec() + 1;
B
bessani@gmail.com 已提交
1377
            if (execManager.thereArePendingMessages(nextExecution)) {
1378
                Logger.println("(TOMLayer.processOutOfContext) starting processing out of context messages for consensus " + nextExecution);
1379
                execManager.getExecution(nextExecution);
1380 1381 1382 1383 1384 1385
                Logger.println("(TOMLayer.processOutOfContext) finished processing out fo context messages for consensus " + nextExecution);
            }
            else break;
        }
    }
    /********************************************************************/
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572

    /*** ISTO E CODIGO DO JOAO, RELACIONADO COM A TROCA DE LIDER */

    /**
     * Este metodo e invocado quando ha um timeout e o request ja foi re-encaminhado para o lider
     * @param requestList Lista de pedidos que a replica quer ordenar mas nao conseguiu
     */
    public void triggerTimeout(List<TOMMessage> requestList) {

        ObjectOutputStream out = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        lcManager.nexttsLock();
        lcManager.lasttsLock();

        // ainda nao estou na fase de troca de lider?
        if (lcManager.getNextts() == lcManager.getLastts()) {

                lcManager.setNextts(lcManager.getLastts() + 1); // definir proximo timestamp

                int ts = lcManager.getNextts();

                lcManager.nexttsUnlock();
                lcManager.lasttsUnlock();

                // guardar mensagens para ordenar
                lcManager.setCurrentRequestTimedOut(requestList);

                // guardar informacao da mensagem que vou enviar
                lcManager.StopsLock();
                lcManager.addStop(ts, this.reconfManager.getStaticConf().getProcessId());
                lcManager.StopsUnlock();

                execManager.stop(); // parar execucao do consenso

                try { // serializar conteudo a enviar na mensagem STOP
                    out = new ObjectOutputStream(bos);

                    if (lcManager.getCurrentRequestTimedOut() != null) {

                        //TODO: Se isto estiver a null, e porque nao houve timeout. Fazer o q?
                        out.writeBoolean(true);
                        out.writeObject(lcManager.getCurrentRequestTimedOut());
                    }
                    else {
                        out.writeBoolean(false);
                    }

                    byte[] payload = bos.toByteArray();
                    out.close();
                    bos.close();

                    // enviar mensagem STOP
                    communication.send(this.reconfManager.getCurrentViewOtherAcceptors(),
                    new LCMessage(this.reconfManager.getStaticConf().getProcessId(), TOMUtil.STOP, ts, payload));

                } catch (IOException ex) {
                    java.util.logging.Logger.getLogger(TOMLayer.class.getName()).log(Level.SEVERE, null, ex);
                } finally {
                    try {
                        out.close();
                        bos.close();
                    } catch (IOException ex) {
                        java.util.logging.Logger.getLogger(TOMLayer.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

                evaluateStops(ts); // avaliar mensagens stops

        }

        else {
                lcManager.nexttsUnlock();
                lcManager.lasttsUnlock();
        }
    }

    // este metodo e invocado aquando de um timeout ou da recepcao de uma mensagem STOP
    private void evaluateStops(int nextTS) {

        ObjectOutputStream out = null;
        ByteArrayOutputStream bos = null;

        lcManager.nexttsLock();
        lcManager.lasttsLock();
        lcManager.StopsLock();

        // passar para a fase de troca de lider se já tiver recebido mais de f mensagens
        if (lcManager.getStopsSize(nextTS) > this.reconfManager.getQuorumF() && lcManager.getNextts() == lcManager.getLastts()) {

            lcManager.setNextts(lcManager.getLastts() + 1); // definir proximo timestamp

            int ts = lcManager.getNextts();

            // guardar informacao da mensagem que vou enviar
            lcManager.addStop(ts, this.reconfManager.getStaticConf().getProcessId());

            execManager.stop(); // parar execucao do consenso

            try { // serializar conteudo a enviar na mensagem STOP
                bos = new ByteArrayOutputStream();
                out = new ObjectOutputStream(bos);

                if (lcManager.getCurrentRequestTimedOut() != null) {

                    //TODO: Se isto estiver a null, e porque nao houve timeout. Fazer o q?
                    out.writeBoolean(true);
                    out.writeObject(lcManager.getCurrentRequestTimedOut());
                }
                else {
                    out.writeBoolean(false);
                }

                out.flush();
                bos.flush();

                byte[] payload = bos.toByteArray();
                out.close();
                bos.close();

                // enviar mensagem STOP
                communication.send(this.reconfManager.getCurrentViewOtherAcceptors(),
                    new LCMessage(this.reconfManager.getStaticConf().getProcessId(), TOMUtil.STOP, ts, payload));

            } catch (IOException ex) {
                java.util.logging.Logger.getLogger(TOMLayer.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                try {
                    out.close();
                    bos.close();
                } catch (IOException ex) {
                    java.util.logging.Logger.getLogger(TOMLayer.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

        // posso passar para a fase de sincronizacao?
        if (lcManager.getStopsSize(nextTS) > this.reconfManager.getQuorum2F() && lcManager.getNextts() > lcManager.getLastts()) {

            lcManager.setLastts(lcManager.getNextts()); // definir ultimo timestamp

            lcManager.nexttsUnlock();

            int ts = lcManager.getLastts();
            lcManager.lasttsUnlock();

            // evitar um memory leak
            lcManager.removeStops(nextTS);

            lcManager.StopsUnlock();

            int leader = ts % this.reconfManager.getCurrentViewN(); // novo lider
            int in = getInExec(); // eid a executar
            int last = getLastExec(); // ultimo eid decidido

            // Se eu nao for o lider, tenho que enviar uma mensagem SYNC para ele
            if (leader != this.reconfManager.getStaticConf().getProcessId()) {

                try { // serializar o conteudo da mensagem SYNC

                    bos = new ByteArrayOutputStream();
                    out = new ObjectOutputStream(bos);

                    if (last > -1) { // conteudo do ultimo eid decidido

                        out.writeBoolean(true);
                        out.writeInt(last);
                        Execution exec = execManager.getExecution(last);
                        byte[] decision = exec.getLearner().getDecision();

                        out.writeObject(decision);

                        // TODO: VAI SER PRECISO METER UMA PROVA!!!

                    }

                    else out.writeBoolean(false);

                    if (in > -1) { // conteudo do eid a executar

                        Execution exec = execManager.getExecution(in);

                        RoundValuePair quorumWeaks = exec.getQuorumWeaks();
                        HashSet<RoundValuePair> writeSet = exec.getWriteSet();

                        CollectData collect = new CollectData(this.reconfManager.getStaticConf().getProcessId(), in, quorumWeaks, writeSet);

B
bessani@gmail.com 已提交
1573
                        SignedObject signedCollect = sign(collect);
1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585

                        out.writeObject(signedCollect);

                        //out.writeInt(in);
                        //out.writeObject(exec.getQuorumWeaks());
                        //out.writeObject(exec.getWriteSet());
                    }

                    else {

                        CollectData collect = new CollectData(this.reconfManager.getStaticConf().getProcessId(), -1, new RoundValuePair(-1, new byte[0]), new HashSet<RoundValuePair>());

B
bessani@gmail.com 已提交
1586
                        SignedObject signedCollect = sign(collect);
1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651

                        out.writeObject(signedCollect);

                    }

                    out.flush();
                    bos.flush();

                    byte[] payload = bos.toByteArray();
                    out.close();
                    bos.close();

                    leaderLock.lock();
                    lm.setNewTS(ts);
                    leaderLock.unlock();

                    int[] b = new int[1];
                    b[0] = leader;

                    // enviar mensagem SYNC para o novo lider
                    communication.send(b,
                        new LCMessage(this.reconfManager.getStaticConf().getProcessId(), TOMUtil.SYNC, ts, payload));

                    //TODO: Voltar a ligar o timeout

                } catch (IOException ex) {
                    java.util.logging.Logger.getLogger(TOMLayer.class.getName()).log(Level.SEVERE, null, ex);
                } finally {
                    try {
                        out.close();
                        bos.close();
                    } catch (IOException ex) {
                        java.util.logging.Logger.getLogger(TOMLayer.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

            } else { // se for o lider, vou guardar a informacao que enviaria na mensagem SYNC

                LastEidData lastData = null;
                CollectData collect = null;

                if (last > -1) {  // conteudo do ultimo eid decidido
                    Execution exec = execManager.getExecution(last);
                    byte[] decision = exec.getLearner().getDecision();

                    lastData = new LastEidData(this.reconfManager.getStaticConf().getProcessId(), last, decision, null);
                    // TODO: VAI SER PRECISO METER UMA PROVA!!!

                }
                else lastData = new LastEidData(this.reconfManager.getStaticConf().getProcessId(), last, null, null);

                lcManager.addLastEid(ts, lastData);


                if (in > -1) { // conteudo do eid a executar
                    Execution exec = execManager.getExecution(in);

                    RoundValuePair quorumWeaks = exec.getQuorumWeaks();
                    HashSet<RoundValuePair> writeSet = exec.getWriteSet();

                    collect = new CollectData(this.reconfManager.getStaticConf().getProcessId(), in, quorumWeaks, writeSet);

                }
                else collect = new CollectData(this.reconfManager.getStaticConf().getProcessId(), -1, new RoundValuePair(-1, new byte[0]), new HashSet<RoundValuePair>());

B
bessani@gmail.com 已提交
1652
                SignedObject signedCollect = sign(collect);
1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845

                lcManager.addCollect(ts, signedCollect);
            }

        }
        else {
            lcManager.StopsUnlock();
            lcManager.nexttsUnlock();
            lcManager.lasttsUnlock();
        }
    }

    /**
     * Este metodo e invocado pelo MessageHandler sempre que receber mensagens relacionados
     * com a troca de lider
     * @param msg Mensagem recebida de outra replica
     */
    public void deliverTimeoutRequest(LCMessage msg) {

        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;

        switch (msg.getType()) {
            case TOMUtil.STOP: // mensagens STOP

                {
                    lcManager.lasttsLock();

                    // esta mensagem e para a proxima mudanca de lider?
                    if (msg.getTs() == lcManager.getLastts() + 1) {

                        lcManager.lasttsUnlock();

                        try { // descerializar o conteudo da mensagem STOP

                            bis = new ByteArrayInputStream(msg.getPayload());
                            ois = new ObjectInputStream(bis);

                            boolean hasReq = ois.readBoolean();
                            clientsManager.getClientsLock().lock();

                            if (hasReq) {

                                // Guardar os pedidos que a outra replica nao conseguiu ordenar
                                //TODO: Os requests  tem q ser verificados!
                                List<TOMMessage> requests = (List<TOMMessage>) ois.readObject();

                                for (TOMMessage r : requests) {

                                    clientsManager.requestReceived(r, false);
                                }

                            }
                            clientsManager.getClientsLock().unlock();

                            ois.close();
                            bis.close();

                        } catch (IOException ex) {
                            java.util.logging.Logger.getLogger(TOMLayer.class.getName()).log(Level.SEVERE, null, ex);
                        } catch (ClassNotFoundException ex) {
                            java.util.logging.Logger.getLogger(TOMLayer.class.getName()).log(Level.SEVERE, null, ex);

                        }

                        // guardar informacao sobre a mensagem STOP
                        lcManager.StopsLock();
                        lcManager.addStop(msg.getTs(), msg.getSender());
                        lcManager.StopsUnlock();

                        evaluateStops(msg.getTs()); // avaliar mensagens stops
                    }
                    else {
                        lcManager.lasttsUnlock();
                    }
                }
                break;
            case TOMUtil.SYNC: // mensagens SYNC
                {

                    int ts = msg.getTs();

                    lcManager.lasttsLock();

                    // Sou o novo lider e estou a espera destas mensagem?
                    if (ts == lcManager.getLastts() &&
                            this.reconfManager.getStaticConf().getProcessId() == (ts % this.reconfManager.getCurrentViewN())) {

                        //TODO: E preciso verificar a prova do ultimo consenso decidido e a assinatura do estado do consenso actual!

                        lcManager.lasttsUnlock();

                        LastEidData lastData = null;
                        SignedObject signedCollect = null;

                        int last = -1;
                        byte[] lastValue = null;

                        int in = -1;

                        RoundValuePair quorumWeaks = null;
                        HashSet<RoundValuePair> writeSet = null;


                        try { // descerializar o conteudo da mensagem

                            bis = new ByteArrayInputStream(msg.getPayload());
                            ois = new ObjectInputStream(bis);

                            if (ois.readBoolean()) { // conteudo do ultimo eid decidido


                                last = ois.readInt();

                                lastValue = (byte[]) ois.readObject();

                                //TODO: Falta a prova!

                            }

                            lastData = new LastEidData(msg.getSender(), last, lastValue, null);

                            lcManager.addLastEid(ts, lastData);

                            // conteudo do eid a executar

                            signedCollect = (SignedObject) ois.readObject();

                            /*in = ois.readInt();
                            quorumWeaks = (RoundValuePair) ois.readObject();
                            writeSet = (HashSet<RoundValuePair>) ois.readObject();*/



                            /*collect = new CollectData(msg.getSender(), in,
                                    quorumWeaks, writeSet);*/

                            ois.close();
                            bis.close();

                            lcManager.addCollect(ts, signedCollect);

                            int bizantineQuorum = (reconfManager.getCurrentViewN() + reconfManager.getCurrentViewF()) / 2;

                            // ja recebi mensagens de um quorum bizantino,
                            // referentes tanto ao ultimo eid como o actual?s
                            if (lcManager.getLastEidsSize(ts) > bizantineQuorum &&
                                    lcManager.getCollectsSize(ts) > bizantineQuorum) {

                                catch_up(ts);
                            }

                        } catch (IOException ex) {
                            java.util.logging.Logger.getLogger(TOMLayer.class.getName()).log(Level.SEVERE, null, ex);
                        } catch (ClassNotFoundException ex) {
                            java.util.logging.Logger.getLogger(TOMLayer.class.getName()).log(Level.SEVERE, null, ex);

                        }

                  }
            }
            break;
        case TOMUtil.CATCH_UP: // mensagens de CATCH-UP
            {
                int ts = msg.getTs();

                lcManager.lasttsLock();

                // Estou a espera desta mensagem, e recebi-a do novo lider?
                if (msg.getTs() == lcManager.getLastts() && msg.getSender() == (ts % this.reconfManager.getCurrentViewN())) {

                    lcManager.lasttsUnlock();

                    LastEidData lastHighestEid = null;
                    int currentEid = -1;
                    HashSet<SignedObject> signedCollects = null;
                    byte[] propose = null;
                    int batchSize = -1;

                    try { // descerializar o conteudo da mensagem

                        bis = new ByteArrayInputStream(msg.getPayload());
                        ois = new ObjectInputStream(bis);

                        lastHighestEid = (LastEidData) ois.readObject();
                        currentEid = ois.readInt();
                        signedCollects = (HashSet<SignedObject>) ois.readObject();
                        propose = (byte[]) ois.readObject();
                        batchSize = ois.readInt();

                        lcManager.setCollects(ts, signedCollects);

                        // o predicado sound e verdadeiro?
B
bessani@gmail.com 已提交
1846
                        if (lcManager.sound(lcManager.selectCollects(ts, currentEid))) {
1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886

                            finalise(ts, lastHighestEid, currentEid, signedCollects, propose, batchSize, false);
                        }

                        ois.close();
                        bis.close();

                    } catch (IOException ex) {
                        java.util.logging.Logger.getLogger(TOMLayer.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (ClassNotFoundException ex) {
                        java.util.logging.Logger.getLogger(TOMLayer.class.getName()).log(Level.SEVERE, null, ex);

                    }

                }
                else {
                    lcManager.lasttsUnlock();
                }
            }
            break;

        }

    }

    // este metodo e usado para verificar se o lider pode fazer a mensagem catch-up
    // e tambem envia-la
    private void catch_up(int ts) {

        ObjectOutputStream out = null;
        ByteArrayOutputStream bos = null;

        LastEidData lastHighestEid = lcManager.getHighestLastEid(ts);

        int currentEid = lastHighestEid.getEid() + 1;
        HashSet<SignedObject> signedCollects = null;
        byte[] propose = null;
        int batchSize = -1;

        // normalizar os collects e aplicar-lhes o predicado "sound"
B
bessani@gmail.com 已提交
1887
        if (lcManager.sound(lcManager.selectCollects(ts, currentEid))) {
1888 1889 1890

            signedCollects = lcManager.getCollects(ts); // todos collects originais que esta replica recebeu

B
bessani@gmail.com 已提交
1891
            Consensus cons = new Consensus(-1); // este objecto só serve para obter o batchsize,
1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949
                                                    // a partir do codigo que esta dentro do createPropose()

            propose = createPropose(cons);
            batchSize = cons.batchSize;

            try { // serializar a mensagem CATCH-UP
                bos = new ByteArrayOutputStream();
                out = new ObjectOutputStream(bos);

                out.writeObject(lastHighestEid);

                //TODO: Falta serializar a prova!!

                out.writeInt(currentEid);
                out.writeObject(signedCollects);
                out.writeObject(propose);
                out.writeInt(batchSize);

                out.flush();
                bos.flush();

                byte[] payload = bos.toByteArray();
                out.close();
                bos.close();

                // enviar a mensagem CATCH-UP
                communication.send(this.reconfManager.getCurrentViewOtherAcceptors(),
                    new LCMessage(this.reconfManager.getStaticConf().getProcessId(), TOMUtil.CATCH_UP, ts, payload));

                finalise(ts, lastHighestEid, currentEid, signedCollects, propose, batchSize, true);

            } catch (IOException ex) {
                java.util.logging.Logger.getLogger(TOMLayer.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                try {
                    out.close();
                    bos.close();
                } catch (IOException ex) {
                    java.util.logging.Logger.getLogger(TOMLayer.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    // este metdo e invocado em todas as replicas, e serve para verificar e aplicar
    // a informacao enviada na mensagem catch-up
    private void finalise(int ts, LastEidData lastHighestEid,
            int currentEid, HashSet<SignedObject> signedCollects, byte[] propose, int batchSize, boolean iAmLeader) {

        int me = this.reconfManager.getStaticConf().getProcessId();
        Execution exec = null;
        Round r = null;

        // Esta replica esta atrasada?
        if (getLastExec() + 1 < lastHighestEid.getEid()) {
            //TODO: Caso em que e necessario aplicar a transferencia de estado


B
bessani@gmail.com 已提交
1950
        } else if (getLastExec() + 1 == lastHighestEid.getEid()) {
1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970
        // esta replica ainda esta a executar o ultimo consenso decidido?

            //TODO: e preciso verificar a prova!

            exec = execManager.getExecution(lastHighestEid.getEid());
            r = exec.getLastRound();

            if (r == null) {
                exec.createRound(reconfManager);
            }

            byte[] hash = computeHash(propose);
            r.propValueHash = hash;
            r.propValue = propose;
            r.deserializedPropValue = checkProposedValue(propose);
            r.setDecide(me, hash);
            exec.decided(r, hash); // entregar a decisao a delivery thread
        }
        byte[] tmpval = null;

B
bessani@gmail.com 已提交
1971
        HashSet<CollectData> selectedColls = lcManager.selectCollects(signedCollects, currentEid);
1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001

        // obter um valor que satisfaca o predicado "bind"
        tmpval = lcManager.getBindValue(selectedColls);

        // se tal valor nao existir, obter o valor escrito pelo novo lider
        if (tmpval == null && lcManager.unbound(selectedColls)) {
            tmpval = propose;
        }

        if (tmpval != null) { // consegui chegar a algum valor?

            exec = execManager.getExecution(currentEid);
            exec.incEts();

            exec.removeWritten(tmpval);
            exec.addWritten(tmpval);

            r = exec.getLastRound();

            if (r == null) {
                r = exec.createRound(reconfManager);
            }
            else {
                r.clear();
            }

            byte[] hash = computeHash(tmpval);
            r.propValueHash = hash;
            r.propValue = tmpval;
            r.deserializedPropValue = checkProposedValue(tmpval);
B
bessani@gmail.com 已提交
2002 2003 2004 2005

            if(exec.getLearner().firstMessageProposed == null)
                exec.getLearner().firstMessageProposed = r.deserializedPropValue[0];
            
2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025
            r.setWeak(me, hash);

            lm.setNewTS(ts);

            // resumir a execucao normal
            execManager.restart();
            leaderChanged = true;
            setInExec(currentEid);
            if (iAmLeader) {
                imAmTheLeader();
            } // acordar a thread que propoem valores na operacao normal

            // enviar mensagens WEAK para as outras replicas
            communication.send(this.reconfManager.getCurrentViewOtherAcceptors(),
                    acceptor.getFactory().createWeak(currentEid, r.getNumber(), r.propValueHash));

        }

    }
    /**************************************************************/
P
pjsousa@gmail.com 已提交
2026
}