syncCommit.c 9.5 KB
Newer Older
M
Minghao Li 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 * Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
 *
 * This program is free software: you can use, redistribute, and/or modify
 * it under the terms of the GNU Affero General Public License, version 3
 * or later ("AGPL"), as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

16
#define _DEFAULT_SOURCE
M
Minghao Li 已提交
17
#include "syncCommit.h"
M
Minghao Li 已提交
18
#include "syncIndexMgr.h"
M
Minghao Li 已提交
19
#include "syncRaftLog.h"
M
Minghao Li 已提交
20
#include "syncRaftStore.h"
M
Minghao Li 已提交
21
#include "syncUtil.h"
M
Minghao Li 已提交
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45

// \* Leader i advances its commitIndex.
// \* This is done as a separate step from handling AppendEntries responses,
// \* in part to minimize atomic regions, and in part so that leaders of
// \* single-server clusters are able to mark entries committed.
// AdvanceCommitIndex(i) ==
//     /\ state[i] = Leader
//     /\ LET \* The set of servers that agree up through index.
//            Agree(index) == {i} \cup {k \in Server :
//                                          matchIndex[i][k] >= index}
//            \* The maximum indexes for which a quorum agrees
//            agreeIndexes == {index \in 1..Len(log[i]) :
//                                 Agree(index) \in Quorum}
//            \* New value for commitIndex'[i]
//            newCommitIndex ==
//               IF /\ agreeIndexes /= {}
//                  /\ log[i][Max(agreeIndexes)].term = currentTerm[i]
//               THEN
//                   Max(agreeIndexes)
//               ELSE
//                   commitIndex[i]
//        IN commitIndex' = [commitIndex EXCEPT ![i] = newCommitIndex]
//     /\ UNCHANGED <<messages, serverVars, candidateVars, leaderVars, log>>
//
46 47 48 49 50 51 52
void syncOneReplicaAdvance(SSyncNode* pSyncNode) {
  if (pSyncNode == NULL) {
    sError("pSyncNode is NULL");
    return;
  }

  if (pSyncNode->state != TAOS_SYNC_STATE_LEADER) {
S
Shengliang Guan 已提交
53
    sNError(pSyncNode, "not leader, can not advance commit index");
54 55 56 57
    return;
  }

  if (pSyncNode->replicaNum != 1) {
S
Shengliang Guan 已提交
58
    sNError(pSyncNode, "not one replica, can not advance commit index");
59 60 61 62 63 64 65 66 67 68
    return;
  }

  // advance commit index to snapshot first
  SSnapshot snapshot;
  pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
  if (snapshot.lastApplyIndex > 0 && snapshot.lastApplyIndex > pSyncNode->commitIndex) {
    SyncIndex commitBegin = pSyncNode->commitIndex;
    SyncIndex commitEnd = snapshot.lastApplyIndex;
    pSyncNode->commitIndex = snapshot.lastApplyIndex;
S
Shengliang Guan 已提交
69
    sNTrace(pSyncNode, "commit by snapshot from index:%" PRId64 " to index:%" PRId64, commitBegin, commitEnd);
70 71 72 73 74
  }

  // advance commit index as large as possible
  SyncIndex lastIndex = syncNodeGetLastIndex(pSyncNode);
  if (lastIndex > pSyncNode->commitIndex) {
S
Shengliang Guan 已提交
75
    sNTrace(pSyncNode, "commit by wal from index:%" PRId64 " to index:%" PRId64, pSyncNode->commitIndex + 1, lastIndex);
76 77 78 79 80 81 82 83 84 85
    pSyncNode->commitIndex = lastIndex;
  }

  // call back Wal
  SyncIndex walCommitVer = logStoreWalCommitVer(pSyncNode->pLogStore);
  if (pSyncNode->commitIndex > walCommitVer) {
    pSyncNode->pLogStore->syncLogUpdateCommitIndex(pSyncNode->pLogStore, pSyncNode->commitIndex);
  }
}

