TOMLayer.java 63.7 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
import java.io.ByteArrayInputStream;
import java.io.IOException;
B
bessani@gmail.com 已提交
26
import java.io.Serializable;
P
pjsousa@gmail.com 已提交
27
import java.security.MessageDigest;
B
bessani@gmail.com 已提交
28 29
import java.security.PrivateKey;
import java.security.Signature;
P
pjsousa@gmail.com 已提交
30
import java.security.SignedObject;
31
import java.util.Arrays;
P
pjsousa@gmail.com 已提交
32 33
import java.util.HashSet;
import java.util.List;
34 35
import java.util.Timer;
import java.util.TimerTask;
P
pjsousa@gmail.com 已提交
36 37
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
38
import java.util.logging.Level;
39

P
pjsousa@gmail.com 已提交
40
import navigators.smart.clientsmanagement.ClientsManager;
41
import navigators.smart.clientsmanagement.RequestList;
P
pjsousa@gmail.com 已提交
42 43 44
import navigators.smart.communication.ServerCommunicationSystem;
import navigators.smart.communication.client.RequestReceiver;
import navigators.smart.paxosatwar.Consensus;
45
import navigators.smart.paxosatwar.executionmanager.RoundValuePair;
P
pjsousa@gmail.com 已提交
46 47 48 49 50
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;
51
import navigators.smart.reconfiguration.ReconfigurationManager;
52
import navigators.smart.statemanagment.SMMessage;
53
import navigators.smart.statemanagment.StateLog;
54 55
import navigators.smart.statemanagment.StateManager;
import navigators.smart.statemanagment.TransferableState;
P
pjsousa@gmail.com 已提交
56 57
import navigators.smart.tom.TOMRequestReceiver;
import navigators.smart.tom.core.messages.TOMMessage;
B
bessani@gmail.com 已提交
58
import navigators.smart.tom.core.messages.TOMMessageType;
P
pjsousa@gmail.com 已提交
59 60 61 62 63 64
import navigators.smart.tom.core.timer.RequestsTimer;
import navigators.smart.tom.core.timer.messages.ForwardedMessage;
import navigators.smart.tom.util.BatchBuilder;
import navigators.smart.tom.util.BatchReader;
import navigators.smart.tom.util.Logger;
import navigators.smart.tom.util.TOMUtil;
65 66 67 68
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 已提交
69 70 71 72 73 74 75 76 77 78 79 80 81


/**
 * 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
82
    //private OutOfContextMessageThread ot; // Thread which manages messages that do not belong to the current execution
P
pjsousa@gmail.com 已提交
83
    private DeliveryThread dt; // Thread which delivers total ordered messages to the appication
84
    
P
pjsousa@gmail.com 已提交
85 86 87 88 89 90 91
    /** 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;
B
bessani@gmail.com 已提交
92
    
P
pjsousa@gmail.com 已提交
93
    private MessageDigest md;
B
bessani@gmail.com 已提交
94
    private Signature engine;
P
pjsousa@gmail.com 已提交
95 96

    //the next two are used to generate non-deterministic data in a deterministic way (by the leader)
97
    private BatchBuilder bb = new BatchBuilder();
P
pjsousa@gmail.com 已提交
98 99 100 101 102 103 104 105 106

    /* 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();

107 108 109 110
    /*** ISTO E CODIGO DO JOAO, RELACIONADO COM A TROCA DE LIDER */
    private LCManager lcManager;
    /*************************************************************/

P
pjsousa@gmail.com 已提交
111 112 113 114 115
    /* 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 已提交
116
    private PrivateKey prk;
117 118 119
    
    private ReconfigurationManager reconfManager;
    
P
pjsousa@gmail.com 已提交
120 121 122 123 124 125 126 127 128 129 130 131 132 133
    /**
     * 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 已提交
134
            ReconfigurationManager recManager) {
P
pjsousa@gmail.com 已提交
135 136 137 138 139 140 141

        super("TOM Layer");

        this.execManager = manager;
        this.lm = lm;
        this.acceptor = a;
        this.communication = cs;
142
        this.reconfManager = recManager;
P
pjsousa@gmail.com 已提交
143 144

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

150
        this.clientsManager = new ClientsManager(reconfManager, requestsTimer); // Create clients manager
P
pjsousa@gmail.com 已提交
151 152 153 154 155 156

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

B
bessani@gmail.com 已提交
158 159 160 161 162 163 164
        try {
            this.engine = Signature.getInstance("SHA1withRSA");
        } catch (Exception e) {
            e.printStackTrace();
        }

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

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

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

173
        /** ISTO E CODIGO DO JOAO, PARA TRATAR DOS CHECKPOINTS E TRANSFERENCIA DE ESTADO*/
