mndVgroup.c 70.3 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"
S
Shengliang Guan 已提交
26

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

S
Shengliang Guan 已提交
30 31 32
static SSdbRow *mndVgroupActionDecode(SSdbRaw *pRaw);
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);
S
Shengliang Guan 已提交
43

S
Shengliang Guan 已提交
44
int32_t mndInitVgroup(SMnode *pMnode) {
S
Shengliang Guan 已提交
45 46 47 48 49 50 51 52 53
  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 已提交
54

55 56 57 58
  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 已提交
59
  mndSetMsgHandle(pMnode, TDMT_VND_ALTER_HASHRANGE_RSP, mndTransProcessRsp);
60 61
  mndSetMsgHandle(pMnode, TDMT_DND_DROP_VNODE_RSP, mndTransProcessRsp);
  mndSetMsgHandle(pMnode, TDMT_VND_COMPACT_RSP, mndTransProcessRsp);
S
Shengliang Guan 已提交
62

63
  mndSetMsgHandle(pMnode, TDMT_MND_REDISTRIBUTE_VGROUP, mndProcessRedistributeVgroupMsg);
S
Shengliang Guan 已提交
64
  mndSetMsgHandle(pMnode, TDMT_MND_SPLIT_VGROUP, mndProcessSplitVgroupMsg);
65 66
  mndSetMsgHandle(pMnode, TDMT_MND_BALANCE_VGROUP, mndProcessBalanceVgroupMsg);

S
Shengliang Guan 已提交
67 68
  mndAddShowRetrieveHandle(pMnode, TSDB_MGMT_TABLE_VGROUP, mndRetrieveVgroups);
  mndAddShowFreeIterHandle(pMnode, TSDB_MGMT_TABLE_VGROUP, mndCancelGetNextVgroup);
S
Shengliang Guan 已提交
69 70 71
  mndAddShowRetrieveHandle(pMnode, TSDB_MGMT_TABLE_VNODES, mndRetrieveVnodes);
  mndAddShowFreeIterHandle(pMnode, TSDB_MGMT_TABLE_VNODES, mndCancelGetNextVnode);

S
Shengliang Guan 已提交
72
  return sdbSetTable(pMnode->pSdb, table);
S
Shengliang Guan 已提交
73 74 75 76
}

void mndCleanupVgroup(SMnode *pMnode) {}

S
Shengliang Guan 已提交
77
SSdbRaw *mndVgroupActionEncode(SVgObj *pVgroup) {
78 79
  terrno = TSDB_CODE_OUT_OF_MEMORY;

S
Shengliang Guan 已提交
80
  SSdbRaw *pRaw = sdbAllocRaw(SDB_VGROUP, VGROUP_VER_NUMBER, sizeof(SVgObj) + VGROUP_RESERVE_SIZE);
S
Shengliang Guan 已提交
81
  if (pRaw == NULL) goto _OVER;
S
Shengliang Guan 已提交
82 83

  int32_t dataPos = 0;
S
Shengliang Guan 已提交
84 85 86 87 88 89 90 91
  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 已提交
92
  SDB_SET_INT8(pRaw, dataPos, pVgroup->isTsma, _OVER)
S
Shengliang Guan 已提交
93
  SDB_SET_INT8(pRaw, dataPos, pVgroup->replica, _OVER)
S
Shengliang Guan 已提交
94 95
  for (int8_t i = 0; i < pVgroup->replica; ++i) {
    SVnodeGid *pVgid = &pVgroup->vnodeGid[i];
S
Shengliang Guan 已提交
96
    SDB_SET_INT32(pRaw, dataPos, pVgid->dnodeId, _OVER)
97
  }
S
Shengliang Guan 已提交
98
  SDB_SET_RESERVE(pRaw, dataPos, VGROUP_RESERVE_SIZE, _OVER)
S
Shengliang Guan 已提交
99
  SDB_SET_DATALEN(pRaw, dataPos, _OVER)
100 101 102

  terrno = 0;

S
Shengliang Guan 已提交
103
_OVER:
104 105 106 107
  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 已提交
108 109
  }

110
  mTrace("vgId:%d, encode to raw:%p, row:%p", pVgroup->vgId, pRaw, pVgroup);
S
Shengliang Guan 已提交
111 112 113
  return pRaw;
}

S
Shengliang Guan 已提交
114
SSdbRow *mndVgroupActionDecode(SSdbRaw *pRaw) {
115 116
  terrno = TSDB_CODE_OUT_OF_MEMORY;

S
Shengliang Guan 已提交
117
  int8_t sver = 0;
S
Shengliang Guan 已提交
118
  if (sdbGetRawSoftVer(pRaw, &sver) != 0) goto _OVER;
S
Shengliang Guan 已提交
119

S
Shengliang Guan 已提交
120
  if (sver != VGROUP_VER_NUMBER) {
S
Shengliang Guan 已提交
121
    terrno = TSDB_CODE_SDB_INVALID_DATA_VER;
S
Shengliang Guan 已提交
122
    goto _OVER;
S
Shengliang Guan 已提交
123 124
  }

S
Shengliang Guan 已提交
125
  SSdbRow *pRow = sdbAllocRow(sizeof(SVgObj));
S
Shengliang Guan 已提交
126
  if (pRow == NULL) goto _OVER;
127 128

  SVgObj *pVgroup = sdbGetRowObj(pRow);
S
Shengliang Guan 已提交
129
  if (pVgroup == NULL) goto _OVER;
S
Shengliang Guan 已提交
130 131

  int32_t dataPos = 0;
S
Shengliang Guan 已提交
132 133 134 135 136 137 138 139
  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 已提交
140
  SDB_GET_INT8(pRaw, dataPos, &pVgroup->isTsma, _OVER)
S
Shengliang Guan 已提交
141
  SDB_GET_INT8(pRaw, dataPos, &pVgroup->replica, _OVER)
S
Shengliang Guan 已提交
142 143
  for (int8_t i = 0; i < pVgroup->replica; ++i) {
    SVnodeGid *pVgid = &pVgroup->vnodeGid[i];
S
Shengliang Guan 已提交
144
    SDB_GET_INT32(pRaw, dataPos, &pVgid->dnodeId, _OVER)
S
Shengliang Guan 已提交
145
    if (pVgroup->replica == 1) {
146
      pVgid->syncState = TAOS_SYNC_STATE_LEADER;
S
Shengliang Guan 已提交
147
    }
S
Shengliang Guan 已提交
148
  }
S
Shengliang Guan 已提交
149
  SDB_GET_RESERVE(pRaw, dataPos, VGROUP_RESERVE_SIZE, _OVER)
150 151 152

  terrno = 0;

S
Shengliang Guan 已提交
153
_OVER:
154 155
  if (terrno != 0) {
    mError("vgId:%d, failed to decode from raw:%p since %s", pVgroup->vgId, pRaw, terrstr());
wafwerar's avatar
wafwerar 已提交
156
    taosMemoryFreeClear(pRow);
157 158
    return NULL;
  }
S
Shengliang Guan 已提交
159

160
  mTrace("vgId:%d, decode from raw:%p, row:%p", pVgroup->vgId, pRaw, pVgroup);
S
Shengliang Guan 已提交
161 162 163 164
  return pRow;
}

static int32_t mndVgroupActionInsert(SSdb *pSdb, SVgObj *pVgroup) {
165
  mTrace("vgId:%d, perform insert action, row:%p", pVgroup->vgId, pVgroup);
S
Shengliang Guan 已提交
166 167 168 169
  return 0;
}

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

S
Shengliang Guan 已提交
174 175 176 177 178 179 180
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 已提交
181
  pOld->isTsma = pNew->isTsma;
182 183 184 185 186 187 188 189 190 191
  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;
      }
    }
  }
192 193 194 195 196 197
  pNew->numOfTables = pOld->numOfTables;
  pNew->numOfTimeSeries = pOld->numOfTimeSeries;
  pNew->totalStorage = pOld->totalStorage;
  pNew->compStorage = pOld->compStorage;
  pNew->pointsWritten = pOld->pointsWritten;
  pNew->compact = pOld->compact;
S
Shengliang Guan 已提交
198
  memcpy(pOld->vnodeGid, pNew->vnodeGid, TSDB_MAX_REPLICA * sizeof(SVnodeGid));
S
Shengliang Guan 已提交
199 200 201 202
  return 0;
}

SVgObj *mndAcquireVgroup(SMnode *pMnode, int32_t vgId) {
S
Shengliang Guan 已提交
203 204
  SSdb   *pSdb = pMnode->pSdb;
  SVgObj *pVgroup = sdbAcquire(pSdb, SDB_VGROUP, &vgId);
S
Shengliang Guan 已提交
205
  if (pVgroup == NULL && terrno == TSDB_CODE_SDB_OBJ_NOT_THERE) {
S
Shengliang Guan 已提交
206 207 208
    terrno = TSDB_CODE_MND_VGROUP_NOT_EXIST;
  }
  return pVgroup;
S
Shengliang Guan 已提交
209 210 211 212 213 214 215
}

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

