StateManager.java 16.4 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.ReconfigurationManager;
27 28 29 30
import navigators.smart.tom.core.DeliveryThread;
import navigators.smart.tom.core.TOMLayer;
import navigators.smart.tom.util.Logger;
import navigators.smart.tom.util.TOMUtil;
P
pjsousa@gmail.com 已提交
31 32 33

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

    private StateLog log;
41 42
    private HashSet<SenderEid> senderEids = null;
    private HashSet<SenderState> senderStates = null;
43

44 45
    private ReentrantLock lockState = new ReentrantLock();
    private ReentrantLock lockTimer = new ReentrantLock();
46

47
    private Timer stateTimer = null;
48

49
    private int lastEid;
50
    private int waitingEid;
51 52
    private int replica;
    private byte[] state;
53

54 55 56 57 58
    private ReconfigurationManager reconfManager;
    private TOMLayer tomLayer;
    DeliveryThread dt;
    
    public StateManager(ReconfigurationManager manager, TOMLayer tomLayer, DeliveryThread dt) {
59 60

        //******* EDUARDO BEGIN **************//
61 62
        this.reconfManager = manager;
        int k = this.reconfManager.getStaticConf().getCheckpointPeriod();
63
        //******* EDUARDO END **************//
64

65 66 67
        this.tomLayer = tomLayer;
        this.dt = dt;

68
        this.log = new StateLog(k);
69 70
        senderEids = new HashSet<SenderEid>();
        senderStates = new HashSet<SenderState>();
71
        this.replica = 0;
72 73

        if (replica == manager.getStaticConf().getProcessId()) changeReplica();
74
        this.state = null;
75
        this.lastEid = -1;
76
        this.waitingEid = -1;
77
    }
78
    
79 80 81 82 83
    public int getReplica() {
        return replica;
    }

    public void changeReplica() {
84 85 86

        //******* EDUARDO BEGIN **************//
        int pos = -1;
87
        do {
88
            //TODO: Verificar se continua correto
89 90
            pos = this.reconfManager.getCurrentViewPos(replica);
            replica = this.reconfManager.getCurrentViewProcesses()[(pos + 1) % reconfManager.getCurrentViewN()];
91 92 93

            //replica = (replica + 1) % manager.getCurrentViewN();
        //******* EDUARDO END **************//
94
        } while (replica == reconfManager.getStaticConf().getProcessId());
95 96 97 98 99 100 101 102 103
    }

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

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

105 106
    public void addEID(int sender, int eid) {
        senderEids.add(new SenderEid(sender, eid));
107 108
    }

109 110
    public void emptyEIDs() {
        senderEids.clear();
111 112
    }

113 114 115 116 117 118 119 120 121 122 123 124 125
    public void emptyEIDs(int eid) {
        for (SenderEid m : senderEids)
            if (m.eid <= eid) senderEids.remove(m);
    }

    public void addState(int sender, TransferableState state) {
        senderStates.add(new SenderState(sender, state));
    }

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

126 127
    public int getWaiting() {
        return waitingEid;
128 129
    }

130 131
    public void setWaiting(int wait) {
        this.waitingEid = wait;
132 133 134 135 136 137 138 139 140
    }
    public void setLastEID(int eid) {
        lastEid = eid;
    }

    public int getLastEID() {
        return lastEid;
    }

141
    public boolean moreThenF_EIDs(int eid) {
P
pjsousa@gmail.com 已提交
142

143 144
        int count = 0;
        HashSet<Integer> replicasCounted = new HashSet<Integer>();
P
pjsousa@gmail.com 已提交
145

146
        for (SenderEid m : senderEids) {
147 148 149 150 151
            if (m.eid == eid && !replicasCounted.contains(m.sender)) {
                replicasCounted.add(m.sender);
                count++;
            }
        }
152 153

        //******* EDUARDO BEGIN **************//
154
        return count > reconfManager.getCurrentViewF();
155
        //******* EDUARDO END **************//
P
pjsousa@gmail.com 已提交
156
    }