B
bessani@gmail.com 已提交
174
        this.stateManager = new StateManager(this.reconfManager);
175
        /*******************************************************/
P
pjsousa@gmail.com 已提交
176 177
    }

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

P
pjsousa@gmail.com 已提交
180 181 182 183 184 185
    /**
     * Computes an hash for a TOM message
     * @param message
     * @return Hash for teh specified TOM message
     */
    public final byte[] computeHash(byte[] data) {
186 187
        byte[] ret = null;
        hashLock.lock();
B
bessani@gmail.com 已提交
188
        ret = md.digest(data);
189 190 191
        hashLock.unlock();

        return ret;
B
bessani@gmail.com 已提交
192 193 194 195 196 197
    }

    public SignedObject sign(Serializable obj) {
        try {
            return new SignedObject(obj, prk, engine);
        } catch (Exception e) {
B
bessani@gmail.com 已提交
198
            e.printStackTrace(System.err);
B
bessani@gmail.com 已提交
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
            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 已提交
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
    }

    /**
     * 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 已提交
236
    public void setLastExec(int last) {
P
pjsousa@gmail.com 已提交
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
        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;
B
bessani@gmail.com 已提交
258
        if (inEx == -1  && !isRetrievingState()) {
P
pjsousa@gmail.com 已提交
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
            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 已提交
289
    @Override
P
pjsousa@gmail.com 已提交
290 291 292 293 294 295 296 297 298
    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 已提交
299
      */
P
pjsousa@gmail.com 已提交
300 301 302
        /**********************************************************/
        /**********************************************************/
        /**********************************************************/
B
bessani@gmail.com 已提交
303

304
        // check if this request is valid and add it to the client' pending requests list
B
bessani@gmail.com 已提交
305
        boolean readOnly = (msg.getReqType() == TOMMessageType.READONLY_REQUEST);
B
bessani@gmail.com 已提交
306 307
        if (clientsManager.requestReceived(msg, true, !readOnly, communication)) {
            if (readOnly) {
B
bessani@gmail.com 已提交
308
                dt.deliverUnordered(msg);
P
pjsousa@gmail.com 已提交
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
            } 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
326
        RequestList pendingRequests = clientsManager.getPendingRequests();
P
pjsousa@gmail.com 已提交
327 328

        int numberOfMessages = pendingRequests.size(); // number of messages retrieved
329
        int numberOfNonces = this.reconfManager.getStaticConf().getNumberOfNonces(); // ammount of nonces to be generated
B
bessani@gmail.com 已提交
330 331 332 333

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

P
pjsousa@gmail.com 已提交
336 337
        Logger.println("(TOMLayer.run) creating a PROPOSE with " + numberOfMessages + " msgs");

338
        return bb.makeBatch(pendingRequests, numberOfNonces, System.currentTimeMillis(),reconfManager);
339
    }
P
pjsousa@gmail.com 已提交
340 341 342 343 344 345
    /**
     * 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() {
B
bessani@gmail.com 已提交
346
        Logger.println("Running."); // TODO: isto n podia passar para fora do ciclo?
P
pjsousa@gmail.com 已提交
347 348 349
        while (true) {
            // blocks until this replica learns to be the leader for the current round of the current consensus
            leaderLock.lock();
B
bessani@gmail.com 已提交
350
            Logger.println("Next leader for eid=" + (getLastExec() + 1) + ": " + lm.getCurrentLeader());
351 352
            
            //******* EDUARDO BEGIN **************//
353
            if (/*lm.getLeader(getLastExec() + 1, 0)*/ lm.getCurrentLeader() != this.reconfManager.getStaticConf().getProcessId()) {
P
pjsousa@gmail.com 已提交
354
                iAmLeader.awaitUninterruptibly();
355
                waitForPaxosToFinish();
P
pjsousa@gmail.com 已提交
356
            }
357 358
            //******* EDUARDO END **************//
            
P
pjsousa@gmail.com 已提交
359 360 361 362 363 364 365 366 367 368 369 370 371 372
            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
B
bessani@gmail.com 已提交
373
                Logger.println("(TOMLayer.run) Waiting for consensus " + getInExec() + " termination.");
P
pjsousa@gmail.com 已提交
374 375 376 377 378
                canPropose.awaitUninterruptibly();
            }
            proposeLock.unlock();

            Logger.println("(TOMLayer.run) I can try to propose.");