S
Shengliang Guan 已提交
216
void *mndBuildCreateVnodeReq(SMnode *pMnode, SDnodeObj *pDnode, SDbObj *pDb, SVgObj *pVgroup, int32_t *pContLen) {
S
Shengliang Guan 已提交
217 218 219 220 221
  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 已提交
222 223 224 225
  createReq.numOfStables = pDb->cfg.numOfStables;
  createReq.buffer = pDb->cfg.buffer;
  createReq.pageSize = pDb->cfg.pageSize;
  createReq.pages = pDb->cfg.pages;
226
  createReq.cacheLastSize = pDb->cfg.cacheLastSize;
S
Shengliang Guan 已提交
227 228 229 230
  createReq.daysPerFile = pDb->cfg.daysPerFile;
  createReq.daysToKeep0 = pDb->cfg.daysToKeep0;
  createReq.daysToKeep1 = pDb->cfg.daysToKeep1;
  createReq.daysToKeep2 = pDb->cfg.daysToKeep2;
S
Shengliang Guan 已提交
231 232
  createReq.minRows = pDb->cfg.minRows;
  createReq.maxRows = pDb->cfg.maxRows;
233
  createReq.walFsyncPeriod = pDb->cfg.walFsyncPeriod;
S
Shengliang Guan 已提交
234 235 236
  createReq.walLevel = pDb->cfg.walLevel;
  createReq.precision = pDb->cfg.precision;
  createReq.compression = pDb->cfg.compression;
S
Shengliang Guan 已提交
237
  createReq.strict = pDb->cfg.strict;
238
  createReq.cacheLast = pDb->cfg.cacheLast;
S
Shengliang Guan 已提交
239 240
  createReq.replica = pVgroup->replica;
  createReq.selfIndex = -1;
D
dapan1121 已提交
241 242
  createReq.hashBegin = pVgroup->hashBegin;
  createReq.hashEnd = pVgroup->hashEnd;
S
Shengliang Guan 已提交
243
  createReq.hashMethod = pDb->cfg.hashMethod;
S
sma  
Shengliang Guan 已提交
244 245
  createReq.numOfRetensions = pDb->cfg.numOfRetensions;
  createReq.pRetensions = pDb->cfg.pRetensions;
C
Cary Xu 已提交
246 247
  createReq.isTsma = pVgroup->isTsma;
  createReq.pTsma = pVgroup->pTsma;
S
Shengliang Guan 已提交
248 249 250 251
  createReq.walRetentionPeriod = pDb->cfg.walRetentionPeriod;
  createReq.walRetentionSize = pDb->cfg.walRetentionSize;
  createReq.walRollPeriod = pDb->cfg.walRollPeriod;
  createReq.walSegmentSize = pDb->cfg.walSegmentSize;
252
  createReq.sstTrigger = pDb->cfg.sstTrigger;
253 254
  createReq.hashPrefix = pDb->cfg.hashPrefix;
  createReq.hashSuffix = pDb->cfg.hashSuffix;
255 256
  createReq.tsdbPageSize = pDb->cfg.tsdbPageSize;

S
Shengliang Guan 已提交
257
  for (int32_t v = 0; v < pVgroup->replica; ++v) {
S
Shengliang Guan 已提交
258
    SReplica  *pReplica = &createReq.replicas[v];
S
Shengliang Guan 已提交
259 260 261 262 263 264
    SVnodeGid *pVgid = &pVgroup->vnodeGid[v];
    SDnodeObj *pVgidDnode = mndAcquireDnode(pMnode, pVgid->dnodeId);
    if (pVgidDnode == NULL) {
      return NULL;
    }

S
Shengliang Guan 已提交
265 266
    pReplica->id = pVgidDnode->id;
    pReplica->port = pVgidDnode->port;
S
Shengliang Guan 已提交
267 268 269 270
    memcpy(pReplica->fqdn, pVgidDnode->fqdn, TSDB_FQDN_LEN);
    mndReleaseDnode(pMnode, pVgidDnode);

    if (pDnode->id == pVgid->dnodeId) {
S
Shengliang Guan 已提交
271
      createReq.selfIndex = v;
S
Shengliang Guan 已提交
272 273 274
    }
  }

S
Shengliang Guan 已提交
275
  if (createReq.selfIndex == -1) {
S
Shengliang Guan 已提交
276 277 278 279
    terrno = TSDB_CODE_MND_APP_ERROR;
    return NULL;
  }

S
Shengliang Guan 已提交
280 281 282 283 284 285
  mInfo("vgId:%d, build create vnode req, replica:%d selfIndex:%d strict:%d", createReq.vgId, createReq.replica,
        createReq.selfIndex, createReq.strict);
  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);
  }

S
Shengliang Guan 已提交
286 287 288 289 290 291
  int32_t contLen = tSerializeSCreateVnodeReq(NULL, 0, &createReq);
  if (contLen < 0) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

wafwerar's avatar
wafwerar 已提交
292
  void *pReq = taosMemoryMalloc(contLen);
S
Shengliang Guan 已提交
293 294 295 296 297 298 299 300
  if (pReq == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

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

S
Shengliang Guan 已提交
303 304
static void *mndBuildAlterVnodeConfigReq(SMnode *pMnode, SDbObj *pDb, SVgObj *pVgroup, int32_t *pContLen) {
  SAlterVnodeConfigReq alterReq = {0};
S
Shengliang Guan 已提交
305 306 307
  alterReq.vgVersion = pVgroup->version;
  alterReq.buffer = pDb->cfg.buffer;
  alterReq.pageSize = pDb->cfg.pageSize;
308
  alterReq.pages = pDb->cfg.pages;
309
  alterReq.cacheLastSize = pDb->cfg.cacheLastSize;
S
Shengliang Guan 已提交
310 311 312 313
  alterReq.daysPerFile = pDb->cfg.daysPerFile;
  alterReq.daysToKeep0 = pDb->cfg.daysToKeep0;
  alterReq.daysToKeep1 = pDb->cfg.daysToKeep1;
  alterReq.daysToKeep2 = pDb->cfg.daysToKeep2;
314
  alterReq.walFsyncPeriod = pDb->cfg.walFsyncPeriod;
S
Shengliang Guan 已提交
315 316
  alterReq.walLevel = pDb->cfg.walLevel;
  alterReq.strict = pDb->cfg.strict;
317
  alterReq.cacheLast = pDb->cfg.cacheLast;
S
Shengliang Guan 已提交
318

S
Shengliang Guan 已提交
319
  mInfo("vgId:%d, build alter vnode config req", pVgroup->vgId);
S
Shengliang Guan 已提交
320
  int32_t contLen = tSerializeSAlterVnodeConfigReq(NULL, 0, &alterReq);
S
Shengliang Guan 已提交
321 322 323 324
  if (contLen < 0) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }
S
Shengliang Guan 已提交
325
  contLen += sizeof(SMsgHead);
S
Shengliang Guan 已提交
326 327 328 329 330 331 332 333 334 335 336

  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 已提交
337
  tSerializeSAlterVnodeConfigReq((char *)pReq + sizeof(SMsgHead), contLen, &alterReq);
S
Shengliang Guan 已提交
338 339 340 341
  *pContLen = contLen;
  return pReq;
}

S
Shengliang Guan 已提交
342
static void *mndBuildAlterVnodeReplicaReq(SMnode *pMnode, SDbObj *pDb, SVgObj *pVgroup, int32_t dnodeId,
S
Shengliang Guan 已提交
343
                                          int32_t *pContLen) {
S
Shengliang Guan 已提交
344
  SAlterVnodeReplicaReq alterReq = {
S
Shengliang Guan 已提交
345 346 347 348
      .vgId = pVgroup->vgId,
      .strict = pDb->cfg.strict,
      .replica = pVgroup->replica,
      .selfIndex = -1,
S
Shengliang Guan 已提交
349
  };
S
Shengliang Guan 已提交
350 351 352 353 354 355 356 357 358 359 360 361 362 363

  for (int32_t v = 0; v < pVgroup->replica; ++v) {
    SReplica  *pReplica = &alterReq.replicas[v];
    SVnodeGid *pVgid = &pVgroup->vnodeGid[v];
    SDnodeObj *pVgidDnode = mndAcquireDnode(pMnode, pVgid->dnodeId);
    if (pVgidDnode == NULL) {
      return NULL;
    }

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

S
Shengliang Guan 已提交
364
    if (dnodeId == pVgid->dnodeId) {
S
Shengliang Guan 已提交
365 366 367
      alterReq.selfIndex = v;
    }
  }
368
  alterReq.replica = pVgroup->replica;
S
Shengliang Guan 已提交
369
  mInfo("vgId:%d, build alter vnode req, replica:%d selfIndex:%d strict:%d", alterReq.vgId, alterReq.replica,
370 371 372 373
        alterReq.selfIndex, alterReq.strict);
  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);
  }
S
Shengliang Guan 已提交
374 375 376 377 378

  if (alterReq.selfIndex == -1) {
    terrno = TSDB_CODE_MND_APP_ERROR;
    return NULL;
  }
379

S
Shengliang Guan 已提交
380
  int32_t contLen = tSerializeSAlterVnodeReplicaReq(NULL, 0, &alterReq);
381 382 383 384 385 386 387 388 389 390 391
  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 已提交
392
  tSerializeSAlterVnodeReplicaReq(pReq, contLen, &alterReq);
393 394 395 396
  *pContLen = contLen;
  return pReq;
}

