StateManager.java 19.0 KB
Newer Older
P
pjsousa@gmail.com 已提交
1 2
/**
 * Copyright (c) 2007-2009 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags
3
 *
P
pjsousa@gmail.com 已提交
4
 * This file is part of SMaRt.
5
 *
P
pjsousa@gmail.com 已提交
6 7 8 9
 * 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.
10
 *
P
pjsousa@gmail.com 已提交
11 12
 * SMaRt is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
P
pjsousa@gmail.com 已提交
14
 * GNU General Public License for more details.
15
 *
P
pjsousa@gmail.com 已提交
16 17 18 19 20
 * 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.statemanagment;

21
import java.util.Arrays;
22
import java.util.HashSet;
23 24 25
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.locks.ReentrantLock;
26
import navigators.smart.reconfiguration.ServerViewManager;
27 28
import navigators.smart.tom.core.DeliveryThread;
import navigators.smart.tom.core.TOMLayer;
29
import navigators.smart.tom.leaderchange.LCManager;
30 31
import navigators.smart.tom.util.Logger;
import navigators.smart.tom.util.TOMUtil;
P
pjsousa@gmail.com 已提交
32 33 34

/**
 * TODO: Não sei se esta classe sera usada. Para já, deixo ficar
35 36
 *
 *  Verificar se as alterações para suportar dinamismo estão corretas
37
 * @author Joao Sousa
P
pjsousa@gmail.com 已提交
38 39 40 41
 */
public class StateManager {

    private StateLog log;
42 43
    private HashSet<SenderEid> senderEids = null;
    private HashSet<SenderState> senderStates = null;
44
    private HashSet<SenderRegency> senderRegencies = null;
45

46 47
    private ReentrantLock lockState = new ReentrantLock();
    private ReentrantLock lockTimer = new ReentrantLock();
48

49
    private Timer stateTimer = null;
50

51
    private int lastEid;
52
    private int waitingEid;
53 54
    private int replica;
    private byte[] state;
55

56
    private ServerViewManager SVManager;
57
    private TOMLayer tomLayer;
58 59
    private DeliveryThread dt;
    private LCManager lcManager;
60
    
61
    public StateManager(ServerViewManager manager, TOMLayer tomLayer, DeliveryThread dt, LCManager lcManager) {
62 63

        //******* EDUARDO BEGIN **************//
64 65
        this.SVManager = manager;
        int k = this.SVManager.getStaticConf().getCheckpointPeriod();
66
        //******* EDUARDO END **************//
67

68 69
        this.tomLayer = tomLayer;
        this.dt = dt;
70
        this.lcManager = lcManager;
71

72
        this.log = new StateLog(k);
73 74
        senderEids = new HashSet<SenderEid>();
        senderStates = new HashSet<SenderState>();
75
        senderRegencies = new HashSet<SenderRegency>();
76

77
        this.replica = 0;
78 79

        if (replica == manager.getStaticConf().getProcessId()) changeReplica();
80
        this.state = null;
81
        this.lastEid = -1;
82
        this.waitingEid = -1;
83
    }
84
    
85 86 87 88 89
    public int getReplica() {
        return replica;
    }

    public void changeReplica() {
90 91 92

        //******* EDUARDO BEGIN **************//
        int pos = -1;
93
        do {
94
            //TODO: Verificar se continua correto
95 96
            pos = this.SVManager.getCurrentViewPos(replica);
            replica = this.SVManager.getCurrentViewProcesses()[(pos + 1) % SVManager.getCurrentViewN()];
97 98

        //******* EDUARDO END **************//
99
        } while (replica == SVManager.getStaticConf().getProcessId());
100 101 102 103 104 105 106 107 108
    }

    public void setReplicaState(byte[] state) {
        this.state = state;
    }

