91a5dddb981b3f7b09e9a79dd44fa0c09d4448a2
[controller.git] / opendaylight / md-sal / sal-akka-raft / src / main / java / org / opendaylight / controller / cluster / raft / FollowerLogInformationImpl.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.controller.cluster.raft;
10
11 import com.google.common.base.Stopwatch;
12 import java.util.concurrent.TimeUnit;
13 import java.util.concurrent.atomic.AtomicLong;
14 import scala.concurrent.duration.FiniteDuration;
15
16 public class FollowerLogInformationImpl implements FollowerLogInformation {
17
18     private final String id;
19
20     private final AtomicLong nextIndex;
21
22     private final AtomicLong matchIndex;
23
24     private final Stopwatch stopwatch;
25
26     private final long followerTimeoutMillis;
27
28     public FollowerLogInformationImpl(String id, long nextIndex,
29         long matchIndex, FiniteDuration followerTimeoutDuration) {
30         this.id = id;
31         this.nextIndex = new AtomicLong(nextIndex);
32         this.matchIndex = new AtomicLong(matchIndex);
33         this.stopwatch = new Stopwatch();
34         this.followerTimeoutMillis = followerTimeoutDuration.toMillis();
35     }
36
37     @Override
38     public long incrNextIndex(){
39         return nextIndex.incrementAndGet();
40     }
41
42     @Override
43     public long decrNextIndex() {
44         return nextIndex.decrementAndGet();
45     }
46
47     @Override
48     public void setNextIndex(long nextIndex) {
49         this.nextIndex.set(nextIndex);
50     }
51
52     @Override
53     public long incrMatchIndex(){
54         return matchIndex.incrementAndGet();
55     }
56
57     @Override
58     public void setMatchIndex(long matchIndex) {
59         this.matchIndex.set(matchIndex);
60     }
61
62     @Override
63     public String getId() {
64         return id;
65     }
66
67     @Override
68     public long getNextIndex() {
69         return nextIndex.get();
70     }
71
72     @Override
73     public long getMatchIndex() {
74         return matchIndex.get();
75     }
76
77     @Override
78     public boolean isFollowerActive() {
79         long elapsed = stopwatch.elapsed(TimeUnit.MILLISECONDS);
80         return (stopwatch.isRunning()) && (elapsed <= followerTimeoutMillis);
81     }
82
83     @Override
84     public void markFollowerActive() {
85         if (stopwatch.isRunning()) {
86             stopwatch.reset();
87         }
88         stopwatch.start();
89     }
90
91     @Override
92     public void markFollowerInActive() {
93         if (stopwatch.isRunning()) {
94             stopwatch.stop();
95         }
96     }
97 }