mndVgroup.c 89.7 KB
Newer Older
H
refact  
Hongze Cheng 已提交
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/>.
 */

S
Shengliang Guan 已提交
16
#define _DEFAULT_SOURCE
S
Shengliang Guan 已提交
17
#include "mndVgroup.h"
S
Shengliang Guan 已提交
18
#include "mndDb.h"
S
Shengliang Guan 已提交
19
#include "mndDnode.h"
S
Shengliang Guan 已提交
20
#include "mndMnode.h"
21
#include "mndPrivilege.h"
S
Shengliang Guan 已提交
22 23
#include "mndShow.h"
#include "mndTrans.h"
S
Shengliang Guan 已提交
24
#include "mndUser.h"
H
Haojun Liao 已提交
25
#include "tmisce.h"
C
cadem 已提交
26
#include "mndStb.h"
S
Shengliang Guan 已提交
27

S
Shengliang Guan 已提交
28 29
#define VGROUP_VER_NUMBER   1
#define VGROUP_RESERVE_SIZE 64
S
Shengliang Guan 已提交
30

S
Shengliang Guan 已提交
31 32
static int32_t  mndVgroupActionInsert(SSdb *pSdb, SVgObj *pVgroup);
static int32_t  mndVgroupActionDelete(SSdb *pSdb, SVgObj *pVgroup);
S
Shengliang Guan 已提交
33
static int32_t  mndVgroupActionUpdate(SSdb *pSdb, SVgObj *pOld, SVgObj *pNew);
S
Shengliang Guan 已提交
34

S
Shengliang Guan 已提交
35
static int32_t mndRetrieveVgroups(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pBlock, int32_t rows);
S
Shengliang Guan 已提交
36
static void    mndCancelGetNextVgroup(SMnode *pMnode, void *pIter);
S
Shengliang Guan 已提交
37
static int32_t mndRetrieveVnodes(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pBlock, int32_t rows);
S
Shengliang Guan 已提交
38 39
static void    mndCancelGetNextVnode(SMnode *pMnode, void *pIter);

S
Shengliang Guan 已提交
40 41
static int32_t mndProcessRedistributeVgroupMsg(SRpcMsg *pReq);
static int32_t mndProcessSplitVgroupMsg(SRpcMsg *pReq);
S
Shengliang Guan 已提交
42
static int32_t mndProcessBalanceVgroupMsg(SRpcMsg *pReq);
C
cadem 已提交
43
static int32_t mndProcessVgroupBalanceLeaderMsg(SRpcMsg *pReq);
S
Shengliang Guan 已提交
44

S
Shengliang Guan 已提交
45
int32_t mndInitVgroup(SMnode *pMnode) {
S
Shengliang Guan 已提交
46 47 48 49 50 51 52 53 54
  SSdbTable table = {
      .sdbType = SDB_VGROUP,
      .keyType = SDB_KEY_INT32,
      .encodeFp = (SdbEncodeFp)mndVgroupActionEncode,
      .decodeFp = (SdbDecodeFp)mndVgroupActionDecode,
      .insertFp = (SdbInsertFp)mndVgroupActionInsert,
      .updateFp = (SdbUpdateFp)mndVgroupActionUpdate,
      .deleteFp = (SdbDeleteFp)mndVgroupActionDelete,
  };
S
Shengliang Guan 已提交
55

56 57 58 59
  mndSetMsgHandle(pMnode, TDMT_DND_CREATE_VNODE_RSP, mndTransProcessRsp);
  mndSetMsgHandle(pMnode, TDMT_VND_ALTER_REPLICA_RSP, mndTransProcessRsp);
  mndSetMsgHandle(pMnode, TDMT_VND_ALTER_CONFIG_RSP, mndTransProcessRsp);
  mndSetMsgHandle(pMnode, TDMT_VND_ALTER_CONFIRM_RSP, mndTransProcessRsp);
S
Shengliang Guan 已提交
60
  mndSetMsgHandle(pMnode, TDMT_VND_ALTER_HASHRANGE_RSP, mndTransProcessRsp);
61 62
  mndSetMsgHandle(pMnode, TDMT_DND_DROP_VNODE_RSP, mndTransProcessRsp);
  mndSetMsgHandle(pMnode, TDMT_VND_COMPACT_RSP, mndTransProcessRsp);
63
  mndSetMsgHandle(pMnode, TDMT_VND_DISABLE_WRITE_RSP, mndTransProcessRsp);
C
cadem 已提交
64
  mndSetMsgHandle(pMnode, TDMT_SYNC_FORCE_FOLLOWER_RSP, mndTransProcessRsp);
C
cadem 已提交
65
  mndSetMsgHandle(pMnode, TDMT_DND_ALTER_VNODE_TYPE_RSP, mndTransProcessRsp);
S
Shengliang Guan 已提交
66

67
  mndSetMsgHandle(pMnode, TDMT_MND_REDISTRIBUTE_VGROUP, mndProcessRedistributeVgroupMsg);
S
Shengliang Guan 已提交
68
  mndSetMsgHandle(pMnode, TDMT_MND_SPLIT_VGROUP, mndProcessSplitVgroupMsg);
C
cadem 已提交
69
  //mndSetMsgHandle(pMnode, TDMT_MND_BALANCE_VGROUP, mndProcessVgroupBalanceLeaderMsg);
70
  mndSetMsgHandle(pMnode, TDMT_MND_BALANCE_VGROUP, mndProcessBalanceVgroupMsg);
C
cadem 已提交
71
  mndSetMsgHandle(pMnode, TDMT_MND_BALANCE_VGROUP_LEADER, mndProcessVgroupBalanceLeaderMsg);
72

S
Shengliang Guan 已提交
73 74
  mndAddShowRetrieveHandle(pMnode, TSDB_MGMT_TABLE_VGROUP, mndRetrieveVgroups);
  mndAddShowFreeIterHandle(pMnode, TSDB_MGMT_TABLE_VGROUP, mndCancelGetNextVgroup);
S
Shengliang Guan 已提交
75 76 77
  mndAddShowRetrieveHandle(pMnode, TSDB_MGMT_TABLE_VNODES, mndRetrieveVnodes);
  mndAddShowFreeIterHandle(pMnode, TSDB_MGMT_TABLE_VNODES, mndCancelGetNextVnode);

S
Shengliang Guan 已提交
78
  return sdbSetTable(pMnode->pSdb, table);
S
Shengliang Guan 已提交
79 80 81 82
}

void mndCleanupVgroup(SMnode *pMnode) {}

S
Shengliang Guan 已提交
83
SSdbRaw *mndVgroupActionEncode(SVgObj *pVgroup) {
84 85
  terrno = TSDB_CODE_OUT_OF_MEMORY;

S
Shengliang Guan 已提交
86
  SSdbRaw *pRaw = sdbAllocRaw(SDB_VGROUP, VGROUP_VER_NUMBER, sizeof(SVgObj) + VGROUP_RESERVE_SIZE);
S
Shengliang Guan 已提交
87
  if (pRaw == NULL) goto _OVER;
S
Shengliang Guan 已提交
88 89

  int32_t dataPos = 0;
S
Shengliang Guan 已提交
90 91 92 93 94 95 96 97
  SDB_SET_INT32(pRaw, dataPos, pVgroup->vgId, _OVER)
  SDB_SET_INT64(pRaw, dataPos, pVgroup->createdTime, _OVER)
  SDB_SET_INT64(pRaw, dataPos, pVgroup->updateTime, _OVER)
  SDB_SET_INT32(pRaw, dataPos, pVgroup->version, _OVER)
  SDB_SET_INT32(pRaw, dataPos, pVgroup->hashBegin, _OVER)
  SDB_SET_INT32(pRaw, dataPos, pVgroup->hashEnd, _OVER)
  SDB_SET_BINARY(pRaw, dataPos, pVgroup->dbName, TSDB_DB_FNAME_LEN, _OVER)
  SDB_SET_INT64(pRaw, dataPos, pVgroup->dbUid, _OVER)
S
Shengliang Guan 已提交
98
  SDB_SET_INT8(pRaw, dataPos, pVgroup->isTsma, _OVER)
S
Shengliang Guan 已提交
99
  SDB_SET_INT8(pRaw, dataPos, pVgroup->replica, _OVER)
S
Shengliang Guan 已提交
100 101
  for (int8_t i = 0; i < pVgroup->replica; ++i) {
    SVnodeGid *pVgid = &pVgroup->vnodeGid[i];
S
Shengliang Guan 已提交
102
    SDB_SET_INT32(pRaw, dataPos, pVgid->dnodeId, _OVER)
103
  }
S
Shengliang Guan 已提交
104
  SDB_SET_RESERVE(pRaw, dataPos, VGROUP_RESERVE_SIZE, _OVER)
S
Shengliang Guan 已提交
105
  SDB_SET_DATALEN(pRaw, dataPos, _OVER)
106 107 108

  terrno = 0;

S
Shengliang Guan 已提交
109
_OVER:
110 111 112 113
  if (terrno != 0) {
    mError("vgId:%d, failed to encode to raw:%p since %s", pVgroup->vgId, pRaw, terrstr());
    sdbFreeRaw(pRaw);
    return NULL;
S
Shengliang Guan 已提交
114 115
  }

116
  mTrace("vgId:%d, encode to raw:%p, row:%p", pVgroup->vgId, pRaw, pVgroup);
S
Shengliang Guan 已提交
117 118 119
  return pRaw;
}

S
Shengliang Guan 已提交
120
SSdbRow *mndVgroupActionDecode(SSdbRaw *pRaw) {
121
  terrno = TSDB_CODE_OUT_OF_MEMORY;
122 123
  SSdbRow *pRow = NULL;
  SVgObj  *pVgroup = NULL;
124

S
Shengliang Guan 已提交
125
  int8_t sver = 0;
S
Shengliang Guan 已提交
126
  if (sdbGetRawSoftVer(pRaw, &sver) != 0) goto _OVER;
S
Shengliang Guan 已提交
127

S
Shengliang Guan 已提交
128
  if (sver != VGROUP_VER_NUMBER) {
S
Shengliang Guan 已提交
129
    terrno = TSDB_CODE_SDB_INVALID_DATA_VER;
S
Shengliang Guan 已提交
130
    goto _OVER;
S
Shengliang Guan 已提交
131 132
  }

133
  pRow = sdbAllocRow(sizeof(SVgObj));
S
Shengliang Guan 已提交
134
  if (pRow == NULL) goto _OVER;
135

136
  pVgroup = sdbGetRowObj(pRow);
S
Shengliang Guan 已提交
137
  if (pVgroup == NULL) goto _OVER;
S
Shengliang Guan 已提交
138 139

  int32_t dataPos = 0;
S
Shengliang Guan 已提交
140 141 142 143 144 145 146 147
  SDB_GET_INT32(pRaw, dataPos, &pVgroup->vgId, _OVER)
  SDB_GET_INT64(pRaw, dataPos, &pVgroup->createdTime, _OVER)
  SDB_GET_INT64(pRaw, dataPos, &pVgroup->updateTime, _OVER)
  SDB_GET_INT32(pRaw, dataPos, &pVgroup->version, _OVER)
  SDB_GET_INT32(pRaw, dataPos, &pVgroup->hashBegin, _OVER)
  SDB_GET_INT32(pRaw, dataPos, &pVgroup->hashEnd, _OVER)
  SDB_GET_BINARY(pRaw, dataPos, pVgroup->dbName, TSDB_DB_FNAME_LEN, _OVER)
  SDB_GET_INT64(pRaw, dataPos, &pVgroup->dbUid, _OVER)
S
Shengliang Guan 已提交
148
  SDB_GET_INT8(pRaw, dataPos, &pVgroup->isTsma, _OVER)
S
Shengliang Guan 已提交
149
  SDB_GET_INT8(pRaw, dataPos, &pVgroup->replica, _OVER)
S
Shengliang Guan 已提交
150 151
  for (int8_t i = 0; i < pVgroup->replica; ++i) {
    SVnodeGid *pVgid = &pVgroup->vnodeGid[i];
S
Shengliang Guan 已提交
152
    SDB_GET_INT32(pRaw, dataPos, &pVgid->dnodeId, _OVER)
S
Shengliang Guan 已提交
153
    if (pVgroup->replica == 1) {
154
      pVgid->syncState = TAOS_SYNC_STATE_LEADER;
S
Shengliang Guan 已提交
155
    }
S
Shengliang Guan 已提交
156
  }
S
Shengliang Guan 已提交
157
  SDB_GET_RESERVE(pRaw, dataPos, VGROUP_RESERVE_SIZE, _OVER)
158 159 160

  terrno = 0;

S
Shengliang Guan 已提交
161
_OVER:
162
  if (terrno != 0) {
163
    mError("vgId:%d, failed to decode from raw:%p since %s", pVgroup == NULL ? 0 : pVgroup->vgId, pRaw, terrstr());
wafwerar's avatar
wafwerar 已提交
164
    taosMemoryFreeClear(pRow);
165 166
    return NULL;
  }
S
Shengliang Guan 已提交
167

168
  mTrace("vgId:%d, decode from raw:%p, row:%p", pVgroup->vgId, pRaw, pVgroup);
S
Shengliang Guan 已提交
169 170 171 172
  return pRow;
}

static int32_t mndVgroupActionInsert(SSdb *pSdb, SVgObj *pVgroup) {
173
  mTrace("vgId:%d, perform insert action, row:%p", pVgroup->vgId, pVgroup);
S
Shengliang Guan 已提交
174 175 176 177
  return 0;
}

static int32_t mndVgroupActionDelete(SSdb *pSdb, SVgObj *pVgroup) {
178
  mTrace("vgId:%d, perform delete action, row:%p", pVgroup->vgId, pVgroup);
S
Shengliang Guan 已提交
179 180 181
  return 0;
}

S
Shengliang Guan 已提交
182 183 184 185 186 187 188
static int32_t mndVgroupActionUpdate(SSdb *pSdb, SVgObj *pOld, SVgObj *pNew) {
  mTrace("vgId:%d, perform update action, old row:%p new row:%p", pOld->vgId, pOld, pNew);
  pOld->updateTime = pNew->updateTime;
  pOld->version = pNew->version;
  pOld->hashBegin = pNew->hashBegin;
  pOld->hashEnd = pNew->hashEnd;
  pOld->replica = pNew->replica;
S
Shengliang Guan 已提交
189
  pOld->isTsma = pNew->isTsma;
190 191 192 193 194 195 196
  for (int32_t i = 0; i < pNew->replica; ++i) {
    SVnodeGid *pNewGid = &pNew->vnodeGid[i];
    for (int32_t j = 0; j < pOld->replica; ++j) {
      SVnodeGid *pOldGid = &pOld->vnodeGid[j];
      if (pNewGid->dnodeId == pOldGid->dnodeId) {
        pNewGid->syncState = pOldGid->syncState;
        pNewGid->syncRestore = pOldGid->syncRestore;
197
        pNewGid->syncCanRead = pOldGid->syncCanRead;
198 199 200
      }
    }
  }
201 202 203 204 205 206
  pNew->numOfTables = pOld->numOfTables;
  pNew->numOfTimeSeries = pOld->numOfTimeSeries;
  pNew->totalStorage = pOld->totalStorage;
  pNew->compStorage = pOld->compStorage;
  pNew->pointsWritten = pOld->pointsWritten;
  pNew->compact = pOld->compact;
C
cadem 已提交
207
  memcpy(pOld->vnodeGid, pNew->vnodeGid, (TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA) * sizeof(SVnodeGid));
S
Shengliang Guan 已提交
208 209 210 211
  return 0;
}

SVgObj *mndAcquireVgroup(SMnode *pMnode, int32_t vgId) {
S
Shengliang Guan 已提交
212 213
  SSdb   *pSdb = pMnode->pSdb;
  SVgObj *pVgroup = sdbAcquire(pSdb, SDB_VGROUP, &vgId);
S
Shengliang Guan 已提交
214
  if (pVgroup == NULL && terrno == TSDB_CODE_SDB_OBJ_NOT_THERE) {
S
Shengliang Guan 已提交
215 216 217
    terrno = TSDB_CODE_MND_VGROUP_NOT_EXIST;
  }
  return pVgroup;
S
Shengliang Guan 已提交
218 219 220 221 222 223 224
}

void mndReleaseVgroup(SMnode *pMnode, SVgObj *pVgroup) {
  SSdb *pSdb = pMnode->pSdb;
  sdbRelease(pSdb, pVgroup);
}