379
            if ((lm.getCurrentLeader() == this.reconfManager.getStaticConf().getProcessId()) && //I'm the leader
P
pjsousa@gmail.com 已提交
380 381 382 383 384 385 386 387 388
                    (clientsManager.havePendingRequests()) && //there are messages to be ordered
                    (getInExec() == -1 || leaderChanged)) { //there is no consensus in execution

                leaderChanged = false;

                // Sets the current execution
                int execId = getLastExec() + 1;
                setInExec(execId);

B
bessani@gmail.com 已提交
389 390
                execManager.getProposer().startExecution(execId,
                        createPropose(execManager.getExecution(execId).getLearner()));
P
pjsousa@gmail.com 已提交
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
            }
        }
    }

    /**
     * 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
     */
413
    public TOMMessage[] checkProposedValue(byte[] proposedValue) {
P
pjsousa@gmail.com 已提交
414
        Logger.println("(TOMLayer.isProposedValueValid) starting");
415

416 417
        BatchReader batchReader = new BatchReader(proposedValue, 
                this.reconfManager.getStaticConf().getUseSignatures() == 1);
P
pjsousa@gmail.com 已提交
418

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

421 422 423
        try {
            //deserialize the message
            //TODO: verify Timestamps and Nonces
424
            requests = batchReader.deserialiseRequests(this.reconfManager);
P
pjsousa@gmail.com 已提交
425

426
            for (int i = 0; i < requests.length; i++) {
B
bessani@gmail.com 已提交
427 428 429 430 431 432
                //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");
433 434 435 436 437 438
                    return null;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            clientsManager.getClientsLock().unlock();
B
bessani@gmail.com 已提交
439
            Logger.println("(TOMLayer.isProposedValueValid) finished, return=false");
440
            return null;
P
pjsousa@gmail.com 已提交
441
        }
B
bessani@gmail.com 已提交
442
        Logger.println("(TOMLayer.isProposedValueValid) finished, return=true");
P
pjsousa@gmail.com 已提交
443

444
        return requests;
P
pjsousa@gmail.com 已提交
445 446
    }
    public void forwardRequestToLeader(TOMMessage request) {
447
        int leaderId = lm.getCurrentLeader();
B
bessani@gmail.com 已提交
448
        System.out.println("(TOMLayer.forwardRequestToLeader) forwarding " + request + " to " + leaderId);
449 450 451 452 453
        
            //******* EDUARDO BEGIN **************//
        communication.send(new int[]{leaderId}, 
                new ForwardedMessage(this.reconfManager.getStaticConf().getProcessId(), request));
            //******* EDUARDO END **************//
P
pjsousa@gmail.com 已提交
454 455 456
    }

    /** ISTO E CODIGO DO JOAO, PARA TRATAR DOS CHECKPOINTS */
457
    private StateManager stateManager = null;
458
    private ReentrantLock lockState = new ReentrantLock();
459 460
    private ReentrantLock lockTimer = new ReentrantLock();
    private Timer stateTimer = null;
461

462
    public void saveState(byte[] state, int lastEid, int decisionRound, int leader) {
463 464 465 466 467

        StateLog log = stateManager.getLog();

        lockState.lock();

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

470
        log.newCheckpoint(state, computeHash(state));
471 472
        log.setLastEid(-1);
        log.setLastCheckpointEid(lastEid);
473 474
        log.setLastCheckpointRound(decisionRound);
        log.setLastCheckpointLeader(leader);
475

476
        /************************* TESTE *************************
477
        System.out.println("[TOMLayer.saveState]");
478 479 480
        int value = 0;
        for (int i = 0; i < 4; i++) {
            int shift = (4 - 1 - i) * 8;
481
            value += (log.getState()[i] & 0x000000FF) << shift;
482
        }
483
        System.out.println("//////////////////CHECKPOINT//////////////////////");
484
        System.out.println("Estado: " + value);
485 486
        System.out.println("Checkpoint: " + log.getLastCheckpointEid());
        System.out.println("Ultimo EID: " + log.getLastEid());
487
        System.out.println("//////////////////////////////////////////////////");
488
        System.out.println("[/TOMLayer.saveState]");
489
        /************************* TESTE *************************/
490 491
        
        lockState.unlock();
492 493

        Logger.println("(TOMLayer.saveState) Finished saving state of EID " + lastEid + ", round " + decisionRound + " and leader " + leader);
P
pjsousa@gmail.com 已提交
494
    }
495
    public void saveBatch(byte[] batch, int lastEid, int decisionRound, int leader) {
496 497 498 499

        StateLog log = stateManager.getLog();

        lockState.lock();
500 501 502

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

503
        log.addMessageBatch(batch, decisionRound, leader);
504
        log.setLastEid(lastEid);
505 506

        /************************* TESTE *************************
507
        System.out.println("[TOMLayer.saveBatch]");
508
        byte[][] batches = log.getMessageBatches();
509 510 511 512 513 514 515
        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);
516
        System.out.println("Ultimo EID: " + log.getLastEid());
517 518
        //System.out.println("Espaco restante para armazenar batches: " + (stateManager.getLog().getMessageBatches().length - count));
        System.out.println("//////////////////////////////////////////////////");
519
        System.out.println("[/TOMLayer.saveBatch]");
520 521
        /************************* TESTE *************************/

522
        lockState.unlock();
523 524

        Logger.println("(TOMLayer.saveBatch) Finished saving batch of EID " + lastEid + ", round " + decisionRound + " and leader " + leader);
525 526 527 528
    }

    /** ISTO E CODIGO DO JOAO, PARA TRATAR DA TRANSFERENCIA DE ESTADO */
    
B
bessani@gmail.com 已提交
529
    public void requestState(int sender, int eid) {
530

531 532 533
        //******* EDUARDO BEGIN **************//
        if (reconfManager.getStaticConf().isStateTransferEnabled()) {
        //******* EDUARDO END **************//
534

535
            Logger.println("(TOMLayer.requestState) The state transfer protocol is enabled");
536

537
            if (stateManager.getWaiting() == -1) {
538

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

542
                /************************* TESTE *************************
543 544
                System.out.println("Nao estou a espera");
                System.out.println("Numero de mensagens recebidas para este EID de replicas diferentes: " + stateManager.moreThenF_EIDs(eid));
545
                /************************* TESTE *************************/
546

547 548
                if (stateManager.getLastEID() < eid && stateManager.moreThenF_EIDs(eid)) {

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

554
                    requestsTimer.clearAll();
555 556 557
                    stateManager.setLastEID(eid);
                    stateManager.setWaiting(eid - 1);
                    //stateManager.emptyReplicas(eid);// isto causa uma excepcao
558

B
bessani@gmail.com 已提交
559 560 561
                    SMMessage smsg = new SMMessage(reconfManager.getStaticConf().getProcessId(), 
                            eid - 1, TOMUtil.SM_REQUEST, stateManager.getReplica(), null);
                    communication.send(reconfManager.getCurrentViewOtherAcceptors(), smsg);
562

563
                    Logger.println("(TOMLayer.requestState) I just sent a request to the other replicas for the state up to EID " + (eid - 1));
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583

                    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);
584 585 586 587 588 589 590 591 592 593
                    /************************* 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 *************************/
                }
594
            }
595
        }
596 597 598 599 600 601 602 603
        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("##################################################################################");
        }
