AsynchServiceProxy.java 21.2 KB
Newer Older
1 2 3
package bftsmart.tom;

import bftsmart.communication.client.ReplyListener;
4
import bftsmart.reconfiguration.views.View;
5 6
import bftsmart.tom.core.messages.TOMMessage;
import bftsmart.tom.core.messages.TOMMessageType;
7
import bftsmart.tom.util.Extractor;
8
import bftsmart.tom.util.KeyLoader;
9
import bftsmart.tom.util.TOMUtil;
10
import java.nio.ByteBuffer;
11
import java.util.Arrays;
12
import java.util.Comparator;
13
import java.util.HashMap;
14 15 16 17 18
import java.util.HashSet;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
19

20 21 22
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

23
/**
24 25
 * This class is an extension of 'ServiceProxy' that can waits for replies
 * asynchronously.
26
 *
27
 */
28
public class AsynchServiceProxy extends ServiceProxy {
29 30
    
    private Logger logger = LoggerFactory.getLogger(this.getClass());
31

32 33 34
    private HashMap<Integer, RequestContext> requestsContext;
    private HashMap<Integer, TOMMessage[]> requestsReplies;
    private HashMap<Integer, Integer> requestsAlias;
35 36 37 38 39 40 41
    private HashSet<Integer> requestsAcked;
    private ReentrantLock ackLock;
    private Condition gotAcked;
    private LinkedBlockingQueue<Integer> cleanQueue;
    private Thread cleanerThread;
    private LinkedBlockingQueue<RequestContext> invokeQueue;
    private Thread invokeThread;
42
    private boolean doWork = true;
43
    
44 45
/**
     * Constructor
46
     *
47
     * @see bellow
48 49 50 51 52
     */
    public AsynchServiceProxy(int processId) {
        this(processId, null);
    }

53 54
/**
     * Constructor
55
     *
56
     * @see bellow
57 58 59 60 61
     */
    public AsynchServiceProxy(int processId, String configHome) {
        super(processId, configHome);
        init();
    }
62 63 64 65 66 67
    
    /**
     * Constructor
     *
     * @see bellow
     */
68 69
    public AsynchServiceProxy(int processId, String configHome, KeyLoader loader) {
        super(processId, configHome, loader);
70 71 72
        init();
    }
    
73 74 75 76 77 78 79 80 81 82 83
    /**
     * Constructor
     *
     * @param processId Process id for this client (should be different from replicas)
     * @param configHome Configuration directory for BFT-SMART
     * @param replyComparator Used for comparing replies from different servers
     *                        to extract one returned by f+1
     * @param replyExtractor Used for extracting the response from the matching
     *                       quorum of replies
     * @param loader Used to load signature keys from disk
     */
84
    public AsynchServiceProxy(int processId, String configHome,
85
            Comparator<byte[]> replyComparator, Extractor replyExtractor, KeyLoader loader) {
86
        
87
        super(processId, configHome, replyComparator, replyExtractor, loader);
88 89 90 91 92 93 94
        init();
    }