M
Minghao Li 已提交
86
void syncMaybeAdvanceCommitIndex(SSyncNode* pSyncNode) {
M
Minghao Li 已提交
87 88 89 90 91
  if (pSyncNode == NULL) {
    sError("pSyncNode is NULL");
    return;
  }

M
Minghao Li 已提交
92
  if (pSyncNode->state != TAOS_SYNC_STATE_LEADER) {
S
Shengliang Guan 已提交
93
    sNError(pSyncNode, "not leader, can not advance commit index");
M
Minghao Li 已提交
94 95
    return;
  }
M
Minghao Li 已提交
96

97 98
  // advance commit index to sanpshot first
  SSnapshot snapshot;
99
  pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
100 101 102 103
  if (snapshot.lastApplyIndex > 0 && snapshot.lastApplyIndex > pSyncNode->commitIndex) {
    SyncIndex commitBegin = pSyncNode->commitIndex;
    SyncIndex commitEnd = snapshot.lastApplyIndex;
    pSyncNode->commitIndex = snapshot.lastApplyIndex;
S
Shengliang Guan 已提交
104
    sNTrace(pSyncNode, "commit by snapshot from index:%" PRId64 " to index:%" PRId64, commitBegin, commitEnd);
105 106
  }

M
Minghao Li 已提交
107
  // update commit index
M
Minghao Li 已提交
108
  SyncIndex newCommitIndex = pSyncNode->commitIndex;
109
  for (SyncIndex index = syncNodeGetLastIndex(pSyncNode); index > pSyncNode->commitIndex; --index) {
M
Minghao Li 已提交
110
    bool agree = syncAgree(pSyncNode, index);
111

M
Minghao Li 已提交
112
    if (agree) {
M
Minghao Li 已提交
113
      // term
114 115 116 117 118
      SSyncRaftEntry* pEntry = NULL;
      SLRUCache*      pCache = pSyncNode->pLogStore->pCache;
      LRUHandle*      h = taosLRUCacheLookup(pCache, &index, sizeof(index));
      if (h) {
        pEntry = (SSyncRaftEntry*)taosLRUCacheValue(pCache, h);
119

120
        pSyncNode->pLogStore->cacheHit++;
121 122
        sNTrace(pSyncNode, "hit cache index:%" PRId64 ", bytes:%u, %p", index, pEntry->bytes, pEntry);

123
      } else {
124
        pSyncNode->pLogStore->cacheMiss++;
125 126
        sNTrace(pSyncNode, "miss cache index:%" PRId64, index);

M
Minghao Li 已提交
127
        int32_t code = pSyncNode->pLogStore->syncLogGetEntry(pSyncNode->pLogStore, index, &pEntry);
M
Minghao Li 已提交
128
        if (code != 0) {
S
Shengliang Guan 已提交
129
          sNError(pSyncNode, "advance commit index error, read wal index:%" PRId64, index);
130
          return;
131
        }
132
      }
M
Minghao Li 已提交
133
      // cannot commit, even if quorum agree. need check term!
134
      if (pEntry->term <= pSyncNode->pRaftStore->currentTerm) {
M
Minghao Li 已提交
135 136
        // update commit index
        newCommitIndex = index;
137

138 139 140 141 142 143
        if (h) {
          taosLRUCacheRelease(pCache, h, false);
        } else {
          syncEntryDestory(pEntry);
        }

M
Minghao Li 已提交
144
        break;
M
Minghao Li 已提交
145
      } else {
S
Shengliang Guan 已提交
146 147
        sNTrace(pSyncNode, "can not commit due to term not equal, index:%" PRId64 ", term:%" PRIu64, pEntry->index,
                pEntry->term);
M
Minghao Li 已提交
148
      }
M
Minghao Li 已提交
149

150 151 152 153 154
      if (h) {
        taosLRUCacheRelease(pCache, h, false);
      } else {
        syncEntryDestory(pEntry);
      }
M
Minghao Li 已提交
155 156
    }
  }
M
Minghao Li 已提交
157

158 159 160 161 162 163
  // advance commit index as large as possible
  SyncIndex walCommitVer = logStoreWalCommitVer(pSyncNode->pLogStore);
  if (walCommitVer > newCommitIndex) {
    newCommitIndex = walCommitVer;
  }

164
  // maybe execute fsm
M
Minghao Li 已提交
165 166 167
  if (newCommitIndex > pSyncNode->commitIndex) {
    SyncIndex beginIndex = pSyncNode->commitIndex + 1;
    SyncIndex endIndex = newCommitIndex;
M
Minghao Li 已提交
168 169

    // update commit index
M
Minghao Li 已提交
170
    pSyncNode->commitIndex = newCommitIndex;
M
Minghao Li 已提交
171

M
Minghao Li 已提交
172
    // call back Wal
M
Minghao Li 已提交
173
    pSyncNode->pLogStore->syncLogUpdateCommitIndex(pSyncNode->pLogStore, pSyncNode->commitIndex);
M
Minghao Li 已提交
174 175

    // execute fsm
176
    if (pSyncNode != NULL && pSyncNode->pFsm != NULL) {
M
Minghao Li 已提交
177
      int32_t code = syncNodeDoCommit(pSyncNode, beginIndex, endIndex, pSyncNode->state);
178
      if (code != 0) {
S
Shengliang Guan 已提交
179 180
        sNError(pSyncNode, "advance commit index error, do commit begin:%" PRId64 ", end:%" PRId64, beginIndex,
                endIndex);
M
Minghao Li 已提交
181
        return;
182
      }
M
Minghao Li 已提交
183 184
    }
  }
M
Minghao Li 已提交
185 186 187
}