L
Liu Jicong 已提交
397
void *mndBuildDropVnodeReq(SMnode *pMnode, SDnodeObj *pDnode, SDbObj *pDb, SVgObj *pVgroup, int32_t *pContLen) {
S
Shengliang Guan 已提交
398 399 400 401 402 403
  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 已提交
404
  mInfo("vgId:%d, build drop vnode req", dropReq.vgId);
S
Shengliang Guan 已提交
405 406
  int32_t contLen = tSerializeSDropVnodeReq(NULL, 0, &dropReq);
  if (contLen < 0) {
S
Shengliang Guan 已提交
407 408 409 410
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

wafwerar's avatar
wafwerar 已提交
411
  void *pReq = taosMemoryMalloc(contLen);
S
Shengliang Guan 已提交
412 413 414 415
  if (pReq == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }
S
Shengliang Guan 已提交
416

S
Shengliang Guan 已提交
417 418 419
  tSerializeSDropVnodeReq(pReq, contLen, &dropReq);
  *pContLen = contLen;
  return pReq;
S
Shengliang Guan 已提交
420 421
}

S
Shengliang Guan 已提交
422 423 424 425 426 427 428 429 430
static bool mndResetDnodesArrayFp(SMnode *pMnode, void *pObj, void *p1, void *p2, void *p3) {
  SDnodeObj *pDnode = pObj;
  pDnode->numOfVnodes = 0;
  return true;
}

static bool mndBuildDnodesArrayFp(SMnode *pMnode, void *pObj, void *p1, void *p2, void *p3) {
  SDnodeObj *pDnode = pObj;
  SArray    *pArray = p1;
S
Shengliang Guan 已提交
431 432 433 434 435
  int32_t    exceptDnodeId = *(int32_t *)p2;

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

  int64_t curMs = taosGetTimestampMs();
S
Shengliang Guan 已提交
438
  bool    online = mndIsDnodeOnline(pDnode, curMs);
S
Shengliang Guan 已提交
439 440
  bool    isMnode = mndIsMnode(pMnode, pDnode->id);
  pDnode->numOfVnodes = mndGetVnodesNum(pMnode, pDnode->id);
441
  pDnode->memUsed = mndGetVnodesMemory(pMnode, pDnode->id);
S
Shengliang Guan 已提交
442

443
  mInfo("dnode:%d, vnodes:%d supportVnodes:%d isMnode:%d online:%d memory avail:%" PRId64 " used:%" PRId64, pDnode->id,
444
        pDnode->numOfVnodes, pDnode->numOfSupportVnodes, isMnode, online, pDnode->memAvail, pDnode->memUsed);
S
Shengliang Guan 已提交
445 446 447 448 449

  if (isMnode) {
    pDnode->numOfVnodes++;
  }

S
Shengliang Guan 已提交
450 451 452
  if (online && pDnode->numOfSupportVnodes > 0) {
    taosArrayPush(pArray, pDnode);
  }
S
Shengliang Guan 已提交
453 454 455
  return true;
}

S
Shengliang Guan 已提交
456
SArray *mndBuildDnodesArray(SMnode *pMnode, int32_t exceptDnodeId) {
S
Shengliang Guan 已提交
457
  SSdb   *pSdb = pMnode->pSdb;
S
Shengliang Guan 已提交
458
  int32_t numOfDnodes = mndGetDnodeSize(pMnode);
S
Shengliang Guan 已提交
459

S
Shengliang Guan 已提交
460 461 462 463 464
  SArray *pArray = taosArrayInit(numOfDnodes, sizeof(SDnodeObj));
  if (pArray == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }
S
Shengliang Guan 已提交
465

S
Shengliang Guan 已提交
466
  sdbTraverse(pSdb, SDB_DNODE, mndResetDnodesArrayFp, NULL, NULL, NULL);
S
Shengliang Guan 已提交
467
  sdbTraverse(pSdb, SDB_DNODE, mndBuildDnodesArrayFp, pArray, &exceptDnodeId, NULL);
S
Shengliang Guan 已提交
468 469 470
  return pArray;
}

S
Shengliang Guan 已提交
471 472
static int32_t mndCompareDnodeId(int32_t *dnode1Id, int32_t *dnode2Id) { return *dnode1Id >= *dnode2Id ? 1 : 0; }

S
Shengliang Guan 已提交
473 474 475
static int32_t mndCompareDnodeVnodes(SDnodeObj *pDnode1, SDnodeObj *pDnode2) {
  float d1Score = (float)pDnode1->numOfVnodes / pDnode1->numOfSupportVnodes;
  float d2Score = (float)pDnode2->numOfVnodes / pDnode2->numOfSupportVnodes;
S
Shengliang Guan 已提交
476
  return d1Score >= d2Score ? 1 : 0;
S
Shengliang Guan 已提交
477 478
}

S
Shengliang Guan 已提交
479 480 481 482 483 484 485 486 487 488
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]);
      }
    }
  }
}

489
static int32_t mndGetAvailableDnode(SMnode *pMnode, SDbObj *pDb, SVgObj *pVgroup, SArray *pArray) {
S
Shengliang Guan 已提交
490 491 492 493 494 495
  SSdb   *pSdb = pMnode->pSdb;
  int32_t allocedVnodes = 0;
  void   *pIter = NULL;

  taosArraySort(pArray, (__compar_fn_t)mndCompareDnodeVnodes);

S
Shengliang Guan 已提交
496 497 498 499 500 501 502 503
  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 已提交
504 505 506 507 508 509 510 511
  for (int32_t v = 0; v < pVgroup->replica; ++v) {
    SVnodeGid *pVgid = &pVgroup->vnodeGid[v];
    SDnodeObj *pDnode = taosArrayGet(pArray, v);
    if (pDnode == NULL || pDnode->numOfVnodes > pDnode->numOfSupportVnodes) {
      terrno = TSDB_CODE_MND_NO_ENOUGH_DNODES;
      return -1;
    }

512 513 514 515 516 517 518 519 520 521
    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 已提交
522 523
    pVgid->dnodeId = pDnode->id;
    if (pVgroup->replica == 1) {
524
      pVgid->syncState = TAOS_SYNC_STATE_LEADER;
S
Shengliang Guan 已提交
525
    } else {
526
      pVgid->syncState = TAOS_SYNC_STATE_FOLLOWER;
S
Shengliang Guan 已提交
527 528
    }

529 530
    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 已提交
531
    pDnode->numOfVnodes++;
S
Shengliang Guan 已提交
532
  }
S
Shengliang Guan 已提交
533

S
Shengliang Guan 已提交
534
  mndSortVnodeGid(pVgroup);
S
Shengliang Guan 已提交
535 536
  return 0;
}
537

S
Shengliang Guan 已提交
538
int32_t mndAllocSmaVgroup(SMnode *pMnode, SDbObj *pDb, SVgObj *pVgroup) {
S
Shengliang Guan 已提交
539
  SArray *pArray = mndBuildDnodesArray(pMnode, 0);
S
Shengliang Guan 已提交
540 541 542 543 544 545 546 547 548 549 550
  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;

551
  if (mndGetAvailableDnode(pMnode, pDb, pVgroup, pArray) != 0) return -1;
L
Liu Jicong 已提交
552
  taosArrayDestroy(pArray);
S
Shengliang Guan 已提交
553 554 555 556 557

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

S
Shengliang Guan 已提交
558
int32_t mndAllocVgroup(SMnode *pMnode, SDbObj *pDb, SVgObj **ppVgroups) {
S
Shengliang Guan 已提交
559 560 561 562
  int32_t code = -1;
  SArray *pArray = NULL;
  SVgObj *pVgroups = NULL;

wafwerar's avatar
wafwerar 已提交
563
  pVgroups = taosMemoryCalloc(pDb->cfg.numOfVgroups, sizeof(SVgObj));
S
Shengliang Guan 已提交
564 565
  if (pVgroups == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
S
Shengliang Guan 已提交
566
    goto _OVER;
S
Shengliang Guan 已提交
567 568
  }

S
Shengliang Guan 已提交
569
  pArray = mndBuildDnodesArray(pMnode, 0);
S
Shengliang Guan 已提交
570
  if (pArray == NULL) goto _OVER;
S
Shengliang Guan 已提交
571

S
Shengliang Guan 已提交
572 573
  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 已提交
574

S
Shengliang Guan 已提交
575
  int32_t  allocedVgroups = 0;
S
Shengliang Guan 已提交
576 577 578
  int32_t  maxVgId = sdbGetMaxId(pMnode->pSdb, SDB_VGROUP);
  uint32_t hashMin = 0;
  uint32_t hashMax = UINT32_MAX;
579
  uint32_t hashInterval = (hashMax - hashMin) / pDb->cfg.numOfVgroups;
S
Shengliang Guan 已提交
580

581 582
  if (maxVgId < 2) maxVgId = 2;

583
  for (uint32_t v = 0; v < pDb->cfg.numOfVgroups; v++) {
S
Shengliang Guan 已提交
584
    SVgObj *pVgroup = &pVgroups[v];
S
Shengliang Guan 已提交
585
    pVgroup->vgId = maxVgId++;
S
Shengliang Guan 已提交
586 587
    pVgroup->createdTime = taosGetTimestampMs();
    pVgroup->updateTime = pVgroups->createdTime;
S
Shengliang Guan 已提交
588
    pVgroup->version = 1;
S
Shengliang Guan 已提交
589
    pVgroup->hashBegin = hashMin + hashInterval * v;
590
    if (v == pDb->cfg.numOfVgroups - 1) {
S
Shengliang Guan 已提交
591 592
      pVgroup->hashEnd = hashMax;
    } else {
S
Shengliang Guan 已提交
593
      pVgroup->hashEnd = hashMin + hashInterval * (v + 1) - 1;
S
Shengliang Guan 已提交
594
    }
S
Shengliang Guan 已提交
595

596
    memcpy(pVgroup->dbName, pDb->name, TSDB_DB_FNAME_LEN);
S
Shengliang Guan 已提交
597
    pVgroup->dbUid = pDb->uid;
S
Shengliang Guan 已提交
598
    pVgroup->replica = pDb->cfg.replications;
S
Shengliang Guan 已提交
599

600
    if (mndGetAvailableDnode(pMnode, pDb, pVgroup, pArray) != 0) {
S
Shengliang Guan 已提交
601
      goto _OVER;
S
Shengliang Guan 已提交
602 603
    }

S
Shengliang Guan 已提交
604
    allocedVgroups++;
605 606
  }

S
Shengliang Guan 已提交
607
  *ppVgroups = pVgroups;
S
Shengliang Guan 已提交
608 609
  code = 0;

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

S
Shengliang Guan 已提交
612
_OVER:
wafwerar's avatar
wafwerar 已提交
613
  if (code != 0) taosMemoryFree(pVgroups);
S
Shengliang Guan 已提交
614 615
  taosArrayDestroy(pArray);
  return code;
616
}
617

L
Liu Jicong 已提交
618
SEpSet mndGetVgroupEpset(SMnode *pMnode, const SVgObj *pVgroup) {
619 620 621
  SEpSet epset = {0};

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

626
    if (pVgid->syncState == TAOS_SYNC_STATE_LEADER) {
627 628 629
      epset.inUse = epset.numOfEps;
    }

H
Haojun Liao 已提交
630
    addEpIntoEpSet(&epset, pDnode->fqdn, pDnode->port);
631 632 633 634 635 636
    mndReleaseDnode(pMnode, pDnode);
  }

  return epset;
}