157
    public boolean moreThanF_Replies() {
158 159 160 161 162

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

        for (SenderState m : senderStates) {
163
            if (!replicasCounted.contains(m.sender)) {
164 165 166 167 168
                replicasCounted.add(m.sender);
                count++;
            }
        }

169
        //******* EDUARDO BEGIN **************//
170
        return count > reconfManager.getCurrentViewF();
171
        //******* EDUARDO END **************//
172
    }
P
pjsousa@gmail.com 已提交
173

174
    public TransferableState getValidHash() {
175

176 177 178 179 180 181 182 183
        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++) {

184
                if (st[i].state.equals(st[j].state) && st[j].state.hasState()) count++;
185
                //******* EDUARDO BEGIN **************//
186
                if (count > reconfManager.getCurrentViewF()) return st[j].state;
187
                //******* EDUARDO END **************//
188 189 190 191 192 193
            }
        }

        return null;
    }

194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
    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;
    }

212 213 214 215
    public int getReplies() {
        return senderStates.size();
    }

216 217
    public StateLog getLog() {
        return log;
P
pjsousa@gmail.com 已提交
218
    }
219

220
    private class SenderEid {
221 222 223 224

        private int sender;
        private int eid;

225
        SenderEid(int sender, int eid) {
226 227 228 229 230 231
            this.sender = sender;
            this.eid = eid;
        }

        @Override
        public boolean equals(Object obj) {
232 233
            if (obj instanceof SenderEid) {
                SenderEid m = (SenderEid) obj;
234 235 236 237 238 239 240 241 242 243 244 245
                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;
        }
246
    }
247 248 249 250 251 252 253 254 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 301 302 303 304 305 306 307 308 309 310 311 312 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 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
    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);

                if (getLastEID() < eid && moreThenF_EIDs(eid)) {

                    Logger.println("(TOMLayer.requestState) I have now more than " + reconfManager.getCurrentViewF() + " messages for EID " + eid + " which are beyond EID " + getLastEID());

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

                    SMMessage smsg = new SMMessage(reconfManager.getStaticConf().getProcessId(),
                            eid - 1, TOMUtil.SM_REQUEST, getReplica(), null);
                    tomLayer.getCommunication().send(reconfManager.getCurrentViewOtherAcceptors(), smsg);

                    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 **************//
        if (reconfManager.getStaticConf().isStateTransferEnabled()) {
        //******* 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());

            boolean sendState = msg.getReplica() == reconfManager.getStaticConf().getProcessId();
            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() };
            SMMessage smsg = new SMMessage(reconfManager.getStaticConf().getProcessId(),
                    msg.getEid(), TOMUtil.SM_REPLY, -1, thisState);

            // 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();
        if (reconfManager.getStaticConf().isStateTransferEnabled()) {
        //******* 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()) {

                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()) {

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

                    TransferableState state = getValidHash();

                    int haveState = 0;
                    if (getReplicaState() != null) {
                        byte[] hash = null;
                        hash = tomLayer.computeHash(getReplicaState());
                        if (state != null) {
                            if (Arrays.equals(hash, state.getStateHash())) haveState = 1;
                            else if (getNumValidHashes() > reconfManager.getCurrentViewF()) haveState = -1;

                        }
                    }

                    if (state != null && haveState == 1) {

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

                        state.setState(getReplicaState());

                        lockState.lock();

                        getLog().update(state);

                        lockState.unlock();

                        dt.deliverLock();

                        //ot.OutOfContextLock();

                        setWaiting(-1);

                        dt.update(state);
                        tomLayer.processOutOfContext();

                        dt.canDeliver();

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

                        emptyStates();
                        setReplicaState(null);

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

                    //******* EDUARDO BEGIN **************//
                    } else if (state == null && (reconfManager.getCurrentViewN() / 2) < getReplies()) {
                    //******* EDUARDO END **************//

                        Logger.println("(TOMLayer.SMReplyDeliver) I have more than " +
                                (reconfManager.getCurrentViewN() / 2) + " messages that are no good!");

                        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();
    }
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497

    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 已提交
498
}