DeliveryThread.java 18.6 KB
Newer Older
P
pjsousa@gmail.com 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/**
 * 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;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.util.concurrent.LinkedBlockingQueue;

25
import java.util.concurrent.TimeUnit;
26 27
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
P
pjsousa@gmail.com 已提交
28
import navigators.smart.paxosatwar.Consensus;
29
import navigators.smart.statemanagment.StateManager;
30
import navigators.smart.statemanagment.TransferableState;
P
pjsousa@gmail.com 已提交
31 32 33
import navigators.smart.tom.TOMRequestReceiver;
import navigators.smart.tom.core.messages.TOMMessage;
import navigators.smart.tom.util.BatchReader;
34
import navigators.smart.tom.util.DebugInfo;
P
pjsousa@gmail.com 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
import navigators.smart.tom.util.Logger;
import navigators.smart.tom.util.TOMConfiguration;
import navigators.smart.tom.util.TOMUtil;


/**
 * This class implements a thread which will deliver totally ordered requests to the application
 * 
 */
public class DeliveryThread extends Thread {

    private LinkedBlockingQueue<Consensus> decided = new LinkedBlockingQueue<Consensus>(); // decided consensus
    private TOMLayer tomLayer; // TOM layer
    private RequestRecover requestRecover; // TODO: isto ainda vai ser usado?
    private TOMRequestReceiver receiver; // Object that receives requests from clients
    private TOMConfiguration conf;

    /**
     * Creates a new instance of DeliveryThread
     * @param tomLayer TOM layer
     * @param receiver Object that receives requests from clients
     * @param conf TOM configuration
     */
    public DeliveryThread(TOMLayer tomLayer, TOMRequestReceiver receiver, TOMConfiguration conf) {
        super("Delivery Thread");

        this.tomLayer = tomLayer;
        this.receiver = receiver;
        this.conf = conf;
        this.requestRecover = new RequestRecover(tomLayer, conf);
    }

