DeliveryThread.java 15.8 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 26
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
P
pjsousa@gmail.com 已提交
27
import navigators.smart.paxosatwar.Consensus;
28
import navigators.smart.statemanagment.StateManager;
29
import navigators.smart.statemanagment.TransferableState;
P
pjsousa@gmail.com 已提交
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 75 76 77
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);
        }
    }

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

    public void deliverLock() {
        deliverLock.lock();
    }
86

87 88 89 90 91 92 93
    public void deliverUnlock() {
        deliverLock.unlock();
    }

    public void canDeliver() {
        canDeliver.signalAll();
    }
94 95
    public void update(TransferableState state) {

96 97
        //deliverLock.lock();
        
98
        receiver.setState(state.getState());
99

100 101 102
        int lastCheckpointEid = state.getLastCheckpointEid();
        int lastEid = state.getLastEid();

103
        for (int eid = lastCheckpointEid + 1; eid <= lastEid; eid++) {
104 105 106 107 108 109 110 111

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

112
                Logger.println("(DeliveryThread.update) interpreting and verifying batched requests.");
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 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175

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

176
                /****** Julgo que isto nao sera necessario ***********
177 178
                if (conf.getCheckpoint_period() > 0) {
                    if ((eid > 0) && (eid % conf.getCheckpoint_period() == 0)) {
179
                        Logger.println("(DeliveryThread.update) Performing checkpoint for consensus " + eid);
180 181 182 183 184
                        byte[] state2 = receiver.getState();
                        tomLayer.saveState(state2, eid);
                        //TODO: possivelmente fazer mais alguma coisa
                    }
                    else {
185
                        Logger.println("(DeliveryThread.update) Storing message batch in the state log for consensus " + eid);
186 187 188 189
                        tomLayer.saveBatch(batch, eid);
                        //TODO: possivelmente fazer mais alguma coisa
                    }
                }
190
                */
191 192 193 194 195 196
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

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) {
203
            int stableConsensus = lastEid - 3;
204 205

            //tomLayer.lm.removeStableMultipleConsenusInfos(lastCheckpointEid, stableConsensus);
206
            tomLayer.execManager.removeOutOfContexts(stableConsensus);
207 208 209
        }

        //define that end of this execution
210
        //stateManager.setWaiting(-1);
211 212
        tomLayer.setInExec(-1);

213
        decided.clear();
214 215 216 217
        //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 *****/
218 219 220 221
        //int nextExecution = lastEid + 1;
        //if(tomLayer.acceptor.executeAcceptedPendent(nextExecution)) {
        //Logger.println("(DeliveryThread.update) Executed propose for " + nextExecution);
        //}
222 223
        /******************************************************************/

224 225
        //canDeliver.signalAll();
        //deliverLock.unlock();
226 227 228 229
    }
    
    /********************************************************/

P
pjsousa@gmail.com 已提交
230 231 232 233 234
    /**
     * 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() {
235

P
pjsousa@gmail.com 已提交
236 237
        long startTime;
        while (true) {
238 239 240 241 242 243 244 245 246 247 248

            /** ISTO E CODIGO DO JOAO, PARA TRATAR DA TRANSFERENCIA DE ESTADO */
            deliverLock.lock();

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

P
pjsousa@gmail.com 已提交
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 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
            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]);
                }

345
                /** ISTO E CODIGO DO JOAO, PARA TRATAR DOS CHECKPOINTS */
346 347 348 349

                System.out.println("[DeliveryThread.run]");
                System.out.println("Acabei de entregar o batch do EID " + cons.getId());
                System.out.println("[/DeliveryThread.run]");
P
pjsousa@gmail.com 已提交
350
                if (conf.getCheckpoint_period() > 0) {
351
                    if ((cons.getId() > 0) && ((cons.getId() % conf.getCheckpoint_period()) == 0)) {
P
pjsousa@gmail.com 已提交
352 353
                        Logger.println("(DeliveryThread.run) Performing checkpoint for consensus " + cons.getId());
                        byte[] state = receiver.getState();
354
                        tomLayer.saveState(state, cons.getId());
P
pjsousa@gmail.com 已提交
355 356 357 358
                        //TODO: possivelmente fazer mais alguma coisa
                    }
                    else {
                        Logger.println("(DeliveryThread.run) Storing message batch in the state log for consensus " + cons.getId());
359
                        tomLayer.saveBatch(cons.getDecision(), cons.getId());
P
pjsousa@gmail.com 已提交
360 361 362 363 364 365 366 367 368
                        //TODO: possivelmente fazer mais alguma coisa
                    }
                }
                /********************************************************/

                Logger.println("(DeliveryThread.run) All finished for " + cons.getId() + ", took " + (System.currentTimeMillis() - startTime));
            } catch (Exception e) {
                e.printStackTrace();
            }
369 370 371 372
            /** ISTO E CODIGO DO JOAO, PARA TRATAR DA TRANSFERENCIA DE ESTADO */
            deliverLock.unlock();
            /******************************************************************/

P
pjsousa@gmail.com 已提交
373 374 375
        }
    }
}