DeliveryThread.java 14.4 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 25
/**
 * 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;

import navigators.smart.paxosatwar.Consensus;
26
import navigators.smart.statemanagment.TransferableState;
P
pjsousa@gmail.com 已提交
27 28 29 30 31 32 33 34 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
import navigators.smart.tom.TOMRequestReceiver;
import navigators.smart.tom.core.messages.TOMMessage;
import navigators.smart.tom.util.BatchReader;
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);
        }
    }

75 76 77 78 79
    /** ISTO E CODIGO DO JOAO, PARA TRATAR DA TRANSFERENCIA DE ESTADO */

    public void update(TransferableState state) {

        receiver.setState(state.getState());
80

81 82 83
        int lastCheckpointEid = state.getLastCheckpointEid();
        int lastEid = state.getLastEid();

84
        for (int eid = lastCheckpointEid + 1; eid <= lastEid; eid++) {
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156

            try {

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

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

                Logger.println("(DeliveryThread.run) interpreting and verifying batched requests.");

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

                        /******* 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) {
                        e.printStackTrace();
                    }
                }

                //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]);
                }

157
                /****** Julgo que isto nao sera necessario ***********
158 159 160 161 162 163 164 165 166 167 168 169 170
                if (conf.getCheckpoint_period() > 0) {
                    if ((eid > 0) && (eid % conf.getCheckpoint_period() == 0)) {
                        Logger.println("(DeliveryThread.run) Performing checkpoint for consensus " + eid);
                        byte[] state2 = receiver.getState();
                        tomLayer.saveState(state2, eid);
                        //TODO: possivelmente fazer mais alguma coisa
                    }
                    else {
                        Logger.println("(DeliveryThread.run) Storing message batch in the state log for consensus " + eid);
                        tomLayer.saveBatch(batch, eid);
                        //TODO: possivelmente fazer mais alguma coisa
                    }
                }
171
                */
172 173 174 175 176 177
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
        //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) {
        int stableConsensus = lastEid - 3;

            //tomLayer.lm.removeStableMultipleConsenusInfos(lastCheckpointEid, stableConsensus);
            //tomLayer.execManager.removeExecutions(stableConsensus);
        }

        //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
        /** Nao consigo perceber se isto tem utilidade neste contexto *****/
        int nextExecution = lastEid + 1;
        if(tomLayer.acceptor.executeAcceptedPendent(nextExecution)) {
            Logger.println("(DeliveryThread.run) Executed propose for " + nextExecution);
        }
        /******************************************************************/

203 204 205 206
    }
    
    /********************************************************/

P
pjsousa@gmail.com 已提交
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 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 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
    /**
     * 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() {
        long startTime;
        while (true) {
            try {
                Consensus cons = decided.take(); // take a decided consensus
                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;
                            requests[i] = tm;
                            //requests[i] = (TOMMessage) ois.readObject();
                            tomLayer.clientsManager.requestOrdered(requests[i]);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    Logger.println("(DeliveryThread.run) using cached requests from the propose.");
                    tomLayer.clientsManager.getClientsLock().lock();
                    for (int i = 0; i < requests.length; i++) {
                        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
                if (cons.getId() > 2) {
                    int stableConsensus = cons.getId() - 3;

                    tomLayer.lm.removeStableConsenusInfos(stableConsensus);
                    tomLayer.execManager.removeExecution(stableConsensus);
                }

                //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]);
                }

310
                /** ISTO E CODIGO DO JOAO, PARA TRATAR DOS CHECKPOINTS */
P
pjsousa@gmail.com 已提交
311
                if (conf.getCheckpoint_period() > 0) {
312
                    if ((cons.getId() > 0) && ((cons.getId() % conf.getCheckpoint_period()) == 0)) {
P
pjsousa@gmail.com 已提交
313 314
                        Logger.println("(DeliveryThread.run) Performing checkpoint for consensus " + cons.getId());
                        byte[] state = receiver.getState();
315
                        tomLayer.saveState(state, cons.getId());
P
pjsousa@gmail.com 已提交
316 317 318 319
                        //TODO: possivelmente fazer mais alguma coisa
                    }
                    else {
                        Logger.println("(DeliveryThread.run) Storing message batch in the state log for consensus " + cons.getId());
320
                        tomLayer.saveBatch(cons.getDecision(), cons.getId());
P
pjsousa@gmail.com 已提交
321 322 323 324 325 326 327 328 329 330 331 332
                        //TODO: possivelmente fazer mais alguma coisa
                    }
                }
                /********************************************************/

                Logger.println("(DeliveryThread.run) All finished for " + cons.getId() + ", took " + (System.currentTimeMillis() - startTime));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}