    public byte[] getReplicaState() {
        return state;
    }
109

110 111
    public void addEID(int sender, int eid) {
        senderEids.add(new SenderEid(sender, eid));
112 113
    }

114 115
    public void emptyEIDs() {
        senderEids.clear();
116 117
    }

118 119 120 121 122
    public void emptyEIDs(int eid) {
        for (SenderEid m : senderEids)
            if (m.eid <= eid) senderEids.remove(m);
    }

123 124 125 126 127 128 129 130 131 132 133 134 135
    public boolean moreThanF_EIDs(int eid) {

        int count = 0;
        HashSet<Integer> replicasCounted = new HashSet<Integer>();

        for (SenderEid m : senderEids) {
            if (m.eid == eid && !replicasCounted.contains(m.sender)) {
                replicasCounted.add(m.sender);
                count++;
            }
        }

        //******* EDUARDO BEGIN **************//
136
        return count > SVManager.getCurrentViewF();
137 138 139
        //******* EDUARDO END **************//
    }

140 141
    public void addRegency(int sender, int regency) {
        senderRegencies.add(new SenderRegency(sender, regency));
142 143
    }

144 145
    public void emptyRegencies() {
        senderRegencies.clear();
146 147
    }

148 149 150
    public void emptyRegencies(int regency) {
        for (SenderRegency m : senderRegencies)
            if (m.regency <= regency) senderRegencies.remove(m);
151 152
    }
    
153
    public boolean moreThan2F_Regencies(int regency) {
154 155 156 157

        int count = 0;
        HashSet<Integer> replicasCounted = new HashSet<Integer>();

158 159
        for (SenderRegency m : senderRegencies) {
            if (m.regency == regency && !replicasCounted.contains(m.sender)) {
160 161 162 163 164 165
                replicasCounted.add(m.sender);
                count++;
            }
        }

        //******* EDUARDO BEGIN **************//
166
        return count > SVManager.getQuorum2F();
167 168 169
        //******* EDUARDO END **************//
    }

170 171 172 173 174 175 176 177
    public void addState(int sender, TransferableState state) {
        senderStates.add(new SenderState(sender, state));
    }

    public void emptyStates() {
        senderStates.clear();
    }

178 179
    public int getWaiting() {
        return waitingEid;
180 181
    }

182 183
    public void setWaiting(int wait) {
        this.waitingEid = wait;
184 185 186 187 188 189 190 191 192
    }
    public void setLastEID(int eid) {
        lastEid = eid;
    }

    public int getLastEID() {
        return lastEid;
    }

193

194
    public boolean moreThanF_Replies() {
195 196 197 198 199

        int count = 0;
        HashSet<Integer> replicasCounted = new HashSet<Integer>();

        for (SenderState m : senderStates) {
200
            if (!replicasCounted.contains(m.sender)) {
201 202 203 204 205
                replicasCounted.add(m.sender);
                count++;
            }
        }

206
        //******* EDUARDO BEGIN **************//
207
        return count > SVManager.getCurrentViewF();
208
        //******* EDUARDO END **************//
209
    }
P
pjsousa@gmail.com 已提交
210

211
    private TransferableState getValidHash() {
212

213 214 215 216 217 218 219 220
        SenderState[] st = new SenderState[senderStates.size()];
        senderStates.toArray(st);
        int count = 0;

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

            for (int j = i; j < st.length; j++) {

221
                if (st[i].state.equals(st[j].state) && st[j].state.hasState()) count++;
222
                //******* EDUARDO BEGIN **************//
223
                if (count > SVManager.getCurrentViewF()) return st[j].state;
224
                //******* EDUARDO END **************//
225 226 227 228 229 230
            }
        }

        return null;
    }

231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
    public int getNumValidHashes() {

        SenderState[] st = new SenderState[senderStates.size()];
        senderStates.toArray(st);
        int count = 0;

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

            for (int j = i; j < st.length; j++) {

                if (st[i].state.equals(st[j].state) && st[j].state.hasState()) count++;
 
            }
        }

        return count;
    }

249 250 251 252
    public int getReplies() {
        return senderStates.size();
    }