S
Shengliang Guan 已提交
637 638
static int32_t mndRetrieveVgroups(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pBlock, int32_t rows) {
  SMnode *pMnode = pReq->info.node;
S
Shengliang Guan 已提交
639 640 641 642
  SSdb   *pSdb = pMnode->pSdb;
  int32_t numOfRows = 0;
  SVgObj *pVgroup = NULL;
  int32_t cols = 0;
643
  int64_t curMs = taosGetTimestampMs();
S
Shengliang Guan 已提交
644

H
Haojun Liao 已提交
645 646 647 648 649 650 651
  SDbObj *pDb = NULL;
  if (strlen(pShow->db) > 0) {
    pDb = mndAcquireDb(pMnode, pShow->db);
    if (pDb == NULL) {
      return 0;
    }
  }
S
Shengliang Guan 已提交
652

S
Shengliang Guan 已提交
653 654 655 656
  while (numOfRows < rows) {
    pShow->pIter = sdbFetch(pSdb, SDB_VGROUP, pShow->pIter, (void **)&pVgroup);
    if (pShow->pIter == NULL) break;

H
Haojun Liao 已提交
657
    if (pDb != NULL && pVgroup->dbUid != pDb->uid) {
658
      sdbRelease(pSdb, pVgroup);
H
Haojun Liao 已提交
659 660 661 662
      continue;
    }

    cols = 0;
663 664
    SColumnInfoData *pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
    colDataAppend(pColInfo, numOfRows, (const char *)&pVgroup->vgId, false);
H
Haojun Liao 已提交
665 666

    SName name = {0};
667 668 669 670
    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 已提交
671

672 673
    pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
    colDataAppend(pColInfo, numOfRows, (const char *)db, false);
H
Haojun Liao 已提交
674

675 676
    pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
    colDataAppend(pColInfo, numOfRows, (const char *)&pVgroup->numOfTables, false);
H
Haojun Liao 已提交
677

678 679
    // default 3 replica, add 1 replica if move vnode
    for (int32_t i = 0; i < 4; ++i) {
680
      pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
681
      if (i < pVgroup->replica) {
682 683
        int16_t dnodeId = (int16_t)pVgroup->vnodeGid[i].dnodeId;
        colDataAppend(pColInfo, numOfRows, (const char *)&dnodeId, false);
684

685
        bool       exist = false;
686 687 688
        bool       online = false;
        SDnodeObj *pDnode = mndAcquireDnode(pMnode, pVgroup->vnodeGid[i].dnodeId);
        if (pDnode != NULL) {
689
          exist = true;
S
Shengliang Guan 已提交
690
          online = mndIsDnodeOnline(pDnode, curMs);
691 692 693
          mndReleaseDnode(pMnode, pDnode);
        }

694 695
        char buf1[20] = {0};
        char role[20] = "offline";
696 697 698
        if (!exist) {
          strcpy(role, "dropping");
        } else if (online) {
699 700
          bool show = (pVgroup->vnodeGid[i].syncState == TAOS_SYNC_STATE_LEADER && !pVgroup->vnodeGid[i].syncRestore);
          snprintf(role, sizeof(role), "%s%s", syncStr(pVgroup->vnodeGid[i].syncState), show ? "*" : "");
701
        } else {
702
        }
S
Shengliang Guan 已提交
703
        STR_WITH_MAXSIZE_TO_VARSTR(buf1, role, pShow->pMeta->pSchemas[cols].bytes);
704 705 706 707 708 709 710 711

        pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
        colDataAppend(pColInfo, numOfRows, (const char *)buf1, false);
      } else {
        colDataAppendNULL(pColInfo, numOfRows);
        pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
        colDataAppendNULL(pColInfo, numOfRows);
      }
S
Shengliang Guan 已提交
712
    }
S
Shengliang Guan 已提交
713

714
    pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
715 716
    int32_t cacheUsage = (int32_t)pVgroup->cacheUsage;
    colDataAppend(pColInfo, numOfRows, (const char *)&cacheUsage, false);
717

S
Shengliang Guan 已提交
718 719 720
    pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
    colDataAppend(pColInfo, numOfRows, (const char *)&pVgroup->isTsma, false);

H
Haojun Liao 已提交
721
    numOfRows++;
S
Shengliang Guan 已提交
722 723 724
    sdbRelease(pSdb, pVgroup);
  }

H
Haojun Liao 已提交
725 726 727 728
  if (pDb != NULL) {
    mndReleaseDb(pMnode, pDb);
  }

729
  pShow->numOfRows += numOfRows;
S
Shengliang Guan 已提交
730 731 732 733 734 735 736 737
  return numOfRows;
}

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

S
Shengliang Guan 已提交
738 739 740 741
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 已提交
742

S
Shengliang Guan 已提交
743 744 745
  for (int32_t v = 0; v < pVgroup->replica; ++v) {
    if (pVgroup->vnodeGid[v].dnodeId == dnodeId) {
      (*pNumOfVnodes)++;
S
Shengliang Guan 已提交
746
    }
S
Shengliang Guan 已提交
747 748
  }

S
Shengliang Guan 已提交
749 750 751 752 753 754
  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 已提交
755
  return numOfVnodes;
S
Shengliang Guan 已提交
756 757
}

758 759 760 761 762 763
int64_t mndGetVgroupMemory(SMnode *pMnode, SDbObj *pDbInput, SVgObj *pVgroup) {
  SDbObj *pDb = pDbInput;
  if (pDbInput == NULL) {
    pDb = mndAcquireDb(pMnode, pVgroup->dbName);
  }

S
Shengliang Guan 已提交
764 765 766
  int64_t vgroupMemroy = 0;
  if (pDb != NULL) {
    vgroupMemroy = (int64_t)pDb->cfg.buffer * 1024 * 1024 + (int64_t)pDb->cfg.pages * pDb->cfg.pageSize * 1024;
767 768
    if (pDb->cfg.cacheLast > 0) {
      vgroupMemroy += (int64_t)pDb->cfg.cacheLastSize * 1024 * 1024;
S
Shengliang Guan 已提交
769
    }
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
  }

  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 已提交
798 799
static int32_t mndRetrieveVnodes(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pBlock, int32_t rows) {
  SMnode *pMnode = pReq->info.node;
S
Shengliang Guan 已提交
800 801 802 803 804 805 806 807 808
  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 已提交
809
    for (int32_t i = 0; i < pVgroup->replica && numOfRows < rows; ++i) {
S
Shengliang Guan 已提交
810 811
      SVnodeGid       *pVgid = &pVgroup->vnodeGid[i];
      SColumnInfoData *pColInfo = NULL;
S
Shengliang Guan 已提交
812 813
      cols = 0;

814
      pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
S
Shengliang Guan 已提交
815
      colDataAppend(pColInfo, numOfRows, (const char *)&pVgroup->vgId, false);
H
Haojun Liao 已提交
816

817
      pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
S
Shengliang Guan 已提交
818
      colDataAppend(pColInfo, numOfRows, (const char *)&pVgroup->replica, false);
H
Haojun Liao 已提交
819

820
      char buf[20] = {0};
821
      STR_TO_VARSTR(buf, syncStr(pVgid->syncState));
822 823
      pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
      colDataAppend(pColInfo, numOfRows, (const char *)buf, false);
H
Haojun Liao 已提交
824

S
Shengliang Guan 已提交
825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
      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++);
      colDataAppend(pColInfo, numOfRows, (const char *)b1, false);

      pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
      colDataAppend(pColInfo, numOfRows, (const char *)&pVgid->dnodeId, false);

      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);
      }
845
      pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
S
Shengliang Guan 已提交
846
      colDataAppend(pColInfo, numOfRows, (const char *)b2, false);
H
Haojun Liao 已提交
847

S
Shengliang Guan 已提交
848 849 850 851 852 853
      numOfRows++;
    }

    sdbRelease(pSdb, pVgroup);
  }

854
  pShow->numOfRows += numOfRows;
S
Shengliang Guan 已提交
855 856 857 858 859 860
  return numOfRows;
}

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

863
static int32_t mndAddVnodeToVgroup(SMnode *pMnode, STrans *pTrans, SVgObj *pVgroup, SArray *pArray) {
S
Shengliang Guan 已提交
864 865 866
  taosArraySort(pArray, (__compar_fn_t)mndCompareDnodeVnodes);
  for (int32_t i = 0; i < taosArrayGetSize(pArray); ++i) {
    SDnodeObj *pDnode = taosArrayGet(pArray, i);
867
    mInfo("dnode:%d, equivalent vnodes:%d", pDnode->id, pDnode->numOfVnodes);
S
Shengliang Guan 已提交
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
  }

  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;

    if (pDnode == NULL || pDnode->numOfVnodes > pDnode->numOfSupportVnodes) {
      terrno = TSDB_CODE_MND_NO_ENOUGH_DNODES;
      return -1;
    }

888 889 890 891 892 893 894 895 896 897
    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 已提交
898
    pVgid->dnodeId = pDnode->id;
S
Shengliang Guan 已提交
899
    pVgid->syncState = TAOS_SYNC_STATE_OFFLINE;
900 901
    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 已提交
902 903 904

    pVgroup->replica++;
    pDnode->numOfVnodes++;
905 906 907 908 909 910 911 912 913

    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 已提交
914 915 916 917 918 919 920 921
    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;
}

922 923
static int32_t mndRemoveVnodeFromVgroup(SMnode *pMnode, STrans *pTrans, SVgObj *pVgroup, SArray *pArray,
                                        SVnodeGid *pDelVgid) {
S
Shengliang Guan 已提交
924 925 926
  taosArraySort(pArray, (__compar_fn_t)mndCompareDnodeVnodes);
  for (int32_t i = 0; i < taosArrayGetSize(pArray); ++i) {
    SDnodeObj *pDnode = taosArrayGet(pArray, i);
927
    mInfo("dnode:%d, equivalent vnodes:%d", pDnode->id, pDnode->numOfVnodes);
S
Shengliang Guan 已提交
928 929 930 931 932 933 934 935 936
  }

  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) {
937 938 939 940
        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 已提交
941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962
        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);
  }
