DeliveryThread.java 11.3 KB
Newer Older
P
pjsousa@gmail.com 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/**
 * 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/>.
 */
18
package bftsmart.tom.core;
P
pjsousa@gmail.com 已提交
19

20
import java.util.ArrayList;
P
pjsousa@gmail.com 已提交
21 22
import java.util.concurrent.LinkedBlockingQueue;

23
import java.util.concurrent.locks.Condition;
24
import java.util.concurrent.locks.Lock;
25
import java.util.concurrent.locks.ReentrantLock;
26 27 28

import bftsmart.paxosatwar.Consensus;
import bftsmart.reconfiguration.ServerViewManager;
29
import bftsmart.statemanagement.ApplicationState;
30
import bftsmart.tom.MessageContext;
31
import bftsmart.tom.ServiceReplica;
32 33 34 35 36
import bftsmart.tom.core.messages.TOMMessage;
import bftsmart.tom.core.messages.TOMMessageType;
import bftsmart.tom.server.Recoverable;
import bftsmart.tom.util.BatchReader;
import bftsmart.tom.util.Logger;
P
pjsousa@gmail.com 已提交
37 38 39 40 41

/**
 * This class implements a thread which will deliver totally ordered requests to the application
 * 
 */
B
bessani@gmail.com 已提交
42
public final class DeliveryThread extends Thread {
P
pjsousa@gmail.com 已提交
43 44 45

    private LinkedBlockingQueue<Consensus> decided = new LinkedBlockingQueue<Consensus>(); // decided consensus
    private TOMLayer tomLayer; // TOM layer
46
    private ServiceReplica receiver; // Object that receives requests from clients
47
    private Recoverable recoverer; // Object that uses state transfer
48
    private ServerViewManager manager;
49 50
    private Lock decidedLock = new ReentrantLock();
    private Condition notEmptyQueue = decidedLock.newCondition();
P
pjsousa@gmail.com 已提交
51 52 53 54 55

    /**
     * Creates a new instance of DeliveryThread
     * @param tomLayer TOM layer
     * @param receiver Object that receives requests from clients
56
     * @param conf TOM configuration
P
pjsousa@gmail.com 已提交
57
     */
58
    public DeliveryThread(TOMLayer tomLayer, ServiceReplica receiver, Recoverable recoverer, ServerViewManager manager) {
P
pjsousa@gmail.com 已提交
59 60 61 62
        super("Delivery Thread");

        this.tomLayer = tomLayer;
        this.receiver = receiver;
63
        this.recoverer = recoverer;
64 65 66
        //******* EDUARDO BEGIN **************//
        this.manager = manager;
        //******* EDUARDO END **************//
P
pjsousa@gmail.com 已提交
67 68
    }

69 70 71 72 73
    