604
        /************************* TESTE *************************
605 606
        System.out.println("[/TOMLayer.requestState]");
        /************************* TESTE *************************/
607 608 609
    }

    public void SMRequestDeliver(SMMessage msg) {
610

611 612 613
        //******* EDUARDO BEGIN **************//
        if (reconfManager.getStaticConf().isStateTransferEnabled()) {
        //******* EDUARDO END **************//
614

615 616 617
            Logger.println("(TOMLayer.SMRequestDeliver) The state transfer protocol is enabled");
            
            lockState.lock();
618

619 620 621 622 623 624 625 626
            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 *************************/
627

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

631
            TransferableState state = stateManager.getLog().getTransferableState(msg.getEid(), sendState);
632

633
            lockState.unlock();
634

635 636 637 638 639 640 641
            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();
            }
642
        
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
            /************************* 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 *************************/

659
            /** CODIGO MALICIOSO, PARA FORCAR A REPLICA ATRASADA A PEDIR O ESTADO A OUTRA DAS REPLICAS */
660 661
            //byte[] badState = {127};
            //if (sendState && reconfManager.getStaticConf().getProcessId() == 0) state.setState(badState);
662
            /*******************************************************************************************/
663

664
            int[] targets = { msg.getSender() };
665 666
            SMMessage smsg = new SMMessage(reconfManager.getStaticConf().getProcessId(), 
                    msg.getEid(), TOMUtil.SM_REPLY, -1, state);
667 668 669

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

672 673 674 675 676 677 678 679 680 681 682
            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 *************************/
        }
