syncAppendEntriesReply.c 13.3 KB
Newer Older
M
Minghao Li 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * 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/>.
 */

#include "syncAppendEntriesReply.h"
M
Minghao Li 已提交
17
#include "syncCommit.h"
M
Minghao Li 已提交
18 19
#include "syncIndexMgr.h"
#include "syncInt.h"
M
Minghao Li 已提交
20
#include "syncRaftCfg.h"
M
Minghao Li 已提交
21 22
#include "syncRaftLog.h"
#include "syncRaftStore.h"
23
#include "syncSnapshot.h"
M
Minghao Li 已提交
24 25
#include "syncUtil.h"
#include "syncVoteMgr.h"
M
Minghao Li 已提交
26

M
Minghao Li 已提交
27 28 29 30 31 32 33 34 35 36 37 38
// TLA+ Spec
// HandleAppendEntriesResponse(i, j, m) ==
//    /\ m.mterm = currentTerm[i]
//    /\ \/ /\ m.msuccess \* successful
//          /\ nextIndex'  = [nextIndex  EXCEPT ![i][j] = m.mmatchIndex + 1]
//          /\ matchIndex' = [matchIndex EXCEPT ![i][j] = m.mmatchIndex]
//       \/ /\ \lnot m.msuccess \* not successful
//          /\ nextIndex' = [nextIndex EXCEPT ![i][j] =
//                               Max({nextIndex[i][j] - 1, 1})]
//          /\ UNCHANGED <<matchIndex>>
//    /\ Discard(m)
//    /\ UNCHANGED <<serverVars, candidateVars, logVars, elections>>
M
Minghao Li 已提交
39
//
M
Minghao Li 已提交
40 41
int32_t syncNodeOnAppendEntriesReplyCb(SSyncNode* ths, SyncAppendEntriesReply* pMsg) {
  int32_t ret = 0;
M
Minghao Li 已提交
42

M
Minghao Li 已提交
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
  // print log
  syncAppendEntriesReplyLog2("==syncNodeOnAppendEntriesReplyCb==", pMsg);

  // if already drop replica, do not process
  if (!syncNodeInRaftGroup(ths, &(pMsg->srcId)) && !ths->pRaftCfg->isStandBy) {
    syncNodeEventLog(ths, "recv sync-append-entries-reply,  maybe replica already dropped");
    return 0;
  }

  // drop stale response
  if (pMsg->term < ths->pRaftStore->currentTerm) {
    char logBuf[128];
    snprintf(logBuf, sizeof(logBuf), "recv sync-append-entries-reply, recv-term:%lu, drop stale response", pMsg->term);
    syncNodeEventLog(ths, logBuf);
    return 0;
  }

  if (gRaftDetailLog) {
    syncNodeEventLog(ths, "recv sync-append-entries-reply, before");
  }
  syncIndexMgrLog2("==syncNodeOnAppendEntriesReplyCb== before pNextIndex", ths->pNextIndex);
  syncIndexMgrLog2("==syncNodeOnAppendEntriesReplyCb== before pMatchIndex", ths->pMatchIndex);

  // no need this code, because if I receive reply.term, then I must have sent for that term.
  //  if (pMsg->term > ths->pRaftStore->currentTerm) {
  //    syncNodeUpdateTerm(ths, pMsg->term);
  //  }

  if (pMsg->term > ths->pRaftStore->currentTerm) {
    char logBuf[128];
    snprintf(logBuf, sizeof(logBuf), "recv sync-append-entries-reply, error term, recv-term:%lu", pMsg->term);
    syncNodeErrorLog(ths, logBuf);
    return -1;
  }

  ASSERT(pMsg->term == ths->pRaftStore->currentTerm);

  if (pMsg->success) {
    // nextIndex'  = [nextIndex  EXCEPT ![i][j] = m.mmatchIndex + 1]
    syncIndexMgrSetIndex(ths->pNextIndex, &(pMsg->srcId), pMsg->matchIndex + 1);

    // matchIndex' = [matchIndex EXCEPT ![i][j] = m.mmatchIndex]
    syncIndexMgrSetIndex(ths->pMatchIndex, &(pMsg->srcId), pMsg->matchIndex);

    // maybe commit
    syncMaybeAdvanceCommitIndex(ths);

  } else {
    SyncIndex nextIndex = syncIndexMgrGetIndex(ths->pNextIndex, &(pMsg->srcId));

    // notice! int64, uint64
    if (nextIndex > SYNC_INDEX_BEGIN) {
      --nextIndex;
    } else {
      nextIndex = SYNC_INDEX_BEGIN;
    }
    syncIndexMgrSetIndex(ths->pNextIndex, &(pMsg->srcId), nextIndex);
  }

  if (gRaftDetailLog) {
    syncNodeEventLog(ths, "recv sync-append-entries-reply, after");
  }
  syncIndexMgrLog2("==syncNodeOnAppendEntriesReplyCb== after pNextIndex", ths->pNextIndex);
  syncIndexMgrLog2("==syncNodeOnAppendEntriesReplyCb== after pMatchIndex", ths->pMatchIndex);

  return ret;
}