bool syncAgreeIndex(SSyncNode* pSyncNode, SRaftId* pRaftId, SyncIndex index) {
M
Minghao Li 已提交
188 189 190 191
  // I am leader, I agree
  if (syncUtilSameId(pRaftId, &(pSyncNode->myRaftId)) && pSyncNode->state == TAOS_SYNC_STATE_LEADER) {
    return true;
  }
M
Minghao Li 已提交
192

M
Minghao Li 已提交
193 194
  // follower agree
  SyncIndex matchIndex = syncIndexMgrGetIndex(pSyncNode->pMatchIndex, pRaftId);
M
Minghao Li 已提交
195
  if (matchIndex >= index) {
M
Minghao Li 已提交
196
    return true;
M
Minghao Li 已提交
197
  }
M
Minghao Li 已提交
198

M
Minghao Li 已提交
199
  // not agree
M
Minghao Li 已提交
200
  return false;
M
Minghao Li 已提交
201 202
}

203 204 205 206 207 208 209 210 211
static inline int64_t syncNodeAbs64(int64_t a, int64_t b) {
  ASSERT(a >= 0);
  ASSERT(b >= 0);

  int64_t c = a > b ? a - b : b - a;
  return c;
}

int32_t syncNodeDynamicQuorum(const SSyncNode* pSyncNode) {
M
Minghao Li 已提交
212 213
  return pSyncNode->quorum;

M
Minghao Li 已提交
214
#if 0
215 216 217 218
  int32_t quorum = 1;  // self

  int64_t timeNow = taosGetTimestampMs();
  for (int i = 0; i < pSyncNode->peersNum; ++i) {
219 220 221
    int64_t   peerStartTime = syncIndexMgrGetStartTime(pSyncNode->pNextIndex, &(pSyncNode->peersId)[i]);
    int64_t   peerRecvTime = syncIndexMgrGetRecvTime(pSyncNode->pNextIndex, &(pSyncNode->peersId)[i]);
    SyncIndex peerMatchIndex = syncIndexMgrGetIndex(pSyncNode->pMatchIndex, &(pSyncNode->peersId)[i]);
222

223 224 225 226 227 228 229 230 231
    int64_t recvTimeDiff = TABS(peerRecvTime - timeNow);
    int64_t startTimeDiff = TABS(peerStartTime - pSyncNode->startTime);
    int64_t logDiff = TABS(peerMatchIndex - syncNodeGetLastIndex(pSyncNode));

    /*
        int64_t recvTimeDiff = syncNodeAbs64(peerRecvTime, timeNow);
        int64_t startTimeDiff = syncNodeAbs64(peerStartTime, pSyncNode->startTime);
        int64_t logDiff = syncNodeAbs64(peerMatchIndex, syncNodeGetLastIndex(pSyncNode));
    */
232 233 234 235

    int32_t addQuorum = 0;

    if (recvTimeDiff < SYNC_MAX_RECV_TIME_RANGE_MS) {
236 237 238 239 240 241 242 243 244
      if (startTimeDiff < SYNC_MAX_START_TIME_RANGE_MS) {
        addQuorum = 1;
      } else {
        if (logDiff < SYNC_ADD_QUORUM_COUNT) {
          addQuorum = 1;
        } else {
          addQuorum = 0;
        }
      }
245 246 247 248
    } else {
      addQuorum = 0;
    }

249 250 251 252 253 254 255 256 257 258 259
    /*
        if (recvTimeDiff < SYNC_MAX_RECV_TIME_RANGE_MS) {
          addQuorum = 1;
        } else {
          addQuorum = 0;
        }

        if (startTimeDiff > SYNC_MAX_START_TIME_RANGE_MS) {
          addQuorum = 0;
        }
    */
260 261 262 263 264 265 266 267 268 269 270

    quorum += addQuorum;
  }

  ASSERT(quorum <= pSyncNode->replicaNum);

  if (quorum < pSyncNode->quorum) {
    quorum = pSyncNode->quorum;
  }

  return quorum;
M
Minghao Li 已提交
271
#endif
272 273
}

M
Minghao Li 已提交
274
/*
275 276 277 278 279 280 281 282 283 284 285 286
bool syncAgree(SSyncNode* pSyncNode, SyncIndex index) {
  int agreeCount = 0;
  for (int i = 0; i < pSyncNode->replicaNum; ++i) {
    if (syncAgreeIndex(pSyncNode, &(pSyncNode->replicasId[i]), index)) {
      ++agreeCount;
    }
    if (agreeCount >= syncNodeDynamicQuorum(pSyncNode)) {
      return true;
    }
  }
  return false;
}
M
Minghao Li 已提交
287
*/
288

M
Minghao Li 已提交
289 290 291 292 293 294 295 296 297 298 299
bool syncAgree(SSyncNode* pSyncNode, SyncIndex index) {
  int agreeCount = 0;
  for (int i = 0; i < pSyncNode->replicaNum; ++i) {
    if (syncAgreeIndex(pSyncNode, &(pSyncNode->replicasId[i]), index)) {
      ++agreeCount;
    }
    if (agreeCount >= pSyncNode->quorum) {
      return true;
    }
  }
  return false;
300
}