683 684 685 686
    }

    public void SMReplyDeliver(SMMessage msg) {

687
        /************************* TESTE *************************
688
        System.out.println("[TOMLayer.SMReplyDeliver]");
689
        System.out.println("Recebi uma resposta de uma replica!");
690 691 692
        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());
693
        if (msg.getState().getMessageBatches() != null)
694 695 696 697 698 699 700 701 702 703 704 705 706
            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");
707
        /************************* TESTE *************************/
708
        //******* EDUARDO BEGIN **************//
709 710

        lockTimer.lock();
711 712
        if (reconfManager.getStaticConf().isStateTransferEnabled()) {
        //******* EDUARDO END **************//
713

714 715
            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());
716

717
            if (stateManager.getWaiting() != -1 && msg.getEid() == stateManager.getWaiting()) {
718

719 720 721 722
                /************************* 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!");
723
            
724 725 726
                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());
727
                    if (stateTimer != null) stateTimer.cancel();
728
                }
729

730
                stateManager.addState(msg.getSender(),msg.getState());
731

732
                if (stateManager.moreThanF_Replies()) {
733

734
                    Logger.println("(TOMLayer.SMReplyDeliver) I have at least " + reconfManager.getCurrentViewF() + " replies!");
735
                    /************************* TESTE *************************
736
                    System.out.println("Ja tenho mais que " + reconfManager.getQuorumF() + " respostas iguais!");
737
                    /************************* TESTE *************************/
738

739
                    TransferableState state = stateManager.getValidHash();
740

741 742 743 744 745 746
                    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;
747 748
                            else if (stateManager.getNumValidHashes() > reconfManager.getCurrentViewF()) haveState = -1;

749
                        }
750 751
                    }

752
                    if (state != null && haveState == 1) {
753

754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
                        /************************* 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);
772
                        }
773
                        else System.out.println("[state] Nao ha estado");
774

775 776
                        //System.exit(0);
                        /************************* TESTE *************************/
777

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

780
                        state.setState(stateManager.getReplicaState());
781
                    
782
                        lockState.lock();
783

784
                        stateManager.getLog().update(state);
785

786 787 788 789 790 791 792
                        /************************* 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);
793
                    
794 795 796 797 798 799
                            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);
800
                        }
801 802
                        //System.exit(0);
                        /************************* TESTE *************************/
803

804
                        lockState.unlock();
805

806 807
                        //System.out.println("Desbloqueei o lock para o log do estado");
                        dt.deliverLock();
808

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

811
                        //ot.OutOfContextLock();
812

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

815
                        stateManager.setWaiting(-1);
816

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

819
                        dt.update(state);
820
                        processOutOfContext();
821

822
                        dt.canDeliver();
823

824
                        //ot.OutOfContextUnlock();
825
                        dt.deliverUnlock();
826
                    
827 828
                        stateManager.emptyStates();
                        stateManager.setReplicaState(null);
829

830 831
                        System.out.println("Actualizei o estado!");

832 833 834 835 836 837
                    //******* 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!");
838 839 840 841
                        /************************* TESTE *************************
                        System.out.println("Tenho mais de 2F respostas que nao servem para nada!");
                        //System.exit(0);
                        /************************* TESTE *************************/
842

843 844 845
                        stateManager.setWaiting(-1);
                        stateManager.emptyStates();
                        stateManager.setReplicaState(null);
846 847

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

850
                        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");
851

852 853 854 855
                        stateManager.setWaiting(-1);
                        stateManager.changeReplica();
                        stateManager.emptyStates();
                        stateManager.setReplicaState(null);
856 857

                        if (stateTimer != null) stateTimer.cancel();
858
                    }