111
// only start once
M
Minghao Li 已提交
112 113
static void syncNodeStartSnapshotOnce(SSyncNode* ths, SyncIndex beginIndex, SyncIndex endIndex, SyncTerm lastApplyTerm,
                                      SyncAppendEntriesReply* pMsg) {
114 115 116 117
  // get sender
  SSyncSnapshotSender* pSender = syncNodeGetSnapshotSender(ths, &(pMsg->srcId));
  ASSERT(pSender != NULL);

M
Minghao Li 已提交
118 119 120 121 122 123 124 125 126 127
  if (snapshotSenderIsStart(pSender)) {
    do {
      char* eventLog = snapshotSender2SimpleStr(pSender, "snapshot sender already start");
      syncNodeErrorLog(ths, eventLog);
      taosMemoryFree(eventLog);
    } while (0);

    return;
  }

128 129
  SSnapshot snapshot = {
      .data = NULL, .lastApplyIndex = endIndex, .lastApplyTerm = lastApplyTerm, .lastConfigIndex = SYNC_INDEX_INVALID};
130 131
  void*          pReader = NULL;
  SSnapshotParam readerParam = {.start = beginIndex, .end = endIndex};
M
Minghao Li 已提交
132 133 134 135
  int32_t        code = ths->pFsm->FpSnapshotStartRead(ths->pFsm, &readerParam, &pReader);
  ASSERT(code == 0);

  if (pMsg->privateTerm < pSender->privateTerm) {
136
    ASSERT(pReader != NULL);
137
    snapshotSenderStart(pSender, readerParam, snapshot, pReader);
M
Minghao Li 已提交
138 139

  } else {
140 141
    if (pReader != NULL) {
      ths->pFsm->FpSnapshotStopRead(ths->pFsm, pReader);
M
Minghao Li 已提交
142 143 144
    }
  }
}
M
Minghao Li 已提交
145