253 254
    public StateLog getLog() {
        return log;
P
pjsousa@gmail.com 已提交
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
    public void saveState(byte[] state, int lastEid, int decisionRound, int leader) {

        StateLog thisLog = getLog();

        lockState.lock();

        Logger.println("(TOMLayer.saveState) Saving state of EID " + lastEid + ", round " + decisionRound + " and leader " + leader);

        thisLog.newCheckpoint(state, tomLayer.computeHash(state));
        thisLog.setLastEid(-1);
        thisLog.setLastCheckpointEid(lastEid);
        thisLog.setLastCheckpointRound(decisionRound);
        thisLog.setLastCheckpointLeader(leader);

        lockState.unlock();

        Logger.println("(TOMLayer.saveState) Finished saving state of EID " + lastEid + ", round " + decisionRound + " and leader " + leader);
    }

    public void saveBatch(byte[] batch, int lastEid, int decisionRound, int leader) {

        StateLog thisLog = getLog();

        lockState.lock();

        Logger.println("(TOMLayer.saveBatch) Saving batch of EID " + lastEid + ", round " + decisionRound + " and leader " + leader);

        thisLog.addMessageBatch(batch, decisionRound, leader);
        thisLog.setLastEid(lastEid);

        lockState.unlock();

        Logger.println("(TOMLayer.saveBatch) Finished saving batch of EID " + lastEid + ", round " + decisionRound + " and leader " + leader);
    }

292
    public void analyzeState(int sender, int eid) {
293

294
            Logger.println("(TOMLayer.analyzeState) The state transfer protocol is enabled");
295 296 297

            if (getWaiting() == -1) {

298
                Logger.println("(TOMLayer.analyzeState) I'm not waiting for any state, so I will keep record of this message");
299 300
                addEID(sender, eid);

301
                if (getLastEID() < eid && moreThanF_EIDs(eid)) {
302

303 304
                    Logger.println("(TOMLayer.analyzeState) I have now more than " + SVManager.getCurrentViewF() + " messages for EID " + eid + " which are beyond EID " + getLastEID());
                    
305 306
                    setLastEID(eid);
                    setWaiting(eid - 1);
307 308 309 310
        
                    requestState();
                }
            }
311

312 313 314 315
        /************************* TESTE *************************
        System.out.println("[/TOMLayer.requestState]");
        /************************* TESTE *************************/
    }
316

317 318
    private void requestState() {
        if (tomLayer.requestsTimer != null) tomLayer.requestsTimer.clearAll();
319

320
        //stateManager.emptyReplicas(eid);// isto causa uma excepcao
321

322 323 324
        SMMessage smsg = new SMMessage(SVManager.getStaticConf().getProcessId(),
                getWaiting(), TOMUtil.SM_REQUEST, getReplica(), null, -1);
        tomLayer.getCommunication().send(SVManager.getCurrentViewOtherAcceptors(), smsg);
325

326
        Logger.println("(TOMLayer.requestState) I just sent a request to the other replicas for the state up to EID " + getWaiting());
327

328 329
        TimerTask stateTask =  new TimerTask() {
            public void run() {
330 331


332 333 334 335 336 337 338
                int[] myself = new int[1];
                myself[0] = SVManager.getStaticConf().getProcessId();
                                
                tomLayer.getCommunication().send(myself, new SMMessage(-1, getWaiting(), TOMUtil.TRIGGER_SM_LOCALLY, -1, null, -1));

                
                
339
            }
340 341 342 343
        };

        stateTimer = new Timer("state timer");
        stateTimer.schedule(stateTask,1500);
344 345

    }
346 347 348 349 350 351
    
    public void stateTimeout() {
        lockTimer.lock();
        
        Logger.println("(StateManager.stateTimeout) Timeout for the replica that was supposed to send the complete state. Changing desired replica.");
        System.out.println("Timeout no timer do estado!");
352

353 354 355 356 357 358 359 360 361 362 363 364 365

        if (stateTimer != null) stateTimer.cancel();
                
        //setWaiting(-1);
        changeReplica();
        emptyStates();
        setReplicaState(null);
        
        requestState();

        lockTimer.unlock();
    }
    
366 367 368
    public void SMRequestDeliver(SMMessage msg) {

        //******* EDUARDO BEGIN **************//
369
        if (SVManager.getStaticConf().isStateTransferEnabled()) {
370 371 372 373 374 375 376 377
        //******* EDUARDO END **************//

            Logger.println("(TOMLayer.SMRequestDeliver) The state transfer protocol is enabled");

            lockState.lock();

            Logger.println("(TOMLayer.SMRequestDeliver) I received a state request for EID " + msg.getEid() + " from replica " + msg.getSender());

378
            boolean sendState = msg.getReplica() == SVManager.getStaticConf().getProcessId();
379 380 381 382 383 384 385 386 387 388 389 390 391
            if (sendState) Logger.println("(TOMLayer.SMRequestDeliver) I should be the one sending the state");

            TransferableState thisState = getLog().getTransferableState(msg.getEid(), sendState);

            lockState.unlock();

            if (thisState == null) {
                Logger.println("(TOMLayer.SMRequestDeliver) I don't have the state requested :-(");

              thisState = new TransferableState();
            }

            int[] targets = { msg.getSender() };
392 393
            SMMessage smsg = new SMMessage(SVManager.getStaticConf().getProcessId(),
                    msg.getEid(), TOMUtil.SM_REPLY, -1, thisState, lcManager.getLastReg());
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408

            // malicious code, to force the replica not to send the state
            //if (reconfManager.getStaticConf().getProcessId() != 0 || !sendState)
            tomLayer.getCommunication().send(targets, smsg);

            Logger.println("(TOMLayer.SMRequestDeliver) I sent the state for checkpoint " + thisState.getLastCheckpointEid() + " with batches until EID " + thisState.getLastEid());

        }
    }

    public void SMReplyDeliver(SMMessage msg) {

        //******* EDUARDO BEGIN **************//

        lockTimer.lock();
409
        if (SVManager.getStaticConf().isStateTransferEnabled()) {
410 411 412 413 414 415 416
        //******* EDUARDO END **************//

            Logger.println("(TOMLayer.SMReplyDeliver) The state transfer protocol is enabled");
            Logger.println("(TOMLayer.SMReplyDeliver) I received a state reply for EID " + msg.getEid() + " from replica " + msg.getSender());

            if (getWaiting() != -1 && msg.getEid() == getWaiting()) {

417 418 419
                int currentRegency = -1;
                addRegency(msg.getSender(), msg.getRegency());
                if (moreThan2F_Regencies(msg.getRegency())) currentRegency = msg.getRegency();
420

421 422 423 424 425 426 427 428 429 430 431 432
                Logger.println("(TOMLayer.SMReplyDeliver) The reply is for the EID that I want!");

                if (msg.getSender() == getReplica() && msg.getState().getState() != null) {
                    Logger.println("(TOMLayer.SMReplyDeliver) I received the state, from the replica that I was expecting");
                    setReplicaState(msg.getState().getState());
                    if (stateTimer != null) stateTimer.cancel();
                }

                addState(msg.getSender(),msg.getState());

                if (moreThanF_Replies()) {

433
                    Logger.println("(TOMLayer.SMReplyDeliver) I have at least " + SVManager.getCurrentViewF() + " replies!");
434

435
                    TransferableState recvState = getValidHash();
436 437 438 439 440

                    int haveState = 0;
                    if (getReplicaState() != null) {
                        byte[] hash = null;
                        hash = tomLayer.computeHash(getReplicaState());
441 442
                        if (recvState != null) {
                            if (Arrays.equals(hash, recvState.getStateHash())) haveState = 1;
443
                            else if (getNumValidHashes() > SVManager.getCurrentViewF()) haveState = -1;
444 445 446 447

                        }
                    }

448
                    if (recvState != null && haveState == 1 && currentRegency > -1) {
449

450
                        lcManager.setLastReg(currentRegency);
451
                        lcManager.setNextReg(currentRegency);
452
                        tomLayer.lm.setNewReg(currentRegency);
453 454 455

                        Logger.println("(TOMLayer.SMReplyDeliver) The state of those replies is good!");

456
                        recvState.setState(getReplicaState());
457 458 459

                        lockState.lock();

460
                        getLog().update(recvState);
461 462 463 464 465 466 467 468 469

                        lockState.unlock();

                        dt.deliverLock();

                        //ot.OutOfContextLock();

                        setWaiting(-1);

470
                        dt.update(recvState);
471 472 473 474 475 476 477 478 479 480 481 482 483
                        tomLayer.processOutOfContext();

                        dt.canDeliver();

                        //ot.OutOfContextUnlock();
                        dt.deliverUnlock();

                        emptyStates();
                        setReplicaState(null);

                        System.out.println("Actualizei o estado!");

                    //******* EDUARDO BEGIN **************//
484
                    } else if (recvState == null && (SVManager.getCurrentViewN() / 2) < getReplies()) {
485 486 487
                    //******* EDUARDO END **************//

                        Logger.println("(TOMLayer.SMReplyDeliver) I have more than " +
488
                                (SVManager.getCurrentViewN() / 2) + " messages that are no good!");
489 490 491 492

                        setWaiting(-1);
                        emptyStates();
                        setReplicaState(null);
493
                        //requestState();
494 495 496 497 498 499

                        if (stateTimer != null) stateTimer.cancel();
                    } else if (haveState == -1) {

                        Logger.println("(TOMLayer.SMReplyDeliver) The replica from which I expected the state, sent one which doesn't match the hash of the others, or it never sent it at all");

500
                        //setWaiting(-1);
501 502 503
                        changeReplica();
                        emptyStates();
                        setReplicaState(null);
504
                        requestState();
505 506 507 508 509 510 511 512

                        if (stateTimer != null) stateTimer.cancel();
                    }
                }
            }
        }
        lockTimer.unlock();
    }
513

514
    private class SenderRegency {
515 516

        private int sender;
517
        private int regency;
518

519
        SenderRegency(int sender, int regency) {
520
            this.sender = sender;
521
            this.regency = regency;
522 523 524 525 526 527
        }

        @Override
        public boolean equals(Object obj) {
            if (obj instanceof SenderEid) {
                SenderEid m = (SenderEid) obj;
528
                return (m.eid == this.regency && m.sender == this.sender);
529 530 531 532 533 534 535 536
            }
            return false;
        }

        @Override
        public int hashCode() {
            int hash = 1;
            hash = hash * 31 + this.sender;
537
            hash = hash * 31 + this.regency;
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
            return hash;
        }
    }

    private class SenderEid {

        private int sender;
        private int eid;

        SenderEid(int sender, int eid) {
            this.sender = sender;
            this.eid = eid;
        }

        @Override
        public boolean equals(Object obj) {
            if (obj instanceof SenderEid) {
                SenderEid m = (SenderEid) obj;
                return (m.eid == this.eid && m.sender == this.sender);
            }
            return false;
        }

        @Override
        public int hashCode() {
            int hash = 1;
            hash = hash * 31 + this.sender;
            hash = hash * 31 + this.eid;
            return hash;
        }
    }
    
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
    private class SenderState {

        private int sender;
        private TransferableState state;

        SenderState(int sender, TransferableState state) {
            this.sender = sender;
            this.state = state;
        }

        @Override
        public boolean equals(Object obj) {
            if (obj instanceof SenderState) {
                SenderState m = (SenderState) obj;
                return (this.state.equals(m.state) && m.sender == this.sender);
            }
            return false;
        }

        @Override
        public int hashCode() {
            int hash = 1;
            hash = hash * 31 + this.sender;
            hash = hash * 31 + this.state.hashCode();
            return hash;
        }
    }
P
pjsousa@gmail.com 已提交
597
}