   public Recoverable getRecoverer() {
        return recoverer;
    }
   
P
pjsousa@gmail.com 已提交
74 75 76 77 78
    /**
     * Invoked by the TOM layer, to deliver a decide consensus
     * @param cons Consensus established as being decided
     */
    public void delivery(Consensus cons) {
79
        if (!containsGoodReconfig(cons)) {
80 81

            Logger.println("(DeliveryThread.delivery) Consensus ID " + cons.getId() + " does not contain good reconfiguration");
B
bessani@gmail.com 已提交
82 83 84 85 86
            //set this consensus as the last executed
            tomLayer.setLastExec(cons.getId());
            //define that end of this execution
            tomLayer.setInExec(-1);
        }
P
pjsousa@gmail.com 已提交
87
        try {
88
        	decidedLock.lock();
P
pjsousa@gmail.com 已提交
89
            decided.put(cons);
90 91
            notEmptyQueue.signalAll();
            decidedLock.unlock();
B
bessani@gmail.com 已提交
92
            Logger.println("(DeliveryThread.delivery) Consensus " + cons.getId() + " finished. Decided size=" + decided.size());
P
pjsousa@gmail.com 已提交
93 94 95 96
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
    }
B
bessani@gmail.com 已提交
97

98
    private boolean containsGoodReconfig(Consensus cons) {
B
bessani@gmail.com 已提交
99 100 101
        TOMMessage[] decidedMessages = cons.getDeserializedDecision();

        for (TOMMessage decidedMessage : decidedMessages) {
102 103
            if (decidedMessage.getReqType() == TOMMessageType.RECONFIG
                    && decidedMessage.getViewID() == manager.getCurrentViewId()) {
B
bessani@gmail.com 已提交
104 105 106 107 108 109
                return true;
            }
        }
        return false;
    }

R
reiser@cs.fau.de 已提交
110
    /** THIS IS JOAO'S CODE, TO HANDLE STATE TRANSFER */
111 112 113 114
    private ReentrantLock deliverLock = new ReentrantLock();
    private Condition canDeliver = deliverLock.newCondition();

    public void deliverLock() {
115 116 117 118 119
    	// release the delivery lock to avoid blocking on state transfer
		decidedLock.lock();
		notEmptyQueue.signalAll();
		decidedLock.unlock();
    	
120 121
        deliverLock.lock();
    }
122

123 124 125 126 127 128 129
    public void deliverUnlock() {
        deliverLock.unlock();
    }

    public void canDeliver() {
        canDeliver.signalAll();
    }
130

131
    public void update(ApplicationState state) {
132
       
133
        int lastEid =  recoverer.setState(state);
134

135
        //set this consensus as the last executed
136
        System.out.println("Setting last EID to " + lastEid);
137 138 139 140 141
        tomLayer.setLastExec(lastEid);

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

            //tomLayer.lm.removeStableMultipleConsenusInfos(lastCheckpointEid, stableConsensus);
145
            tomLayer.execManager.removeOutOfContexts(stableConsensus);
146 147 148
        }

        //define that end of this execution
149
        //stateManager.setWaiting(-1);
150
        tomLayer.setNoExec();
151

152
        System.out.print("Current decided size: " + decided.size());
153
        decided.clear();
154

155
        System.out.println("(DeliveryThread.update) All finished up to " + lastEid);
156 157
    }

P
pjsousa@gmail.com 已提交
158
    /**
B
bessani@gmail.com 已提交
159 160
     * This is the code for the thread. It delivers decided consensus to the TOM
     * request receiver object (which is the application)
P
pjsousa@gmail.com 已提交
161 162 163 164
     */
    @Override
    public void run() {
        while (true) {
165 166 167 168 169 170 171 172 173 174 175 176 177 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 203 204 205 206 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
  			/** THIS IS JOAO'S CODE, TO HANDLE STATE TRANSFER */
  			deliverLock();
  			while (tomLayer.isRetrievingState()) {
  				System.out.println("(DeliveryThread.run) Retrieving State.");
  				canDeliver.awaitUninterruptibly();
  				System.out.println("(DeliveryThread.run) canDeliver unleashed.");
  			}
  			try {
  				ArrayList<Consensus> consensuses = new ArrayList<Consensus>();
  				decidedLock.lock();
  				if(decided.isEmpty()) {
  					notEmptyQueue.await();
  				}
  				decided.drainTo(consensuses);
  				decidedLock.unlock();
  				if (consensuses.size() > 0) {
  					TOMMessage[][] requests = new TOMMessage[consensuses.size()][];
					int[] consensusIds = new int[requests.length];
  					int count = 0;
  					for (Consensus c : consensuses) {
  						requests[count] = extractMessagesFromDecision(c);
						consensusIds[count] = c.getId();
  						// cons.firstMessageProposed contains the performance counters
  						if (requests[count][0].equals(c.firstMessageProposed)) {
  	                    	long time = requests[count][0].timestamp;
  							requests[count][0] = c.firstMessageProposed;
  	                        requests[count][0].timestamp = time;
  						}
  						
  						count++;
  					}

  					Consensus lastConsensus = consensuses.get(consensuses.size() - 1);

  					if (requests != null && requests.length > 0) {
  						// clean the ordered messages from the pending buffer
  						for(int i = 0; i < requests.length; i++) {
  							tomLayer.clientsManager.requestsOrdered(requests[i]);
  						}
  						
  						deliverMessages(consensusIds, tomLayer.getLCManager().getLastReg(), requests);

  						// ******* EDUARDO BEGIN ***********//
  						if (manager.hasUpdates()) {
  							processReconfigMessages(lastConsensus.getId(),
  									lastConsensus.getDecisionRound()
  											.getNumber());

  							// set this consensus as the last executed
  							tomLayer.setLastExec(lastConsensus.getId());
  							// define that end of this execution
  							tomLayer.setInExec(-1);
  							// ******* EDUARDO END **************//
  						}
  					}

  					// define the last stable consensus... the stable consensus can
  					// be removed from the leaderManager and the executionManager
  					// TODO: Is this part necessary? If it is, can we put it
  					// inside setLastExec
  					int eid = lastConsensus.getId();
  					if (eid > 2) {
  						int stableConsensus = eid - 3;

  						tomLayer.lm.removeStableConsenusInfos(stableConsensus);
  						tomLayer.execManager.removeExecution(stableConsensus);
  					}
  				}
  			} catch (Exception e) {
  				e.printStackTrace(System.err);
  			}

  			/** THIS IS JOAO'S CODE, TO HANDLE STATE TRANSFER */
  			deliverUnlock();
  			/******************************************************************/
  		}
B
bessani@gmail.com 已提交
241
    }
242
    
B
bessani@gmail.com 已提交
243
    private TOMMessage[] extractMessagesFromDecision(Consensus cons) {
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
    	TOMMessage[] requests = (TOMMessage[]) cons.getDeserializedDecision();
    	if (requests == null) {
    		// there are no cached deserialized requests
    		// this may happen if this batch proposal was not verified
    		// TODO: this condition is possible?

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

    		// obtain an array of requests from the taken consensus
    		BatchReader batchReader = new BatchReader(cons.getDecision(),
    				manager.getStaticConf().getUseSignatures() == 1);
    		requests = batchReader.deserialiseRequests(manager);
    	} else {
    		Logger.println("(DeliveryThread.run) using cached requests from the propose.");
    	}

    	return requests;
B
bessani@gmail.com 已提交
261
    }
262
    
263
    public void deliverUnordered(TOMMessage request, int regency) {
B
bessani@gmail.com 已提交
264
        MessageContext msgCtx = new MessageContext(System.currentTimeMillis(),
265
                new byte[0], regency, -1, request.getSender(), null);
266
        receiver.receiveReadonlyMessage(request, msgCtx);
B
bessani@gmail.com 已提交
267 268
    }

269 270
    private void deliverMessages(int consId[], int regency, TOMMessage[][] requests) {
        receiver.receiveMessages(consId, regency, requests);
B
bessani@gmail.com 已提交
271 272 273 274 275 276 277 278 279 280
    }