    private void init() {
        requestsContext = new HashMap<>();
        requestsReplies = new HashMap<>();
        requestsAlias = new HashMap<>();
95 96 97 98 99 100 101 102 103
        requestsAcked = new HashSet<>();
        ackLock = new ReentrantLock();
        gotAcked =ackLock.newCondition();
        
        cleanQueue = new LinkedBlockingQueue<>();
        cleanerThread = new Thread() {
            
            public void run() {
                
104
                while (doWork) {
105 106
                    
                    try {
107 108 109
                        
                        if (cleanQueue.poll(200, TimeUnit.MILLISECONDS) == null) continue;
                        
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
                        int requestId = cleanQueue.take();
                        
                        Integer id = requestId;

                        do {
                            
                            ackLock.lock();

                            while (!requestsAcked.contains(id)) {
                                try {
                                    gotAcked.await();
                                } catch (InterruptedException ex) {
                                    logger.error("Interruption error.",ex);
                                }
                            }

                            ackLock.unlock();

                            requestsAcked.remove(id);
                        
                            requestsContext.remove(id);
                            requestsReplies.remove(id);

                            id = requestsAlias.remove(id);

                        } while (id != null);
        
                    } catch (InterruptedException ex) {
                        
                        logger.error("Interrupted error.",ex);
                    }
                }
            }
        };
        
        cleanerThread.start();
        
147
        invokeQueue = new LinkedBlockingQueue<>();
148 149 150 151
        invokeThread = new Thread() {
            
            public void run() {
                
152
                while(doWork) {
153 154
                    
                    try {
155 156 157
                        RequestContext requestContext = null;
                        
                        requestContext = invokeQueue.poll(200, TimeUnit.MILLISECONDS);
158
                        
159 160 161
                        if (requestContext == null) continue;
                        
                        logger.debug("Dequeued invoke at client {} for request #{}", getViewManager().getStaticConf().getProcessId(), requestContext.getOperationId());
162 163 164 165 166

                        invokeAsynch(requestContext);

                        logger.debug("Finished invoke at client {} for request #{}", getViewManager().getStaticConf().getProcessId(), requestContext.getOperationId());

167 168 169 170 171 172 173 174
                        
                    } catch (InterruptedException ex) {
                        logger.error("Interrupted error.",ex);
                    }
                }
            }
        };
        
175
        invokeThread.start();
176 177
    }
    
178 179 180 181 182 183
    private View newView(byte[] bytes) {
        
        Object o = TOMUtil.getObject(bytes);
        return (o != null && o instanceof View ? (View) o : null);
    }
    /**
184
     * @see bellow
185
     */
186 187
    public int invokeAsynchRequest(byte[] request, ReplyListener replyListener, TOMMessageType reqType) throws InterruptedException {
        return invokeAsynchRequest(request, super.getViewManager().getCurrentViewProcesses(), replyListener, reqType, false);
188 189
    }

190 191 192 193 194 195 196
    /**
     * @see bellow
     */
    public int invokeAsynchRequest(byte[] request, ReplyListener replyListener, TOMMessageType reqType, boolean dos) throws InterruptedException {
        return invokeAsynchRequest(request, super.getViewManager().getCurrentViewProcesses(), replyListener, reqType, dos);
    }
    
197
    /**
198
     * This method asynchronously sends a request to the replicas.
199 200
     * It returns immediately after adding the request to an internal queue, hence preventing the current thread from blocking while waiting for a quorum of ACKS.
     * After instantiation, developers must either always use one of the 'invokeAsynchRequest' or always the 'invokeAsynch' method.
201 202 203 204
     * 
     * @param request Request to be sent
     * @param targets The IDs for the replicas to which to send the request
     * @param replyListener Callback object that handles reception of replies
205
     * @param reqType Request type
206
     * @param dos Ignore control flow mechanism
207 208
     * 
     * @return A unique identification for the request
209
     */
210 211
    public int invokeAsynchRequest(byte[] request, int[] targets, ReplyListener replyListener, TOMMessageType reqType, boolean dos) throws InterruptedException {
                
212
         RequestContext requestContext = generateNextContext(request, targets, replyListener, reqType, dos);
213
        
214 215 216 217
         logger.debug("Enqueuing invoke at client {} for request #{}", getViewManager().getStaticConf().getProcessId(), requestContext.getOperationId());

        invokeQueue.put(requestContext);
                            
218
        return requestContext.getOperationId();
219
    }
220

221 222 223 224
    /**
     * @see bellow
     */
    public RequestContext generateNextContext(byte[] request, ReplyListener replyListener, TOMMessageType reqType) throws InterruptedException {
J
João Sousa 已提交
225
        return generateNextContext(request, super.getViewManager().getCurrentViewProcesses(), replyListener, reqType, false, System.nanoTime());
226 227 228 229 230 231
    }

