StateManager.java 18.6 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
    public 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 292 293 294 295 296 297 298 299 300
    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);
    }

    public void requestState(int sender, int eid) {

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

            if (getWaiting() == -1) {

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

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

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

                    if (tomLayer.requestsTimer != null) tomLayer.requestsTimer.clearAll();
                    setLastEID(eid);
                    setWaiting(eid - 1);
                    //stateManager.emptyReplicas(eid);// isto causa uma excepcao

310
                    SMMessage smsg = new SMMessage(SVManager.getStaticConf().getProcessId(),
311
                            eid - 1, TOMUtil.SM_REQUEST, getReplica(), null, -1);
312
                    tomLayer.getCommunication().send(SVManager.getCurrentViewOtherAcceptors(), smsg);
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 345

                    Logger.println("(TOMLayer.requestState) I just sent a request to the other replicas for the state up to EID " + (eid - 1));

                    TimerTask stateTask =  new TimerTask() {
                        public void run() {

                        lockTimer.lock();

                        Logger.println("(TimerTask.run) Timeout for the replica that was supposed to send the complete state. Changing desired replica.");
                        System.out.println("Timeout no timer do estado!");

                        setWaiting(-1);
                        changeReplica();
                        emptyStates();
                        setReplicaState(null);

                        lockTimer.unlock();
                        }
                    };

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

        /************************* TESTE *************************
        System.out.println("[/TOMLayer.requestState]");
        /************************* TESTE *************************/
    }

    public void SMRequestDeliver(SMMessage msg) {

        //******* EDUARDO BEGIN **************//
346
        if (SVManager.getStaticConf().isStateTransferEnabled()) {
347 348 349 350 351 352 353 354
        //******* 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());

355
            boolean sendState = msg.getReplica() == SVManager.getStaticConf().getProcessId();
356 357 358 359 360 361 362 363 364 365 366 367 368
            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() };
369 370
            SMMessage smsg = new SMMessage(SVManager.getStaticConf().getProcessId(),
                    msg.getEid(), TOMUtil.SM_REPLY, -1, thisState, lcManager.getLastReg());
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385

            // 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();
386
        if (SVManager.getStaticConf().isStateTransferEnabled()) {
387 388 389 390 391 392 393
        //******* 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()) {

394 395 396
                int currentRegency = -1;
                addRegency(msg.getSender(), msg.getRegency());
                if (moreThan2F_Regencies(msg.getRegency())) currentRegency = msg.getRegency();
397

398 399 400 401 402 403 404 405 406 407 408 409
                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()) {

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

412
                    TransferableState recvState = getValidHash();
413 414 415 416 417

                    int haveState = 0;
                    if (getReplicaState() != null) {
                        byte[] hash = null;
                        hash = tomLayer.computeHash(getReplicaState());
418 419
                        if (recvState != null) {
                            if (Arrays.equals(hash, recvState.getStateHash())) haveState = 1;
420
                            else if (getNumValidHashes() > SVManager.getCurrentViewF()) haveState = -1;
421 422 423 424

                        }
                    }

425
                    if (recvState != null && haveState == 1 && currentRegency > -1) {
426

427 428
                        lcManager.setLastReg(currentRegency);
                        lcManager.setLastReg(currentRegency);
429
                        tomLayer.lm.setNewReg(currentRegency);
430 431 432

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

433
                        recvState.setState(getReplicaState());
434 435 436

                        lockState.lock();

437
                        getLog().update(recvState);
438 439 440 441 442 443 444 445 446

                        lockState.unlock();

                        dt.deliverLock();

                        //ot.OutOfContextLock();

                        setWaiting(-1);

447
                        dt.update(recvState);
448 449 450 451 452 453 454 455 456 457 458 459 460
                        tomLayer.processOutOfContext();

                        dt.canDeliver();

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

                        emptyStates();
                        setReplicaState(null);

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

                    //******* EDUARDO BEGIN **************//
461
                    } else if (recvState == null && (SVManager.getCurrentViewN() / 2) < getReplies()) {
462 463 464
                    //******* EDUARDO END **************//

                        Logger.println("(TOMLayer.SMReplyDeliver) I have more than " +
465
                                (SVManager.getCurrentViewN() / 2) + " messages that are no good!");
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487

                        setWaiting(-1);
                        emptyStates();
                        setReplicaState(null);

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

                        setWaiting(-1);
                        changeReplica();
                        emptyStates();
                        setReplicaState(null);

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

489
    private class SenderRegency {
490 491

        private int sender;
492
        private int regency;
493

494
        SenderRegency(int sender, int regency) {
495
            this.sender = sender;
496
            this.regency = regency;
497 498 499 500 501 502
        }

        @Override
        public boolean equals(Object obj) {
            if (obj instanceof SenderEid) {
                SenderEid m = (SenderEid) obj;
503
                return (m.eid == this.regency && m.sender == this.sender);
504 505 506 507 508 509 510 511
            }
            return false;
        }

        @Override
        public int hashCode() {
            int hash = 1;
            hash = hash * 31 + this.sender;
512
            hash = hash * 31 + this.regency;
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
            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;
        }
    }
    
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 570 571
    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 已提交
572
}