146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
int32_t syncNodeOnAppendEntriesReplySnapshot2Cb(SSyncNode* ths, SyncAppendEntriesReply* pMsg) {
  int32_t ret = 0;

  // if already drop replica, do not process
  if (!syncNodeInRaftGroup(ths, &(pMsg->srcId)) && !ths->pRaftCfg->isStandBy) {
    syncNodeEventLog(ths, "recv sync-append-entries-reply,  maybe replica already dropped");
    return -1;
  }

  // drop stale response
  if (pMsg->term < ths->pRaftStore->currentTerm) {
    char logBuf[128];
    snprintf(logBuf, sizeof(logBuf), "recv sync-append-entries-reply, recv-term:%lu, drop stale response", pMsg->term);
    syncNodeEventLog(ths, logBuf);
    return -1;
  }

163
  // error term
164 165 166 167 168 169 170 171 172 173
  if (pMsg->term > ths->pRaftStore->currentTerm) {
    char logBuf[128];
    snprintf(logBuf, sizeof(logBuf), "recv sync-append-entries-reply, error term, recv-term:%lu", pMsg->term);
    syncNodeErrorLog(ths, logBuf);
    return -1;
  }

  ASSERT(pMsg->term == ths->pRaftStore->currentTerm);

  if (pMsg->success) {
174 175
    SyncIndex newNextIndex = pMsg->matchIndex + 1;
    SyncIndex newMatchIndex = pMsg->matchIndex;
176

177 178 179 180 181 182
    bool needStartSnapshot = false;
    if (newMatchIndex >= SYNC_INDEX_BEGIN && !ths->pLogStore->syncLogExist(ths->pLogStore, newMatchIndex)) {
      needStartSnapshot = true;
    }

    if (!needStartSnapshot) {
183
      // update next-index, match-index
184 185
      syncIndexMgrSetIndex(ths->pNextIndex, &(pMsg->srcId), newNextIndex);
      syncIndexMgrSetIndex(ths->pMatchIndex, &(pMsg->srcId), newMatchIndex);
186

187 188 189 190
      // maybe commit
      if (ths->state == TAOS_SYNC_STATE_LEADER) {
        syncMaybeAdvanceCommitIndex(ths);
      }
191

192 193
    } else {
      // start snapshot <match+1, old snapshot.end>
194 195
      SSnapshot oldSnapshot;
      ths->pFsm->FpGetSnapshotInfo(ths->pFsm, &oldSnapshot);
196 197 198 199
      if (oldSnapshot.lastApplyIndex > newMatchIndex) {
        syncNodeStartSnapshotOnce(ths, newMatchIndex + 1, oldSnapshot.lastApplyIndex, oldSnapshot.lastApplyTerm,
                                  pMsg);  // term maybe not ok?
      }
200

201
      syncIndexMgrSetIndex(ths->pNextIndex, &(pMsg->srcId), oldSnapshot.lastApplyIndex + 1);
202
      syncIndexMgrSetIndex(ths->pMatchIndex, &(pMsg->srcId), newMatchIndex);
203 204
    }

205 206 207 208 209 210 211 212 213 214 215 216 217
    // event log, update next-index
    do {
      char    host[64];
      int16_t port;
      syncUtilU642Addr(pMsg->srcId.addr, host, sizeof(host), &port);

      char logBuf[256];
      snprintf(logBuf, sizeof(logBuf), "reset next-index:%ld, match-index:%ld for %s:%d", newNextIndex, newMatchIndex,
               host, port);
      syncNodeEventLog(ths, logBuf);

    } while (0);

218 219 220 221 222
  } else {
    SyncIndex nextIndex = syncIndexMgrGetIndex(ths->pNextIndex, &(pMsg->srcId));

    if (nextIndex > SYNC_INDEX_BEGIN) {
      --nextIndex;
223

224 225 226 227 228 229 230 231 232
      bool needStartSnapshot = false;
      if (nextIndex >= SYNC_INDEX_BEGIN && !ths->pLogStore->syncLogExist(ths->pLogStore, nextIndex)) {
        needStartSnapshot = true;
      }
      if (nextIndex - 1 >= SYNC_INDEX_BEGIN && !ths->pLogStore->syncLogExist(ths->pLogStore, nextIndex - 1)) {
        needStartSnapshot = true;
      }

      if (!needStartSnapshot) {
233
        // do nothing
234

235 236 237 238
      } else {
        SSyncRaftEntry* pEntry;
        int32_t         code = ths->pLogStore->syncLogGetEntry(ths->pLogStore, nextIndex, &pEntry);
        ASSERT(code == 0);
M
Minghao Li 已提交
239
        syncNodeStartSnapshotOnce(ths, SYNC_INDEX_BEGIN, nextIndex, pEntry->term, pMsg);
240 241 242 243 244 245 246 247 248 249 250 251

        // get sender
        SSyncSnapshotSender* pSender = syncNodeGetSnapshotSender(ths, &(pMsg->srcId));
        ASSERT(pSender != NULL);
        SyncIndex sentryIndex = pSender->snapshot.lastApplyIndex + 1;

        // update nextIndex to sentryIndex
        if (nextIndex <= sentryIndex) {
          nextIndex = sentryIndex;
        }
      }

252 253 254 255
    } else {
      nextIndex = SYNC_INDEX_BEGIN;
    }
    syncIndexMgrSetIndex(ths->pNextIndex, &(pMsg->srcId), nextIndex);
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270

    // event log, update next-index
    do {
      char    host[64];
      int16_t port;
      syncUtilU642Addr(pMsg->srcId.addr, host, sizeof(host), &port);

      SyncIndex newNextIndex = nextIndex;
      SyncIndex newMatchIndex = syncIndexMgrGetIndex(ths->pMatchIndex, &(pMsg->srcId));
      char      logBuf[256];
      snprintf(logBuf, sizeof(logBuf), "reset2 next-index:%ld, match-index:%ld for %s:%d", newNextIndex, newMatchIndex,
               host, port);
      syncNodeEventLog(ths, logBuf);

    } while (0);
271 272 273 274 275
  }

  return 0;
}