S
Shengliang Guan 已提交
225
void *mndBuildCreateVnodeReq(SMnode *pMnode, SDnodeObj *pDnode, SDbObj *pDb, SVgObj *pVgroup, int32_t *pContLen) {
S
Shengliang Guan 已提交
226 227 228 229 230
  SCreateVnodeReq createReq = {0};
  createReq.vgId = pVgroup->vgId;
  memcpy(createReq.db, pDb->name, TSDB_DB_FNAME_LEN);
  createReq.dbUid = pDb->uid;
  createReq.vgVersion = pVgroup->version;
S
Shengliang Guan 已提交
231 232 233 234
  createReq.numOfStables = pDb->cfg.numOfStables;
  createReq.buffer = pDb->cfg.buffer;
  createReq.pageSize = pDb->cfg.pageSize;
  createReq.pages = pDb->cfg.pages;
235
  createReq.cacheLastSize = pDb->cfg.cacheLastSize;
S
Shengliang Guan 已提交
236 237 238 239
  createReq.daysPerFile = pDb->cfg.daysPerFile;
  createReq.daysToKeep0 = pDb->cfg.daysToKeep0;
  createReq.daysToKeep1 = pDb->cfg.daysToKeep1;
  createReq.daysToKeep2 = pDb->cfg.daysToKeep2;
S
Shengliang Guan 已提交
240 241
  createReq.minRows = pDb->cfg.minRows;
  createReq.maxRows = pDb->cfg.maxRows;
242
  createReq.walFsyncPeriod = pDb->cfg.walFsyncPeriod;
S
Shengliang Guan 已提交
243 244 245
  createReq.walLevel = pDb->cfg.walLevel;
  createReq.precision = pDb->cfg.precision;
  createReq.compression = pDb->cfg.compression;
S
Shengliang Guan 已提交
246
  createReq.strict = pDb->cfg.strict;
247
  createReq.cacheLast = pDb->cfg.cacheLast;
C
cadem 已提交
248 249
  createReq.replica = 0;
  createReq.learnerReplica = 0;
S
Shengliang Guan 已提交
250
  createReq.selfIndex = -1;
C
cadem 已提交
251
  createReq.learnerSelfIndex = -1;
D
dapan1121 已提交
252 253
  createReq.hashBegin = pVgroup->hashBegin;
  createReq.hashEnd = pVgroup->hashEnd;
S
Shengliang Guan 已提交
254
  createReq.hashMethod = pDb->cfg.hashMethod;
S
sma  
Shengliang Guan 已提交
255 256
  createReq.numOfRetensions = pDb->cfg.numOfRetensions;
  createReq.pRetensions = pDb->cfg.pRetensions;
C
Cary Xu 已提交
257 258
  createReq.isTsma = pVgroup->isTsma;
  createReq.pTsma = pVgroup->pTsma;
S
Shengliang Guan 已提交
259 260 261 262
  createReq.walRetentionPeriod = pDb->cfg.walRetentionPeriod;
  createReq.walRetentionSize = pDb->cfg.walRetentionSize;
  createReq.walRollPeriod = pDb->cfg.walRollPeriod;
  createReq.walSegmentSize = pDb->cfg.walSegmentSize;
263
  createReq.sstTrigger = pDb->cfg.sstTrigger;
264 265
  createReq.hashPrefix = pDb->cfg.hashPrefix;
  createReq.hashSuffix = pDb->cfg.hashSuffix;
266 267
  createReq.tsdbPageSize = pDb->cfg.tsdbPageSize;

S
Shengliang Guan 已提交
268
  for (int32_t v = 0; v < pVgroup->replica; ++v) {
C
cadem 已提交
269 270 271 272 273 274 275 276 277
    SReplica  *pReplica = NULL;

    if(pVgroup->vnodeGid[v].nodeRole == TAOS_SYNC_ROLE_VOTER){
      pReplica = &createReq.replicas[createReq.replica];
    }
    else{
      pReplica = &createReq.learnerReplicas[createReq.learnerReplica];
    }

S
Shengliang Guan 已提交
278 279 280 281 282 283
    SVnodeGid *pVgid = &pVgroup->vnodeGid[v];
    SDnodeObj *pVgidDnode = mndAcquireDnode(pMnode, pVgid->dnodeId);
    if (pVgidDnode == NULL) {
      return NULL;
    }

S
Shengliang Guan 已提交
284 285
    pReplica->id = pVgidDnode->id;
    pReplica->port = pVgidDnode->port;
S
Shengliang Guan 已提交
286 287 288
    memcpy(pReplica->fqdn, pVgidDnode->fqdn, TSDB_FQDN_LEN);
    mndReleaseDnode(pMnode, pVgidDnode);

C
cadem 已提交
289 290 291 292 293 294 295 296 297 298 299 300
    if(pVgroup->vnodeGid[v].nodeRole == TAOS_SYNC_ROLE_VOTER){
      if (pDnode->id == pVgid->dnodeId) {
        createReq.selfIndex = createReq.replica;
      }
    }
    else{
      if (pDnode->id == pVgid->dnodeId) {
        createReq.learnerSelfIndex = createReq.learnerReplica;
      }
    }

    if(pVgroup->vnodeGid[v].nodeRole == TAOS_SYNC_ROLE_VOTER){
H
Haojun Liao 已提交
301
      createReq.replica++;
C
cadem 已提交
302 303 304
    }
    else{
      createReq.learnerReplica++;
S
Shengliang Guan 已提交
305 306 307
    }
  }

C
cadem 已提交
308
  if (createReq.selfIndex == -1 && createReq.learnerSelfIndex == -1) {
S
Shengliang Guan 已提交
309
    terrno = TSDB_CODE_APP_ERROR;
S
Shengliang Guan 已提交
310 311 312
    return NULL;
  }

H
Haojun Liao 已提交
313
  mInfo("vgId:%d, build create vnode req, replica:%d selfIndex:%d learnerReplica:%d learnerSelfIndex:%d strict:%d",
C
cadem 已提交
314 315
                          createReq.vgId, createReq.replica, createReq.selfIndex, createReq.learnerReplica,
                          createReq.learnerReplica, createReq.strict);
S
Shengliang Guan 已提交
316 317 318
  for (int32_t i = 0; i < createReq.replica; ++i) {
    mInfo("vgId:%d, replica:%d ep:%s:%u", createReq.vgId, i, createReq.replicas[i].fqdn, createReq.replicas[i].port);
  }
C
cadem 已提交
319
  for (int32_t i = 0; i < createReq.learnerReplica; ++i) {
H
Haojun Liao 已提交
320
    mInfo("vgId:%d, replica:%d ep:%s:%u", createReq.vgId, i, createReq.learnerReplicas[i].fqdn,
C
cadem 已提交
321 322
                                                                createReq.learnerReplicas[i].port);
  }
S
Shengliang Guan 已提交
323

S
Shengliang Guan 已提交
324 325 326 327 328 329
  int32_t contLen = tSerializeSCreateVnodeReq(NULL, 0, &createReq);
  if (contLen < 0) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

wafwerar's avatar
wafwerar 已提交
330
  void *pReq = taosMemoryMalloc(contLen);
S
Shengliang Guan 已提交
331 332 333 334 335 336 337 338
  if (pReq == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

  tSerializeSCreateVnodeReq(pReq, contLen, &createReq);
  *pContLen = contLen;
  return pReq;
S
Shengliang Guan 已提交
339 340
}

S
Shengliang Guan 已提交
341 342
static void *mndBuildAlterVnodeConfigReq(SMnode *pMnode, SDbObj *pDb, SVgObj *pVgroup, int32_t *pContLen) {
  SAlterVnodeConfigReq alterReq = {0};
S
Shengliang Guan 已提交
343 344 345
  alterReq.vgVersion = pVgroup->version;
  alterReq.buffer = pDb->cfg.buffer;
  alterReq.pageSize = pDb->cfg.pageSize;
346
  alterReq.pages = pDb->cfg.pages;
347
  alterReq.cacheLastSize = pDb->cfg.cacheLastSize;
S
Shengliang Guan 已提交
348 349 350 351
  alterReq.daysPerFile = pDb->cfg.daysPerFile;
  alterReq.daysToKeep0 = pDb->cfg.daysToKeep0;
  alterReq.daysToKeep1 = pDb->cfg.daysToKeep1;
  alterReq.daysToKeep2 = pDb->cfg.daysToKeep2;
352
  alterReq.walFsyncPeriod = pDb->cfg.walFsyncPeriod;
S
Shengliang Guan 已提交
353 354
  alterReq.walLevel = pDb->cfg.walLevel;
  alterReq.strict = pDb->cfg.strict;
355
  alterReq.cacheLast = pDb->cfg.cacheLast;
356 357
  alterReq.sttTrigger = pDb->cfg.sstTrigger;
  alterReq.minRows = pDb->cfg.minRows;
358 359
  alterReq.walRetentionPeriod = pDb->cfg.walRetentionPeriod;
  alterReq.walRetentionSize = pDb->cfg.walRetentionSize;
S
Shengliang Guan 已提交
360

S
Shengliang Guan 已提交
361
  mInfo("vgId:%d, build alter vnode config req", pVgroup->vgId);
S
Shengliang Guan 已提交
362
  int32_t contLen = tSerializeSAlterVnodeConfigReq(NULL, 0, &alterReq);
S
Shengliang Guan 已提交
363 364 365 366
  if (contLen < 0) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }
S
Shengliang Guan 已提交
367
  contLen += sizeof(SMsgHead);
S
Shengliang Guan 已提交
368 369 370 371 372 373 374 375 376 377 378

  void *pReq = taosMemoryMalloc(contLen);
  if (pReq == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

  SMsgHead *pHead = pReq;
  pHead->contLen = htonl(contLen);
  pHead->vgId = htonl(pVgroup->vgId);

S
Shengliang Guan 已提交
379
  tSerializeSAlterVnodeConfigReq((char *)pReq + sizeof(SMsgHead), contLen, &alterReq);
S
Shengliang Guan 已提交
380 381 382 383
  *pContLen = contLen;
  return pReq;
}

S
Shengliang Guan 已提交
384
static void *mndBuildAlterVnodeReplicaReq(SMnode *pMnode, SDbObj *pDb, SVgObj *pVgroup, int32_t dnodeId,
S
Shengliang Guan 已提交
385
                                          int32_t *pContLen) {
S
Shengliang Guan 已提交
386
  SAlterVnodeReplicaReq alterReq = {
S
Shengliang Guan 已提交
387 388
      .vgId = pVgroup->vgId,
      .strict = pDb->cfg.strict,
C
cadem 已提交
389 390
      .replica = 0,
      .learnerReplica = 0,
S
Shengliang Guan 已提交
391
      .selfIndex = -1,
C
cadem 已提交
392
      .learnerSelfIndex = -1,
S
Shengliang Guan 已提交
393
  };
S
Shengliang Guan 已提交
394 395

  for (int32_t v = 0; v < pVgroup->replica; ++v) {
C
cadem 已提交
396 397 398 399
    SReplica  *pReplica = NULL;

    if(pVgroup->vnodeGid[v].nodeRole == TAOS_SYNC_ROLE_VOTER){
      pReplica = &alterReq.replicas[alterReq.replica];
H
Haojun Liao 已提交
400
      alterReq.replica++;
C
cadem 已提交
401 402 403 404 405
    }
    else{
      pReplica = &alterReq.learnerReplicas[alterReq.learnerReplica];
      alterReq.learnerReplica++;
    }
H
Haojun Liao 已提交
406

S
Shengliang Guan 已提交
407 408
    SVnodeGid *pVgid = &pVgroup->vnodeGid[v];
    SDnodeObj *pVgidDnode = mndAcquireDnode(pMnode, pVgid->dnodeId);
409
    if (pVgidDnode == NULL) return NULL;
S
Shengliang Guan 已提交
410 411 412 413 414 415

    pReplica->id = pVgidDnode->id;
    pReplica->port = pVgidDnode->port;
    memcpy(pReplica->fqdn, pVgidDnode->fqdn, TSDB_FQDN_LEN);
    mndReleaseDnode(pMnode, pVgidDnode);

C
cadem 已提交
416 417 418 419 420 421 422 423 424
    if(pVgroup->vnodeGid[v].nodeRole == TAOS_SYNC_ROLE_VOTER){
      if (dnodeId == pVgid->dnodeId) {
        alterReq.selfIndex = v;
      }
    }
    else{
      if (dnodeId == pVgid->dnodeId) {
        alterReq.learnerSelfIndex = v;
      }
S
Shengliang Guan 已提交
425 426
    }
  }
C
cadem 已提交
427

H
Haojun Liao 已提交
428 429
  mInfo("vgId:%d, build alter vnode req, replica:%d selfIndex:%d learnerReplica:%d learnerSelfIndex:%d strict:%d",
                    alterReq.vgId, alterReq.replica, alterReq.selfIndex, alterReq.learnerReplica,
C
cadem 已提交
430
                                                      alterReq.learnerSelfIndex, alterReq.strict);
431 432 433
  for (int32_t i = 0; i < alterReq.replica; ++i) {
    mInfo("vgId:%d, replica:%d ep:%s:%u", alterReq.vgId, i, alterReq.replicas[i].fqdn, alterReq.replicas[i].port);
  }
C
cadem 已提交
434
  for (int32_t i = 0; i < alterReq.learnerReplica; ++i) {
H
Haojun Liao 已提交
435
    mInfo("vgId:%d, learnerReplica:%d ep:%s:%u", alterReq.vgId, i,
C
cadem 已提交
436 437
                alterReq.learnerReplicas[i].fqdn, alterReq.learnerReplicas[i].port);
  }
S
Shengliang Guan 已提交
438

C
cadem 已提交
439
  if (alterReq.selfIndex == -1 && alterReq.learnerSelfIndex == -1) {
S
Shengliang Guan 已提交
440
    terrno = TSDB_CODE_APP_ERROR;
S
Shengliang Guan 已提交
441 442
    return NULL;
  }
443

S
Shengliang Guan 已提交
444
  int32_t contLen = tSerializeSAlterVnodeReplicaReq(NULL, 0, &alterReq);
445 446 447 448 449 450 451 452 453 454 455
  if (contLen < 0) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

  void *pReq = taosMemoryMalloc(contLen);
  if (pReq == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

S
Shengliang Guan 已提交
456
  tSerializeSAlterVnodeReplicaReq(pReq, contLen, &alterReq);
457 458 459 460
  *pContLen = contLen;
  return pReq;
}

461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
static void *mndBuildDisableVnodeWriteReq(SMnode *pMnode, SDbObj *pDb, int32_t vgId, int32_t *pContLen) {
  SDisableVnodeWriteReq disableReq = {
      .vgId = vgId,
      .disable = 1,
  };

  mInfo("vgId:%d, build disable vnode write req", vgId);
  int32_t contLen = tSerializeSDisableVnodeWriteReq(NULL, 0, &disableReq);
  if (contLen < 0) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

  void *pReq = taosMemoryMalloc(contLen);
  if (pReq == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

  tSerializeSDisableVnodeWriteReq(pReq, contLen, &disableReq);
  *pContLen = contLen;
  return pReq;
}

485
static void *mndBuildAlterVnodeHashRangeReq(SMnode *pMnode, int32_t srcVgId, SVgObj *pVgroup, int32_t *pContLen) {
486
  SAlterVnodeHashRangeReq alterReq = {
487 488
      .srcVgId = srcVgId,
      .dstVgId = pVgroup->vgId,
489 490 491 492
      .hashBegin = pVgroup->hashBegin,
      .hashEnd = pVgroup->hashEnd,
  };

493
  mInfo("vgId:%d, build alter vnode hashrange req, dstVgId:%d, hashrange:[%u, %u]", srcVgId, pVgroup->vgId,
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
        pVgroup->hashBegin, pVgroup->hashEnd);
  int32_t contLen = tSerializeSAlterVnodeHashRangeReq(NULL, 0, &alterReq);
  if (contLen < 0) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

  void *pReq = taosMemoryMalloc(contLen);
  if (pReq == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

  tSerializeSAlterVnodeHashRangeReq(pReq, contLen, &alterReq);
  *pContLen = contLen;
  return pReq;
}

L
Liu Jicong 已提交
512
void *mndBuildDropVnodeReq(SMnode *pMnode, SDnodeObj *pDnode, SDbObj *pDb, SVgObj *pVgroup, int32_t *pContLen) {
S
Shengliang Guan 已提交
513 514 515 516 517 518
  SDropVnodeReq dropReq = {0};
  dropReq.dnodeId = pDnode->id;
  dropReq.vgId = pVgroup->vgId;
  memcpy(dropReq.db, pDb->name, TSDB_DB_FNAME_LEN);
  dropReq.dbUid = pDb->uid;

S
Shengliang Guan 已提交
519
  mInfo("vgId:%d, build drop vnode req", dropReq.vgId);
S
Shengliang Guan 已提交
520 521
  int32_t contLen = tSerializeSDropVnodeReq(NULL, 0, &dropReq);
  if (contLen < 0) {
S
Shengliang Guan 已提交
522 523 524 525
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

wafwerar's avatar
wafwerar 已提交
526
  void *pReq = taosMemoryMalloc(contLen);
S
Shengliang Guan 已提交
527 528 529 530
  if (pReq == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }
S
Shengliang Guan 已提交
531

S
Shengliang Guan 已提交
532 533 534
  tSerializeSDropVnodeReq(pReq, contLen, &dropReq);
  *pContLen = contLen;
  return pReq;
S
Shengliang Guan 已提交
535 536
}

S
Shengliang Guan 已提交
537 538 539
static bool mndResetDnodesArrayFp(SMnode *pMnode, void *pObj, void *p1, void *p2, void *p3) {
  SDnodeObj *pDnode = pObj;
  pDnode->numOfVnodes = 0;
540
  pDnode->numOfOtherNodes = 0;
S
Shengliang Guan 已提交
541 542 543 544 545 546
  return true;
}

static bool mndBuildDnodesArrayFp(SMnode *pMnode, void *pObj, void *p1, void *p2, void *p3) {
  SDnodeObj *pDnode = pObj;
  SArray    *pArray = p1;
S
Shengliang Guan 已提交
547 548 549 550 551
  int32_t    exceptDnodeId = *(int32_t *)p2;

  if (exceptDnodeId == pDnode->id) {
    return true;
  }
S
Shengliang Guan 已提交
552 553

  int64_t curMs = taosGetTimestampMs();
S
Shengliang Guan 已提交
554
  bool    online = mndIsDnodeOnline(pDnode, curMs);
S
Shengliang Guan 已提交
555 556
  bool    isMnode = mndIsMnode(pMnode, pDnode->id);
  pDnode->numOfVnodes = mndGetVnodesNum(pMnode, pDnode->id);
557
  pDnode->memUsed = mndGetVnodesMemory(pMnode, pDnode->id);
S
Shengliang Guan 已提交
558

559
  mInfo("dnode:%d, vnodes:%d supportVnodes:%d isMnode:%d online:%d memory avail:%" PRId64 " used:%" PRId64, pDnode->id,
560
        pDnode->numOfVnodes, pDnode->numOfSupportVnodes, isMnode, online, pDnode->memAvail, pDnode->memUsed);
S
Shengliang Guan 已提交
561 562

  if (isMnode) {
563
    pDnode->numOfOtherNodes++;
S
Shengliang Guan 已提交
564 565
  }

S
Shengliang Guan 已提交
566 567 568
  if (online && pDnode->numOfSupportVnodes > 0) {
    taosArrayPush(pArray, pDnode);
  }
S
Shengliang Guan 已提交
569 570 571
  return true;
}

S
Shengliang Guan 已提交
572
SArray *mndBuildDnodesArray(SMnode *pMnode, int32_t exceptDnodeId) {
S
Shengliang Guan 已提交
573
  SSdb   *pSdb = pMnode->pSdb;
S
Shengliang Guan 已提交
574
  int32_t numOfDnodes = mndGetDnodeSize(pMnode);
S
Shengliang Guan 已提交
575

S
Shengliang Guan 已提交
576 577 578 579 580
  SArray *pArray = taosArrayInit(numOfDnodes, sizeof(SDnodeObj));
  if (pArray == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }
S
Shengliang Guan 已提交
581

S
Shengliang Guan 已提交
582
  sdbTraverse(pSdb, SDB_DNODE, mndResetDnodesArrayFp, NULL, NULL, NULL);
S
Shengliang Guan 已提交
583
  sdbTraverse(pSdb, SDB_DNODE, mndBuildDnodesArrayFp, pArray, &exceptDnodeId, NULL);
584 585 586 587 588 589

  mDebug("build %d dnodes array", (int32_t)taosArrayGetSize(pArray));
  for (int32_t i = 0; i < (int32_t)taosArrayGetSize(pArray); ++i) {
    SDnodeObj *pDnode = taosArrayGet(pArray, i);
    mDebug("dnode:%d, vnodes:%d others:%d", pDnode->id, pDnode->numOfVnodes, pDnode->numOfOtherNodes);
  }
S
Shengliang Guan 已提交
590 591 592
  return pArray;
}

sangshuduo's avatar
sangshuduo 已提交
593
static int32_t mndCompareDnodeId(int32_t *dnode1Id, int32_t *dnode2Id) {
X
Xiaoyu Wang 已提交
594 595 596 597
  if (*dnode1Id == *dnode2Id) {
    return 0;
  }
  return *dnode1Id > *dnode2Id ? 1 : -1;
sangshuduo's avatar
sangshuduo 已提交
598
}
S
Shengliang Guan 已提交
599

600 601 602
static float mndGetDnodeScore(SDnodeObj *pDnode, int32_t additionDnodes, float ratio) {
  float totalDnodes = pDnode->numOfVnodes + (float)pDnode->numOfOtherNodes * ratio + additionDnodes;
  return totalDnodes / pDnode->numOfSupportVnodes;
603 604
}

S
Shengliang Guan 已提交
605
static int32_t mndCompareDnodeVnodes(SDnodeObj *pDnode1, SDnodeObj *pDnode2) {
606 607
  float d1Score = mndGetDnodeScore(pDnode1, 0, 0.9);
  float d2Score = mndGetDnodeScore(pDnode2, 0, 0.9);
X
Xiaoyu Wang 已提交
608 609 610 611
  if (d1Score == d2Score) {
    return 0;
  }
  return d1Score > d2Score ? 1 : -1;
S
Shengliang Guan 已提交
612 613
}

S
Shengliang Guan 已提交
614 615 616 617 618 619 620 621 622 623
void mndSortVnodeGid(SVgObj *pVgroup) {
  for (int32_t i = 0; i < pVgroup->replica; ++i) {
    for (int32_t j = 0; j < pVgroup->replica - 1 - i; ++j) {
      if (pVgroup->vnodeGid[j].dnodeId > pVgroup->vnodeGid[j + 1].dnodeId) {
        TSWAP(pVgroup->vnodeGid[j], pVgroup->vnodeGid[j + 1]);
      }
    }
  }
}

624
static int32_t mndGetAvailableDnode(SMnode *pMnode, SDbObj *pDb, SVgObj *pVgroup, SArray *pArray) {
S
Shengliang Guan 已提交
625 626 627 628
  SSdb   *pSdb = pMnode->pSdb;
  int32_t allocedVnodes = 0;
  void   *pIter = NULL;

629
  mDebug("start to sort %d dnodes", (int32_t)taosArrayGetSize(pArray));
S
Shengliang Guan 已提交
630
  taosArraySort(pArray, (__compar_fn_t)mndCompareDnodeVnodes);
631 632
  for (int32_t i = 0; i < (int32_t)taosArrayGetSize(pArray); ++i) {
    SDnodeObj *pDnode = taosArrayGet(pArray, i);
633
    mDebug("dnode:%d, score:%f", pDnode->id, mndGetDnodeScore(pDnode, 0, 0.9));
634
  }
S
Shengliang Guan 已提交
635

S
Shengliang Guan 已提交
636 637 638 639 640 641 642 643
  int32_t size = taosArrayGetSize(pArray);
  if (size < pVgroup->replica) {
    mError("db:%s, vgId:%d, no enough online dnodes:%d to alloc %d replica", pVgroup->dbName, pVgroup->vgId, size,
           pVgroup->replica);
    terrno = TSDB_CODE_MND_NO_ENOUGH_DNODES;
    return -1;
  }

S
Shengliang Guan 已提交
644 645 646
  for (int32_t v = 0; v < pVgroup->replica; ++v) {
    SVnodeGid *pVgid = &pVgroup->vnodeGid[v];
    SDnodeObj *pDnode = taosArrayGet(pArray, v);
647
    if (pDnode == NULL || pDnode->numOfVnodes >= pDnode->numOfSupportVnodes) {
S
Shengliang Guan 已提交
648 649 650 651
      terrno = TSDB_CODE_MND_NO_ENOUGH_DNODES;
      return -1;
    }

652 653 654 655 656 657 658 659 660 661
    int64_t vgMem = mndGetVgroupMemory(pMnode, pDb, pVgroup);
    if (pDnode->memAvail - vgMem - pDnode->memUsed <= 0) {
      mError("db:%s, vgId:%d, no enough memory:%" PRId64 " in dnode:%d, avail:%" PRId64 " used:%" PRId64,
             pVgroup->dbName, pVgroup->vgId, vgMem, pDnode->id, pDnode->memAvail, pDnode->memUsed);
      terrno = TSDB_CODE_MND_NO_ENOUGH_MEM_IN_DNODE;
      return -1;
    } else {
      pDnode->memUsed += vgMem;
    }

S
Shengliang Guan 已提交
662 663
    pVgid->dnodeId = pDnode->id;
    if (pVgroup->replica == 1) {
664
      pVgid->syncState = TAOS_SYNC_STATE_LEADER;
S
Shengliang Guan 已提交
665
    } else {
666
      pVgid->syncState = TAOS_SYNC_STATE_FOLLOWER;
S
Shengliang Guan 已提交
667 668
    }

669 670
    mInfo("db:%s, vgId:%d, vn:%d is alloced, memory:%" PRId64 ", dnode:%d avail:%" PRId64 " used:%" PRId64,
          pVgroup->dbName, pVgroup->vgId, v, vgMem, pVgid->dnodeId, pDnode->memAvail, pDnode->memUsed);
S
Shengliang Guan 已提交
671
    pDnode->numOfVnodes++;
S
Shengliang Guan 已提交
672
  }
S
Shengliang Guan 已提交
673

S
Shengliang Guan 已提交
674
  mndSortVnodeGid(pVgroup);
S
Shengliang Guan 已提交
675 676
  return 0;
}
677

S
Shengliang Guan 已提交
678
int32_t mndAllocSmaVgroup(SMnode *pMnode, SDbObj *pDb, SVgObj *pVgroup) {
S
Shengliang Guan 已提交
679
  SArray *pArray = mndBuildDnodesArray(pMnode, 0);
S
Shengliang Guan 已提交
680 681 682 683 684 685 686 687 688 689 690
  if (pArray == NULL) return -1;

  pVgroup->vgId = sdbGetMaxId(pMnode->pSdb, SDB_VGROUP);
  pVgroup->isTsma = 1;
  pVgroup->createdTime = taosGetTimestampMs();
  pVgroup->updateTime = pVgroup->createdTime;
  pVgroup->version = 1;
  memcpy(pVgroup->dbName, pDb->name, TSDB_DB_FNAME_LEN);
  pVgroup->dbUid = pDb->uid;
  pVgroup->replica = 1;

691
  if (mndGetAvailableDnode(pMnode, pDb, pVgroup, pArray) != 0) return -1;
L
Liu Jicong 已提交
692
  taosArrayDestroy(pArray);
S
Shengliang Guan 已提交
693 694 695 696 697

  mInfo("db:%s, sma vgId:%d is alloced", pDb->name, pVgroup->vgId);
  return 0;
}

S
Shengliang Guan 已提交
698
int32_t mndAllocVgroup(SMnode *pMnode, SDbObj *pDb, SVgObj **ppVgroups) {
S
Shengliang Guan 已提交
699 700 701 702
  int32_t code = -1;
  SArray *pArray = NULL;
  SVgObj *pVgroups = NULL;

wafwerar's avatar
wafwerar 已提交
703
  pVgroups = taosMemoryCalloc(pDb->cfg.numOfVgroups, sizeof(SVgObj));
S
Shengliang Guan 已提交
704 705
  if (pVgroups == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
S
Shengliang Guan 已提交
706
    goto _OVER;
S
Shengliang Guan 已提交
707 708
  }

S
Shengliang Guan 已提交
709
  pArray = mndBuildDnodesArray(pMnode, 0);
S
Shengliang Guan 已提交
710
  if (pArray == NULL) goto _OVER;
S
Shengliang Guan 已提交
711

S
Shengliang Guan 已提交
712 713
  mInfo("db:%s, total %d dnodes used to create %d vgroups (%d vnodes)", pDb->name, (int32_t)taosArrayGetSize(pArray),
        pDb->cfg.numOfVgroups, pDb->cfg.numOfVgroups * pDb->cfg.replications);
S
Shengliang Guan 已提交
714

S
Shengliang Guan 已提交
715
  int32_t  allocedVgroups = 0;
S
Shengliang Guan 已提交
716 717 718
  int32_t  maxVgId = sdbGetMaxId(pMnode->pSdb, SDB_VGROUP);
  uint32_t hashMin = 0;
  uint32_t hashMax = UINT32_MAX;
719
  uint32_t hashInterval = (hashMax - hashMin) / pDb->cfg.numOfVgroups;
S
Shengliang Guan 已提交
720

721 722
  if (maxVgId < 2) maxVgId = 2;

723
  for (uint32_t v = 0; v < pDb->cfg.numOfVgroups; v++) {
S
Shengliang Guan 已提交
724
    SVgObj *pVgroup = &pVgroups[v];
S
Shengliang Guan 已提交
725
    pVgroup->vgId = maxVgId++;
S
Shengliang Guan 已提交
726 727
    pVgroup->createdTime = taosGetTimestampMs();
    pVgroup->updateTime = pVgroups->createdTime;
S
Shengliang Guan 已提交
728
    pVgroup->version = 1;
S
Shengliang Guan 已提交
729
    pVgroup->hashBegin = hashMin + hashInterval * v;
730
    if (v == pDb->cfg.numOfVgroups - 1) {
S
Shengliang Guan 已提交
731 732
      pVgroup->hashEnd = hashMax;
    } else {
S
Shengliang Guan 已提交
733
      pVgroup->hashEnd = hashMin + hashInterval * (v + 1) - 1;
S
Shengliang Guan 已提交
734
    }
S
Shengliang Guan 已提交
735

736
    memcpy(pVgroup->dbName, pDb->name, TSDB_DB_FNAME_LEN);
S
Shengliang Guan 已提交
737
    pVgroup->dbUid = pDb->uid;
S
Shengliang Guan 已提交
738
    pVgroup->replica = pDb->cfg.replications;
S
Shengliang Guan 已提交
739

740
    if (mndGetAvailableDnode(pMnode, pDb, pVgroup, pArray) != 0) {
S
Shengliang Guan 已提交
741
      goto _OVER;
S
Shengliang Guan 已提交
742 743
    }

S
Shengliang Guan 已提交
744
    allocedVgroups++;
745 746
  }

S
Shengliang Guan 已提交
747
  *ppVgroups = pVgroups;
S
Shengliang Guan 已提交
748 749
  code = 0;

750
  mInfo("db:%s, total %d vgroups is alloced, replica:%d", pDb->name, pDb->cfg.numOfVgroups, pDb->cfg.replications);
S
Shengliang Guan 已提交
751

S
Shengliang Guan 已提交
752
_OVER:
wafwerar's avatar
wafwerar 已提交
753
  if (code != 0) taosMemoryFree(pVgroups);
S
Shengliang Guan 已提交
754 755
  taosArrayDestroy(pArray);
  return code;
756
}
757

L
Liu Jicong 已提交
758
SEpSet mndGetVgroupEpset(SMnode *pMnode, const SVgObj *pVgroup) {
759 760 761
  SEpSet epset = {0};

  for (int32_t v = 0; v < pVgroup->replica; ++v) {
L
Liu Jicong 已提交
762 763
    const SVnodeGid *pVgid = &pVgroup->vnodeGid[v];
    SDnodeObj       *pDnode = mndAcquireDnode(pMnode, pVgid->dnodeId);
764 765
    if (pDnode == NULL) continue;

766
    if (pVgid->syncState == TAOS_SYNC_STATE_LEADER) {
767 768 769
      epset.inUse = epset.numOfEps;
    }

H
Haojun Liao 已提交
770
    addEpIntoEpSet(&epset, pDnode->fqdn, pDnode->port);
771 772 773 774 775 776
    mndReleaseDnode(pMnode, pDnode);
  }

  return epset;
}

S
Shengliang Guan 已提交
777 778
static int32_t mndRetrieveVgroups(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pBlock, int32_t rows) {
  SMnode *pMnode = pReq->info.node;
S
Shengliang Guan 已提交
779 780 781 782
  SSdb   *pSdb = pMnode->pSdb;
  int32_t numOfRows = 0;
  SVgObj *pVgroup = NULL;
  int32_t cols = 0;
783
  int64_t curMs = taosGetTimestampMs();
S
Shengliang Guan 已提交
784

H
Haojun Liao 已提交
785 786 787 788 789 790 791
  SDbObj *pDb = NULL;
  if (strlen(pShow->db) > 0) {
    pDb = mndAcquireDb(pMnode, pShow->db);
    if (pDb == NULL) {
      return 0;
    }
  }
S
Shengliang Guan 已提交
792

S
Shengliang Guan 已提交
793 794 795 796
  while (numOfRows < rows) {
    pShow->pIter = sdbFetch(pSdb, SDB_VGROUP, pShow->pIter, (void **)&pVgroup);
    if (pShow->pIter == NULL) break;

H
Haojun Liao 已提交
797
    if (pDb != NULL && pVgroup->dbUid != pDb->uid) {
798
      sdbRelease(pSdb, pVgroup);
H
Haojun Liao 已提交
799 800 801 802
      continue;
    }

    cols = 0;
803
    SColumnInfoData *pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
804
    colDataSetVal(pColInfo, numOfRows, (const char *)&pVgroup->vgId, false);
H
Haojun Liao 已提交
805 806

    SName name = {0};
807 808 809 810
    char  db[TSDB_DB_NAME_LEN + VARSTR_HEADER_SIZE] = {0};
    tNameFromString(&name, pVgroup->dbName, T_NAME_ACCT | T_NAME_DB);
    tNameGetDbName(&name, varDataVal(db));
    varDataSetLen(db, strlen(varDataVal(db)));
H
Haojun Liao 已提交
811

812
    pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
813
    colDataSetVal(pColInfo, numOfRows, (const char *)db, false);
H
Haojun Liao 已提交
814

815
    pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
816
    colDataSetVal(pColInfo, numOfRows, (const char *)&pVgroup->numOfTables, false);
H
Haojun Liao 已提交
817

818 819
    // default 3 replica, add 1 replica if move vnode
    for (int32_t i = 0; i < 4; ++i) {
820
      pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
821
      if (i < pVgroup->replica) {
822
        int16_t dnodeId = (int16_t)pVgroup->vnodeGid[i].dnodeId;
823
        colDataSetVal(pColInfo, numOfRows, (const char *)&dnodeId, false);
824

825
        bool       exist = false;
826 827 828
        bool       online = false;
        SDnodeObj *pDnode = mndAcquireDnode(pMnode, pVgroup->vnodeGid[i].dnodeId);
        if (pDnode != NULL) {
829
          exist = true;
S
Shengliang Guan 已提交
830
          online = mndIsDnodeOnline(pDnode, curMs);
831 832 833
          mndReleaseDnode(pMnode, pDnode);
        }

834 835
        char buf1[20] = {0};
        char role[20] = "offline";
836 837 838
        if (!exist) {
          strcpy(role, "dropping");
        } else if (online) {
839 840 841 842 843 844 845 846 847 848
          char *star = "";
          if (pVgroup->vnodeGid[i].syncState == TAOS_SYNC_STATE_LEADER) {
            if (!pVgroup->vnodeGid[i].syncRestore && !pVgroup->vnodeGid[i].syncCanRead) {
              star = "**";
            } else if (!pVgroup->vnodeGid[i].syncRestore && pVgroup->vnodeGid[i].syncCanRead) {
              star = "*";
            } else {
            }
          }
          snprintf(role, sizeof(role), "%s%s", syncStr(pVgroup->vnodeGid[i].syncState), star);
849
        } else {
850
        }
S
Shengliang Guan 已提交
851
        STR_WITH_MAXSIZE_TO_VARSTR(buf1, role, pShow->pMeta->pSchemas[cols].bytes);
852 853

        pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
854
        colDataSetVal(pColInfo, numOfRows, (const char *)buf1, false);
855
      } else {
856
        colDataSetNULL(pColInfo, numOfRows);
857
        pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
858
        colDataSetNULL(pColInfo, numOfRows);
859
      }
S
Shengliang Guan 已提交
860
    }
S
Shengliang Guan 已提交
861

862
    pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
863
    int32_t cacheUsage = (int32_t)pVgroup->cacheUsage;
864
    colDataSetVal(pColInfo, numOfRows, (const char *)&cacheUsage, false);
865

D
dapan1121 已提交
866 867 868
    pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
    colDataSetVal(pColInfo, numOfRows, (const char *)&pVgroup->numOfCachedTables, false);

S
Shengliang Guan 已提交
869
    pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
870
    colDataSetVal(pColInfo, numOfRows, (const char *)&pVgroup->isTsma, false);
S
Shengliang Guan 已提交
871

H
Hongze Cheng 已提交
872 873
    // pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
    // if (pDb == NULL || pDb->compactStartTime <= 0) {
X
Xiaoyu Wang 已提交
874
    //   colDataSetNULL(pColInfo, numOfRows);
H
Hongze Cheng 已提交
875 876 877
    // } else {
    //   colDataAppend(pColInfo, numOfRows, (const char *)&pDb->compactStartTime, false);
    // }
878

H
Haojun Liao 已提交
879
    numOfRows++;
S
Shengliang Guan 已提交
880 881 882
    sdbRelease(pSdb, pVgroup);
  }

H
Haojun Liao 已提交
883 884 885 886
  if (pDb != NULL) {
    mndReleaseDb(pMnode, pDb);
  }

887
  pShow->numOfRows += numOfRows;
S
Shengliang Guan 已提交
888 889 890 891 892 893 894 895
  return numOfRows;
}

static void mndCancelGetNextVgroup(SMnode *pMnode, void *pIter) {
  SSdb *pSdb = pMnode->pSdb;
  sdbCancelFetch(pSdb, pIter);
}

S
Shengliang Guan 已提交
896 897 898 899
static bool mndGetVnodesNumFp(SMnode *pMnode, void *pObj, void *p1, void *p2, void *p3) {
  SVgObj  *pVgroup = pObj;
  int32_t  dnodeId = *(int32_t *)p1;
  int32_t *pNumOfVnodes = (int32_t *)p2;
S
Shengliang Guan 已提交
900

S
Shengliang Guan 已提交
901 902 903
  for (int32_t v = 0; v < pVgroup->replica; ++v) {
    if (pVgroup->vnodeGid[v].dnodeId == dnodeId) {
      (*pNumOfVnodes)++;
S
Shengliang Guan 已提交
904
    }
S
Shengliang Guan 已提交
905 906
  }

S
Shengliang Guan 已提交
907 908 909 910 911 912
  return true;
}

int32_t mndGetVnodesNum(SMnode *pMnode, int32_t dnodeId) {
  int32_t numOfVnodes = 0;
  sdbTraverse(pMnode->pSdb, SDB_VGROUP, mndGetVnodesNumFp, &dnodeId, &numOfVnodes, NULL);
S
Shengliang Guan 已提交
913
  return numOfVnodes;
S
Shengliang Guan 已提交
914 915
}

916 917 918 919 920 921
int64_t mndGetVgroupMemory(SMnode *pMnode, SDbObj *pDbInput, SVgObj *pVgroup) {
  SDbObj *pDb = pDbInput;
  if (pDbInput == NULL) {
    pDb = mndAcquireDb(pMnode, pVgroup->dbName);
  }

S
Shengliang Guan 已提交
922 923 924
  int64_t vgroupMemroy = 0;
  if (pDb != NULL) {
    vgroupMemroy = (int64_t)pDb->cfg.buffer * 1024 * 1024 + (int64_t)pDb->cfg.pages * pDb->cfg.pageSize * 1024;
925 926
    if (pDb->cfg.cacheLast > 0) {
      vgroupMemroy += (int64_t)pDb->cfg.cacheLastSize * 1024 * 1024;
S
Shengliang Guan 已提交
927
    }
928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955
  }

  if (pDbInput == NULL) {
    mndReleaseDb(pMnode, pDb);
  }
  return vgroupMemroy;
}

static bool mndGetVnodeMemroyFp(SMnode *pMnode, void *pObj, void *p1, void *p2, void *p3) {
  SVgObj  *pVgroup = pObj;
  int32_t  dnodeId = *(int32_t *)p1;
  int64_t *pVnodeMemory = (int64_t *)p2;

  for (int32_t v = 0; v < pVgroup->replica; ++v) {
    if (pVgroup->vnodeGid[v].dnodeId == dnodeId) {
      *pVnodeMemory += mndGetVgroupMemory(pMnode, NULL, pVgroup);
    }
  }

  return true;
}

int64_t mndGetVnodesMemory(SMnode *pMnode, int32_t dnodeId) {
  int64_t vnodeMemory = 0;
  sdbTraverse(pMnode->pSdb, SDB_VGROUP, mndGetVnodeMemroyFp, &dnodeId, &vnodeMemory, NULL);
  return vnodeMemory;
}

S
Shengliang Guan 已提交
956 957
static int32_t mndRetrieveVnodes(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pBlock, int32_t rows) {
  SMnode *pMnode = pReq->info.node;
S
Shengliang Guan 已提交
958 959 960 961 962 963 964 965 966
  SSdb   *pSdb = pMnode->pSdb;
  int32_t numOfRows = 0;
  SVgObj *pVgroup = NULL;
  int32_t cols = 0;

  while (numOfRows < rows) {
    pShow->pIter = sdbFetch(pSdb, SDB_VGROUP, pShow->pIter, (void **)&pVgroup);
    if (pShow->pIter == NULL) break;

S
Shengliang Guan 已提交
967
    for (int32_t i = 0; i < pVgroup->replica && numOfRows < rows; ++i) {
S
Shengliang Guan 已提交
968 969
      SVnodeGid       *pVgid = &pVgroup->vnodeGid[i];
      SColumnInfoData *pColInfo = NULL;
S
Shengliang Guan 已提交
970 971
      cols = 0;

972
      pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
973
      colDataSetVal(pColInfo, numOfRows, (const char *)&pVgroup->vgId, false);
H
Haojun Liao 已提交
974

975
      pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
976
      colDataSetVal(pColInfo, numOfRows, (const char *)&pVgroup->replica, false);
H
Haojun Liao 已提交
977

978
      char buf[20] = {0};
979
      STR_TO_VARSTR(buf, syncStr(pVgid->syncState));
980
      pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
981
      colDataSetVal(pColInfo, numOfRows, (const char *)buf, false);
H
Haojun Liao 已提交
982

S
Shengliang Guan 已提交
983 984 985 986 987 988 989 990
      const char *dbname = mndGetDbStr(pVgroup->dbName);
      char        b1[TSDB_DB_NAME_LEN + VARSTR_HEADER_SIZE] = {0};
      if (dbname != NULL) {
        STR_WITH_MAXSIZE_TO_VARSTR(b1, dbname, TSDB_DB_NAME_LEN + VARSTR_HEADER_SIZE);
      } else {
        STR_WITH_MAXSIZE_TO_VARSTR(b1, "NULL", TSDB_DB_NAME_LEN + VARSTR_HEADER_SIZE);
      }
      pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
991
      colDataSetVal(pColInfo, numOfRows, (const char *)b1, false);
S
Shengliang Guan 已提交
992 993

      pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
994
      colDataSetVal(pColInfo, numOfRows, (const char *)&pVgid->dnodeId, false);
S
Shengliang Guan 已提交
995 996 997 998 999 1000 1001 1002

      SDnodeObj *pDnode = mndAcquireDnode(pMnode, pVgid->dnodeId);
      char       b2[TSDB_EP_LEN + VARSTR_HEADER_SIZE] = {0};
      if (pDnode != NULL) {
        STR_WITH_MAXSIZE_TO_VARSTR(b2, pDnode->ep, TSDB_EP_LEN + VARSTR_HEADER_SIZE);
      } else {
        STR_WITH_MAXSIZE_TO_VARSTR(b2, "NULL", TSDB_EP_LEN + VARSTR_HEADER_SIZE);
      }
1003
      pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
1004
      colDataSetVal(pColInfo, numOfRows, (const char *)b2, false);
H
Haojun Liao 已提交
1005

S
Shengliang Guan 已提交
1006 1007 1008 1009 1010 1011
      numOfRows++;
    }

    sdbRelease(pSdb, pVgroup);
  }

1012
  pShow->numOfRows += numOfRows;
S
Shengliang Guan 已提交
1013 1014 1015 1016 1017 1018
  return numOfRows;
}

static void mndCancelGetNextVnode(SMnode *pMnode, void *pIter) {
  SSdb *pSdb = pMnode->pSdb;
  sdbCancelFetch(pSdb, pIter);
L
Liu Jicong 已提交
1019
}
S
Shengliang Guan 已提交
1020

1021
static int32_t mndAddVnodeToVgroup(SMnode *pMnode, STrans *pTrans, SVgObj *pVgroup, SArray *pArray) {
S
Shengliang Guan 已提交
1022 1023 1024
  taosArraySort(pArray, (__compar_fn_t)mndCompareDnodeVnodes);
  for (int32_t i = 0; i < taosArrayGetSize(pArray); ++i) {
    SDnodeObj *pDnode = taosArrayGet(pArray, i);
1025
    mInfo("dnode:%d, equivalent vnodes:%d others:%d", pDnode->id, pDnode->numOfVnodes, pDnode->numOfOtherNodes);
S
Shengliang Guan 已提交
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
  }

  SVnodeGid *pVgid = &pVgroup->vnodeGid[pVgroup->replica];
  for (int32_t d = 0; d < taosArrayGetSize(pArray); ++d) {
    SDnodeObj *pDnode = taosArrayGet(pArray, d);

    bool used = false;
    for (int32_t vn = 0; vn < pVgroup->replica; ++vn) {
      if (pDnode->id == pVgroup->vnodeGid[vn].dnodeId) {
        used = true;
        break;
      }
    }
    if (used) continue;

1041
    if (pDnode == NULL || pDnode->numOfVnodes >= pDnode->numOfSupportVnodes) {
S
Shengliang Guan 已提交
1042 1043 1044 1045
      terrno = TSDB_CODE_MND_NO_ENOUGH_DNODES;
      return -1;
    }

1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
    int64_t vgMem = mndGetVgroupMemory(pMnode, NULL, pVgroup);
    if (pDnode->memAvail - vgMem - pDnode->memUsed <= 0) {
      mError("db:%s, vgId:%d, no enough memory:%" PRId64 " in dnode:%d avail:%" PRId64 " used:%" PRId64,
             pVgroup->dbName, pVgroup->vgId, vgMem, pDnode->id, pDnode->memAvail, pDnode->memUsed);
      terrno = TSDB_CODE_MND_NO_ENOUGH_MEM_IN_DNODE;
      return -1;
    } else {
      pDnode->memUsed += vgMem;
    }

S
Shengliang Guan 已提交
1056
    pVgid->dnodeId = pDnode->id;
S
Shengliang Guan 已提交
1057
    pVgid->syncState = TAOS_SYNC_STATE_OFFLINE;
1058 1059
    mInfo("db:%s, vgId:%d, vn:%d is added, memory:%" PRId64 ", dnode:%d avail:%" PRId64 " used:%" PRId64,
          pVgroup->dbName, pVgroup->vgId, pVgroup->replica, vgMem, pVgid->dnodeId, pDnode->memAvail, pDnode->memUsed);
S
Shengliang Guan 已提交
1060 1061 1062

    pVgroup->replica++;
    pDnode->numOfVnodes++;
1063 1064 1065 1066 1067 1068 1069 1070 1071

    SSdbRaw *pVgRaw = mndVgroupActionEncode(pVgroup);
    if (pVgRaw == NULL) return -1;
    if (mndTransAppendRedolog(pTrans, pVgRaw) != 0) {
      sdbFreeRaw(pVgRaw);
      return -1;
    }
    (void)sdbSetRawStatus(pVgRaw, SDB_STATUS_READY);

S
Shengliang Guan 已提交
1072 1073 1074 1075 1076 1077 1078 1079
    return 0;
  }

  terrno = TSDB_CODE_MND_NO_ENOUGH_DNODES;
  mError("db:%s, failed to add vnode to vgId:%d since %s", pVgroup->dbName, pVgroup->vgId, terrstr());
  return -1;
}

1080 1081
static int32_t mndRemoveVnodeFromVgroup(SMnode *pMnode, STrans *pTrans, SVgObj *pVgroup, SArray *pArray,
                                        SVnodeGid *pDelVgid) {
S
Shengliang Guan 已提交
1082 1083 1084
  taosArraySort(pArray, (__compar_fn_t)mndCompareDnodeVnodes);
  for (int32_t i = 0; i < taosArrayGetSize(pArray); ++i) {
    SDnodeObj *pDnode = taosArrayGet(pArray, i);
1085
    mInfo("dnode:%d, equivalent vnodes:%d others:%d", pDnode->id, pDnode->numOfVnodes, pDnode->numOfOtherNodes);
S
Shengliang Guan 已提交
1086 1087 1088 1089 1090 1091 1092 1093 1094
  }

  int32_t code = -1;
  for (int32_t d = taosArrayGetSize(pArray) - 1; d >= 0; --d) {
    SDnodeObj *pDnode = taosArrayGet(pArray, d);

    for (int32_t vn = 0; vn < pVgroup->replica; ++vn) {
      SVnodeGid *pVgid = &pVgroup->vnodeGid[vn];
      if (pVgid->dnodeId == pDnode->id) {
1095 1096 1097 1098
        int64_t vgMem = mndGetVgroupMemory(pMnode, NULL, pVgroup);
        pDnode->memUsed -= vgMem;
        mInfo("db:%s, vgId:%d, vn:%d is removed, memory:%" PRId64 ", dnode:%d avail:%" PRId64 " used:%" PRId64,
              pVgroup->dbName, pVgroup->vgId, vn, vgMem, pVgid->dnodeId, pDnode->memAvail, pDnode->memUsed);
S
Shengliang Guan 已提交
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
        pDnode->numOfVnodes--;
        pVgroup->replica--;
        *pDelVgid = *pVgid;
        *pVgid = pVgroup->vnodeGid[pVgroup->replica];
        memset(&pVgroup->vnodeGid[pVgroup->replica], 0, sizeof(SVnodeGid));
        code = 0;
        goto _OVER;
      }
    }
  }

_OVER:
  if (code != 0) {
    terrno = TSDB_CODE_APP_ERROR;
    mError("db:%s, failed to remove vnode from vgId:%d since %s", pVgroup->dbName, pVgroup->vgId, terrstr());
    return -1;
  }

  for (int32_t vn = 0; vn < pVgroup->replica; ++vn) {
    SVnodeGid *pVgid = &pVgroup->vnodeGid[vn];
    mInfo("db:%s, vgId:%d, vn:%d dnode:%d is reserved", pVgroup->dbName, pVgroup->vgId, vn, pVgid->dnodeId);
  }
1121 1122 1123 1124 1125 1126 1127 1128 1129

  SSdbRaw *pVgRaw = mndVgroupActionEncode(pVgroup);
  if (pVgRaw == NULL) return -1;
  if (mndTransAppendRedolog(pTrans, pVgRaw) != 0) {
    sdbFreeRaw(pVgRaw);
    return -1;
  }
  (void)sdbSetRawStatus(pVgRaw, SDB_STATUS_READY);

S
Shengliang Guan 已提交
1130 1131 1132
  return 0;
}

S
Shengliang Guan 已提交
1133
int32_t mndAddCreateVnodeAction(SMnode *pMnode, STrans *pTrans, SDbObj *pDb, SVgObj *pVgroup, SVnodeGid *pVgid) {
S
Shengliang Guan 已提交
1134 1135 1136 1137 1138 1139 1140 1141
  STransAction action = {0};

  SDnodeObj *pDnode = mndAcquireDnode(pMnode, pVgid->dnodeId);
  if (pDnode == NULL) return -1;
  action.epSet = mndGetDnodeEpset(pDnode);
  mndReleaseDnode(pMnode, pDnode);

  int32_t contLen = 0;
S
Shengliang Guan 已提交
1142
  void   *pReq = mndBuildCreateVnodeReq(pMnode, pDnode, pDb, pVgroup, &contLen);
S
Shengliang Guan 已提交
1143 1144 1145 1146 1147
  if (pReq == NULL) return -1;

  action.pCont = pReq;
  action.contLen = contLen;
  action.msgType = TDMT_DND_CREATE_VNODE;
1148
  action.acceptableCode = TSDB_CODE_VND_ALREADY_EXIST;
S
Shengliang Guan 已提交
1149 1150 1151 1152 1153 1154 1155 1156 1157

  if (mndTransAppendRedoAction(pTrans, &action) != 0) {
    taosMemoryFree(pReq);
    return -1;
  }

  return 0;
}

C
cadem 已提交
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
int32_t mndRestoreAddCreateVnodeAction(SMnode *pMnode, STrans *pTrans, SDbObj *pDb, SVgObj *pVgroup, SDnodeObj *pDnode) {
  STransAction action = {0};

  action.epSet = mndGetDnodeEpset(pDnode);

  int32_t contLen = 0;
  void   *pReq = mndBuildCreateVnodeReq(pMnode, pDnode, pDb, pVgroup, &contLen);
  if (pReq == NULL) return -1;

  action.pCont = pReq;
  action.contLen = contLen;
  action.msgType = TDMT_DND_CREATE_VNODE;
  action.acceptableCode = TSDB_CODE_VND_ALREADY_EXIST;

  if (mndTransAppendRedoAction(pTrans, &action) != 0) {
    taosMemoryFree(pReq);
    return -1;
  }

  return 0;
}

S
Shengliang Guan 已提交
1180 1181 1182 1183
int32_t mndAddAlterVnodeConfirmAction(SMnode *pMnode, STrans *pTrans, SDbObj *pDb, SVgObj *pVgroup) {
  STransAction action = {0};
  action.epSet = mndGetVgroupEpset(pMnode, pVgroup);

1184
  mInfo("vgId:%d, build alter vnode confirm req", pVgroup->vgId);
S
Shengliang Guan 已提交
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
  int32_t   contLen = sizeof(SMsgHead);
  SMsgHead *pHead = taosMemoryMalloc(contLen);
  if (pHead == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return -1;
  }

  pHead->contLen = htonl(contLen);
  pHead->vgId = htonl(pVgroup->vgId);

  action.pCont = pHead;
  action.contLen = contLen;
  action.msgType = TDMT_VND_ALTER_CONFIRM;
1198 1199
  // incorrect redirect result will cause this erro
  action.retryCode = TSDB_CODE_VND_INVALID_VGROUP_ID;
S
Shengliang Guan 已提交
1200 1201 1202 1203 1204 1205 1206 1207 1208

  if (mndTransAppendRedoAction(pTrans, &action) != 0) {
    taosMemoryFree(pHead);
    return -1;
  }

  return 0;
}

1209
static int32_t mndAddAlterVnodeHashRangeAction(SMnode *pMnode, STrans *pTrans, int32_t srcVgId, SVgObj *pVgroup) {
1210 1211 1212 1213
  STransAction action = {0};
  action.epSet = mndGetVgroupEpset(pMnode, pVgroup);

  int32_t contLen = 0;
1214
  void   *pReq = mndBuildAlterVnodeHashRangeReq(pMnode, srcVgId, pVgroup, &contLen);
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
  if (pReq == NULL) return -1;

  action.pCont = pReq;
  action.contLen = contLen;
  action.msgType = TDMT_VND_ALTER_HASHRANGE;

  if (mndTransAppendRedoAction(pTrans, &action) != 0) {
    taosMemoryFree(pReq);
    return -1;
  }

  return 0;
}
S
Shengliang Guan 已提交
1228 1229

int32_t mndAddAlterVnodeConfigAction(SMnode *pMnode, STrans *pTrans, SDbObj *pDb, SVgObj *pVgroup) {
S
Shengliang Guan 已提交
1230 1231 1232 1233
  STransAction action = {0};
  action.epSet = mndGetVgroupEpset(pMnode, pVgroup);

  int32_t contLen = 0;
S
Shengliang Guan 已提交
1234
  void   *pReq = mndBuildAlterVnodeConfigReq(pMnode, pDb, pVgroup, &contLen);
S
Shengliang Guan 已提交
1235 1236 1237 1238
  if (pReq == NULL) return -1;

  action.pCont = pReq;
  action.contLen = contLen;
S
Shengliang Guan 已提交
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
  action.msgType = TDMT_VND_ALTER_CONFIG;

  if (mndTransAppendRedoAction(pTrans, &action) != 0) {
    taosMemoryFree(pReq);
    return -1;
  }

  return 0;
}

1249 1250 1251 1252
int32_t mndAddPrepareNewVgAction(SMnode *pMnode, STrans *pTrans, SVgObj *pVg) {
  SSdbRaw *pRaw = mndVgroupActionEncode(pVg);
  if (pRaw == NULL) goto _err;

1253
  STransAction action = {.pRaw = pRaw, .msgType = TDMT_MND_CREATE_VG};
1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
  if (mndTransAppendPrepareAction(pTrans, &action) != 0) goto _err;
  (void)sdbSetRawStatus(pRaw, SDB_STATUS_CREATING);
  pRaw = NULL;
  return 0;

_err:
  sdbFreeRaw(pRaw);
  return -1;
}

S
Shengliang Guan 已提交
1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278
int32_t mndAddAlterVnodeReplicaAction(SMnode *pMnode, STrans *pTrans, SDbObj *pDb, SVgObj *pVgroup, int32_t dnodeId) {
  SDnodeObj *pDnode = mndAcquireDnode(pMnode, dnodeId);
  if (pDnode == NULL) return -1;

  STransAction action = {0};
  action.epSet = mndGetDnodeEpset(pDnode);
  mndReleaseDnode(pMnode, pDnode);

  int32_t contLen = 0;
  void   *pReq = mndBuildAlterVnodeReplicaReq(pMnode, pDb, pVgroup, dnodeId, &contLen);
  if (pReq == NULL) return -1;

  action.pCont = pReq;
  action.contLen = contLen;
  action.msgType = TDMT_VND_ALTER_REPLICA;
S
Shengliang Guan 已提交
1279 1280 1281 1282 1283 1284 1285 1286 1287

  if (mndTransAppendRedoAction(pTrans, &action) != 0) {
    taosMemoryFree(pReq);
    return -1;
  }

  return 0;
}

C
cadem 已提交
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302
int32_t mndAddAlterVnodeTypeAction(SMnode *pMnode, STrans *pTrans, SDbObj *pDb, SVgObj *pVgroup, int32_t dnodeId) {
  SDnodeObj *pDnode = mndAcquireDnode(pMnode, dnodeId);
  if (pDnode == NULL) return -1;

  STransAction action = {0};
  action.epSet = mndGetDnodeEpset(pDnode);
  mndReleaseDnode(pMnode, pDnode);

  int32_t contLen = 0;
  void   *pReq = mndBuildAlterVnodeReplicaReq(pMnode, pDb, pVgroup, dnodeId, &contLen);
  if (pReq == NULL) return -1;

  action.pCont = pReq;
  action.contLen = contLen;
  action.msgType = TDMT_DND_ALTER_VNODE_TYPE;
C
cadem 已提交
1303 1304
  action.acceptableCode = TSDB_CODE_VND_ALREADY_IS_VOTER;
  action.retryCode = TSDB_CODE_VND_NOT_CATCH_UP;
C
cadem 已提交
1305 1306 1307 1308 1309 1310 1311 1312 1313

  if (mndTransAppendRedoAction(pTrans, &action) != 0) {
    taosMemoryFree(pReq);
    return -1;
  }

  return 0;
}

H
Haojun Liao 已提交
1314
int32_t mndRestoreAddAlterVnodeTypeAction(SMnode *pMnode, STrans *pTrans, SDbObj *pDb, SVgObj *pVgroup,
C
cadem 已提交
1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336
                                          SDnodeObj *pDnode) {
  STransAction action = {0};
  action.epSet = mndGetDnodeEpset(pDnode);

  int32_t contLen = 0;
  void   *pReq = mndBuildAlterVnodeReplicaReq(pMnode, pDb, pVgroup, pDnode->id, &contLen);
  if (pReq == NULL) return -1;

  action.pCont = pReq;
  action.contLen = contLen;
  action.msgType = TDMT_DND_ALTER_VNODE_TYPE;
  action.acceptableCode = TSDB_CODE_VND_ALREADY_IS_VOTER;
  action.retryCode = TSDB_CODE_VND_NOT_CATCH_UP;

  if (mndTransAppendRedoAction(pTrans, &action) != 0) {
    taosMemoryFree(pReq);
    return -1;
  }

  return 0;
}

X
Xiaoyu Wang 已提交
1337 1338
static int32_t mndAddDisableVnodeWriteAction(SMnode *pMnode, STrans *pTrans, SDbObj *pDb, SVgObj *pVgroup,
                                             int32_t dnodeId) {
1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
  SDnodeObj *pDnode = mndAcquireDnode(pMnode, dnodeId);
  if (pDnode == NULL) return -1;

  STransAction action = {0};
  action.epSet = mndGetDnodeEpset(pDnode);
  mndReleaseDnode(pMnode, pDnode);

  int32_t contLen = 0;
  void   *pReq = mndBuildDisableVnodeWriteReq(pMnode, pDb, pVgroup->vgId, &contLen);
  if (pReq == NULL) return -1;

  action.pCont = pReq;
  action.contLen = contLen;
  action.msgType = TDMT_VND_DISABLE_WRITE;

  if (mndTransAppendRedoAction(pTrans, &action) != 0) {
    taosMemoryFree(pReq);
    return -1;
  }

  return 0;
}

S
Shengliang Guan 已提交
1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
int32_t mndAddDropVnodeAction(SMnode *pMnode, STrans *pTrans, SDbObj *pDb, SVgObj *pVgroup, SVnodeGid *pVgid,
                              bool isRedo) {
  STransAction action = {0};

  SDnodeObj *pDnode = mndAcquireDnode(pMnode, pVgid->dnodeId);
  if (pDnode == NULL) return -1;
  action.epSet = mndGetDnodeEpset(pDnode);
  mndReleaseDnode(pMnode, pDnode);

  int32_t contLen = 0;
  void   *pReq = mndBuildDropVnodeReq(pMnode, pDnode, pDb, pVgroup, &contLen);
  if (pReq == NULL) return -1;

  action.pCont = pReq;
  action.contLen = contLen;
  action.msgType = TDMT_DND_DROP_VNODE;
1378
  action.acceptableCode = TSDB_CODE_VND_NOT_EXIST;
S
Shengliang Guan 已提交
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395

  if (isRedo) {
    if (mndTransAppendRedoAction(pTrans, &action) != 0) {
      taosMemoryFree(pReq);
      return -1;
    }
  } else {
    if (mndTransAppendUndoAction(pTrans, &action) != 0) {
      taosMemoryFree(pReq);
      return -1;
    }
  }

  return 0;
}

int32_t mndSetMoveVgroupInfoToTrans(SMnode *pMnode, STrans *pTrans, SDbObj *pDb, SVgObj *pVgroup, int32_t vnIndex,
D
dmchen 已提交
1396
                                    SArray *pArray, bool force, bool unsafe) {
S
Shengliang Guan 已提交
1397 1398
  SVgObj newVg = {0};
  memcpy(&newVg, pVgroup, sizeof(SVgObj));
S
Shengliang Guan 已提交
1399

S
Shengliang Guan 已提交
1400 1401 1402
  mInfo("vgId:%d, vgroup info before move, replica:%d", newVg.vgId, newVg.replica);
  for (int32_t i = 0; i < newVg.replica; ++i) {
    mInfo("vgId:%d, vnode:%d dnode:%d", newVg.vgId, i, newVg.vnodeGid[i].dnodeId);
S
Shengliang Guan 已提交
1403 1404
  }

S
Shengliang Guan 已提交
1405
  if (!force) {
1406 1407 1408
#if 1
    {
#else
1409
    if (newVg.replica == 1) {
1410 1411
#endif
      mInfo("vgId:%d, will add 1 vnode, replca:%d", pVgroup->vgId, newVg.replica);
1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
      if (mndAddVnodeToVgroup(pMnode, pTrans, &newVg, pArray) != 0) return -1;
      for (int32_t i = 0; i < newVg.replica - 1; ++i) {
        if (mndAddAlterVnodeReplicaAction(pMnode, pTrans, pDb, &newVg, newVg.vnodeGid[i].dnodeId) != 0) return -1;
      }
      if (mndAddCreateVnodeAction(pMnode, pTrans, pDb, &newVg, &newVg.vnodeGid[newVg.replica - 1]) != 0) return -1;
      if (mndAddAlterVnodeConfirmAction(pMnode, pTrans, pDb, &newVg) != 0) return -1;

      mInfo("vgId:%d, will remove 1 vnode, replca:2", pVgroup->vgId);
      newVg.replica--;
      SVnodeGid del = newVg.vnodeGid[vnIndex];
      newVg.vnodeGid[vnIndex] = newVg.vnodeGid[newVg.replica];
      memset(&newVg.vnodeGid[newVg.replica], 0, sizeof(SVnodeGid));
      {
        SSdbRaw *pRaw = mndVgroupActionEncode(&newVg);
        if (pRaw == NULL) return -1;
        if (mndTransAppendRedolog(pTrans, pRaw) != 0) {
          sdbFreeRaw(pRaw);
          return -1;
        }
        (void)sdbSetRawStatus(pRaw, SDB_STATUS_READY);
1432 1433
      }

1434 1435 1436 1437 1438
      if (mndAddDropVnodeAction(pMnode, pTrans, pDb, &newVg, &del, true) != 0) return -1;
      for (int32_t i = 0; i < newVg.replica; ++i) {
        if (mndAddAlterVnodeReplicaAction(pMnode, pTrans, pDb, &newVg, newVg.vnodeGid[i].dnodeId) != 0) return -1;
      }
      if (mndAddAlterVnodeConfirmAction(pMnode, pTrans, pDb, &newVg) != 0) return -1;
1439 1440 1441
#if 1
    }
#else
1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
    } else {  // new replica == 3
      mInfo("vgId:%d, will add 1 vnode, replca:3", pVgroup->vgId);
      if (mndAddVnodeToVgroup(pMnode, pTrans, &newVg, pArray) != 0) return -1;
      mInfo("vgId:%d, will remove 1 vnode, replca:4", pVgroup->vgId);
      newVg.replica--;
      SVnodeGid del = newVg.vnodeGid[vnIndex];
      newVg.vnodeGid[vnIndex] = newVg.vnodeGid[newVg.replica];
      memset(&newVg.vnodeGid[newVg.replica], 0, sizeof(SVnodeGid));
      {
        SSdbRaw *pRaw = mndVgroupActionEncode(&newVg);
        if (pRaw == NULL) return -1;
        if (mndTransAppendRedolog(pTrans, pRaw) != 0) {
          sdbFreeRaw(pRaw);
          return -1;
        }
        (void)sdbSetRawStatus(pRaw, SDB_STATUS_READY);
      }

      if (mndAddDropVnodeAction(pMnode, pTrans, pDb, &newVg, &del, true) != 0) return -1;
1461
      for (int32_t i = 0; i < newVg.replica; ++i) {
1462 1463 1464 1465 1466
        if (i == vnIndex) continue;
        if (mndAddAlterVnodeReplicaAction(pMnode, pTrans, pDb, &newVg, newVg.vnodeGid[i].dnodeId) != 0) return -1;
      }
      if (mndAddCreateVnodeAction(pMnode, pTrans, pDb, &newVg, &newVg.vnodeGid[vnIndex]) != 0) return -1;
      if (mndAddAlterVnodeConfirmAction(pMnode, pTrans, pDb, &newVg) != 0) return -1;
S
Shengliang Guan 已提交
1467
    }
1468
#endif
S
Shengliang Guan 已提交
1469 1470
  } else {
    mInfo("vgId:%d, will add 1 vnode and force remove 1 vnode", pVgroup->vgId);
1471
    if (mndAddVnodeToVgroup(pMnode, pTrans, &newVg, pArray) != 0) return -1;
S
Shengliang Guan 已提交
1472
    newVg.replica--;
D
fix ci  
dmchen 已提交
1473
    //SVnodeGid del = newVg.vnodeGid[vnIndex];
S
Shengliang Guan 已提交
1474 1475
    newVg.vnodeGid[vnIndex] = newVg.vnodeGid[newVg.replica];
    memset(&newVg.vnodeGid[newVg.replica], 0, sizeof(SVnodeGid));
1476 1477 1478 1479 1480 1481 1482 1483 1484
    {
      SSdbRaw *pRaw = mndVgroupActionEncode(&newVg);
      if (pRaw == NULL) return -1;
      if (mndTransAppendRedolog(pTrans, pRaw) != 0) {
        sdbFreeRaw(pRaw);
        return -1;
      }
      (void)sdbSetRawStatus(pRaw, SDB_STATUS_READY);
    }
S
Shengliang Guan 已提交
1485 1486 1487 1488 1489 1490

    for (int32_t i = 0; i < newVg.replica; ++i) {
      if (i != vnIndex) {
        if (mndAddAlterVnodeReplicaAction(pMnode, pTrans, pDb, &newVg, newVg.vnodeGid[i].dnodeId) != 0) return -1;
      }
    }
1491
    if (mndAddCreateVnodeAction(pMnode, pTrans, pDb, &newVg, &newVg.vnodeGid[vnIndex]) != 0) return -1;
S
Shengliang Guan 已提交
1492 1493
    if (mndAddAlterVnodeConfirmAction(pMnode, pTrans, pDb, &newVg) != 0) return -1;

C
cadem 已提交
1494
    if(newVg.replica == 1){
D
dmchen 已提交
1495 1496 1497 1498 1499
      if(force && !unsafe){
        terrno = TSDB_CODE_VND_META_DATA_UNSAFE_DELETE;
        return -1;
      }
      
C
cadem 已提交
1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518
      SSdb   *pSdb = pMnode->pSdb;
      void   *pIter = NULL; 

      while (1) {
        SStbObj *pStb = NULL;
        pIter = sdbFetch(pSdb, SDB_STB, pIter, (void **)&pStb);
        if (pIter == NULL) break;

        if (strcmp(pStb->db, pDb->name) == 0) {
          if (mndSetForceDropCreateStbRedoActions(pMnode, pTrans, &newVg, pStb) != 0) {
            sdbCancelFetch(pSdb, pIter);
            sdbRelease(pSdb, pStb);
            return -1;
          }
        }

        sdbRelease(pSdb, pStb);
      }

S
Shengliang Guan 已提交
1519
      mInfo("vgId:%d, all data is dropped since replica=1", pVgroup->vgId);
S
Shengliang Guan 已提交
1520
    }
S
Shengliang Guan 已提交
1521
  }
S
Shengliang Guan 已提交
1522

1523 1524
  {
    SSdbRaw *pRaw = mndVgroupActionEncode(&newVg);
1525 1526 1527 1528 1529
    if (pRaw == NULL) return -1;
    if (mndTransAppendCommitlog(pTrans, pRaw) != 0) {
      sdbFreeRaw(pRaw);
      return -1;
    }
S
Shengliang Guan 已提交
1530
    (void)sdbSetRawStatus(pRaw, SDB_STATUS_READY);
1531
  }
S
Shengliang Guan 已提交
1532

S
Shengliang Guan 已提交
1533 1534 1535
  mInfo("vgId:%d, vgroup info after move, replica:%d", newVg.vgId, newVg.replica);
  for (int32_t i = 0; i < newVg.replica; ++i) {
    mInfo("vgId:%d, vnode:%d dnode:%d", newVg.vgId, i, newVg.vnodeGid[i].dnodeId);
S
Shengliang Guan 已提交
1536 1537 1538 1539
  }
  return 0;
}

D
dmchen 已提交
1540
int32_t mndSetMoveVgroupsInfoToTrans(SMnode *pMnode, STrans *pTrans, int32_t delDnodeId, bool force, bool unsafe) {
S
Shengliang Guan 已提交
1541
  int32_t code = 0;
S
Shengliang Guan 已提交
1542
  SArray *pArray = mndBuildDnodesArray(pMnode, delDnodeId);
S
Shengliang Guan 已提交
1543 1544 1545 1546 1547 1548 1549 1550 1551 1552
  if (pArray == NULL) return -1;

  void *pIter = NULL;
  while (1) {
    SVgObj *pVgroup = NULL;
    pIter = sdbFetch(pMnode->pSdb, SDB_VGROUP, pIter, (void **)&pVgroup);
    if (pIter == NULL) break;

    int32_t vnIndex = -1;
    for (int32_t i = 0; i < pVgroup->replica; ++i) {
S
Shengliang Guan 已提交
1553
      if (pVgroup->vnodeGid[i].dnodeId == delDnodeId) {
S
Shengliang Guan 已提交
1554 1555 1556 1557 1558
        vnIndex = i;
        break;
      }
    }

S
Shengliang Guan 已提交
1559
    code = 0;
S
Shengliang Guan 已提交
1560
    if (vnIndex != -1) {
S
Shengliang Guan 已提交
1561
      mInfo("vgId:%d, vnode:%d will be removed from dnode:%d, force:%d", pVgroup->vgId, vnIndex, delDnodeId, force);
S
Shengliang Guan 已提交
1562
      SDbObj *pDb = mndAcquireDb(pMnode, pVgroup->dbName);
D
dmchen 已提交
1563
      code = mndSetMoveVgroupInfoToTrans(pMnode, pTrans, pDb, pVgroup, vnIndex, pArray, force, unsafe);
S
Shengliang Guan 已提交
1564 1565 1566 1567
      mndReleaseDb(pMnode, pDb);
    }

    sdbRelease(pMnode->pSdb, pVgroup);
S
Shengliang Guan 已提交
1568 1569 1570 1571 1572

    if (code != 0) {
      sdbCancelFetch(pMnode->pSdb, pIter);
      break;
    }
S
Shengliang Guan 已提交
1573 1574 1575
  }

  taosArrayDestroy(pArray);
S
Shengliang Guan 已提交
1576
  return code;
S
Shengliang Guan 已提交
1577 1578 1579 1580
}

static int32_t mndAddIncVgroupReplicaToTrans(SMnode *pMnode, STrans *pTrans, SDbObj *pDb, SVgObj *pVgroup,
                                             int32_t newDnodeId) {
1581
  mInfo("vgId:%d, will add 1 vnode, replica:%d dnode:%d", pVgroup->vgId, pVgroup->replica, newDnodeId);
S
Shengliang Guan 已提交
1582 1583 1584 1585

  SVnodeGid *pGid = &pVgroup->vnodeGid[pVgroup->replica];
  pVgroup->replica++;
  pGid->dnodeId = newDnodeId;
S
Shengliang Guan 已提交
1586
  pGid->syncState = TAOS_SYNC_STATE_OFFLINE;
S
Shengliang Guan 已提交
1587

1588 1589 1590 1591 1592 1593 1594 1595
  SSdbRaw *pVgRaw = mndVgroupActionEncode(pVgroup);
  if (pVgRaw == NULL) return -1;
  if (mndTransAppendRedolog(pTrans, pVgRaw) != 0) {
    sdbFreeRaw(pVgRaw);
    return -1;
  }
  (void)sdbSetRawStatus(pVgRaw, SDB_STATUS_READY);

S
Shengliang Guan 已提交
1596 1597
  for (int32_t i = 0; i < pVgroup->replica - 1; ++i) {
    if (mndAddAlterVnodeReplicaAction(pMnode, pTrans, pDb, pVgroup, pVgroup->vnodeGid[i].dnodeId) != 0) return -1;
S
Shengliang Guan 已提交
1598
  }
1599
  if (mndAddCreateVnodeAction(pMnode, pTrans, pDb, pVgroup, pGid) != 0) return -1;
S
Shengliang Guan 已提交
1600
  if (mndAddAlterVnodeConfirmAction(pMnode, pTrans, pDb, pVgroup) != 0) return -1;
S
Shengliang Guan 已提交
1601 1602 1603 1604 1605 1606

  return 0;
}

static int32_t mndAddDecVgroupReplicaFromTrans(SMnode *pMnode, STrans *pTrans, SDbObj *pDb, SVgObj *pVgroup,
                                               int32_t delDnodeId) {
1607
  mInfo("vgId:%d, will remove 1 vnode, replica:%d dnode:%d", pVgroup->vgId, pVgroup->replica, delDnodeId);
S
Shengliang Guan 已提交
1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619

  SVnodeGid *pGid = NULL;
  SVnodeGid  delGid = {0};
  for (int32_t i = 0; i < pVgroup->replica; ++i) {
    if (pVgroup->vnodeGid[i].dnodeId == delDnodeId) {
      pGid = &pVgroup->vnodeGid[i];
      break;
    }
  }

  if (pGid == NULL) return 0;

1620
  pVgroup->replica--;
S
Shengliang Guan 已提交
1621 1622 1623 1624
  memcpy(&delGid, pGid, sizeof(SVnodeGid));
  memcpy(pGid, &pVgroup->vnodeGid[pVgroup->replica], sizeof(SVnodeGid));
  memset(&pVgroup->vnodeGid[pVgroup->replica], 0, sizeof(SVnodeGid));

1625 1626 1627 1628 1629 1630 1631 1632
  SSdbRaw *pVgRaw = mndVgroupActionEncode(pVgroup);
  if (pVgRaw == NULL) return -1;
  if (mndTransAppendRedolog(pTrans, pVgRaw) != 0) {
    sdbFreeRaw(pVgRaw);
    return -1;
  }
  (void)sdbSetRawStatus(pVgRaw, SDB_STATUS_READY);

S
Shengliang Guan 已提交
1633 1634 1635
  if (mndAddDropVnodeAction(pMnode, pTrans, pDb, pVgroup, &delGid, true) != 0) return -1;
  for (int32_t i = 0; i < pVgroup->replica; ++i) {
    if (mndAddAlterVnodeReplicaAction(pMnode, pTrans, pDb, pVgroup, pVgroup->vnodeGid[i].dnodeId) != 0) return -1;
S
Shengliang Guan 已提交
1636
  }
S
Shengliang Guan 已提交
1637
  if (mndAddAlterVnodeConfirmAction(pMnode, pTrans, pDb, pVgroup) != 0) return -1;
S
Shengliang Guan 已提交
1638 1639 1640 1641 1642 1643 1644

  return 0;
}

static int32_t mndRedistributeVgroup(SMnode *pMnode, SRpcMsg *pReq, SDbObj *pDb, SVgObj *pVgroup, SDnodeObj *pNew1,
                                     SDnodeObj *pOld1, SDnodeObj *pNew2, SDnodeObj *pOld2, SDnodeObj *pNew3,
                                     SDnodeObj *pOld3) {
1645 1646
  int32_t code = -1;
  STrans *pTrans = NULL;
S
Shengliang Guan 已提交
1647

1648
  pTrans = mndTransCreate(pMnode, TRN_POLICY_RETRY, TRN_CONFLICT_GLOBAL, pReq, "red-vgroup");
S
Shengliang Guan 已提交
1649 1650
  if (pTrans == NULL) goto _OVER;
  mndTransSetSerial(pTrans);
1651
  mInfo("trans:%d, used to redistribute vgroup, vgId:%d", pTrans->id, pVgroup->vgId);
S
Shengliang Guan 已提交
1652 1653 1654 1655 1656

  SVgObj newVg = {0};
  memcpy(&newVg, pVgroup, sizeof(SVgObj));
  mInfo("vgId:%d, vgroup info before redistribute, replica:%d", newVg.vgId, newVg.replica);
  for (int32_t i = 0; i < newVg.replica; ++i) {
S
Shengliang Guan 已提交
1657
    mInfo("vgId:%d, vnode:%d dnode:%d role:%s", newVg.vgId, i, newVg.vnodeGid[i].dnodeId,
1658
          syncStr(newVg.vnodeGid[i].syncState));
S
Shengliang Guan 已提交
1659 1660
  }

S
Shengliang Guan 已提交
1661
  if (pNew1 != NULL && pOld1 != NULL) {
1662 1663 1664 1665 1666 1667 1668
    int32_t numOfVnodes = mndGetVnodesNum(pMnode, pNew1->id);
    if (numOfVnodes >= pNew1->numOfSupportVnodes) {
      mError("vgId:%d, no enough vnodes in dnode:%d, numOfVnodes:%d support:%d", newVg.vgId, pNew1->id, numOfVnodes,
             pNew1->numOfSupportVnodes);
      terrno = TSDB_CODE_MND_NO_ENOUGH_DNODES;
      goto _OVER;
    }
1669 1670 1671 1672 1673 1674

    int64_t vgMem = mndGetVgroupMemory(pMnode, NULL, pVgroup);
    if (pNew1->memAvail - vgMem - pNew1->memUsed <= 0) {
      mError("db:%s, vgId:%d, no enough memory:%" PRId64 " in dnode:%d avail:%" PRId64 " used:%" PRId64,
             pVgroup->dbName, pVgroup->vgId, vgMem, pNew1->id, pNew1->memAvail, pNew1->memUsed);
      terrno = TSDB_CODE_MND_NO_ENOUGH_MEM_IN_DNODE;
S
Shengliang Guan 已提交
1675
      goto _OVER;
1676 1677 1678 1679
    } else {
      pNew1->memUsed += vgMem;
    }

1680 1681 1682
    if (mndAddIncVgroupReplicaToTrans(pMnode, pTrans, pDb, &newVg, pNew1->id) != 0) goto _OVER;
    if (mndAddDecVgroupReplicaFromTrans(pMnode, pTrans, pDb, &newVg, pOld1->id) != 0) goto _OVER;
  }
S
Shengliang Guan 已提交
1683 1684

  if (pNew2 != NULL && pOld2 != NULL) {
1685 1686 1687 1688 1689 1690 1691
    int32_t numOfVnodes = mndGetVnodesNum(pMnode, pNew2->id);
    if (numOfVnodes >= pNew2->numOfSupportVnodes) {
      mError("vgId:%d, no enough vnodes in dnode:%d, numOfVnodes:%d support:%d", newVg.vgId, pNew2->id, numOfVnodes,
             pNew2->numOfSupportVnodes);
      terrno = TSDB_CODE_MND_NO_ENOUGH_DNODES;
      goto _OVER;
    }
1692 1693 1694 1695 1696
    int64_t vgMem = mndGetVgroupMemory(pMnode, NULL, pVgroup);
    if (pNew2->memAvail - vgMem - pNew2->memUsed <= 0) {
      mError("db:%s, vgId:%d, no enough memory:%" PRId64 " in dnode:%d avail:%" PRId64 " used:%" PRId64,
             pVgroup->dbName, pVgroup->vgId, vgMem, pNew2->id, pNew2->memAvail, pNew2->memUsed);
      terrno = TSDB_CODE_MND_NO_ENOUGH_MEM_IN_DNODE;
S
Shengliang Guan 已提交
1697
      goto _OVER;
1698 1699 1700
    } else {
      pNew2->memUsed += vgMem;
    }
S
Shengliang Guan 已提交
1701 1702
    if (mndAddIncVgroupReplicaToTrans(pMnode, pTrans, pDb, &newVg, pNew2->id) != 0) goto _OVER;
    if (mndAddDecVgroupReplicaFromTrans(pMnode, pTrans, pDb, &newVg, pOld2->id) != 0) goto _OVER;
1703
  }
S
Shengliang Guan 已提交
1704 1705

  if (pNew3 != NULL && pOld3 != NULL) {
1706 1707 1708 1709 1710 1711 1712
    int32_t numOfVnodes = mndGetVnodesNum(pMnode, pNew3->id);
    if (numOfVnodes >= pNew3->numOfSupportVnodes) {
      mError("vgId:%d, no enough vnodes in dnode:%d, numOfVnodes:%d support:%d", newVg.vgId, pNew3->id, numOfVnodes,
             pNew3->numOfSupportVnodes);
      terrno = TSDB_CODE_MND_NO_ENOUGH_DNODES;
      goto _OVER;
    }
1713 1714 1715 1716 1717
    int64_t vgMem = mndGetVgroupMemory(pMnode, NULL, pVgroup);
    if (pNew3->memAvail - vgMem - pNew3->memUsed <= 0) {
      mError("db:%s, vgId:%d, no enough memory:%" PRId64 " in dnode:%d avail:%" PRId64 " used:%" PRId64,
             pVgroup->dbName, pVgroup->vgId, vgMem, pNew3->id, pNew3->memAvail, pNew3->memUsed);
      terrno = TSDB_CODE_MND_NO_ENOUGH_MEM_IN_DNODE;
1718
      goto _OVER;
1719 1720 1721
    } else {
      pNew3->memUsed += vgMem;
    }
S
Shengliang Guan 已提交
1722 1723 1724 1725
    if (mndAddIncVgroupReplicaToTrans(pMnode, pTrans, pDb, &newVg, pNew3->id) != 0) goto _OVER;
    if (mndAddDecVgroupReplicaFromTrans(pMnode, pTrans, pDb, &newVg, pOld3->id) != 0) goto _OVER;
  }

1726
  {
1727
    SSdbRaw *pRaw = mndVgroupActionEncode(&newVg);
S
Shengliang Guan 已提交
1728
    if (pRaw == NULL) goto _OVER;
1729 1730
    if (mndTransAppendCommitlog(pTrans, pRaw) != 0) {
      sdbFreeRaw(pRaw);
S
Shengliang Guan 已提交
1731
      goto _OVER;
1732
    }
S
Shengliang Guan 已提交
1733
    (void)sdbSetRawStatus(pRaw, SDB_STATUS_READY);
1734
  }
S
Shengliang Guan 已提交
1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750

  mInfo("vgId:%d, vgroup info after redistribute, replica:%d", newVg.vgId, newVg.replica);
  for (int32_t i = 0; i < newVg.replica; ++i) {
    mInfo("vgId:%d, vnode:%d dnode:%d", newVg.vgId, i, newVg.vnodeGid[i].dnodeId);
  }

  if (mndTransPrepare(pMnode, pTrans) != 0) goto _OVER;
  code = 0;

_OVER:
  mndTransDrop(pTrans);
  mndReleaseDb(pMnode, pDb);
  return code;
}

static int32_t mndProcessRedistributeVgroupMsg(SRpcMsg *pReq) {
1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761
  SMnode    *pMnode = pReq->info.node;
  SDnodeObj *pNew1 = NULL;
  SDnodeObj *pNew2 = NULL;
  SDnodeObj *pNew3 = NULL;
  SDnodeObj *pOld1 = NULL;
  SDnodeObj *pOld2 = NULL;
  SDnodeObj *pOld3 = NULL;
  SVgObj    *pVgroup = NULL;
  SDbObj    *pDb = NULL;
  int32_t    code = -1;
  int64_t    curMs = taosGetTimestampMs();
S
Shengliang Guan 已提交
1762 1763 1764 1765
  int32_t    newDnodeId[3] = {0};
  int32_t    oldDnodeId[3] = {0};
  int32_t    newIndex = -1;
  int32_t    oldIndex = -1;
1766

S
Shengliang Guan 已提交
1767 1768
  SRedistributeVgroupReq req = {0};
  if (tDeserializeSRedistributeVgroupReq(pReq->pCont, pReq->contLen, &req) != 0) {
S
Shengliang Guan 已提交
1769 1770 1771 1772
    terrno = TSDB_CODE_INVALID_MSG;
    goto _OVER;
  }

S
Shengliang Guan 已提交
1773
  mInfo("vgId:%d, start to redistribute vgroup to dnode %d:%d:%d", req.vgId, req.dnodeId1, req.dnodeId2, req.dnodeId3);
1774
  if (mndCheckOperPrivilege(pMnode, pReq->info.conn.user, MND_OPER_REDISTRIBUTE_VGROUP) != 0) {
S
Shengliang Guan 已提交
1775 1776
    goto _OVER;
  }
S
Shengliang Guan 已提交
1777

S
Shengliang Guan 已提交
1778
  pVgroup = mndAcquireVgroup(pMnode, req.vgId);
S
Shengliang Guan 已提交
1779 1780 1781 1782 1783 1784
  if (pVgroup == NULL) goto _OVER;

  pDb = mndAcquireDb(pMnode, pVgroup->dbName);
  if (pDb == NULL) goto _OVER;

  if (pVgroup->replica == 1) {
S
Shengliang Guan 已提交
1785
    if (req.dnodeId1 <= 0 || req.dnodeId2 > 0 || req.dnodeId3 > 0) {
1786 1787 1788
      terrno = TSDB_CODE_MND_INVALID_REPLICA;
      goto _OVER;
    }
S
Shengliang Guan 已提交
1789 1790

    if (req.dnodeId1 == pVgroup->vnodeGid[0].dnodeId) {
1791 1792
      // terrno = TSDB_CODE_MND_VGROUP_UN_CHANGED;
      code = 0;
S
Shengliang Guan 已提交
1793 1794
      goto _OVER;
    }
S
Shengliang Guan 已提交
1795 1796 1797 1798 1799

    pNew1 = mndAcquireDnode(pMnode, req.dnodeId1);
    if (pNew1 == NULL) goto _OVER;
    if (!mndIsDnodeOnline(pNew1, curMs)) {
      terrno = TSDB_CODE_MND_HAS_OFFLINE_DNODE;
S
Shengliang Guan 已提交
1800 1801
      goto _OVER;
    }
S
Shengliang Guan 已提交
1802 1803 1804 1805

    pOld1 = mndAcquireDnode(pMnode, pVgroup->vnodeGid[0].dnodeId);
    if (pOld1 == NULL) goto _OVER;
    if (!mndIsDnodeOnline(pOld1, curMs)) {
1806 1807 1808
      terrno = TSDB_CODE_MND_HAS_OFFLINE_DNODE;
      goto _OVER;
    }
S
Shengliang Guan 已提交
1809

1810
    code = mndRedistributeVgroup(pMnode, pReq, pDb, pVgroup, pNew1, pOld1, NULL, NULL, NULL, NULL);
S
Shengliang Guan 已提交
1811

1812
  } else if (pVgroup->replica == 3) {
S
Shengliang Guan 已提交
1813
    if (req.dnodeId1 <= 0 || req.dnodeId2 <= 0 || req.dnodeId3 <= 0) {
1814 1815 1816
      terrno = TSDB_CODE_MND_INVALID_REPLICA;
      goto _OVER;
    }
S
Shengliang Guan 已提交
1817 1818

    if (req.dnodeId1 == req.dnodeId2 || req.dnodeId1 == req.dnodeId3 || req.dnodeId2 == req.dnodeId3) {
1819 1820 1821
      terrno = TSDB_CODE_MND_INVALID_REPLICA;
      goto _OVER;
    }
S
Shengliang Guan 已提交
1822 1823 1824 1825

    if (req.dnodeId1 != pVgroup->vnodeGid[0].dnodeId && req.dnodeId1 != pVgroup->vnodeGid[1].dnodeId &&
        req.dnodeId1 != pVgroup->vnodeGid[2].dnodeId) {
      newDnodeId[++newIndex] = req.dnodeId1;
S
Shengliang Guan 已提交
1826
      mInfo("vgId:%d, dnode:%d will be added, index:%d", pVgroup->vgId, newDnodeId[newIndex], newIndex);
S
Shengliang Guan 已提交
1827
    }
S
Shengliang Guan 已提交
1828 1829 1830 1831

    if (req.dnodeId2 != pVgroup->vnodeGid[0].dnodeId && req.dnodeId2 != pVgroup->vnodeGid[1].dnodeId &&
        req.dnodeId2 != pVgroup->vnodeGid[2].dnodeId) {
      newDnodeId[++newIndex] = req.dnodeId2;
S
Shengliang Guan 已提交
1832
      mInfo("vgId:%d, dnode:%d will be added, index:%d", pVgroup->vgId, newDnodeId[newIndex], newIndex);
S
Shengliang Guan 已提交
1833 1834 1835 1836 1837
    }

    if (req.dnodeId3 != pVgroup->vnodeGid[0].dnodeId && req.dnodeId3 != pVgroup->vnodeGid[1].dnodeId &&
        req.dnodeId3 != pVgroup->vnodeGid[2].dnodeId) {
      newDnodeId[++newIndex] = req.dnodeId3;
S
Shengliang Guan 已提交
1838
      mInfo("vgId:%d, dnode:%d will be added, index:%d", pVgroup->vgId, newDnodeId[newIndex], newIndex);
S
Shengliang Guan 已提交
1839 1840 1841 1842 1843
    }

    if (req.dnodeId1 != pVgroup->vnodeGid[0].dnodeId && req.dnodeId2 != pVgroup->vnodeGid[0].dnodeId &&
        req.dnodeId3 != pVgroup->vnodeGid[0].dnodeId) {
      oldDnodeId[++oldIndex] = pVgroup->vnodeGid[0].dnodeId;
S
Shengliang Guan 已提交
1844
      mInfo("vgId:%d, dnode:%d will be removed, index:%d", pVgroup->vgId, oldDnodeId[oldIndex], oldIndex);
S
Shengliang Guan 已提交
1845 1846 1847 1848 1849
    }

    if (req.dnodeId1 != pVgroup->vnodeGid[1].dnodeId && req.dnodeId2 != pVgroup->vnodeGid[1].dnodeId &&
        req.dnodeId3 != pVgroup->vnodeGid[1].dnodeId) {
      oldDnodeId[++oldIndex] = pVgroup->vnodeGid[1].dnodeId;
S
Shengliang Guan 已提交
1850
      mInfo("vgId:%d, dnode:%d will be removed, index:%d", pVgroup->vgId, oldDnodeId[oldIndex], oldIndex);
S
Shengliang Guan 已提交
1851 1852 1853 1854 1855
    }

    if (req.dnodeId1 != pVgroup->vnodeGid[2].dnodeId && req.dnodeId2 != pVgroup->vnodeGid[2].dnodeId &&
        req.dnodeId3 != pVgroup->vnodeGid[2].dnodeId) {
      oldDnodeId[++oldIndex] = pVgroup->vnodeGid[2].dnodeId;
S
Shengliang Guan 已提交
1856
      mInfo("vgId:%d, dnode:%d will be removed, index:%d", pVgroup->vgId, oldDnodeId[oldIndex], oldIndex);
S
Shengliang Guan 已提交
1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913
    }

    if (newDnodeId[0] != 0) {
      pNew1 = mndAcquireDnode(pMnode, newDnodeId[0]);
      if (pNew1 == NULL) goto _OVER;
      if (!mndIsDnodeOnline(pNew1, curMs)) {
        terrno = TSDB_CODE_MND_HAS_OFFLINE_DNODE;
        goto _OVER;
      }
    }

    if (newDnodeId[1] != 0) {
      pNew2 = mndAcquireDnode(pMnode, newDnodeId[1]);
      if (pNew2 == NULL) goto _OVER;
      if (!mndIsDnodeOnline(pNew2, curMs)) {
        terrno = TSDB_CODE_MND_HAS_OFFLINE_DNODE;
        goto _OVER;
      }
    }

    if (newDnodeId[2] != 0) {
      pNew3 = mndAcquireDnode(pMnode, newDnodeId[2]);
      if (pNew3 == NULL) goto _OVER;
      if (!mndIsDnodeOnline(pNew3, curMs)) {
        terrno = TSDB_CODE_MND_HAS_OFFLINE_DNODE;
        goto _OVER;
      }
    }

    if (oldDnodeId[0] != 0) {
      pOld1 = mndAcquireDnode(pMnode, oldDnodeId[0]);
      if (pOld1 == NULL) goto _OVER;
      if (!mndIsDnodeOnline(pOld1, curMs)) {
        terrno = TSDB_CODE_MND_HAS_OFFLINE_DNODE;
        goto _OVER;
      }
    }

    if (oldDnodeId[1] != 0) {
      pOld2 = mndAcquireDnode(pMnode, oldDnodeId[1]);
      if (pOld2 == NULL) goto _OVER;
      if (!mndIsDnodeOnline(pOld2, curMs)) {
        terrno = TSDB_CODE_MND_HAS_OFFLINE_DNODE;
        goto _OVER;
      }
    }

    if (oldDnodeId[2] != 0) {
      pOld3 = mndAcquireDnode(pMnode, oldDnodeId[2]);
      if (pOld3 == NULL) goto _OVER;
      if (!mndIsDnodeOnline(pOld3, curMs)) {
        terrno = TSDB_CODE_MND_HAS_OFFLINE_DNODE;
        goto _OVER;
      }
    }

    if (pNew1 == NULL && pOld1 == NULL && pNew2 == NULL && pOld2 == NULL && pNew3 == NULL && pOld3 == NULL) {
1914 1915
      // terrno = TSDB_CODE_MND_VGROUP_UN_CHANGED;
      code = 0;
1916 1917
      goto _OVER;
    }
S
Shengliang Guan 已提交
1918

1919
    code = mndRedistributeVgroup(pMnode, pReq, pDb, pVgroup, pNew1, pOld1, pNew2, pOld2, pNew3, pOld3);
S
Shengliang Guan 已提交
1920

1921 1922 1923
  } else {
    terrno = TSDB_CODE_MND_INVALID_REPLICA;
    goto _OVER;
S
Shengliang Guan 已提交
1924 1925 1926 1927 1928 1929
  }

  if (code == 0) code = TSDB_CODE_ACTION_IN_PROGRESS;

_OVER:
  if (code != 0 && code != TSDB_CODE_ACTION_IN_PROGRESS) {
S
Shengliang Guan 已提交
1930 1931
    mError("vgId:%d, failed to redistribute to dnode %d:%d:%d since %s", req.vgId, req.dnodeId1, req.dnodeId2,
           req.dnodeId3, terrstr());
S
Shengliang Guan 已提交
1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945
  }

  mndReleaseDnode(pMnode, pNew1);
  mndReleaseDnode(pMnode, pNew2);
  mndReleaseDnode(pMnode, pNew3);
  mndReleaseDnode(pMnode, pOld1);
  mndReleaseDnode(pMnode, pOld2);
  mndReleaseDnode(pMnode, pOld3);
  mndReleaseVgroup(pMnode, pVgroup);
  mndReleaseDb(pMnode, pDb);

  return code;
}

C
cadem 已提交
1946
static void *mndBuildSForceBecomeFollowerReq(SMnode *pMnode, SVgObj *pVgroup, int32_t dnodeId,
C
cadem 已提交
1947
                                          int32_t *pContLen) {
C
cadem 已提交
1948
  SForceBecomeFollowerReq balanceReq = {
C
cadem 已提交
1949 1950 1951
      .vgId = pVgroup->vgId,
  };

C
cadem 已提交
1952
  int32_t contLen = tSerializeSForceBecomeFollowerReq(NULL, 0, &balanceReq);
C
cadem 已提交
1953 1954 1955 1956
  if (contLen < 0) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }
C
cadem 已提交
1957
  contLen += sizeof(SMsgHead);
C
cadem 已提交
1958 1959 1960 1961 1962 1963 1964

  void *pReq = taosMemoryMalloc(contLen);
  if (pReq == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

C
cadem 已提交
1965 1966 1967 1968 1969
  SMsgHead *pHead = pReq;
  pHead->contLen = htonl(contLen);
  pHead->vgId = htonl(pVgroup->vgId);

  tSerializeSForceBecomeFollowerReq((char *)pReq + sizeof(SMsgHead), contLen, &balanceReq);
C
cadem 已提交
1970
  *pContLen = contLen;
C
cadem 已提交
1971
  return pReq;                                  
C
cadem 已提交
1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982
}

int32_t mndAddBalanceVgroupLeaderAction(SMnode *pMnode, STrans *pTrans, SVgObj *pVgroup, int32_t dnodeId) {
  SDnodeObj *pDnode = mndAcquireDnode(pMnode, dnodeId);
  if (pDnode == NULL) return -1;

  STransAction action = {0};
  action.epSet = mndGetDnodeEpset(pDnode);
  mndReleaseDnode(pMnode, pDnode);

  int32_t contLen = 0;
C
cadem 已提交
1983
  void   *pReq = mndBuildSForceBecomeFollowerReq(pMnode, pVgroup, dnodeId, &contLen);
C
cadem 已提交
1984 1985 1986 1987
  if (pReq == NULL) return -1;

  action.pCont = pReq;
  action.contLen = contLen;
C
cadem 已提交
1988
  action.msgType = TDMT_SYNC_FORCE_FOLLOWER;
C
cadem 已提交
1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003

  if (mndTransAppendRedoAction(pTrans, &action) != 0) {
    taosMemoryFree(pReq);
    return -1;
  }

  return 0;
}

int32_t mndAddVgroupBalanceToTrans(SMnode *pMnode, SVgObj *pVgroup, STrans *pTrans){
  SSdb *pSdb = pMnode->pSdb;

  int32_t vgid = pVgroup->vgId;
  int8_t replica = pVgroup->replica;

D
dmchen 已提交
2004
  if(pVgroup->replica <= 1) {
C
cadem 已提交
2005 2006 2007 2008
    mInfo("trans:%d, vgid:%d no need to balance, replica:%d", pTrans->id, vgid, replica);
    return -1;
  }

C
cadem 已提交
2009 2010 2011 2012 2013 2014 2015 2016 2017
  int32_t dnodeId = pVgroup->vnodeGid[0].dnodeId;

  for(int i = 0; i < replica; i++)
  {
    if(pVgroup->vnodeGid[i].syncState == TAOS_SYNC_STATE_LEADER){
      dnodeId = pVgroup->vnodeGid[i].dnodeId;
      break;
    }
  }
C
cadem 已提交
2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037

  bool       exist = false;
  bool       online = false;
  int64_t curMs = taosGetTimestampMs();
  SDnodeObj *pDnode = mndAcquireDnode(pMnode, dnodeId);
  if (pDnode != NULL) {
    exist = true;
    online = mndIsDnodeOnline(pDnode, curMs);
    mndReleaseDnode(pMnode, pDnode);
  }

  if(exist && online)
  {
    mInfo("trans:%d, vgid:%d leader to dnode:%d", pTrans->id, vgid, dnodeId);

    if (mndAddBalanceVgroupLeaderAction(pMnode, pTrans, pVgroup, dnodeId) != 0) {
      mError("trans:%d, vgid:%d failed to be balanced to dnode:%d", pTrans->id, vgid, dnodeId);
      return -1;
    }

D
dmchen 已提交
2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050
    SDbObj *pDb = mndAcquireDb(pMnode, pVgroup->dbName);
    if (pDb == NULL) {
      mError("trans:%d, vgid:%d failed to be balanced to dnode:%d, because db not exist", pTrans->id, vgid, dnodeId);
      return -1;
    }

    if (mndAddAlterVnodeConfirmAction(pMnode, pTrans, pDb, pVgroup) != 0) {
      mError("trans:%d, vgid:%d failed to be balanced to dnode:%d", pTrans->id, vgid, dnodeId);
      return -1;
    }

    mndReleaseDb(pMnode, pDb);

C
cadem 已提交
2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064
    SSdbRaw *pRaw = mndVgroupActionEncode(pVgroup);
    if (pRaw == NULL) {
      mError("trans:%d, vgid:%d failed to encode action to dnode:%d", pTrans->id, vgid, dnodeId);
      return -1;
    }
    if (mndTransAppendCommitlog(pTrans, pRaw) != 0) {
      sdbFreeRaw(pRaw);
      mError("trans:%d, vgid:%d failed to append commit log dnode:%d", pTrans->id, vgid, dnodeId);
      return -1;
    }
    (void)sdbSetRawStatus(pRaw, SDB_STATUS_READY);
  }
  else
  {
H
Haojun Liao 已提交
2065
    mInfo("trans:%d, vgid:%d cant be balanced to dnode:%d, exist:%d, online:%d",
D
dmchen 已提交
2066
                              pTrans->id, vgid, dnodeId, exist, online);
C
cadem 已提交
2067 2068 2069 2070 2071
  }

  return 0;
}

C
cadem 已提交
2072
extern int32_t mndProcessVgroupBalanceLeaderMsgImp(SRpcMsg *pReq);
C
cadem 已提交
2073

C
cadem 已提交
2074 2075 2076
int32_t mndProcessVgroupBalanceLeaderMsg(SRpcMsg *pReq) {
  return mndProcessVgroupBalanceLeaderMsgImp(pReq);
}
C
cadem 已提交
2077

C
cadem 已提交
2078 2079 2080
#ifndef TD_ENTERPRISE
int32_t mndProcessVgroupBalanceLeaderMsgImp(SRpcMsg *pReq) {
  return 0;
C
cadem 已提交
2081
}
C
cadem 已提交
2082
#endif
C
cadem 已提交
2083

2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108
static int32_t mndCheckDnodeMemory(SMnode *pMnode, SDbObj *pOldDb, SDbObj *pNewDb, SVgObj *pOldVgroup,
                                   SVgObj *pNewVgroup, SArray *pArray) {
  for (int32_t i = 0; i < (int32_t)taosArrayGetSize(pArray); ++i) {
    SDnodeObj *pDnode = taosArrayGet(pArray, i);
    bool       inVgroup = false;
    for (int32_t j = 0; j < pOldVgroup->replica; ++j) {
      SVnodeGid *pVgId = &pOldVgroup->vnodeGid[i];
      if (pDnode->id == pVgId->dnodeId) {
        pDnode->memUsed -= mndGetVgroupMemory(pMnode, pOldDb, pOldVgroup);
        inVgroup = true;
      }
    }
    for (int32_t j = 0; j < pNewVgroup->replica; ++j) {
      SVnodeGid *pVgId = &pNewVgroup->vnodeGid[i];
      if (pDnode->id == pVgId->dnodeId) {
        pDnode->memUsed += mndGetVgroupMemory(pMnode, pNewDb, pNewVgroup);
        inVgroup = true;
      }
    }
    if (pDnode->memAvail - pDnode->memUsed <= 0) {
      mError("db:%s, vgId:%d, no enough memory in dnode:%d, avail:%" PRId64 " used:%" PRId64, pNewVgroup->dbName,
             pNewVgroup->vgId, pDnode->id, pDnode->memAvail, pDnode->memUsed);
      terrno = TSDB_CODE_MND_NO_ENOUGH_MEM_IN_DNODE;
      return -1;
    } else if (inVgroup) {
H
Hongze Cheng 已提交
2109 2110
      mInfo("db:%s, vgId:%d, memory in dnode:%d, avail:%" PRId64 " used:%" PRId64, pNewVgroup->dbName, pNewVgroup->vgId,
            pDnode->id, pDnode->memAvail, pDnode->memUsed);
2111 2112
    } else {
    }
S
Shengliang Guan 已提交
2113
  }
2114 2115
  return 0;
}
S
Shengliang Guan 已提交
2116

2117 2118
int32_t mndBuildAlterVgroupAction(SMnode *pMnode, STrans *pTrans, SDbObj *pOldDb, SDbObj *pNewDb, SVgObj *pVgroup,
                                  SArray *pArray) {
S
Shengliang Guan 已提交
2119 2120
  SVgObj newVgroup = {0};
  memcpy(&newVgroup, pVgroup, sizeof(SVgObj));
2121 2122

  if (pVgroup->replica <= 0 || pVgroup->replica == pNewDb->cfg.replications) {
S
Shengliang Guan 已提交
2123
    if (mndAddAlterVnodeConfigAction(pMnode, pTrans, pNewDb, pVgroup) != 0) return -1;
2124 2125 2126 2127
    if (mndCheckDnodeMemory(pMnode, pOldDb, pNewDb, &newVgroup, pVgroup, pArray) != 0) return -1;
    return 0;
  }

S
Shengliang Guan 已提交
2128 2129
  mndTransSetSerial(pTrans);

S
Shengliang Guan 已提交
2130 2131
  if (newVgroup.replica == 1 && pNewDb->cfg.replications == 3) {
    mInfo("db:%s, vgId:%d, will add 2 vnodes, vn:0 dnode:%d", pVgroup->dbName, pVgroup->vgId,
S
Shengliang Guan 已提交
2132 2133
          pVgroup->vnodeGid[0].dnodeId);

C
cadem 已提交
2134
    //add first
2135
    if (mndAddVnodeToVgroup(pMnode, pTrans, &newVgroup, pArray) != 0) return -1;
C
cadem 已提交
2136 2137 2138

    newVgroup.vnodeGid[0].nodeRole = TAOS_SYNC_ROLE_VOTER;
    newVgroup.vnodeGid[1].nodeRole = TAOS_SYNC_ROLE_LEARNER;
S
Shengliang Guan 已提交
2139 2140
    if (mndAddAlterVnodeReplicaAction(pMnode, pTrans, pNewDb, &newVgroup, newVgroup.vnodeGid[0].dnodeId) != 0)
      return -1;
C
cadem 已提交
2141

2142
    if (mndAddCreateVnodeAction(pMnode, pTrans, pNewDb, &newVgroup, &newVgroup.vnodeGid[1]) != 0) return -1;
C
cadem 已提交
2143 2144 2145 2146
    newVgroup.vnodeGid[1].nodeRole = TAOS_SYNC_ROLE_VOTER;
    if (mndAddAlterVnodeTypeAction(pMnode, pTrans, pNewDb, &newVgroup, newVgroup.vnodeGid[1].dnodeId) != 0)
      return -1;

2147
    if (mndAddAlterVnodeConfirmAction(pMnode, pTrans, pNewDb, &newVgroup) != 0) return -1;
2148

C
cadem 已提交
2149
    //add second
2150
    if (mndAddVnodeToVgroup(pMnode, pTrans, &newVgroup, pArray) != 0) return -1;
C
cadem 已提交
2151 2152 2153 2154
    newVgroup.vnodeGid[0].nodeRole = TAOS_SYNC_ROLE_VOTER;
    newVgroup.vnodeGid[1].nodeRole = TAOS_SYNC_ROLE_VOTER;
    newVgroup.vnodeGid[2].nodeRole = TAOS_SYNC_ROLE_VOTER;

2155 2156 2157 2158
    if (mndAddAlterVnodeReplicaAction(pMnode, pTrans, pNewDb, &newVgroup, newVgroup.vnodeGid[0].dnodeId) != 0)
      return -1;
    if (mndAddAlterVnodeReplicaAction(pMnode, pTrans, pNewDb, &newVgroup, newVgroup.vnodeGid[1].dnodeId) != 0)
      return -1;
S
Shengliang Guan 已提交
2159
    if (mndAddCreateVnodeAction(pMnode, pTrans, pNewDb, &newVgroup, &newVgroup.vnodeGid[2]) != 0) return -1;
C
cadem 已提交
2160

S
Shengliang Guan 已提交
2161
    if (mndAddAlterVnodeConfirmAction(pMnode, pTrans, pNewDb, &newVgroup) != 0) return -1;
S
Shengliang Guan 已提交
2162
  } else if (newVgroup.replica == 3 && pNewDb->cfg.replications == 1) {
S
Shengliang Guan 已提交
2163 2164
    mInfo("db:%s, vgId:%d, will remove 2 vnodes, vn:0 dnode:%d vn:1 dnode:%d vn:2 dnode:%d", pVgroup->dbName,
          pVgroup->vgId, pVgroup->vnodeGid[0].dnodeId, pVgroup->vnodeGid[1].dnodeId, pVgroup->vnodeGid[2].dnodeId);
S
Shengliang Guan 已提交
2165

S
Shengliang Guan 已提交
2166
    SVnodeGid del1 = {0};
S
Shengliang Guan 已提交
2167
    SVnodeGid del2 = {0};
2168
    if (mndRemoveVnodeFromVgroup(pMnode, pTrans, &newVgroup, pArray, &del1) != 0) return -1;
S
Shengliang Guan 已提交
2169
    if (mndAddDropVnodeAction(pMnode, pTrans, pNewDb, &newVgroup, &del1, true) != 0) return -1;
2170 2171 2172 2173
    if (mndAddAlterVnodeReplicaAction(pMnode, pTrans, pNewDb, &newVgroup, newVgroup.vnodeGid[0].dnodeId) != 0)
      return -1;
    if (mndAddAlterVnodeReplicaAction(pMnode, pTrans, pNewDb, &newVgroup, newVgroup.vnodeGid[1].dnodeId) != 0)
      return -1;
S
Shengliang Guan 已提交
2174
    if (mndAddAlterVnodeConfirmAction(pMnode, pTrans, pNewDb, &newVgroup) != 0) return -1;
2175

2176
    if (mndRemoveVnodeFromVgroup(pMnode, pTrans, &newVgroup, pArray, &del2) != 0) return -1;
2177
    if (mndAddDropVnodeAction(pMnode, pTrans, pNewDb, &newVgroup, &del2, true) != 0) return -1;
S
Shengliang Guan 已提交
2178 2179
    if (mndAddAlterVnodeReplicaAction(pMnode, pTrans, pNewDb, &newVgroup, newVgroup.vnodeGid[0].dnodeId) != 0)
      return -1;
2180
    if (mndAddAlterVnodeConfirmAction(pMnode, pTrans, pNewDb, &newVgroup) != 0) return -1;
S
Shengliang Guan 已提交
2181
  } else {
S
Shengliang Guan 已提交
2182
    return -1;
S
Shengliang Guan 已提交
2183
  }
S
Shengliang Guan 已提交
2184

2185 2186
  mndSortVnodeGid(&newVgroup);

S
Shengliang Guan 已提交
2187 2188 2189 2190 2191 2192
  {
    SSdbRaw *pVgRaw = mndVgroupActionEncode(&newVgroup);
    if (pVgRaw == NULL) return -1;
    if (mndTransAppendCommitlog(pTrans, pVgRaw) != 0) {
      sdbFreeRaw(pVgRaw);
      return -1;
S
Shengliang Guan 已提交
2193
    }
S
Shengliang Guan 已提交
2194
    (void)sdbSetRawStatus(pVgRaw, SDB_STATUS_READY);
S
Shengliang Guan 已提交
2195 2196 2197 2198 2199
  }

  return 0;
}

H
Haojun Liao 已提交
2200
int32_t mndBuildRestoreAlterVgroupAction(SMnode *pMnode, STrans *pTrans, SDbObj *db, SVgObj *pVgroup,
C
cadem 已提交
2201 2202 2203 2204 2205 2206 2207 2208 2209 2210
                                        SDnodeObj *pDnode) {
  SVgObj newVgroup = {0};
  memcpy(&newVgroup, pVgroup, sizeof(SVgObj));

  mInfo("db:%s, vgId:%d, restore vnodes, vn:0 dnode:%d", pVgroup->dbName, pVgroup->vgId,
        pVgroup->vnodeGid[0].dnodeId);

  if(newVgroup.replica == 1){
    int selected = 0;
    for(int i = 0; i < newVgroup.replica; i++){
H
Haojun Liao 已提交
2211
      newVgroup.vnodeGid[i].nodeRole = TAOS_SYNC_ROLE_VOTER;
C
cadem 已提交
2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224
      if(newVgroup.vnodeGid[i].dnodeId == pDnode->id){
        selected = i;
      }
    }
    if (mndAddCreateVnodeAction(pMnode, pTrans, db, &newVgroup, &newVgroup.vnodeGid[selected]) != 0) return -1;
  }
  else if(newVgroup.replica == 3){
    for(int i = 0; i < newVgroup.replica; i++){
      if(newVgroup.vnodeGid[i].dnodeId == pDnode->id){
        newVgroup.vnodeGid[i].nodeRole = TAOS_SYNC_ROLE_LEARNER;
      }
      else{
        newVgroup.vnodeGid[i].nodeRole = TAOS_SYNC_ROLE_VOTER;
H
Haojun Liao 已提交
2225
      }
C
cadem 已提交
2226 2227 2228 2229
    }
    if (mndRestoreAddCreateVnodeAction(pMnode, pTrans, db, &newVgroup, pDnode) != 0) return -1;

    for(int i = 0; i < newVgroup.replica; i++){
H
Haojun Liao 已提交
2230
      newVgroup.vnodeGid[i].nodeRole = TAOS_SYNC_ROLE_VOTER;
C
cadem 已提交
2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248
    if(newVgroup.vnodeGid[i].dnodeId == pDnode->id){
      }
    }
    if (mndRestoreAddAlterVnodeTypeAction(pMnode, pTrans, db, &newVgroup, pDnode) != 0)
        return -1;
  }

  SSdbRaw *pVgRaw = mndVgroupActionEncode(&newVgroup);
  if (pVgRaw == NULL) return -1;
  if (mndTransAppendCommitlog(pTrans, pVgRaw) != 0) {
    sdbFreeRaw(pVgRaw);
    return -1;
  }
  (void)sdbSetRawStatus(pVgRaw, SDB_STATUS_READY);

  return 0;
}

S
Shengliang Guan 已提交
2249 2250 2251 2252
static int32_t mndAddAdjustVnodeHashRangeAction(SMnode *pMnode, STrans *pTrans, SDbObj *pDb, SVgObj *pVgroup) {
  return 0;
}

B
Benguang Zhao 已提交
2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264
static int32_t mndTransCommitVgStatus(STrans *pTrans, SVgObj *pVg, ESdbStatus vgStatus) {
  SSdbRaw *pRaw = mndVgroupActionEncode(pVg);
  if (pRaw == NULL) goto _err;
  if (mndTransAppendCommitlog(pTrans, pRaw) != 0) goto _err;
  (void)sdbSetRawStatus(pRaw, vgStatus);
  pRaw = NULL;
  return 0;
_err:
  sdbFreeRaw(pRaw);
  return -1;
}

2265
int32_t mndSplitVgroup(SMnode *pMnode, SRpcMsg *pReq, SDbObj *pDb, SVgObj *pVgroup) {
2266 2267 2268
  int32_t  code = -1;
  STrans  *pTrans = NULL;
  SSdbRaw *pRaw = NULL;
2269
  SDbObj   dbObj = {0};
2270
  SArray  *pArray = mndBuildDnodesArray(pMnode, 0);
S
Shengliang Guan 已提交
2271

2272
  pTrans = mndTransCreate(pMnode, TRN_POLICY_RETRY, TRN_CONFLICT_DB, pReq, "split-vgroup");
S
Shengliang Guan 已提交
2273 2274
  if (pTrans == NULL) goto _OVER;
  mndTransSetSerial(pTrans);
2275
  mInfo("trans:%d, used to split vgroup, vgId:%d", pTrans->id, pVgroup->vgId);
S
Shengliang Guan 已提交
2276

2277 2278
  mndTransSetDbName(pTrans, pDb->name, NULL);

S
Shengliang Guan 已提交
2279 2280 2281 2282 2283 2284 2285 2286 2287
  SVgObj newVg1 = {0};
  memcpy(&newVg1, pVgroup, sizeof(SVgObj));
  mInfo("vgId:%d, vgroup info before split, replica:%d hashBegin:%u hashEnd:%u", newVg1.vgId, newVg1.replica,
        newVg1.hashBegin, newVg1.hashEnd);
  for (int32_t i = 0; i < newVg1.replica; ++i) {
    mInfo("vgId:%d, vnode:%d dnode:%d", newVg1.vgId, i, newVg1.vnodeGid[i].dnodeId);
  }

  if (newVg1.replica == 1) {
2288
    if (mndAddVnodeToVgroup(pMnode, pTrans, &newVg1, pArray) != 0) goto _OVER;
S
Shengliang Guan 已提交
2289
    if (mndAddAlterVnodeReplicaAction(pMnode, pTrans, pDb, &newVg1, newVg1.vnodeGid[0].dnodeId) != 0) goto _OVER;
2290
    if (mndAddCreateVnodeAction(pMnode, pTrans, pDb, &newVg1, &newVg1.vnodeGid[1]) != 0) goto _OVER;
S
Shengliang Guan 已提交
2291 2292
  } else if (newVg1.replica == 3) {
    SVnodeGid del1 = {0};
2293
    if (mndRemoveVnodeFromVgroup(pMnode, pTrans, &newVg1, pArray, &del1) != 0) goto _OVER;
2294
    if (mndAddDropVnodeAction(pMnode, pTrans, pDb, &newVg1, &del1, true) != 0) goto _OVER;
S
Shengliang Guan 已提交
2295 2296
    if (mndAddAlterVnodeReplicaAction(pMnode, pTrans, pDb, &newVg1, newVg1.vnodeGid[0].dnodeId) != 0) goto _OVER;
    if (mndAddAlterVnodeReplicaAction(pMnode, pTrans, pDb, &newVg1, newVg1.vnodeGid[1].dnodeId) != 0) goto _OVER;
S
Shengliang Guan 已提交
2297 2298 2299 2300
  } else {
    goto _OVER;
  }

2301 2302 2303 2304 2305
  for (int32_t i = 0; i < newVg1.replica; ++i) {
    if (mndAddDisableVnodeWriteAction(pMnode, pTrans, pDb, &newVg1, newVg1.vnodeGid[i].dnodeId) != 0) goto _OVER;
  }
  if (mndAddAlterVnodeConfirmAction(pMnode, pTrans, pDb, &newVg1) != 0) goto _OVER;

S
Shengliang Guan 已提交
2306
  SVgObj newVg2 = {0};
S
Shengliang Guan 已提交
2307
  memcpy(&newVg2, &newVg1, sizeof(SVgObj));
S
Shengliang Guan 已提交
2308
  newVg1.replica = 1;
S
Shengliang Guan 已提交
2309
  newVg1.hashEnd = newVg1.hashBegin / 2 + newVg1.hashEnd / 2;
S
Shengliang Guan 已提交
2310 2311 2312 2313 2314
  memset(&newVg1.vnodeGid[1], 0, sizeof(SVnodeGid));

  newVg2.replica = 1;
  newVg2.hashBegin = newVg1.hashEnd + 1;
  memcpy(&newVg2.vnodeGid[0], &newVg2.vnodeGid[1], sizeof(SVnodeGid));
S
Shengliang Guan 已提交
2315 2316
  memset(&newVg2.vnodeGid[1], 0, sizeof(SVnodeGid));

2317 2318
  mInfo("vgId:%d, vgroup info after split, replica:%d hashrange:[%u, %u] vnode:0 dnode:%d", newVg1.vgId, newVg1.replica,
        newVg1.hashBegin, newVg1.hashEnd, newVg1.vnodeGid[0].dnodeId);
2319 2320 2321
  for (int32_t i = 0; i < newVg1.replica; ++i) {
    mInfo("vgId:%d, vnode:%d dnode:%d", newVg1.vgId, i, newVg1.vnodeGid[i].dnodeId);
  }
2322 2323
  mInfo("vgId:%d, vgroup info after split, replica:%d hashrange:[%u, %u] vnode:0 dnode:%d", newVg2.vgId, newVg2.replica,
        newVg2.hashBegin, newVg2.hashEnd, newVg2.vnodeGid[0].dnodeId);
2324 2325 2326
  for (int32_t i = 0; i < newVg1.replica; ++i) {
    mInfo("vgId:%d, vnode:%d dnode:%d", newVg2.vgId, i, newVg2.vnodeGid[i].dnodeId);
  }
S
Shengliang Guan 已提交
2327

2328
  // alter vgId and hash range
2329
  int32_t maxVgId = sdbGetMaxId(pMnode->pSdb, SDB_VGROUP);
2330
  int32_t srcVgId = newVg1.vgId;
2331
  newVg1.vgId = maxVgId;
2332 2333
  if (mndAddPrepareNewVgAction(pMnode, pTrans, &newVg1) != 0) goto _OVER;
  if (mndAddAlterVnodeHashRangeAction(pMnode, pTrans, srcVgId, &newVg1) != 0) goto _OVER;
2334 2335

  maxVgId++;
2336
  srcVgId = newVg2.vgId;
2337
  newVg2.vgId = maxVgId;
2338 2339
  if (mndAddPrepareNewVgAction(pMnode, pTrans, &newVg2) != 0) goto _OVER;
  if (mndAddAlterVnodeHashRangeAction(pMnode, pTrans, srcVgId, &newVg2) != 0) goto _OVER;
S
Shengliang Guan 已提交
2340

B
Benguang Zhao 已提交
2341 2342 2343 2344
  if (mndAddAlterVnodeConfirmAction(pMnode, pTrans, pDb, &newVg1) != 0) goto _OVER;

  if (mndAddAlterVnodeConfirmAction(pMnode, pTrans, pDb, &newVg2) != 0) goto _OVER;

S
Shengliang Guan 已提交
2345 2346 2347
  // adjust vgroup replica
  if (pDb->cfg.replications != newVg1.replica) {
    if (mndBuildAlterVgroupAction(pMnode, pTrans, pDb, pDb, &newVg1, pArray) != 0) goto _OVER;
2348
  } else {
B
Benguang Zhao 已提交
2349
    if (mndTransCommitVgStatus(pTrans, &newVg1, SDB_STATUS_READY) < 0) goto _OVER;
S
Shengliang Guan 已提交
2350
  }
2351

S
Shengliang Guan 已提交
2352 2353
  if (pDb->cfg.replications != newVg2.replica) {
    if (mndBuildAlterVgroupAction(pMnode, pTrans, pDb, pDb, &newVg2, pArray) != 0) goto _OVER;
2354
  } else {
B
Benguang Zhao 已提交
2355
    if (mndTransCommitVgStatus(pTrans, &newVg2, SDB_STATUS_READY) < 0) goto _OVER;
S
Shengliang Guan 已提交
2356 2357
  }

B
Benguang Zhao 已提交
2358
  if (mndTransCommitVgStatus(pTrans, pVgroup, SDB_STATUS_DROPPED) < 0) goto _OVER;
2359

2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372
  memcpy(&dbObj, pDb, sizeof(SDbObj));
  if (dbObj.cfg.pRetensions != NULL) {
    dbObj.cfg.pRetensions = taosArrayDup(pDb->cfg.pRetensions, NULL);
    if (dbObj.cfg.pRetensions == NULL) goto _OVER;
  }
  dbObj.vgVersion++;
  dbObj.updateTime = taosGetTimestampMs();
  dbObj.cfg.numOfVgroups++;
  pRaw = mndDbActionEncode(&dbObj);
  if (pRaw == NULL) goto _OVER;
  if (mndTransAppendCommitlog(pTrans, pRaw) != 0) goto _OVER;
  (void)sdbSetRawStatus(pRaw, SDB_STATUS_READY);
  pRaw = NULL;
S
Shengliang Guan 已提交
2373 2374 2375

  if (mndTransPrepare(pMnode, pTrans) != 0) goto _OVER;
  code = 0;
S
Shengliang Guan 已提交
2376 2377

_OVER:
S
Shengliang Guan 已提交
2378
  taosArrayDestroy(pArray);
S
Shengliang Guan 已提交
2379
  mndTransDrop(pTrans);
2380
  sdbFreeRaw(pRaw);
2381
  taosArrayDestroy(dbObj.cfg.pRetensions);
S
Shengliang Guan 已提交
2382 2383 2384
  return code;
}

2385
extern int32_t mndProcessSplitVgroupMsgImp(SRpcMsg *pReq);
S
Shengliang Guan 已提交
2386

2387
static int32_t mndProcessSplitVgroupMsg(SRpcMsg *pReq) { return mndProcessSplitVgroupMsgImp(pReq); }
S
Shengliang Guan 已提交
2388

2389 2390 2391
#ifndef TD_ENTERPRISE
int32_t mndProcessSplitVgroupMsgImp(SRpcMsg *pReq) { return 0; }
#endif
S
Shengliang Guan 已提交
2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404

static int32_t mndSetBalanceVgroupInfoToTrans(SMnode *pMnode, STrans *pTrans, SDbObj *pDb, SVgObj *pVgroup,
                                              SDnodeObj *pSrc, SDnodeObj *pDst) {
  SVgObj newVg = {0};
  memcpy(&newVg, pVgroup, sizeof(SVgObj));
  mInfo("vgId:%d, vgroup info before balance, replica:%d", newVg.vgId, newVg.replica);
  for (int32_t i = 0; i < newVg.replica; ++i) {
    mInfo("vgId:%d, vnode:%d dnode:%d", newVg.vgId, i, newVg.vnodeGid[i].dnodeId);
  }

  if (mndAddIncVgroupReplicaToTrans(pMnode, pTrans, pDb, &newVg, pDst->id) != 0) return -1;
  if (mndAddDecVgroupReplicaFromTrans(pMnode, pTrans, pDb, &newVg, pSrc->id) != 0) return -1;

2405 2406
  {
    SSdbRaw *pRaw = mndVgroupActionEncode(&newVg);
2407 2408
    if (pRaw == NULL) return -1;
    if (mndTransAppendCommitlog(pTrans, pRaw) != 0) {
2409 2410 2411
      sdbFreeRaw(pRaw);
      return -1;
    }
S
Shengliang Guan 已提交
2412
    (void)sdbSetRawStatus(pRaw, SDB_STATUS_READY);
S
Shengliang Guan 已提交
2413 2414 2415 2416 2417 2418 2419 2420 2421
  }

  mInfo("vgId:%d, vgroup info after balance, replica:%d", newVg.vgId, newVg.replica);
  for (int32_t i = 0; i < newVg.replica; ++i) {
    mInfo("vgId:%d, vnode:%d dnode:%d", newVg.vgId, i, newVg.vnodeGid[i].dnodeId);
  }
  return 0;
}

S
Shengliang Guan 已提交
2422 2423
static int32_t mndBalanceVgroupBetweenDnode(SMnode *pMnode, STrans *pTrans, SDnodeObj *pSrc, SDnodeObj *pDst,
                                            SHashObj *pBalancedVgroups) {
S
Shengliang Guan 已提交
2424 2425
  void   *pIter = NULL;
  int32_t code = -1;
S
Shengliang Guan 已提交
2426
  SSdb   *pSdb = pMnode->pSdb;
S
Shengliang Guan 已提交
2427 2428 2429

  while (1) {
    SVgObj *pVgroup = NULL;
S
Shengliang Guan 已提交
2430
    pIter = sdbFetch(pSdb, SDB_VGROUP, pIter, (void **)&pVgroup);
S
Shengliang Guan 已提交
2431
    if (pIter == NULL) break;
S
Shengliang Guan 已提交
2432 2433 2434 2435
    if (taosHashGet(pBalancedVgroups, &pVgroup->vgId, sizeof(int32_t)) != NULL) {
      sdbRelease(pSdb, pVgroup);
      continue;
    }
S
Shengliang Guan 已提交
2436 2437 2438 2439 2440 2441 2442 2443 2444 2445

    bool existInSrc = false;
    bool existInDst = false;
    for (int32_t i = 0; i < pVgroup->replica; ++i) {
      SVnodeGid *pGid = &pVgroup->vnodeGid[i];
      if (pGid->dnodeId == pSrc->id) existInSrc = true;
      if (pGid->dnodeId == pDst->id) existInDst = true;
    }

    if (!existInSrc || existInDst) {
S
Shengliang Guan 已提交
2446 2447
      sdbRelease(pSdb, pVgroup);
      continue;
S
Shengliang Guan 已提交
2448 2449 2450 2451
    }

    SDbObj *pDb = mndAcquireDb(pMnode, pVgroup->dbName);
    code = mndSetBalanceVgroupInfoToTrans(pMnode, pTrans, pDb, pVgroup, pSrc, pDst);
S
Shengliang Guan 已提交
2452 2453 2454
    if (code == 0) {
      code = taosHashPut(pBalancedVgroups, &pVgroup->vgId, sizeof(int32_t), &pVgroup->vgId, sizeof(int32_t));
    }
S
Shengliang Guan 已提交
2455
    mndReleaseDb(pMnode, pDb);
S
Shengliang Guan 已提交
2456 2457
    sdbRelease(pSdb, pVgroup);
    sdbCancelFetch(pSdb, pIter);
S
Shengliang Guan 已提交
2458 2459 2460 2461 2462 2463 2464
    break;
  }

  return code;
}

static int32_t mndBalanceVgroup(SMnode *pMnode, SRpcMsg *pReq, SArray *pArray) {
2465 2466 2467
  int32_t   code = -1;
  int32_t   numOfVgroups = 0;
  STrans   *pTrans = NULL;
S
Shengliang Guan 已提交
2468 2469 2470 2471
  SHashObj *pBalancedVgroups = NULL;

  pBalancedVgroups = taosHashInit(16, taosGetDefaultHashFunction(TSDB_DATA_TYPE_INT), false, HASH_NO_LOCK);
  if (pBalancedVgroups == NULL) goto _OVER;
S
Shengliang Guan 已提交
2472

2473
  pTrans = mndTransCreate(pMnode, TRN_POLICY_RETRY, TRN_CONFLICT_GLOBAL, pReq, "balance-vgroup");
S
Shengliang Guan 已提交
2474 2475
  if (pTrans == NULL) goto _OVER;
  mndTransSetSerial(pTrans);
2476
  mInfo("trans:%d, used to balance vgroup", pTrans->id);
S
Shengliang Guan 已提交
2477 2478 2479

  while (1) {
    taosArraySort(pArray, (__compar_fn_t)mndCompareDnodeVnodes);
S
Shengliang Guan 已提交
2480 2481
    for (int32_t i = 0; i < taosArrayGetSize(pArray); ++i) {
      SDnodeObj *pDnode = taosArrayGet(pArray, i);
2482 2483
      mInfo("dnode:%d, equivalent vnodes:%d others:%d support:%d, score:%f", pDnode->id, pDnode->numOfVnodes,
            pDnode->numOfSupportVnodes, pDnode->numOfOtherNodes, mndGetDnodeScore(pDnode, 0, 1));
S
Shengliang Guan 已提交
2484 2485 2486 2487
    }

    SDnodeObj *pSrc = taosArrayGet(pArray, taosArrayGetSize(pArray) - 1);
    SDnodeObj *pDst = taosArrayGet(pArray, 0);
S
Shengliang Guan 已提交
2488

2489 2490 2491
    float srcScore = mndGetDnodeScore(pSrc, -1, 1);
    float dstScore = mndGetDnodeScore(pDst, 1, 1);
    mInfo("trans:%d, after balance, src dnode:%d score:%f, dst dnode:%d score:%f", pTrans->id, pSrc->id, dstScore,
2492
          pDst->id, dstScore);
S
Shengliang Guan 已提交
2493 2494

    if (srcScore > dstScore - 0.000001) {
S
Shengliang Guan 已提交
2495
      code = mndBalanceVgroupBetweenDnode(pMnode, pTrans, pSrc, pDst, pBalancedVgroups);
S
Shengliang Guan 已提交
2496
      if (code == 0) {
S
Shengliang Guan 已提交
2497 2498
        pSrc->numOfVnodes--;
        pDst->numOfVnodes++;
S
Shengliang Guan 已提交
2499 2500 2501
        numOfVgroups++;
        continue;
      } else {
2502
        mInfo("trans:%d, no vgroup need to balance from dnode:%d to dnode:%d", pTrans->id, pSrc->id, pDst->id);
S
Shengliang Guan 已提交
2503
        break;
S
Shengliang Guan 已提交
2504 2505
      }
    } else {
2506
      mInfo("trans:%d, no vgroup need to balance any more", pTrans->id);
S
Shengliang Guan 已提交
2507 2508 2509 2510 2511
      break;
    }
  }

  if (numOfVgroups <= 0) {
2512
    mInfo("no need to balance vgroup");
S
Shengliang Guan 已提交
2513 2514
    code = 0;
  } else {
2515
    mInfo("start to balance vgroup, numOfVgroups:%d", numOfVgroups);
S
Shengliang Guan 已提交
2516 2517 2518 2519 2520
    if (mndTransPrepare(pMnode, pTrans) != 0) goto _OVER;
    code = TSDB_CODE_ACTION_IN_PROGRESS;
  }

_OVER:
2521
  taosHashCleanup(pBalancedVgroups);
S
Shengliang Guan 已提交
2522 2523 2524 2525 2526
  mndTransDrop(pTrans);
  return code;
}

static int32_t mndProcessBalanceVgroupMsg(SRpcMsg *pReq) {
2527 2528 2529
  SMnode *pMnode = pReq->info.node;
  int32_t code = -1;
  SArray *pArray = NULL;
S
Shengliang Guan 已提交
2530
  void   *pIter = NULL;
2531
  int64_t curMs = taosGetTimestampMs();
S
Shengliang Guan 已提交
2532

S
Shengliang Guan 已提交
2533 2534 2535 2536 2537 2538 2539
  SBalanceVgroupReq req = {0};
  if (tDeserializeSBalanceVgroupReq(pReq->pCont, pReq->contLen, &req) != 0) {
    terrno = TSDB_CODE_INVALID_MSG;
    goto _OVER;
  }

  mInfo("start to balance vgroup");
2540
  if (mndCheckOperPrivilege(pMnode, pReq->info.conn.user, MND_OPER_BALANCE_VGROUP) != 0) {
S
Shengliang Guan 已提交
2541 2542
    goto _OVER;
  }
S
Shengliang Guan 已提交
2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561

  while (1) {
    SDnodeObj *pDnode = NULL;
    pIter = sdbFetch(pMnode->pSdb, SDB_DNODE, pIter, (void **)&pDnode);
    if (pIter == NULL) break;
    if (!mndIsDnodeOnline(pDnode, curMs)) {
      terrno = TSDB_CODE_MND_HAS_OFFLINE_DNODE;
      mError("failed to balance vgroup since %s, dnode:%d", terrstr(), pDnode->id);
      sdbRelease(pMnode->pSdb, pDnode);
      goto _OVER;
    }

    sdbRelease(pMnode->pSdb, pDnode);
  }

  pArray = mndBuildDnodesArray(pMnode, 0);
  if (pArray == NULL) goto _OVER;

  if (taosArrayGetSize(pArray) < 2) {
2562
    mInfo("no need to balance vgroup since dnode num less than 2");
S
Shengliang Guan 已提交
2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574
    code = 0;
  } else {
    code = mndBalanceVgroup(pMnode, pReq, pArray);
  }

_OVER:
  if (code != 0 && code != TSDB_CODE_ACTION_IN_PROGRESS) {
    mError("failed to balance vgroup since %s", terrstr());
  }

  taosArrayDestroy(pArray);
  return code;
S
Shengliang Guan 已提交
2575 2576
}

L
Liu Jicong 已提交
2577
bool mndVgroupInDb(SVgObj *pVgroup, int64_t dbUid) { return !pVgroup->isTsma && pVgroup->dbUid == dbUid; }
2578

H
Haojun Liao 已提交
2579
bool mndVgroupInDnode(SVgObj *pVgroup, int32_t dnodeId) {
C
cadem 已提交
2580 2581 2582
  for(int i = 0; i < pVgroup->replica; i++){
    if(pVgroup->vnodeGid[i].dnodeId == dnodeId) return true;
  }
H
Haojun Liao 已提交
2583
  return false;
C
cadem 已提交
2584 2585
}

H
Hongze Cheng 已提交
2586 2587
static void *mndBuildCompactVnodeReq(SMnode *pMnode, SDbObj *pDb, SVgObj *pVgroup, int32_t *pContLen, int64_t compactTs,
                                     STimeWindow tw) {
2588 2589 2590
  SCompactVnodeReq compactReq = {0};
  compactReq.dbUid = pDb->uid;
  compactReq.compactStartTime = compactTs;
H
Hongze Cheng 已提交
2591
  compactReq.tw = tw;
2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616
  tstrncpy(compactReq.db, pDb->name, TSDB_DB_FNAME_LEN);

  mInfo("vgId:%d, build compact vnode config req", pVgroup->vgId);
  int32_t contLen = tSerializeSCompactVnodeReq(NULL, 0, &compactReq);
  if (contLen < 0) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }
  contLen += sizeof(SMsgHead);

  void *pReq = taosMemoryMalloc(contLen);
  if (pReq == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

  SMsgHead *pHead = pReq;
  pHead->contLen = htonl(contLen);
  pHead->vgId = htonl(pVgroup->vgId);

  tSerializeSCompactVnodeReq((char *)pReq + sizeof(SMsgHead), contLen, &compactReq);
  *pContLen = contLen;
  return pReq;
}

H
Hongze Cheng 已提交
2617 2618
static int32_t mndAddCompactVnodeAction(SMnode *pMnode, STrans *pTrans, SDbObj *pDb, SVgObj *pVgroup, int64_t compactTs,
                                        STimeWindow tw) {
2619 2620 2621 2622
  STransAction action = {0};
  action.epSet = mndGetVgroupEpset(pMnode, pVgroup);

  int32_t contLen = 0;
H
Hongze Cheng 已提交
2623
  void   *pReq = mndBuildCompactVnodeReq(pMnode, pDb, pVgroup, &contLen, compactTs, tw);
2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637
  if (pReq == NULL) return -1;

  action.pCont = pReq;
  action.contLen = contLen;
  action.msgType = TDMT_VND_COMPACT;

  if (mndTransAppendRedoAction(pTrans, &action) != 0) {
    taosMemoryFree(pReq);
    return -1;
  }

  return 0;
}

H
Hongze Cheng 已提交
2638 2639 2640
int32_t mndBuildCompactVgroupAction(SMnode *pMnode, STrans *pTrans, SDbObj *pDb, SVgObj *pVgroup, int64_t compactTs,
                                    STimeWindow tw) {
  if (mndAddCompactVnodeAction(pMnode, pTrans, pDb, pVgroup, compactTs, tw) != 0) return -1;
2641
  return 0;
2642
}