DeliveryThread.java 10.1 KB
Newer Older
P
pjsousa@gmail.com 已提交
1
/**
2 3 4 5 6 7 8 9 10 11 12 13 14 15
Copyright (c) 2007-2013 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
16
package bftsmart.tom.core;
P
pjsousa@gmail.com 已提交
17

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

21
import java.util.concurrent.locks.Condition;
22
import java.util.concurrent.locks.Lock;
23
import java.util.concurrent.locks.ReentrantLock;
24 25 26

import bftsmart.paxosatwar.Consensus;
import bftsmart.reconfiguration.ServerViewManager;
27
import bftsmart.statemanagement.ApplicationState;
28
import bftsmart.tom.MessageContext;
29
import bftsmart.tom.ServiceReplica;
30 31 32 33 34
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 已提交
35 36 37 38 39

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

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

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

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

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

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

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

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

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

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

126 127 128 129 130 131 132
    public void deliverUnlock() {
        deliverLock.unlock();
    }

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

134
    public void update(ApplicationState state) {
135
       
136
        int lastEid =  recoverer.setState(state);
137

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

        //define the last stable consensus... the stable consensus can
        //be removed from the leaderManager and the executionManager
        if (lastEid > 2) {
145 146
            int stableConsensus = lastEid - 3;
            tomLayer.execManager.removeOutOfContexts(stableConsensus);
147 148 149
        }

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

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

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

P
pjsousa@gmail.com 已提交
159
    /**
B
bessani@gmail.com 已提交
160 161
     * 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 已提交
162 163 164 165
     */
    @Override
    public void run() {
        while (true) {
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
  			/** 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) {
  						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 已提交
237
    }
238
    
B
bessani@gmail.com 已提交
239
    private TOMMessage[] extractMessagesFromDecision(Consensus cons) {
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
    	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 已提交
257
    }
258
    
259
    protected void deliverUnordered(TOMMessage request, int regency) {
B
bessani@gmail.com 已提交
260
        MessageContext msgCtx = new MessageContext(System.currentTimeMillis(),
261
                new byte[0], regency, -1, request.getSender(), null);
262
        receiver.receiveReadonlyMessage(request, msgCtx);
B
bessani@gmail.com 已提交
263 264
    }

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

    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,
277
                    manager.getCurrentViewId(),TOMMessageType.RECONFIG));
B
bessani@gmail.com 已提交
278 279 280 281 282
        }

        tomLayer.getCommunication().updateServersConnections();
    }

P
pjsousa@gmail.com 已提交
283
}