963 964 965 966 967 968 969 970 971

  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 已提交
972 973 974
  return 0;
}

S
Shengliang Guan 已提交
975
int32_t mndAddCreateVnodeAction(SMnode *pMnode, STrans *pTrans, SDbObj *pDb, SVgObj *pVgroup, SVnodeGid *pVgid) {
S
Shengliang Guan 已提交
976 977 978 979 980 981 982 983
  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 已提交
984
  void   *pReq = mndBuildCreateVnodeReq(pMnode, pDnode, pDb, pVgroup, &contLen);
S
Shengliang Guan 已提交
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
  if (pReq == NULL) return -1;

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

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

  return 0;
}

int32_t mndAddAlterVnodeConfirmAction(SMnode *pMnode, STrans *pTrans, SDbObj *pDb, SVgObj *pVgroup) {
  STransAction action = {0};
  action.epSet = mndGetVgroupEpset(pMnode, pVgroup);

  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;
1017 1018
  // incorrect redirect result will cause this erro
  action.retryCode = TSDB_CODE_VND_INVALID_VGROUP_ID;
S
Shengliang Guan 已提交
1019 1020 1021 1022 1023 1024 1025 1026 1027

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

  return 0;
}

S
Shengliang Guan 已提交
1028 1029 1030
int32_t mndAddAlterVnodeHashRangeAction(SMnode *pMnode, STrans *pTrans, SDbObj *pDb, SVgObj *pVgroup) { return 0; }

int32_t mndAddAlterVnodeConfigAction(SMnode *pMnode, STrans *pTrans, SDbObj *pDb, SVgObj *pVgroup) {
S
Shengliang Guan 已提交
1031 1032 1033 1034
  STransAction action = {0};
  action.epSet = mndGetVgroupEpset(pMnode, pVgroup);

  int32_t contLen = 0;
S
Shengliang Guan 已提交
1035
  void   *pReq = mndBuildAlterVnodeConfigReq(pMnode, pDb, pVgroup, &contLen);
S
Shengliang Guan 已提交
1036 1037 1038 1039
  if (pReq == NULL) return -1;

  action.pCont = pReq;
  action.contLen = contLen;
S
Shengliang Guan 已提交
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
  action.msgType = TDMT_VND_ALTER_CONFIG;

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

  return 0;
}

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 已提交
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107

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

  return 0;
}

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;
  action.acceptableCode = TSDB_CODE_NODE_NOT_DEPLOYED;

  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,
S
Shengliang Guan 已提交
1108
                                    SArray *pArray, bool force) {
S
Shengliang Guan 已提交
1109 1110
  SVgObj newVg = {0};
  memcpy(&newVg, pVgroup, sizeof(SVgObj));
S
Shengliang Guan 已提交
1111

S
Shengliang Guan 已提交
1112 1113 1114
  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 已提交
1115 1116
  }

S
Shengliang Guan 已提交
1117 1118
  if (!force) {
    mInfo("vgId:%d, will add 1 vnode", pVgroup->vgId);
1119
    if (mndAddVnodeToVgroup(pMnode, pTrans, &newVg, pArray) != 0) return -1;
S
Shengliang Guan 已提交
1120 1121 1122
    for (int32_t i = 0; i < newVg.replica - 1; ++i) {
      if (mndAddAlterVnodeReplicaAction(pMnode, pTrans, pDb, &newVg, newVg.vnodeGid[i].dnodeId) != 0) return -1;
    }
1123
    if (mndAddCreateVnodeAction(pMnode, pTrans, pDb, &newVg, &newVg.vnodeGid[newVg.replica - 1]) != 0) return -1;
S
Shengliang Guan 已提交
1124 1125 1126 1127 1128 1129 1130
    if (mndAddAlterVnodeConfirmAction(pMnode, pTrans, pDb, &newVg) != 0) return -1;

    mInfo("vgId:%d, will remove 1 vnode", pVgroup->vgId);
    newVg.replica--;
    SVnodeGid del = newVg.vnodeGid[vnIndex];
    newVg.vnodeGid[vnIndex] = newVg.vnodeGid[newVg.replica];
    memset(&newVg.vnodeGid[newVg.replica], 0, sizeof(SVnodeGid));
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
    {
      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 已提交
1141 1142 1143 1144 1145 1146 1147
    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;
  } else {
    mInfo("vgId:%d, will add 1 vnode and force remove 1 vnode", pVgroup->vgId);
1148
    if (mndAddVnodeToVgroup(pMnode, pTrans, &newVg, pArray) != 0) return -1;
S
Shengliang Guan 已提交
1149 1150 1151 1152
    newVg.replica--;
    SVnodeGid del = newVg.vnodeGid[vnIndex];
    newVg.vnodeGid[vnIndex] = newVg.vnodeGid[newVg.replica];
    memset(&newVg.vnodeGid[newVg.replica], 0, sizeof(SVnodeGid));
1153 1154 1155 1156 1157 1158 1159 1160 1161
    {
      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 已提交
1162 1163 1164 1165 1166 1167

    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;
      }
    }
1168
    if (mndAddCreateVnodeAction(pMnode, pTrans, pDb, &newVg, &newVg.vnodeGid[vnIndex]) != 0) return -1;
S
Shengliang Guan 已提交
1169 1170 1171
    if (mndAddAlterVnodeConfirmAction(pMnode, pTrans, pDb, &newVg) != 0) return -1;

    if (newVg.replica == 1) {
S
Shengliang Guan 已提交
1172
      mInfo("vgId:%d, all data is dropped since replica=1", pVgroup->vgId);
S
Shengliang Guan 已提交
1173
    }
S
Shengliang Guan 已提交
1174
  }
S
Shengliang Guan 已提交
1175

1176 1177
  {
    SSdbRaw *pRaw = mndVgroupActionEncode(&newVg);
1178 1179 1180 1181 1182
    if (pRaw == NULL) return -1;
    if (mndTransAppendCommitlog(pTrans, pRaw) != 0) {
      sdbFreeRaw(pRaw);
      return -1;
    }
S
Shengliang Guan 已提交
1183
    (void)sdbSetRawStatus(pRaw, SDB_STATUS_READY);
1184
  }
S
Shengliang Guan 已提交
1185

S
Shengliang Guan 已提交
1186 1187 1188
  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 已提交
1189 1190 1191 1192
  }
  return 0;
}

S
Shengliang Guan 已提交
1193
int32_t mndSetMoveVgroupsInfoToTrans(SMnode *pMnode, STrans *pTrans, int32_t delDnodeId, bool force) {
S
Shengliang Guan 已提交
1194
  int32_t code = 0;
S
Shengliang Guan 已提交
1195
  SArray *pArray = mndBuildDnodesArray(pMnode, delDnodeId);
S
Shengliang Guan 已提交
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
  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 已提交
1206
      if (pVgroup->vnodeGid[i].dnodeId == delDnodeId) {
S
Shengliang Guan 已提交
1207 1208 1209 1210 1211
        vnIndex = i;
        break;
      }
    }

S
Shengliang Guan 已提交
1212
    code = 0;
S
Shengliang Guan 已提交
1213
    if (vnIndex != -1) {
S
Shengliang Guan 已提交
1214
      mInfo("vgId:%d, vnode:%d will be removed from dnode:%d, force:%d", pVgroup->vgId, vnIndex, delDnodeId, force);
S
Shengliang Guan 已提交
1215
      SDbObj *pDb = mndAcquireDb(pMnode, pVgroup->dbName);
S
Shengliang Guan 已提交
1216
      code = mndSetMoveVgroupInfoToTrans(pMnode, pTrans, pDb, pVgroup, vnIndex, pArray, force);
S
Shengliang Guan 已提交
1217 1218 1219 1220
      mndReleaseDb(pMnode, pDb);
    }

    sdbRelease(pMnode->pSdb, pVgroup);
S
Shengliang Guan 已提交
1221 1222 1223 1224 1225

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

  taosArrayDestroy(pArray);
S
Shengliang Guan 已提交
1229
  return code;
S
Shengliang Guan 已提交
1230 1231 1232 1233
}

static int32_t mndAddIncVgroupReplicaToTrans(SMnode *pMnode, STrans *pTrans, SDbObj *pDb, SVgObj *pVgroup,
                                             int32_t newDnodeId) {
1234
  mInfo("vgId:%d, will add 1 vnode, replica:%d dnode:%d", pVgroup->vgId, pVgroup->replica, newDnodeId);
S
Shengliang Guan 已提交
1235 1236 1237 1238

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

1241 1242 1243 1244 1245 1246 1247 1248
  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 已提交
1249 1250
  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 已提交
1251
  }
1252
  if (mndAddCreateVnodeAction(pMnode, pTrans, pDb, pVgroup, pGid) != 0) return -1;
S
Shengliang Guan 已提交
1253
  if (mndAddAlterVnodeConfirmAction(pMnode, pTrans, pDb, pVgroup) != 0) return -1;
S
Shengliang Guan 已提交
1254 1255 1256 1257 1258 1259

  return 0;
}

static int32_t mndAddDecVgroupReplicaFromTrans(SMnode *pMnode, STrans *pTrans, SDbObj *pDb, SVgObj *pVgroup,
                                               int32_t delDnodeId) {
1260
  mInfo("vgId:%d, will remove 1 vnode, replica:%d dnode:%d", pVgroup->vgId, pVgroup->replica, delDnodeId);
S
Shengliang Guan 已提交
1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272

  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;

1273
  pVgroup->replica--;
S
Shengliang Guan 已提交
1274 1275 1276 1277
  memcpy(&delGid, pGid, sizeof(SVnodeGid));
  memcpy(pGid, &pVgroup->vnodeGid[pVgroup->replica], sizeof(SVnodeGid));
  memset(&pVgroup->vnodeGid[pVgroup->replica], 0, sizeof(SVnodeGid));

1278 1279 1280 1281 1282 1283 1284 1285
  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 已提交
1286 1287 1288
  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 已提交
1289
  }