276 277 278
int32_t syncNodeOnAppendEntriesReplySnapshotCb(SSyncNode* ths, SyncAppendEntriesReply* pMsg) {
  int32_t ret = 0;

279
  // print log
280
  syncAppendEntriesReplyLog2("==syncNodeOnAppendEntriesReplySnapshotCb==", pMsg);
281

282
  // if already drop replica, do not process
M
Minghao Li 已提交
283
  if (!syncNodeInRaftGroup(ths, &(pMsg->srcId)) && !ths->pRaftCfg->isStandBy) {
284 285
    syncNodeEventLog(ths, "recv sync-append-entries-reply,  maybe replica already dropped");
    return 0;
286 287
  }

288
  // drop stale response
289
  if (pMsg->term < ths->pRaftStore->currentTerm) {
290 291 292 293
    char logBuf[128];
    snprintf(logBuf, sizeof(logBuf), "recv sync-append-entries-reply, recv-term:%lu, drop stale response", pMsg->term);
    syncNodeEventLog(ths, logBuf);
    return 0;
294 295
  }

296
  if (gRaftDetailLog) {
297
    syncNodeEventLog(ths, "recv sync-append-entries-reply, before");
M
Minghao Li 已提交
298
  }
299 300
  syncIndexMgrLog2("recv sync-append-entries-reply, before pNextIndex:", ths->pNextIndex);
  syncIndexMgrLog2("recv sync-append-entries-reply, before pMatchIndex:", ths->pMatchIndex);
301 302 303 304 305 306 307

  // no need this code, because if I receive reply.term, then I must have sent for that term.
  //  if (pMsg->term > ths->pRaftStore->currentTerm) {
  //    syncNodeUpdateTerm(ths, pMsg->term);
  //  }

  if (pMsg->term > ths->pRaftStore->currentTerm) {
308 309 310 311
    char logBuf[128];
    snprintf(logBuf, sizeof(logBuf), "recv sync-append-entries-reply, error term, recv-term:%lu", pMsg->term);
    syncNodeErrorLog(ths, logBuf);
    return -1;
312 313
  }

314
  ASSERT(pMsg->term == ths->pRaftStore->currentTerm);
315 316 317 318

  if (pMsg->success) {
    // nextIndex'  = [nextIndex  EXCEPT ![i][j] = m.mmatchIndex + 1]
    syncIndexMgrSetIndex(ths->pNextIndex, &(pMsg->srcId), pMsg->matchIndex + 1);
319 320 321 322

    if (gRaftDetailLog) {
      sTrace("update next match, index:%ld, success:%d", pMsg->matchIndex + 1, pMsg->success);
    }
323 324 325 326 327

    // matchIndex' = [matchIndex EXCEPT ![i][j] = m.mmatchIndex]
    syncIndexMgrSetIndex(ths->pMatchIndex, &(pMsg->srcId), pMsg->matchIndex);

    // maybe commit
328 329 330
    if (ths->state == TAOS_SYNC_STATE_LEADER) {
      syncMaybeAdvanceCommitIndex(ths);
    }
331 332 333

  } else {
    SyncIndex nextIndex = syncIndexMgrGetIndex(ths->pNextIndex, &(pMsg->srcId));
334 335 336
    if (gRaftDetailLog) {
      sTrace("update next index not match, begin, index:%ld, success:%d", nextIndex, pMsg->success);
    }
337 338 339 340

    // notice! int64, uint64
    if (nextIndex > SYNC_INDEX_BEGIN) {
      --nextIndex;
341

342 343 344 345
      // get sender
      SSyncSnapshotSender* pSender = syncNodeGetSnapshotSender(ths, &(pMsg->srcId));
      ASSERT(pSender != NULL);

346 347 348 349
      SSnapshot snapshot = {.data = NULL,
                            .lastApplyIndex = SYNC_INDEX_INVALID,
                            .lastApplyTerm = 0,
                            .lastConfigIndex = SYNC_INDEX_INVALID};
M
Minghao Li 已提交
350 351 352 353 354 355
      void*     pReader = NULL;
      ths->pFsm->FpGetSnapshot(ths->pFsm, &snapshot, NULL, &pReader);
      if (snapshot.lastApplyIndex >= SYNC_INDEX_BEGIN && nextIndex <= snapshot.lastApplyIndex + 1 &&
          !snapshotSenderIsStart(pSender) && pMsg->privateTerm < pSender->privateTerm) {
        // has snapshot
        ASSERT(pReader != NULL);
356 357
        SSnapshotParam readerParam = {.start = 0, .end = snapshot.lastApplyIndex};
        snapshotSenderStart(pSender, readerParam, snapshot, pReader);
358

M
Minghao Li 已提交
359 360 361 362 363
      } else {
        // no snapshot
        if (pReader != NULL) {
          ths->pFsm->FpSnapshotStopRead(ths->pFsm, pReader);
        }
364 365 366 367 368 369 370
      }

      SyncIndex sentryIndex = pSender->snapshot.lastApplyIndex + 1;

      // update nextIndex to sentryIndex
      if (nextIndex <= sentryIndex) {
        nextIndex = sentryIndex;
371 372
      }

373 374 375
    } else {
      nextIndex = SYNC_INDEX_BEGIN;
    }
M
Minghao Li 已提交
376

377
    syncIndexMgrSetIndex(ths->pNextIndex, &(pMsg->srcId), nextIndex);
378 379 380
    if (gRaftDetailLog) {
      sTrace("update next index not match, end, index:%ld, success:%d", nextIndex, pMsg->success);
    }
381 382
  }

383 384 385 386 387
  if (gRaftDetailLog) {
    syncNodeEventLog(ths, "recv sync-append-entries-reply, after");
  }
  syncIndexMgrLog2("recv sync-append-entries-reply, after pNextIndex:", ths->pNextIndex);
  syncIndexMgrLog2("recv sync-append-entries-reply, after pMatchIndex:", ths->pMatchIndex);
388

389
  return 0;
390
}