    /**
     * @see bellow
     */
    public RequestContext generateNextContext(byte[] request, ReplyListener replyListener, TOMMessageType reqType, boolean dos) throws InterruptedException {
J
João Sousa 已提交
232 233 234 235 236 237 238 239 240 241
        return generateNextContext(request, super.getViewManager().getCurrentViewProcesses(), replyListener, reqType, dos, System.nanoTime());
    }
    
    
    /**
     * @see bellow
     */
    public RequestContext generateNextContext(byte[] request, int[] targets, ReplyListener replyListener, TOMMessageType reqType, boolean dos) {
        
        return generateNextContext(request, super.getViewManager().getCurrentViewProcesses(), replyListener, reqType, false, System.nanoTime());
242 243 244 245 246 247 248 249 250 251
    }
    
    /**
     * Generate the next request context. This method should only be used if request are to be submitted using 'invokeAsych'.
     * 
     * @param request Request to be sent
     * @param targets The IDs for the replicas to which to send the request
     * @param replyListener Callback object that handles reception of replies
     * @param reqType Request type
     * @param dos Ignore control flow mechanism
J
João Sousa 已提交
252
     * @param sentTime Timestamp of the time of creating
253 254 255
     * 
     * @return A unique identification for the request
     */
J
João Sousa 已提交
256
    public RequestContext generateNextContext(byte[] request, int[] targets, ReplyListener replyListener, TOMMessageType reqType, boolean dos, long sentTime) {
257 258
        
        return new RequestContext(generateRequestId(reqType), generateOperationId(),
J
João Sousa 已提交
259
                reqType, targets, sentTime, replyListener, request, dos);
260
    }
J
João Sousa 已提交
261
    
262
    /**
263 264 265 266
     * Purges all information associated to the request.
     * This should always be invoked once enough replies are received and processed by the ReplyListener callback.
     * 
     * @param requestId A unique identification for a previously sent request
267
     */
268 269 270
    public void cleanAsynchRequest(int requestId) throws InterruptedException {
        
        cleanQueue.put(requestId);
271 272 273

    }

274 275 276 277 278
    @Override
    public void close() {
        doWork = false;
        super.close();
    }
279
    /**
280
     * This is the method invoked by the client side communication system.
281
     *
282
     * @param reply The reply delivered by the client side communication system
283 284 285
     */
    @Override
    public void replyReceived(TOMMessage reply) {
286
        logger.debug("Asynchronously received reply from " + reply.getSender() + " with sequence number " + reply.getSequence() + " and operation ID " + reply.getOperationId());
J
Joao Sousa 已提交
287 288

        try {
289
            canReceiveLock.lock();
290

291
            RequestContext requestContext = requestsContext.get(reply.getOperationId());
292

293
            if (requestContext == null) { // it is not a asynchronous request                
294 295 296
                super.replyReceived(reply);
                return;
            }
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
            
            //control flow mechanism
            if (reply.getReqType() == TOMMessageType.ACK) {

                logger.debug("Received ACK from {} to {}",reply.getSender(), getProcessId());

                if (reply.getSession() == getSession() && ackId == requestContext.getOperationId() &&
                        reply.getOperationId() == requestContext.getOperationId() && reply.getSequence() == requestContext.getReqId()) {

                    logger.debug("ACK is for the current request ({})", requestContext.getOperationId());
                    
                    int pos = getViewManager().getCurrentViewPos(reply.getSender());
                    
                    int sameContent = 1;
                    int leader = -1;
312
                    int ackSeq = -1;
313 314 315 316 317 318 319 320 321 322

                    acks[pos] = reply;

                    for (int i = 0; i < acks.length; i++) {

                        if ((i != pos || getViewManager().getCurrentViewN() == 1) && acks[i] != null
                                        && (comparator.compare(acks[i].getContent(), reply.getContent()) == 0)) {
                                sameContent++;
                                if (sameContent >= getReplyQuorum()) {
                                        ByteBuffer buff = ByteBuffer.wrap(extractor.extractResponse(acks, sameContent, pos).getContent());
323 324
                                        
                                        ackSeq = buff.getInt();
325 326 327
                                        leader = buff.getInt();

                                        logger.debug("Client {} received quorum of ACKs for req id #{} "+
328 329
                                                  "with ACK sequence {} indicating replica {} as the leader", 
                                                    getProcessId(), requestContext.getOperationId(), ackSeq,leader);
330 331 332

                                        int p = getViewManager().getCurrentViewPos(leader);

333
                                        if (this.ackSeq == ackSeq && p != -1 && acks[p] != null) {
334 335 336 337

                                            logger.debug("Client {} also received ACK from leader, client "+
                                                    "can stop re-transmiting request #{}", getProcessId(), requestContext.getOperationId());

338
                                            this.leader = leader;
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
                                            Arrays.fill(acks, null);
                                            requestsAcked.add(ackId);
                                            ackId = -1;
                                            
                                            this.controlFlow.release();
                                            ackLock.lock();
                                            gotAcked.signalAll();
                                            ackLock.unlock();
                                        }
                                }
                        }
                    }
                }

                //canReceiveLock.unlock();

                return;
            }
J
Joao Sousa 已提交
357

358 359 360 361
            if (contains(requestContext.getTargets(), reply.getSender())
                    && (reply.getSequence() == requestContext.getReqId())
                    //&& (reply.getOperationId() == requestContext.getOperationId())
                    && (reply.getReqType().compareTo(requestContext.getRequestType())) == 0) {
J
Joao Sousa 已提交
362

363
                logger.debug("Deliverying message from " + reply.getSender() + " with sequence number " + reply.getSequence() + " and operation ID " + reply.getOperationId() + " to the listener");
364

365 366 367
                ReplyListener replyListener = requestContext.getReplyListener();
                
                View v = null;
368

369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
                if (replyListener != null) {

                    //if (reply.getViewID() > getViewManager().getCurrentViewId()) { // Deal with a system reconfiguration
                    if ((v = newView(reply.getContent())) != null && !requestsAlias.containsKey(reply.getOperationId())) { // Deal with a system reconfiguration
    
                        TOMMessage[] replies = requestsReplies.get(reply.getOperationId());

                        int sameContent = 1;
                        int replyQuorum = getReplyQuorum();

                        int pos = getViewManager().getCurrentViewPos(reply.getSender());

                        replies[pos] = reply;

                        for (int i = 0; i < replies.length; i++) {

                            if ((replies[i] != null) && (i != pos || getViewManager().getCurrentViewN() == 1)
                                    && (reply.getReqType() != TOMMessageType.ORDERED_REQUEST || Arrays.equals(replies[i].getContent(), reply.getContent()))) {
                                sameContent++;
J
João Sousa 已提交
388 389 390 391
                            }
                        }
                        
                        if (sameContent >= replyQuorum) {
392

J
João Sousa 已提交
393 394 395 396
                            if (v.getId() > getViewManager().getCurrentViewId()) {

                                reconfigureTo(v);
                            }
397

J
João Sousa 已提交
398
                            requestContext.getReplyListener().reset();
399

400
                            /*Thread t = new Thread() {
401

J
João Sousa 已提交
402 403
                                @Override
                                public void run() {
404

405 406 407 408 409 410 411 412
                                    //int id = invokeAsynch(requestContext.getRequest(), requestContext.getTargets(), requestContext.getReplyListener(), TOMMessageType.ORDERED_REQUEST, false);
                            
                                    //requestsAlias.put(reply.getOperationId(), id);
                            
                                    RequestContext newContext = new RequestContext(generateRequestId(requestContext.getRequestType()), generateOperationId(),
                                        requestContext.getRequestType(), requestContext.getTargets(), System.currentTimeMillis(), replyListener, requestContext.getRequest(), requestContext.getDoS());
                            
                                    requestsAlias.put(reply.getOperationId(), newContext.getOperationId());
413
                                }
J
João Sousa 已提交
414 415 416

                            };

417
                            t.start();*/
418
                            
419 420 421
                            RequestContext newContext = new RequestContext(generateRequestId(requestContext.getRequestType()), generateOperationId(),
                                requestContext.getRequestType(), requestContext.getTargets(), System.currentTimeMillis(), replyListener, requestContext.getRequest(), requestContext.getDoS());
                            invokeQueue.put(newContext);
J
João Sousa 已提交
422

423 424 425 426 427 428 429 430 431 432
                        }
                        
                        
                    } else if (!requestsAlias.containsKey(reply.getOperationId())) {
                            
                            requestContext.getReplyListener().replyReceived(requestContext, reply);
                    }
                }
            }
        } catch (Exception ex) {
433
            logger.error("Error processing received request",ex);
434 435 436 437
        } finally {
            canReceiveLock.unlock();
        }
    }
438

439 440 441 442 443
    /**
     * This method asynchronously sends a request to the replicas using a RequestContext object.
     * It blocks while waiting for a quorum of ACKs from the replicas.
     * After instantiation, developers must either always use one of the 'invokeAsynchRequest' or always the 'invokeAsynch' method.
     * 
444
     * @param reqCtx The context for the request to be submitted.
445
     */
446
    public void invokeAsynch(RequestContext reqCtx) {
447

448
        logger.debug("Asynchronously sending request to " + Arrays.toString(reqCtx.getTargets()));
449 450

        canSendLock.lock();
451
        
452
        try {
453 454 455
            logger.debug("Storing request context for " + reqCtx.getOperationId());
            requestsContext.put(reqCtx.getOperationId(), reqCtx);
            requestsReplies.put(reqCtx.getOperationId(), new TOMMessage[super.getViewManager().getCurrentViewN()]);
456

457 458 459
            ackId = reqCtx.getOperationId();
            ackSeq = 0;
            
460 461
            Arrays.fill(acks, null);
            
462 463
            logger.debug("Sending invoke at client {} for request #{}", getViewManager().getStaticConf().getProcessId(), reqCtx.getOperationId());

464

465 466 467 468 469 470 471 472
            TOMMessage sm = new TOMMessage(getProcessId(), getSession(), reqCtx.getReqId(),
                    reqCtx.getOperationId(), reqCtx.getRequest(), getViewManager().getCurrentViewId(), reqCtx.getRequestType());
            
            //sendMessageToTargets(reqCtx.getRequest(), reqCtx.getReqId(),
            //        reqCtx.getOperationId(), reqCtx.getTargets(), reqCtx.getRequestType());
            
            sm.setAckSeq(ackSeq);
            
473 474
            //int[] targets = (leader != -1 ?  new int[]{leader} : getViewManager().getCurrentViewProcesses());
            
475
            TOMulticast(sm);
476
            
477 478
            //Control flow
            if (!reqCtx.getDoS() && getViewManager().getStaticConf().getControlFlow()) {
479 480 481 482 483 484 485
                while (true) {

                    if (this.controlFlow.tryAcquire(getViewManager().getStaticConf().getControlFlowTimeout(), TimeUnit.MILLISECONDS)) {

                        break;

                    } else {
486 487 488 489 490 491 492
                        
                        sm = new TOMMessage(getProcessId(), getSession(), reqCtx.getReqId(),
                            reqCtx.getOperationId(), reqCtx.getRequest(), getViewManager().getCurrentViewId(), reqCtx.getRequestType());
                        
                        ackSeq++;
                        sm.setAckSeq(ackSeq);

493
                        logger.warn("Retrying invoke at client {} for request #{} with ACK sequence #{}", 
494 495 496 497
                                getViewManager().getStaticConf().getProcessId(), reqCtx.getOperationId(), sm.getAckSeq());
                        Arrays.fill(acks, null);
                        
                        TOMulticast(sm);
498 499 500
                    }
                }
            }
501

502 503
        } catch (InterruptedException ex) {
            logger.error("Problem aquiring semaphore",ex);
504 505 506 507
        } finally {
            canSendLock.unlock();
        }

508
        //return requestContext.getOperationId();
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
    }

    /**
     *
     * @param targets
     * @param senderId
     * @return
     */
    private boolean contains(int[] targets, int senderId) {
        for (int i = 0; i < targets.length; i++) {
            if (targets[i] == senderId) {
                return true;
            }
        }
        return false;
    }

526
}