S
Shengliang Guan 已提交
1290
  if (mndAddAlterVnodeConfirmAction(pMnode, pTrans, pDb, pVgroup) != 0) return -1;
S
Shengliang Guan 已提交
1291 1292 1293 1294 1295 1296 1297

  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) {
1298 1299
  int32_t code = -1;
  STrans *pTrans = NULL;
S
Shengliang Guan 已提交
1300

1301
  pTrans = mndTransCreate(pMnode, TRN_POLICY_RETRY, TRN_CONFLICT_GLOBAL, pReq, "red-vgroup");
S
Shengliang Guan 已提交
1302 1303
  if (pTrans == NULL) goto _OVER;
  mndTransSetSerial(pTrans);
1304
  mInfo("trans:%d, used to redistribute vgroup, vgId:%d", pTrans->id, pVgroup->vgId);
S
Shengliang Guan 已提交
1305 1306 1307 1308 1309

  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 已提交
1310
    mInfo("vgId:%d, vnode:%d dnode:%d role:%s", newVg.vgId, i, newVg.vnodeGid[i].dnodeId,
1311
          syncStr(newVg.vnodeGid[i].syncState));
S
Shengliang Guan 已提交
1312 1313
  }

S
Shengliang Guan 已提交
1314
  if (pNew1 != NULL && pOld1 != NULL) {
1315 1316 1317 1318 1319 1320 1321
    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;
    }
1322 1323 1324 1325 1326 1327

    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 已提交
1328
      goto _OVER;
1329 1330 1331 1332
    } else {
      pNew1->memUsed += vgMem;
    }

1333 1334 1335
    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 已提交
1336 1337

  if (pNew2 != NULL && pOld2 != NULL) {
1338 1339 1340 1341 1342 1343 1344
    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;
    }
1345 1346 1347 1348 1349
    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 已提交
1350
      goto _OVER;
1351 1352 1353
    } else {
      pNew2->memUsed += vgMem;
    }
S
Shengliang Guan 已提交
1354 1355
    if (mndAddIncVgroupReplicaToTrans(pMnode, pTrans, pDb, &newVg, pNew2->id) != 0) goto _OVER;
    if (mndAddDecVgroupReplicaFromTrans(pMnode, pTrans, pDb, &newVg, pOld2->id) != 0) goto _OVER;
1356
  }
S
Shengliang Guan 已提交
1357 1358

  if (pNew3 != NULL && pOld3 != NULL) {
1359 1360 1361 1362 1363 1364 1365
    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;
    }
1366 1367 1368 1369 1370
    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;
1371
      goto _OVER;
1372 1373 1374
    } else {
      pNew3->memUsed += vgMem;
    }
S
Shengliang Guan 已提交
1375 1376 1377 1378
    if (mndAddIncVgroupReplicaToTrans(pMnode, pTrans, pDb, &newVg, pNew3->id) != 0) goto _OVER;
    if (mndAddDecVgroupReplicaFromTrans(pMnode, pTrans, pDb, &newVg, pOld3->id) != 0) goto _OVER;
  }

1379
  {
1380 1381 1382 1383 1384 1385
    SSdbRaw *pRaw = mndVgroupActionEncode(&newVg);
    if (pRaw == NULL) return -1;
    if (mndTransAppendCommitlog(pTrans, pRaw) != 0) {
      sdbFreeRaw(pRaw);
      return -1;
    }
S
Shengliang Guan 已提交
1386
    (void)sdbSetRawStatus(pRaw, SDB_STATUS_READY);
1387
  }
S
Shengliang Guan 已提交
1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403

  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) {
1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
  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 已提交
1415 1416 1417 1418
  int32_t    newDnodeId[3] = {0};
  int32_t    oldDnodeId[3] = {0};
  int32_t    newIndex = -1;
  int32_t    oldIndex = -1;
1419

S
Shengliang Guan 已提交
1420 1421
  SRedistributeVgroupReq req = {0};
  if (tDeserializeSRedistributeVgroupReq(pReq->pCont, pReq->contLen, &req) != 0) {
S
Shengliang Guan 已提交
1422 1423 1424 1425
    terrno = TSDB_CODE_INVALID_MSG;
    goto _OVER;
  }

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

S
Shengliang Guan 已提交
1431
  pVgroup = mndAcquireVgroup(pMnode, req.vgId);
S
Shengliang Guan 已提交
1432 1433 1434 1435 1436 1437
  if (pVgroup == NULL) goto _OVER;

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

  if (pVgroup->replica == 1) {
S
Shengliang Guan 已提交
1438
    if (req.dnodeId1 <= 0 || req.dnodeId2 > 0 || req.dnodeId3 > 0) {
1439 1440 1441
      terrno = TSDB_CODE_MND_INVALID_REPLICA;
      goto _OVER;
    }
S
Shengliang Guan 已提交
1442 1443

    if (req.dnodeId1 == pVgroup->vnodeGid[0].dnodeId) {
1444 1445
      // terrno = TSDB_CODE_MND_VGROUP_UN_CHANGED;
      code = 0;
S
Shengliang Guan 已提交
1446 1447
      goto _OVER;
    }
S
Shengliang Guan 已提交
1448 1449 1450 1451 1452

    pNew1 = mndAcquireDnode(pMnode, req.dnodeId1);
    if (pNew1 == NULL) goto _OVER;
    if (!mndIsDnodeOnline(pNew1, curMs)) {
      terrno = TSDB_CODE_MND_HAS_OFFLINE_DNODE;
S
Shengliang Guan 已提交
1453 1454
      goto _OVER;
    }
S
Shengliang Guan 已提交
1455 1456 1457 1458

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

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

1465
  } else if (pVgroup->replica == 3) {
S
Shengliang Guan 已提交
1466
    if (req.dnodeId1 <= 0 || req.dnodeId2 <= 0 || req.dnodeId3 <= 0) {
1467 1468 1469
      terrno = TSDB_CODE_MND_INVALID_REPLICA;
      goto _OVER;
    }
S
Shengliang Guan 已提交
1470 1471

    if (req.dnodeId1 == req.dnodeId2 || req.dnodeId1 == req.dnodeId3 || req.dnodeId2 == req.dnodeId3) {
1472 1473 1474
      terrno = TSDB_CODE_MND_INVALID_REPLICA;
      goto _OVER;
    }
S
Shengliang Guan 已提交
1475 1476 1477 1478

    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 已提交
1479
      mInfo("vgId:%d, dnode:%d will be added, index:%d", pVgroup->vgId, newDnodeId[newIndex], newIndex);
S
Shengliang Guan 已提交
1480
    }
S
Shengliang Guan 已提交
1481 1482 1483 1484

    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 已提交
1485
      mInfo("vgId:%d, dnode:%d will be added, index:%d", pVgroup->vgId, newDnodeId[newIndex], newIndex);
S
Shengliang Guan 已提交
1486 1487 1488 1489 1490
    }

    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 已提交
1491
      mInfo("vgId:%d, dnode:%d will be added, index:%d", pVgroup->vgId, newDnodeId[newIndex], newIndex);
S
Shengliang Guan 已提交
1492 1493 1494 1495 1496
    }

    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 已提交
1497
      mInfo("vgId:%d, dnode:%d will be removed, index:%d", pVgroup->vgId, oldDnodeId[oldIndex], oldIndex);
S
Shengliang Guan 已提交
1498 1499 1500 1501 1502
    }

    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 已提交
1503
      mInfo("vgId:%d, dnode:%d will be removed, index:%d", pVgroup->vgId, oldDnodeId[oldIndex], oldIndex);
S
Shengliang Guan 已提交
1504 1505 1506 1507 1508
    }

    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 已提交
1509
      mInfo("vgId:%d, dnode:%d will be removed, index:%d", pVgroup->vgId, oldDnodeId[oldIndex], oldIndex);
S
Shengliang Guan 已提交
1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566
    }

    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) {
1567 1568
      // terrno = TSDB_CODE_MND_VGROUP_UN_CHANGED;
      code = 0;
1569 1570
      goto _OVER;
    }
S
Shengliang Guan 已提交
1571

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

1574 1575 1576
  } else {
    terrno = TSDB_CODE_MND_INVALID_REPLICA;
    goto _OVER;
S
Shengliang Guan 已提交
1577 1578 1579 1580 1581 1582
  }

  if (code == 0) code = TSDB_CODE_ACTION_IN_PROGRESS;

_OVER:
  if (code != 0 && code != TSDB_CODE_ACTION_IN_PROGRESS) {
S
Shengliang Guan 已提交
1583 1584
    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 已提交
1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
  }

  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;
}

1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623
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 已提交
1624 1625
      mInfo("db:%s, vgId:%d, memory in dnode:%d, avail:%" PRId64 " used:%" PRId64, pNewVgroup->dbName, pNewVgroup->vgId,
            pDnode->id, pDnode->memAvail, pDnode->memUsed);
1626 1627
    } else {
    }
S
Shengliang Guan 已提交
1628
  }
1629 1630
  return 0;
}
S
Shengliang Guan 已提交
1631

1632 1633
int32_t mndBuildAlterVgroupAction(SMnode *pMnode, STrans *pTrans, SDbObj *pOldDb, SDbObj *pNewDb, SVgObj *pVgroup,
                                  SArray *pArray) {
S
Shengliang Guan 已提交
1634 1635
  SVgObj newVgroup = {0};
  memcpy(&newVgroup, pVgroup, sizeof(SVgObj));
1636 1637

  if (pVgroup->replica <= 0 || pVgroup->replica == pNewDb->cfg.replications) {
S
Shengliang Guan 已提交
1638
    if (mndAddAlterVnodeConfigAction(pMnode, pTrans, pNewDb, pVgroup) != 0) return -1;
1639 1640 1641 1642
    if (mndCheckDnodeMemory(pMnode, pOldDb, pNewDb, &newVgroup, pVgroup, pArray) != 0) return -1;
    return 0;
  }

S
Shengliang Guan 已提交
1643 1644
  mndTransSetSerial(pTrans);

S
Shengliang Guan 已提交
1645 1646
  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 已提交
1647 1648
          pVgroup->vnodeGid[0].dnodeId);