    /**
     * Invoked by the TOM layer, to deliver a decide consensus
     * @param cons Consensus established as being decided
     */
    public void delivery(Consensus cons) {
        try {
            decided.put(cons);
            Logger.println("(DeliveryThread.delivery) Consensus " + cons.getId() + " finished. decided size=" + decided.size());
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
    }

80
    /** ISTO E CODIGO DO JOAO, PARA TRATAR DA TRANSFERENCIA DE ESTADO */
81 82 83 84 85 86
    
    private ReentrantLock deliverLock = new ReentrantLock();
    private Condition canDeliver = deliverLock.newCondition();

    public void deliverLock() {
        deliverLock.lock();
87
        Logger.println("(DeliveryThread.deliverLock) Deliver lock obtained");
88
    }
89

90 91
    public void deliverUnlock() {
        deliverLock.unlock();
92
        Logger.println("(DeliveryThread.deliverUnlock) Deliver Released");
93 94 95 96 97
    }

    public void canDeliver() {
        canDeliver.signalAll();
    }
98 99
    public void update(TransferableState state) {

100
        //deliverLock.lock();
101

102 103
        int lastCheckpointEid = state.getLastCheckpointEid();
        int lastEid = state.getLastEid();
104

105
        Logger.println("(DeliveryThread.update) I'm going to update myself from EID " + lastCheckpointEid + " to EID " + lastEid);
106

107
        receiver.setState(state.getState());
108

109
        tomLayer.lm.addLeaderInfo(lastCheckpointEid, state.getLastCheckpointRound(), state.getLastCheckpointLeader());
110

111
        for (int eid = lastCheckpointEid + 1; eid <= lastEid; eid++) {
112 113 114

            try {

115
                byte[] batch = state.getMessageBatch(eid).batch; // take a batch
116

117 118
                tomLayer.lm.addLeaderInfo(eid, state.getMessageBatch(eid).round, state.getMessageBatch(eid).leader);

119 120 121
                // obtain an array of requests from the taken consensus
                BatchReader batchReader = new BatchReader(batch, conf.getUseSignatures()==1);

122
                Logger.println("(DeliveryThread.update) interpreting and verifying batched requests.");
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146

                int numberOfMessages = batchReader.getNumberOfMessages();

                TOMMessage[] requests = new TOMMessage[numberOfMessages];

                for (int i = 0; i < numberOfMessages; i++) {
                    
                    //read the message and its signature from the batch
                    int messageSize = batchReader.getNextMessageSize();

                    byte[] message = new byte[messageSize];
                    batchReader.getNextMessage(message);

                    byte[] signature = null;
                    if (conf.getUseSignatures()==1){
                        signature = new byte[TOMUtil.getSignatureSize()];
                        batchReader.getNextSignature(signature);
                   }

                    try {
                        DataInputStream ois = new DataInputStream(new ByteArrayInputStream(message));
                        TOMMessage tm = new TOMMessage();
                        tm.readExternal(ois);

147 148 149
                        if (Logger.debug)
                            tm.setSequence(new DebugInfo(eid, state.getMessageBatch(eid).round, state.getMessageBatch(eid).leader));

150 151 152 153 154 155 156 157 158 159 160 161 162
                        /******* Deixo isto comentado, pois nao me parece necessario      ****/
                        /******* Alem disso, esta informacao nao vem no TransferableState ****

                        tm.consensusStartTime = cons.startTime;
                        tm.consensusExecutionTime = cons.executionTime;
                        tm.consensusBatchSize = cons.batchSize;

                        /*********************************************************************/

                        requests[i] = tm;
                        //requests[i] = (TOMMessage) ois.readObject();
                        tomLayer.clientsManager.requestOrdered(requests[i]);
                    } catch (Exception e) {
163
                        e.printStackTrace(System.out);
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
                    }
                }

                //obtain the nonce and timestamps to be delivered to the application
                long timestamp = batchReader.getTimestamp();
                byte[] nonces = new byte[batchReader.getNumberOfNonces()];
                if (nonces.length > 0) {
                    batchReader.getNonces(nonces);
                }

                //deliver the request to the application (receiver)
                for (int i = 0; i < requests.length; i++) {
                    requests[i].timestamp = timestamp;
                    requests[i].nonces = nonces;

                    /******* Deixo isto comentado, pois nao me parece necessario      **********/
                    /******* Alem disso, esta informacao nao vem no TransferableState **********

                    requests[i].requestTotalLatency = System.currentTimeMillis()-cons.startTime;

                    /***************************************************************************/
                    
                    receiver.receiveOrderedMessage(requests[i]);
                }

189
                /****** Julgo que isto nao sera necessario ***********
190 191
                if (conf.getCheckpoint_period() > 0) {
                    if ((eid > 0) && (eid % conf.getCheckpoint_period() == 0)) {
192
                        Logger.println("(DeliveryThread.update) Performing checkpoint for consensus " + eid);
193 194 195 196 197
                        byte[] state2 = receiver.getState();
                        tomLayer.saveState(state2, eid);
                        //TODO: possivelmente fazer mais alguma coisa
                    }
                    else {
198
                        Logger.println("(DeliveryThread.update) Storing message batch in the state log for consensus " + eid);
199 200 201 202
                        tomLayer.saveBatch(batch, eid);
                        //TODO: possivelmente fazer mais alguma coisa
                    }
                }
203
                */
204
            } catch (Exception e) {
205
                e.printStackTrace(System.out);
206 207 208 209
            }

        }

210 211 212 213 214 215
        //set this consensus as the last executed
        tomLayer.setLastExec(lastEid);

        //define the last stable consensus... the stable consensus can
        //be removed from the leaderManager and the executionManager
        if (lastEid > 2) {
216
            int stableConsensus = lastEid - 3;
217 218

            //tomLayer.lm.removeStableMultipleConsenusInfos(lastCheckpointEid, stableConsensus);
219
            tomLayer.execManager.removeOutOfContexts(stableConsensus);
220 221 222
        }

        //define that end of this execution
223
        //stateManager.setWaiting(-1);
224
        tomLayer.setNoExec();
225

226
        decided.clear();
227 228

        Logger.println("(DeliveryThread.update) All finished from " + lastCheckpointEid + " to " + lastEid);
229 230 231 232
        //verify if there is a next proposal to be executed
        //(it only happens if the previous consensus were decided in a
        //round > 0
        /** Nao consigo perceber se isto tem utilidade neste contexto *****/
233 234 235 236
        //int nextExecution = lastEid + 1;
        //if(tomLayer.acceptor.executeAcceptedPendent(nextExecution)) {
        //Logger.println("(DeliveryThread.update) Executed propose for " + nextExecution);
        //}
237 238
        /******************************************************************/

239 240
        //canDeliver.signalAll();
        //deliverLock.unlock();
241 242 243 244
    }
    
    /********************************************************/

P
pjsousa@gmail.com 已提交
245 246 247 248 249
    /**
     * This is the code for the thread. It delivers decided consensus to the TOM request receiver object (which is the application)
     */
    @Override
    public void run() {
250

P
pjsousa@gmail.com 已提交
251 252
        long startTime;
        while (true) {
253 254

            /** ISTO E CODIGO DO JOAO, PARA TRATAR DA TRANSFERENCIA DE ESTADO */
255
            deliverLock();
256 257 258 259 260 261 262 263

            //if (tomLayer != null) {
                while (tomLayer.isRetrievingState()) {
                    canDeliver.awaitUninterruptibly();
                }
            //}
            /******************************************************************/

P
pjsousa@gmail.com 已提交
264
            try {
265 266 267 268 269 270 271 272 273 274 275 276
                
                //Consensus cons = decided.take(); // take a decided consensus
                /** ISTO E CODIGO DO JOAO, PARA TRATAR DA TRANSFERENCIA DE ESTADO */
                Logger.println("(DeliveryThread.run) Waiting for a consensus to be delivered.");
                Consensus cons = decided.poll(1500, TimeUnit.MILLISECONDS); // take a decided consensus
                if (cons == null) {
                    Logger.println("(DeliveryThread.run) Timeout while waiting for a consensus, starting over.");
                    deliverUnlock();
                    continue;
                }
                Logger.println("(DeliveryThread.run) A consensus was delivered.");
                /******************************************************************/
P
pjsousa@gmail.com 已提交
277 278 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 309 310 311
                startTime = System.currentTimeMillis();

                //TODO: avoid the case in which the received valid proposal is
                //different from the decided value

                // obtain an array of requests from the taken consensus
                BatchReader batchReader = new BatchReader(cons.getDecision(), conf.getUseSignatures()==1);
                TOMMessage[] requests = (TOMMessage[]) cons.getDeserializedDecision();

                if (requests == null) {
                    Logger.println("(DeliveryThread.run) interpreting and verifying batched requests.");
                    int numberOfMessages = batchReader.getNumberOfMessages();

                    requests = new TOMMessage[numberOfMessages];

                    for (int i = 0; i < numberOfMessages; i++) {
                        //read the message and its signature from the batch
                        int messageSize = batchReader.getNextMessageSize();

                        byte[] message = new byte[messageSize];
                        batchReader.getNextMessage(message);

                        byte[] signature = null;
                        if (conf.getUseSignatures()==1){
                            signature = new byte[TOMUtil.getSignatureSize()];
                            batchReader.getNextSignature(signature);
                        }

                        try {
                            DataInputStream ois = new DataInputStream(new ByteArrayInputStream(message));
                            TOMMessage tm = new TOMMessage();
                            tm.readExternal(ois);
                            tm.consensusStartTime = cons.startTime;
                            tm.consensusExecutionTime = cons.executionTime;
                            tm.consensusBatchSize = cons.batchSize;
312 313 314 315 316 317

                            /** ISTO E CODIGO DO JOAO, PARA TRATAR DE DEBUGGING */
                            if (Logger.debug)
                                tm.setSequence(new DebugInfo(cons.getId(), cons.getDecisionRound().getNumber(), tomLayer.lm.getLeader(cons.getId(), cons.getDecisionRound().getNumber())));
                            /****************************************************/
                            
P
pjsousa@gmail.com 已提交
318 319 320 321
                            requests[i] = tm;
                            //requests[i] = (TOMMessage) ois.readObject();
                            tomLayer.clientsManager.requestOrdered(requests[i]);
                        } catch (Exception e) {
322
                            e.printStackTrace(System.out);
P
pjsousa@gmail.com 已提交
323 324 325 326 327 328
                        }
                    }
                } else {
                    Logger.println("(DeliveryThread.run) using cached requests from the propose.");
                    tomLayer.clientsManager.getClientsLock().lock();
                    for (int i = 0; i < requests.length; i++) {
329 330 331 332 333 334

                        /** ISTO E CODIGO DO JOAO, PARA TRATAR DE DEBUGGING */
                        if (Logger.debug)
                            requests[i].setSequence(new DebugInfo(cons.getId(), cons.getDecisionRound().getNumber(), tomLayer.lm.getLeader(cons.getId(), cons.getDecisionRound().getNumber())));
                        /****************************************************/

P
pjsousa@gmail.com 已提交
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
                        requests[i].consensusStartTime = cons.startTime;
                        requests[i].consensusExecutionTime = cons.executionTime;
                        requests[i].consensusBatchSize = cons.batchSize;
                        tomLayer.clientsManager.requestOrdered(requests[i]);
                    }
                    tomLayer.clientsManager.getClientsLock().unlock();

                    batchReader.skipMessages();
                }

                //set this consensus as the last executed
                tomLayer.setLastExec(cons.getId());

                //define the last stable consensus... the stable consensus can
                //be removed from the leaderManager and the executionManager
350
                /**/
P
pjsousa@gmail.com 已提交
351 352 353 354 355 356
                if (cons.getId() > 2) {
                    int stableConsensus = cons.getId() - 3;

                    tomLayer.lm.removeStableConsenusInfos(stableConsensus);
                    tomLayer.execManager.removeExecution(stableConsensus);
                }
357
                /**/
P
pjsousa@gmail.com 已提交
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
                //define that end of this execution
                tomLayer.setInExec(-1);

                //verify if there is a next proposal to be executed
                //(it only happens if the previous consensus were decided in a
                //round > 0
                int nextExecution = cons.getId() + 1;
                if(tomLayer.acceptor.executeAcceptedPendent(nextExecution)) {
                    Logger.println("(DeliveryThread.run) Executed propose for " + nextExecution);
                }

                //obtain the nonce and timestamps to be delivered to the application
                long timestamp = batchReader.getTimestamp();
                byte[] nonces = new byte[batchReader.getNumberOfNonces()];
                if (nonces.length > 0) {
                    batchReader.getNonces(nonces);
                }

                //deliver the request to the application (receiver)
                for (int i = 0; i < requests.length; i++) {
                    requests[i].timestamp = timestamp;
                    requests[i].nonces = nonces;
                    requests[i].requestTotalLatency = System.currentTimeMillis()-cons.startTime;
                    receiver.receiveOrderedMessage(requests[i]);
                }

384
                /** ISTO E CODIGO DO JOAO, PARA TRATAR DOS CHECKPOINTS */
385

386 387
                Logger.println("(DeliveryThread.run) I just delivered the batch of EID " + cons.getId());

388 389 390 391 392 393 394 395 396 397 398 399 400 401
                if (conf.isStateTransferEnabled()) {
                    Logger.println("(DeliveryThread.run) The state transfer protocol is enabled");
                    if (conf.getCheckpoint_period() > 0) {
                        if ((cons.getId() > 0) && ((cons.getId() % conf.getCheckpoint_period()) == 0)) {
                            Logger.println("(DeliveryThread.run) Performing checkpoint for consensus " + cons.getId());
                            byte[] state = receiver.getState();
                            tomLayer.saveState(state, cons.getId(), cons.getDecisionRound().getNumber(), tomLayer.lm.getLeader(cons.getId(), cons.getDecisionRound().getNumber()));
                            //TODO: possivelmente fazer mais alguma coisa
                        }
                        else {
                            Logger.println("(DeliveryThread.run) Storing message batch in the state log for consensus " + cons.getId());
                            tomLayer.saveBatch(cons.getDecision(), cons.getId(), cons.getDecisionRound().getNumber(), tomLayer.lm.getLeader(cons.getId(), cons.getDecisionRound().getNumber()));
                            //TODO: possivelmente fazer mais alguma coisa
                        }
P
pjsousa@gmail.com 已提交
402 403 404 405 406 407
                    }
                }
                /********************************************************/

                Logger.println("(DeliveryThread.run) All finished for " + cons.getId() + ", took " + (System.currentTimeMillis() - startTime));
            } catch (Exception e) {
408
                e.printStackTrace(System.out);
P
pjsousa@gmail.com 已提交
409
            }
410
            /** ISTO E CODIGO DO JOAO, PARA TRATAR DA TRANSFERENCIA DE ESTADO */
411
            deliverUnlock();
412 413
            /******************************************************************/

P
pjsousa@gmail.com 已提交
414 415 416
        }
    }
}