    private void processReconfigMessages(int consId, int decisionRoundNumber) {
        byte[] response = manager.executeUpdates(consId, decisionRoundNumber);
        TOMMessage[] dests = manager.clearUpdates();

        for (int i = 0; i < dests.length; i++) {
            tomLayer.getCommunication().send(new int[]{dests[i].getSender()},
                    new TOMMessage(manager.getStaticConf().getProcessId(),
                    dests[i].getSession(), dests[i].getSequence(), response,
281
                    manager.getCurrentViewId(),TOMMessageType.RECONFIG));
B
bessani@gmail.com 已提交
282 283 284 285 286 287 288 289 290
        }

        tomLayer.getCommunication().updateServersConnections();
    }

    private void logDecision(Consensus cons) {
        if (manager.getStaticConf().getCheckpointPeriod() > 0) {
            if ((cons.getId() > 0) && ((cons.getId() % manager.getStaticConf().getCheckpointPeriod()) == 0)) {
                Logger.println("(DeliveryThread.run) Performing checkpoint for consensus " + cons.getId());
291 292
                //byte[] state = receiver.getState();
                //tomLayer.getStateManager().saveState(state, cons.getId(), cons.getDecisionRound().getNumber(), tomLayer.lm.getCurrentLeader()/*tomLayer.lm.getLeader(cons.getId(), cons.getDecisionRound().getNumber())*/);
B
bessani@gmail.com 已提交
293 294
            } else {
                Logger.println("(DeliveryThread.run) Storing message batch in the state log for consensus " + cons.getId());
295
                //tomLayer.getStateManager().saveBatch(cons.getDecision(), cons.getId(), cons.getDecisionRound().getNumber(), tomLayer.lm.getCurrentLeader()/*tomLayer.lm.getLeader(cons.getId(), cons.getDecisionRound().getNumber())*/);
P
pjsousa@gmail.com 已提交
296 297 298 299
            }
        }
    }
}