1649
    if (mndAddVnodeToVgroup(pMnode, pTrans, &newVgroup, pArray) != 0) return -1;
S
Shengliang Guan 已提交
1650 1651
    if (mndAddAlterVnodeReplicaAction(pMnode, pTrans, pNewDb, &newVgroup, newVgroup.vnodeGid[0].dnodeId) != 0)
      return -1;
1652
    if (mndAddCreateVnodeAction(pMnode, pTrans, pNewDb, &newVgroup, &newVgroup.vnodeGid[1]) != 0) return -1;
1653
    if (mndAddAlterVnodeConfirmAction(pMnode, pTrans, pNewDb, &newVgroup) != 0) return -1;
1654

1655
    if (mndAddVnodeToVgroup(pMnode, pTrans, &newVgroup, pArray) != 0) return -1;
1656 1657 1658 1659
    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 已提交
1660 1661
    if (mndAddCreateVnodeAction(pMnode, pTrans, pNewDb, &newVgroup, &newVgroup.vnodeGid[2]) != 0) return -1;
    if (mndAddAlterVnodeConfirmAction(pMnode, pTrans, pNewDb, &newVgroup) != 0) return -1;
S
Shengliang Guan 已提交
1662
  } else if (newVgroup.replica == 3 && pNewDb->cfg.replications == 1) {
S
Shengliang Guan 已提交
1663 1664
    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 已提交
1665

S
Shengliang Guan 已提交
1666
    SVnodeGid del1 = {0};
S
Shengliang Guan 已提交
1667
    SVnodeGid del2 = {0};
1668
    if (mndRemoveVnodeFromVgroup(pMnode, pTrans, &newVgroup, pArray, &del1) != 0) return -1;
S
Shengliang Guan 已提交
1669
    if (mndAddDropVnodeAction(pMnode, pTrans, pNewDb, &newVgroup, &del1, true) != 0) return -1;
1670 1671 1672 1673
    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 已提交
1674
    if (mndAddAlterVnodeConfirmAction(pMnode, pTrans, pNewDb, &newVgroup) != 0) return -1;
1675

1676
    if (mndRemoveVnodeFromVgroup(pMnode, pTrans, &newVgroup, pArray, &del2) != 0) return -1;
1677
    if (mndAddDropVnodeAction(pMnode, pTrans, pNewDb, &newVgroup, &del2, true) != 0) return -1;
S
Shengliang Guan 已提交
1678 1679
    if (mndAddAlterVnodeReplicaAction(pMnode, pTrans, pNewDb, &newVgroup, newVgroup.vnodeGid[0].dnodeId) != 0)
      return -1;
1680
    if (mndAddAlterVnodeConfirmAction(pMnode, pTrans, pNewDb, &newVgroup) != 0) return -1;
S
Shengliang Guan 已提交
1681
  } else {
S
Shengliang Guan 已提交
1682
    return -1;
S
Shengliang Guan 已提交
1683
  }
S
Shengliang Guan 已提交
1684

S
Shengliang Guan 已提交
1685 1686 1687 1688 1689 1690
  {
    SSdbRaw *pVgRaw = mndVgroupActionEncode(&newVgroup);
    if (pVgRaw == NULL) return -1;
    if (mndTransAppendCommitlog(pTrans, pVgRaw) != 0) {
      sdbFreeRaw(pVgRaw);
      return -1;
S
Shengliang Guan 已提交
1691
    }
S
Shengliang Guan 已提交
1692
    (void)sdbSetRawStatus(pVgRaw, SDB_STATUS_READY);
S
Shengliang Guan 已提交
1693 1694 1695 1696 1697 1698 1699 1700 1701 1702
  }

  return 0;
}

static int32_t mndAddAdjustVnodeHashRangeAction(SMnode *pMnode, STrans *pTrans, SDbObj *pDb, SVgObj *pVgroup) {
  return 0;
}

static int32_t mndSplitVgroup(SMnode *pMnode, SRpcMsg *pReq, SDbObj *pDb, SVgObj *pVgroup) {
1703 1704 1705
  int32_t code = -1;
  STrans *pTrans = NULL;
  SArray *pArray = mndBuildDnodesArray(pMnode, 0);
S
Shengliang Guan 已提交
1706

1707
  pTrans = mndTransCreate(pMnode, TRN_POLICY_RETRY, TRN_CONFLICT_GLOBAL, pReq, "split-vgroup");
S
Shengliang Guan 已提交
1708 1709
  if (pTrans == NULL) goto _OVER;
  mndTransSetSerial(pTrans);
1710
  mInfo("trans:%d, used to split vgroup, vgId:%d", pTrans->id, pVgroup->vgId);
S
Shengliang Guan 已提交
1711 1712 1713 1714 1715 1716 1717 1718 1719 1720

  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) {
1721
    if (mndAddVnodeToVgroup(pMnode, pTrans, &newVg1, pArray) != 0) goto _OVER;
S
Shengliang Guan 已提交
1722
    if (mndAddAlterVnodeReplicaAction(pMnode, pTrans, pDb, &newVg1, newVg1.vnodeGid[0].dnodeId) != 0) goto _OVER;
1723
    if (mndAddCreateVnodeAction(pMnode, pTrans, pDb, &newVg1, &newVg1.vnodeGid[1]) != 0) goto _OVER;
S
Shengliang Guan 已提交
1724 1725 1726
    if (mndAddAlterVnodeConfirmAction(pMnode, pTrans, pDb, &newVg1) != 0) goto _OVER;
  } else if (newVg1.replica == 3) {
    SVnodeGid del1 = {0};
1727
    if (mndRemoveVnodeFromVgroup(pMnode, pTrans, &newVg1, pArray, &del1) != 0) goto _OVER;
1728
    if (mndAddDropVnodeAction(pMnode, pTrans, pDb, &newVg1, &del1, true) != 0) goto _OVER;
S
Shengliang Guan 已提交
1729 1730
    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 已提交
1731 1732 1733 1734 1735
    if (mndAddAlterVnodeConfirmAction(pMnode, pTrans, pDb, &newVg1) != 0) goto _OVER;
  } else {
    goto _OVER;
  }

S
Shengliang Guan 已提交
1736 1737 1738 1739 1740 1741
  mInfo("vgId:%d, vgroup info after adjust replica, replica:%d hashBegin:%u hashEnd:%u vnode:0 dnode:%d", newVg1.vgId,
        newVg1.replica, newVg1.hashBegin, newVg1.hashEnd, newVg1.vnodeGid[0].dnodeId);
  for (int32_t i = 0; i < newVg1.replica; ++i) {
    mInfo("vgId:%d, vnode:%d dnode:%d", newVg1.vgId, i, newVg1.vnodeGid[i].dnodeId);
  }

S
Shengliang Guan 已提交
1742
  SVgObj newVg2 = {0};
S
Shengliang Guan 已提交
1743
  memcpy(&newVg2, &newVg1, sizeof(SVgObj));
S
Shengliang Guan 已提交
1744
  newVg1.replica = 1;
S
Shengliang Guan 已提交
1745
  newVg1.hashEnd = newVg1.hashBegin / 2 + newVg1.hashEnd / 2;
S
Shengliang Guan 已提交
1746 1747 1748 1749 1750
  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 已提交
1751 1752 1753 1754 1755 1756
  memset(&newVg2.vnodeGid[1], 0, sizeof(SVnodeGid));

  mInfo("vgId:%d, vgroup info after adjust hash, replica:%d hashBegin:%u hashEnd:%u vnode:0 dnode:%d", newVg1.vgId,
        newVg1.replica, newVg1.hashBegin, newVg1.hashEnd, newVg1.vnodeGid[0].dnodeId);
  mInfo("vgId:%d, vgroup info after adjust hash, replica:%d hashBegin:%u hashEnd:%u vnode:0 dnode:%d", newVg2.vgId,
        newVg2.replica, newVg2.hashBegin, newVg2.hashEnd, newVg2.vnodeGid[0].dnodeId);
S
Shengliang Guan 已提交
1757

S
Shengliang Guan 已提交
1758 1759
  if (mndAddAlterVnodeHashRangeAction(pMnode, pTrans, pDb, &newVg1) != 0) goto _OVER;
  if (mndAddAlterVnodeHashRangeAction(pMnode, pTrans, pDb, &newVg2) != 0) goto _OVER;
S
Shengliang Guan 已提交
1760

S
Shengliang Guan 已提交
1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771
#if 0
  // adjust vgroup replica
  if (pDb->cfg.replications != newVg1.replica) {
    if (mndBuildAlterVgroupAction(pMnode, pTrans, pDb, pDb, &newVg1, pArray) != 0) goto _OVER;
  }
  if (pDb->cfg.replications != newVg2.replica) {
    if (mndBuildAlterVgroupAction(pMnode, pTrans, pDb, pDb, &newVg2, pArray) != 0) goto _OVER;
  }
#endif

  {
1772 1773 1774 1775 1776 1777
    SSdbRaw *pRaw = mndVgroupActionEncode(&newVg1);
    if (pRaw == NULL) return -1;
    if (mndTransAppendCommitlog(pTrans, pRaw) != 0) {
      sdbFreeRaw(pRaw);
      return -1;
    }
S
Shengliang Guan 已提交
1778 1779 1780 1781
    (void)sdbSetRawStatus(pRaw, SDB_STATUS_READY);
  }

  {
1782 1783 1784 1785 1786 1787
    SSdbRaw *pRaw = mndVgroupActionEncode(&newVg2);
    if (pRaw == NULL) return -1;
    if (mndTransAppendCommitlog(pTrans, pRaw) != 0) {
      sdbFreeRaw(pRaw);
      return -1;
    }
S
Shengliang Guan 已提交
1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803
    (void)sdbSetRawStatus(pRaw, SDB_STATUS_READY);
  }

  mInfo("vgId:%d, vgroup info after adjust hash, replica:%d hashBegin:%u hashEnd:%u vnode:0 dnode:%d", newVg1.vgId,
        newVg1.replica, newVg1.hashBegin, newVg1.hashEnd, newVg1.vnodeGid[0].dnodeId);
  for (int32_t i = 0; i < newVg1.replica; ++i) {
    mInfo("vgId:%d, vnode:%d dnode:%d", newVg1.vgId, i, newVg1.vnodeGid[i].dnodeId);
  }
  mInfo("vgId:%d, vgroup info after adjust hash, replica:%d hashBegin:%u hashEnd:%u vnode:0 dnode:%d", newVg2.vgId,
        newVg2.replica, newVg2.hashBegin, newVg2.hashEnd, newVg2.vnodeGid[0].dnodeId);
  for (int32_t i = 0; i < newVg1.replica; ++i) {
    mInfo("vgId:%d, vnode:%d dnode:%d", newVg2.vgId, i, newVg2.vnodeGid[i].dnodeId);
  }

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