859 860 861
                }
            }
        }
862
        lockTimer.unlock();
863
        /************************* TESTE *************************
864 865
        System.out.println("[/TOMLayer.SMReplyDeliver]");
        /************************* TESTE *************************/
P
pjsousa@gmail.com 已提交
866
    }
867 868

    public boolean isRetrievingState() {
869
        //lockTimer.lock();
870
        boolean result =  stateManager != null && stateManager.getWaiting() != -1;
871
        //lockTimer.unlock();
872 873

        return result;
874
    }
875 876

    public void setNoExec() {
877
        Logger.println("(TOMLayer.setNoExec) modifying inExec from " + this.inExecution + " to " + -1);
878 879 880 881 882 883 884 885

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

P
pjsousa@gmail.com 已提交
886
    /********************************************************/
887 888

    public void processOutOfContext() {
B
bessani@gmail.com 已提交
889 890 891 892 893
        for (int nextExecution = getLastExec() + 1;
                execManager.receivedOutOfContextPropose(nextExecution);
                nextExecution = getLastExec() + 1) {
            
            execManager.processOutOfContextPropose(execManager.getExecution(nextExecution));
894 895 896
        }
    }
    /********************************************************************/
897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937

    /*** 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?
938 939
                        byte[] msgs = bb.makeBatch(lcManager.getCurrentRequestTimedOut(), 0, 0, reconfManager);
                        List<TOMMessage> temp = lcManager.getCurrentRequestTimedOut();
940
                        out.writeBoolean(true);
941
                        out.writeObject(msgs);
942 943 944 945 946 947
                    }
                    else {
                        out.writeBoolean(false);
                    }

                    byte[] payload = bos.toByteArray();
948 949 950 951

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

952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
                    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);
1010 1011
                    byte[] msgs = bb.makeBatch(lcManager.getCurrentRequestTimedOut(), 0, 0, reconfManager);
                    out.writeObject(msgs);
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
                }
                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 已提交
1091
                        SignedObject signedCollect = sign(collect);
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103

                        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 已提交
1104
                        SignedObject signedCollect = sign(collect);
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169

                        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 已提交
1170
                SignedObject signedCollect = sign(collect);
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208

                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);

1209
                            boolean hasReqs = ois.readBoolean();
1210 1211
                            clientsManager.getClientsLock().lock();

1212
                            if (hasReqs) {
1213 1214 1215

                                // Guardar os pedidos que a outra replica nao conseguiu ordenar
                                //TODO: Os requests  tem q ser verificados!
1216 1217 1218 1219
                                byte[] temp = (byte[]) ois.readObject();
                                BatchReader batchReader = new BatchReader(temp,
                                        reconfManager.getStaticConf().getUseSignatures() == 1);
                                TOMMessage[] requests = batchReader.deserialiseRequests(reconfManager);
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
                            }
                            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 已提交
1361
                        if (lcManager.sound(lcManager.selectCollects(ts, currentEid))) {
1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401

                            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 已提交
1402
        if (lcManager.sound(lcManager.selectCollects(ts, currentEid))) {
1403 1404 1405

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

B
bessani@gmail.com 已提交
1406
            Consensus cons = new Consensus(-1); // este objecto só serve para obter o batchsize,
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
                                                    // 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 已提交
1465
        } else if (getLastExec() + 1 == lastHighestEid.getEid()) {
1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
        // 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 已提交
1486
        HashSet<CollectData> selectedColls = lcManager.selectCollects(signedCollects, currentEid);
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

        // 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 已提交
1517 1518 1519 1520

            if(exec.getLearner().firstMessageProposed == null)
                exec.getLearner().firstMessageProposed = r.deserializedPropValue[0];
            
1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540
            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 已提交
1541
}