_OVER:
S
Shengliang Guan 已提交
1806
  taosArrayDestroy(pArray);
S
Shengliang Guan 已提交
1807 1808 1809 1810 1811
  mndTransDrop(pTrans);
  return code;
}

static int32_t mndProcessSplitVgroupMsg(SRpcMsg *pReq) {
1812 1813 1814 1815 1816
  SMnode *pMnode = pReq->info.node;
  int32_t code = -1;
  int32_t vgId = 2;
  SVgObj *pVgroup = NULL;
  SDbObj *pDb = NULL;
S
Shengliang Guan 已提交
1817

1818
  mInfo("vgId:%d, start to split", vgId);
1819
  if (mndCheckOperPrivilege(pMnode, pReq->info.conn.user, MND_OPER_SPLIT_VGROUP) != 0) {
S
Shengliang Guan 已提交
1820 1821
    goto _OVER;
  }
S
Shengliang Guan 已提交
1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836

  pVgroup = mndAcquireVgroup(pMnode, vgId);
  if (pVgroup == NULL) goto _OVER;

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

  code = mndSplitVgroup(pMnode, pReq, pDb, pVgroup);
  if (code == 0) code = TSDB_CODE_ACTION_IN_PROGRESS;

_OVER:
  mndReleaseVgroup(pMnode, pVgroup);
  mndReleaseDb(pMnode, pDb);
  return code;
}
S
Shengliang Guan 已提交
1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849

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;

1850 1851
  {
    SSdbRaw *pRaw = mndVgroupActionEncode(&newVg);
1852 1853
    if (pRaw == NULL) return -1;
    if (mndTransAppendCommitlog(pTrans, pRaw) != 0) {
1854 1855 1856
      sdbFreeRaw(pRaw);
      return -1;
    }
S
Shengliang Guan 已提交
1857
    (void)sdbSetRawStatus(pRaw, SDB_STATUS_READY);
S
Shengliang Guan 已提交
1858 1859 1860 1861 1862 1863 1864 1865 1866
  }

  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 已提交
1867 1868
static int32_t mndBalanceVgroupBetweenDnode(SMnode *pMnode, STrans *pTrans, SDnodeObj *pSrc, SDnodeObj *pDst,
                                            SHashObj *pBalancedVgroups) {
S
Shengliang Guan 已提交
1869 1870
  void   *pIter = NULL;
  int32_t code = -1;
S
Shengliang Guan 已提交
1871
  SSdb   *pSdb = pMnode->pSdb;
S
Shengliang Guan 已提交
1872 1873 1874

  while (1) {
    SVgObj *pVgroup = NULL;
S
Shengliang Guan 已提交
1875
    pIter = sdbFetch(pSdb, SDB_VGROUP, pIter, (void **)&pVgroup);
S
Shengliang Guan 已提交
1876
    if (pIter == NULL) break;
S
Shengliang Guan 已提交
1877 1878 1879 1880
    if (taosHashGet(pBalancedVgroups, &pVgroup->vgId, sizeof(int32_t)) != NULL) {
      sdbRelease(pSdb, pVgroup);
      continue;
    }
S
Shengliang Guan 已提交
1881 1882 1883 1884 1885 1886 1887 1888 1889 1890

    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 已提交
1891 1892
      sdbRelease(pSdb, pVgroup);
      continue;
S
Shengliang Guan 已提交
1893 1894 1895 1896
    }

    SDbObj *pDb = mndAcquireDb(pMnode, pVgroup->dbName);
    code = mndSetBalanceVgroupInfoToTrans(pMnode, pTrans, pDb, pVgroup, pSrc, pDst);
S
Shengliang Guan 已提交
1897 1898 1899
    if (code == 0) {
      code = taosHashPut(pBalancedVgroups, &pVgroup->vgId, sizeof(int32_t), &pVgroup->vgId, sizeof(int32_t));
    }
S
Shengliang Guan 已提交
1900
    mndReleaseDb(pMnode, pDb);
S
Shengliang Guan 已提交
1901 1902
    sdbRelease(pSdb, pVgroup);
    sdbCancelFetch(pSdb, pIter);
S
Shengliang Guan 已提交
1903 1904 1905 1906 1907 1908 1909
    break;
  }

  return code;
}

static int32_t mndBalanceVgroup(SMnode *pMnode, SRpcMsg *pReq, SArray *pArray) {
1910 1911 1912
  int32_t   code = -1;
  int32_t   numOfVgroups = 0;
  STrans   *pTrans = NULL;
S
Shengliang Guan 已提交
1913 1914 1915 1916
  SHashObj *pBalancedVgroups = NULL;

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

1918
  pTrans = mndTransCreate(pMnode, TRN_POLICY_RETRY, TRN_CONFLICT_GLOBAL, pReq, "balance-vgroup");
S
Shengliang Guan 已提交
1919 1920
  if (pTrans == NULL) goto _OVER;
  mndTransSetSerial(pTrans);
1921
  mInfo("trans:%d, used to balance vgroup", pTrans->id);
S
Shengliang Guan 已提交
1922 1923 1924

  while (1) {
    taosArraySort(pArray, (__compar_fn_t)mndCompareDnodeVnodes);
S
Shengliang Guan 已提交
1925 1926
    for (int32_t i = 0; i < taosArrayGetSize(pArray); ++i) {
      SDnodeObj *pDnode = taosArrayGet(pArray, i);
1927
      mInfo("dnode:%d, equivalent vnodes:%d support:%d, score:%f", pDnode->id, pDnode->numOfVnodes,
1928
            pDnode->numOfSupportVnodes, (float)pDnode->numOfVnodes / pDnode->numOfSupportVnodes);
S
Shengliang Guan 已提交
1929 1930 1931 1932
    }

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

    float srcScore = (float)(pSrc->numOfVnodes - 1) / pSrc->numOfSupportVnodes;
    float dstScore = (float)(pDst->numOfVnodes + 1) / pDst->numOfSupportVnodes;
1936
    mInfo("trans:%d, after balance, src dnode:%d score:%f, dst dnode:%d score:%f", pTrans->id, pSrc->id, srcScore,
1937
          pDst->id, dstScore);
S
Shengliang Guan 已提交
1938 1939

    if (srcScore > dstScore - 0.000001) {
S
Shengliang Guan 已提交
1940
      code = mndBalanceVgroupBetweenDnode(pMnode, pTrans, pSrc, pDst, pBalancedVgroups);
S
Shengliang Guan 已提交
1941
      if (code == 0) {
S
Shengliang Guan 已提交
1942 1943
        pSrc->numOfVnodes--;
        pDst->numOfVnodes++;
S
Shengliang Guan 已提交
1944 1945 1946
        numOfVgroups++;
        continue;
      } else {
1947
        mInfo("trans:%d, no vgroup need to balance from dnode:%d to dnode:%d", pTrans->id, pSrc->id, pDst->id);
S
Shengliang Guan 已提交
1948
        break;
S
Shengliang Guan 已提交
1949 1950
      }
    } else {
1951
      mInfo("trans:%d, no vgroup need to balance any more", pTrans->id);
S
Shengliang Guan 已提交
1952 1953 1954 1955 1956
      break;
    }
  }

  if (numOfVgroups <= 0) {
1957
    mInfo("no need to balance vgroup");
S
Shengliang Guan 已提交
1958 1959
    code = 0;
  } else {
1960
    mInfo("start to balance vgroup, numOfVgroups:%d", numOfVgroups);
S
Shengliang Guan 已提交
1961 1962 1963 1964 1965
    if (mndTransPrepare(pMnode, pTrans) != 0) goto _OVER;
    code = TSDB_CODE_ACTION_IN_PROGRESS;
  }

_OVER:
1966
  taosHashCleanup(pBalancedVgroups);
S
Shengliang Guan 已提交
1967 1968 1969 1970 1971
  mndTransDrop(pTrans);
  return code;
}

static int32_t mndProcessBalanceVgroupMsg(SRpcMsg *pReq) {
1972 1973 1974
  SMnode *pMnode = pReq->info.node;
  int32_t code = -1;
  SArray *pArray = NULL;
S
Shengliang Guan 已提交
1975
  void   *pIter = NULL;
1976
  int64_t curMs = taosGetTimestampMs();
S
Shengliang Guan 已提交
1977

S
Shengliang Guan 已提交
1978 1979 1980 1981 1982 1983 1984
  SBalanceVgroupReq req = {0};
  if (tDeserializeSBalanceVgroupReq(pReq->pCont, pReq->contLen, &req) != 0) {
    terrno = TSDB_CODE_INVALID_MSG;
    goto _OVER;
  }

  mInfo("start to balance vgroup");
1985
  if (mndCheckOperPrivilege(pMnode, pReq->info.conn.user, MND_OPER_BALANCE_VGROUP) != 0) {
S
Shengliang Guan 已提交
1986 1987
    goto _OVER;
  }
S
Shengliang Guan 已提交
1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006

  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) {
2007
    mInfo("no need to balance vgroup since dnode num less than 2");
S
Shengliang Guan 已提交
2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019
    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 已提交
2020 2021
}

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