clientHb.c 34.8 KB
Newer Older
L
Liu Jicong 已提交
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/>.
 */

D
dapan1121 已提交
16
#include "catalog.h"
L
fix  
Liu Jicong 已提交
17
#include "clientInt.h"
D
dapan1121 已提交
18
#include "clientLog.h"
L
Liu Jicong 已提交
19
#include "scheduler.h"
L
fix  
Liu Jicong 已提交
20
#include "trpc.h"
L
Liu Jicong 已提交
21

K
kailixu 已提交
22 23
typedef struct {
  union {
K
kailixu 已提交
24 25 26
    struct {
      int64_t clusterId;
      int32_t passKeyCnt;
27 28
      int32_t passVer;
      int32_t reqCnt;
K
kailixu 已提交
29
    };
K
kailixu 已提交
30 31 32
  };
} SHbParam;

L
Liu Jicong 已提交
33 34 35 36 37
static SClientHbMgr clientHbMgr = {0};

static int32_t hbCreateThread();
static void    hbStopThread();

L
Liu Jicong 已提交
38 39
static int32_t hbMqHbReqHandle(SClientHbKey *connKey, void *param, SClientHbReq *req) { return 0; }

L
Liu Jicong 已提交
40
static int32_t hbMqHbRspHandle(SAppHbMgr *pAppHbMgr, SClientHbRsp *pRsp) { return 0; }
L
Liu Jicong 已提交
41

D
dapan 已提交
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
static int32_t hbProcessUserAuthInfoRsp(void *value, int32_t valueLen, struct SCatalog *pCatalog) {
  int32_t code = 0;

  SUserAuthBatchRsp batchRsp = {0};
  if (tDeserializeSUserAuthBatchRsp(value, valueLen, &batchRsp) != 0) {
    terrno = TSDB_CODE_INVALID_MSG;
    return -1;
  }

  int32_t numOfBatchs = taosArrayGetSize(batchRsp.pArray);
  for (int32_t i = 0; i < numOfBatchs; ++i) {
    SGetUserAuthRsp *rsp = taosArrayGet(batchRsp.pArray, i);
    tscDebug("hb user auth rsp, user:%s, version:%d", rsp->user, rsp->version);

    catalogUpdateUserAuthInfo(pCatalog, rsp);
  }

D
dapan1121 已提交
59
  taosArrayDestroy(batchRsp.pArray);
D
dapan 已提交
60 61 62
  return TSDB_CODE_SUCCESS;
}

K
kailixu 已提交
63 64 65
static int32_t hbProcessUserPassInfoRsp(void *value, int32_t valueLen, SClientHbKey *connKey, SAppHbMgr *pAppHbMgr) {
  int32_t           code = 0;
  int32_t           numOfBatchs = 0;
K
kailixu 已提交
66 67
  SUserPassBatchRsp batchRsp = {0};
  if (tDeserializeSUserPassBatchRsp(value, valueLen, &batchRsp) != 0) {
68 69
    code = TSDB_CODE_INVALID_MSG;
    return code;
K
kailixu 已提交
70 71
  }

K
kailixu 已提交
72 73 74 75 76 77 78 79 80 81
  numOfBatchs = taosArrayGetSize(batchRsp.pArray);

  SClientHbReq *pReq = NULL;
  while ((pReq = taosHashIterate(pAppHbMgr->activeInfo, pReq))) {
    STscObj *pTscObj = (STscObj *)acquireTscObj(pReq->connKey.tscRid);
    if (!pTscObj) {
      continue;
    }
    SPassInfo *passInfo = &pTscObj->passInfo;
    if (!passInfo->fp) {
K
kailixu 已提交
82
      releaseTscObj(pReq->connKey.tscRid);
K
kailixu 已提交
83 84 85 86 87 88 89 90 91 92 93 94
      continue;
    }

    for (int32_t i = 0; i < numOfBatchs; ++i) {
      SGetUserPassRsp *rsp = taosArrayGet(batchRsp.pArray, i);
      if (0 == strncmp(rsp->user, pTscObj->user, TSDB_USER_LEN)) {
        int32_t oldVer = atomic_load_32(&passInfo->ver);
        if (oldVer < rsp->version) {
          atomic_store_32(&passInfo->ver, rsp->version);
          if (passInfo->fp) {
            (*passInfo->fp)(passInfo->param, &passInfo->ver, TAOS_NOTIFY_PASSVER);
          }
K
kailixu 已提交
95 96
          tscDebug("update passVer of user %s from %d to %d, tscRid:%" PRIi64, rsp->user, oldVer,
                   atomic_load_32(&passInfo->ver), pTscObj->id);
K
kailixu 已提交
97
        }
K
kailixu 已提交
98
        break;
K
kailixu 已提交
99 100
      }
    }
K
kailixu 已提交
101
    releaseTscObj(pReq->connKey.tscRid);
K
kailixu 已提交
102 103 104
  }

  taosArrayDestroy(batchRsp.pArray);
K
kailixu 已提交
105

106
  return code;
K
kailixu 已提交
107 108
}

D
dapan1121 已提交
109
static int32_t hbGenerateVgInfoFromRsp(SDBVgInfo **pInfo, SUseDbRsp *rsp) {
110
  int32_t    code = 0;
D
dapan1121 已提交
111 112 113 114 115
  SDBVgInfo *vgInfo = taosMemoryCalloc(1, sizeof(SDBVgInfo));
  if (NULL == vgInfo) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    return code;
  }
116

D
dapan1121 已提交
117 118 119 120 121 122 123 124 125 126 127 128
  vgInfo->vgVersion = rsp->vgVersion;
  vgInfo->stateTs = rsp->stateTs;
  vgInfo->hashMethod = rsp->hashMethod;
  vgInfo->hashPrefix = rsp->hashPrefix;
  vgInfo->hashSuffix = rsp->hashSuffix;
  vgInfo->vgHash = taosHashInit(rsp->vgNum, taosGetDefaultHashFunction(TSDB_DATA_TYPE_INT), true, HASH_ENTRY_LOCK);
  if (NULL == vgInfo->vgHash) {
    taosMemoryFree(vgInfo);
    tscError("hash init[%d] failed", rsp->vgNum);
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _return;
  }
129

D
dapan1121 已提交
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
  for (int32_t j = 0; j < rsp->vgNum; ++j) {
    SVgroupInfo *pInfo = taosArrayGet(rsp->pVgroupInfos, j);
    if (taosHashPut(vgInfo->vgHash, &pInfo->vgId, sizeof(int32_t), pInfo, sizeof(SVgroupInfo)) != 0) {
      tscError("hash push failed, errno:%d", errno);
      taosHashCleanup(vgInfo->vgHash);
      taosMemoryFree(vgInfo);
      code = TSDB_CODE_OUT_OF_MEMORY;
      goto _return;
    }
  }

_return:
  if (code) {
    taosHashCleanup(vgInfo->vgHash);
    taosMemoryFreeClear(vgInfo);
  }

  *pInfo = vgInfo;
  return code;
}

D
dapan1121 已提交
151 152 153
static int32_t hbProcessDBInfoRsp(void *value, int32_t valueLen, struct SCatalog *pCatalog) {
  int32_t code = 0;

S
Shengliang Guan 已提交
154 155 156 157 158
  SUseDbBatchRsp batchUseRsp = {0};
  if (tDeserializeSUseDbBatchRsp(value, valueLen, &batchUseRsp) != 0) {
    terrno = TSDB_CODE_INVALID_MSG;
    return -1;
  }
D
dapan1121 已提交
159

S
Shengliang Guan 已提交
160 161 162
  int32_t numOfBatchs = taosArrayGetSize(batchUseRsp.pArray);
  for (int32_t i = 0; i < numOfBatchs; ++i) {
    SUseDbRsp *rsp = taosArrayGet(batchUseRsp.pArray, i);
dengyihao's avatar
dengyihao 已提交
163 164
    tscDebug("hb db rsp, db:%s, vgVersion:%d, stateTs:%" PRId64 ", uid:%" PRIx64, rsp->db, rsp->vgVersion, rsp->stateTs,
             rsp->uid);
L
fix  
Liu Jicong 已提交
165

D
dapan1121 已提交
166
    if (rsp->vgVersion < 0) {
D
dapan1121 已提交
167
      code = catalogRemoveDB(pCatalog, rsp->db, rsp->uid);
D
dapan1121 已提交
168
    } else {
D
dapan1121 已提交
169 170 171
      SDBVgInfo *vgInfo = NULL;
      code = hbGenerateVgInfoFromRsp(&vgInfo, rsp);
      if (TSDB_CODE_SUCCESS != code) {
D
dapan1121 已提交
172
        goto _return;
D
dapan1121 已提交
173
      }
174

D
dapan1121 已提交
175
      catalogUpdateDBVgInfo(pCatalog, rsp->db, rsp->uid, vgInfo);
D
dapan1121 已提交
176

D
dapan1121 已提交
177 178 179
      if (IS_SYS_DBNAME(rsp->db)) {
        code = hbGenerateVgInfoFromRsp(&vgInfo, rsp);
        if (TSDB_CODE_SUCCESS != code) {
D
dapan1121 已提交
180
          goto _return;
D
dapan1121 已提交
181
        }
L
fix  
Liu Jicong 已提交
182

183 184
        catalogUpdateDBVgInfo(pCatalog, (rsp->db[0] == 'i') ? TSDB_PERFORMANCE_SCHEMA_DB : TSDB_INFORMATION_SCHEMA_DB,
                              rsp->uid, vgInfo);
D
dapan1121 已提交
185
      }
D
dapan1121 已提交
186 187 188
    }

    if (code) {
D
dapan1121 已提交
189
      goto _return;
D
dapan1121 已提交
190 191 192
    }
  }

D
dapan1121 已提交
193 194
_return:

S
Shengliang Guan 已提交
195
  tFreeSUseDbBatchRsp(&batchUseRsp);
D
dapan1121 已提交
196
  return code;
D
dapan1121 已提交
197 198
}

D
dapan 已提交
199 200 201
static int32_t hbProcessStbInfoRsp(void *value, int32_t valueLen, struct SCatalog *pCatalog) {
  int32_t code = 0;

D
dapan1121 已提交
202 203
  SSTbHbRsp hbRsp = {0};
  if (tDeserializeSSTbHbRsp(value, valueLen, &hbRsp) != 0) {
S
Shengliang Guan 已提交
204 205 206 207
    terrno = TSDB_CODE_INVALID_MSG;
    return -1;
  }

D
dapan1121 已提交
208 209 210
  int32_t numOfMeta = taosArrayGetSize(hbRsp.pMetaRsp);
  for (int32_t i = 0; i < numOfMeta; ++i) {
    STableMetaRsp *rsp = taosArrayGet(hbRsp.pMetaRsp, i);
S
Shengliang Guan 已提交
211

D
dapan 已提交
212 213
    if (rsp->numOfColumns < 0) {
      tscDebug("hb remove stb, db:%s, stb:%s", rsp->dbFName, rsp->stbName);
D
dapan1121 已提交
214
      catalogRemoveStbMeta(pCatalog, rsp->dbFName, rsp->dbId, rsp->stbName, rsp->suid);
D
dapan 已提交
215
    } else {
D
dapan1121 已提交
216
      tscDebug("hb update stb, db:%s, stb:%s", rsp->dbFName, rsp->stbName);
S
Shengliang Guan 已提交
217
      if (rsp->pSchemas[0].colId != PRIMARYKEY_TIMESTAMP_COL_ID) {
218
        tscError("invalid colId[%" PRIi16 "] for the first column in table meta rsp msg", rsp->pSchemas[0].colId);
D
dapan1121 已提交
219
        tFreeSSTbHbRsp(&hbRsp);
D
dapan1121 已提交
220
        return TSDB_CODE_TSC_INVALID_VALUE;
D
dapan 已提交
221 222
      }

D
dapan1121 已提交
223
      catalogUpdateTableMeta(pCatalog, rsp);
D
dapan 已提交
224 225 226
    }
  }

D
dapan1121 已提交
227 228 229 230 231 232 233 234 235 236
  int32_t numOfIndex = taosArrayGetSize(hbRsp.pIndexRsp);
  for (int32_t i = 0; i < numOfIndex; ++i) {
    STableIndexRsp *rsp = taosArrayGet(hbRsp.pIndexRsp, i);

    catalogUpdateTableIndex(pCatalog, rsp);
  }

  taosArrayDestroy(hbRsp.pIndexRsp);
  hbRsp.pIndexRsp = NULL;

D
dapan1121 已提交
237
  tFreeSSTbHbRsp(&hbRsp);
D
dapan 已提交
238 239 240
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
241
static int32_t hbQueryHbRspHandle(SAppHbMgr *pAppHbMgr, SClientHbRsp *pRsp) {
D
dapan1121 已提交
242
  SClientHbReq *pReq = taosHashAcquire(pAppHbMgr->activeInfo, &pRsp->connKey, sizeof(SClientHbKey));
D
dapan1121 已提交
243 244
  if (NULL == pReq) {
    tscWarn("pReq to get activeInfo, may be dropped, refId:%" PRIx64 ", type:%d", pRsp->connKey.tscRid,
L
Liu Jicong 已提交
245
            pRsp->connKey.connType);
D
dapan1121 已提交
246 247 248
    return TSDB_CODE_SUCCESS;
  }

D
dapan1121 已提交
249 250 251 252
  if (pRsp->query) {
    STscObj *pTscObj = (STscObj *)acquireTscObj(pRsp->connKey.tscRid);
    if (NULL == pTscObj) {
      tscDebug("tscObj rid %" PRIx64 " not exist", pRsp->connKey.tscRid);
253
    } else {
D
dapan1121 已提交
254
      if (pRsp->query->totalDnodes > 1 && !isEpsetEqual(&pTscObj->pAppInfo->mgmtEp.epSet, &pRsp->query->epSet)) {
255 256 257 258 259 260 261
        SEpSet *pOrig = &pTscObj->pAppInfo->mgmtEp.epSet;
        SEp    *pOrigEp = &pOrig->eps[pOrig->inUse];
        SEp    *pNewEp = &pRsp->query->epSet.eps[pRsp->query->epSet.inUse];
        tscDebug("mnode epset updated from %d/%d=>%s:%d to %d/%d=>%s:%d in hb", pOrig->inUse, pOrig->numOfEps,
                 pOrigEp->fqdn, pOrigEp->port, pRsp->query->epSet.inUse, pRsp->query->epSet.numOfEps, pNewEp->fqdn,
                 pNewEp->port);

D
dapan1121 已提交
262 263
        updateEpSet_s(&pTscObj->pAppInfo->mgmtEp, &pRsp->query->epSet);
      }
264

D
dapan1121 已提交
265 266
      pTscObj->pAppInfo->totalDnodes = pRsp->query->totalDnodes;
      pTscObj->pAppInfo->onlineDnodes = pRsp->query->onlineDnodes;
D
dapan1121 已提交
267
      pTscObj->connId = pRsp->query->connId;
wmmhello's avatar
wmmhello 已提交
268
      tscTrace("conn %u hb rsp, dnodes %d/%d", pTscObj->connId, pTscObj->pAppInfo->onlineDnodes,
dengyihao's avatar
dengyihao 已提交
269
               pTscObj->pAppInfo->totalDnodes);
L
Liu Jicong 已提交
270

D
dapan1121 已提交
271
      if (pRsp->query->killRid) {
D
dapan1121 已提交
272
        tscDebug("request rid %" PRIx64 " need to be killed now", pRsp->query->killRid);
D
dapan1121 已提交
273 274 275 276 277 278 279 280
        SRequestObj *pRequest = acquireRequest(pRsp->query->killRid);
        if (NULL == pRequest) {
          tscDebug("request 0x%" PRIx64 " not exist to kill", pRsp->query->killRid);
        } else {
          taos_stop_query((TAOS_RES *)pRequest);
          releaseRequest(pRsp->query->killRid);
        }
      }
L
Liu Jicong 已提交
281

D
dapan1121 已提交
282
      if (pRsp->query->killConnection) {
283
        taos_close_internal(pTscObj);
D
dapan1121 已提交
284 285
      }

D
dapan1121 已提交
286 287 288 289
      if (pRsp->query->pQnodeList) {
        updateQnodeList(pTscObj->pAppInfo, pRsp->query->pQnodeList);
      }

D
dapan1121 已提交
290 291 292
      releaseTscObj(pRsp->connKey.tscRid);
    }
  }
L
Liu Jicong 已提交
293

D
dapan1121 已提交
294
  int32_t kvNum = pRsp->info ? taosArrayGetSize(pRsp->info) : 0;
D
dapan1121 已提交
295 296

  tscDebug("hb got %d rsp kv", kvNum);
L
fix  
Liu Jicong 已提交
297

D
dapan1121 已提交
298 299 300
  for (int32_t i = 0; i < kvNum; ++i) {
    SKv *kv = taosArrayGet(pRsp->info, i);
    switch (kv->key) {
D
dapan 已提交
301 302 303 304 305 306 307 308
      case HEARTBEAT_KEY_USER_AUTHINFO: {
        if (kv->valueLen <= 0 || NULL == kv->value) {
          tscError("invalid hb user auth info, len:%d, value:%p", kv->valueLen, kv->value);
          break;
        }

        struct SCatalog *pCatalog = NULL;

D
dapan1121 已提交
309
        int32_t code = catalogGetHandle(pReq->clusterId, &pCatalog);
D
dapan 已提交
310
        if (code != TSDB_CODE_SUCCESS) {
D
dapan1121 已提交
311
          tscWarn("catalogGetHandle failed, clusterId:%" PRIx64 ", error:%s", pReq->clusterId, tstrerror(code));
D
dapan 已提交
312 313 314 315 316 317
          break;
        }

        hbProcessUserAuthInfoRsp(kv->value, kv->valueLen, pCatalog);
        break;
      }
D
dapan1121 已提交
318 319 320 321 322 323 324
      case HEARTBEAT_KEY_DBINFO: {
        if (kv->valueLen <= 0 || NULL == kv->value) {
          tscError("invalid hb db info, len:%d, value:%p", kv->valueLen, kv->value);
          break;
        }

        struct SCatalog *pCatalog = NULL;
L
fix  
Liu Jicong 已提交
325

D
dapan1121 已提交
326
        int32_t code = catalogGetHandle(pReq->clusterId, &pCatalog);
D
dapan1121 已提交
327
        if (code != TSDB_CODE_SUCCESS) {
D
dapan1121 已提交
328
          tscWarn("catalogGetHandle failed, clusterId:%" PRIx64 ", error:%s", pReq->clusterId, tstrerror(code));
D
dapan1121 已提交
329 330 331 332
          break;
        }

        hbProcessDBInfoRsp(kv->value, kv->valueLen, pCatalog);
D
dapan1121 已提交
333
        break;
D
dapan1121 已提交
334
      }
L
fix  
Liu Jicong 已提交
335
      case HEARTBEAT_KEY_STBINFO: {
D
dapan 已提交
336 337 338 339
        if (kv->valueLen <= 0 || NULL == kv->value) {
          tscError("invalid hb stb info, len:%d, value:%p", kv->valueLen, kv->value);
          break;
        }
D
dapan1121 已提交
340

D
dapan 已提交
341
        struct SCatalog *pCatalog = NULL;
L
fix  
Liu Jicong 已提交
342

D
dapan1121 已提交
343
        int32_t code = catalogGetHandle(pReq->clusterId, &pCatalog);
D
dapan 已提交
344
        if (code != TSDB_CODE_SUCCESS) {
D
dapan1121 已提交
345
          tscWarn("catalogGetHandle failed, clusterId:%" PRIx64 ", error:%s", pReq->clusterId, tstrerror(code));
D
dapan 已提交
346 347 348 349
          break;
        }

        hbProcessStbInfoRsp(kv->value, kv->valueLen, pCatalog);
D
dapan1121 已提交
350
        break;
D
dapan 已提交
351
      }
K
kailixu 已提交
352 353 354 355 356 357
      case HEARTBEAT_KEY_USER_PASSINFO: {
        if (kv->valueLen <= 0 || NULL == kv->value) {
          tscError("invalid hb user pass info, len:%d, value:%p", kv->valueLen, kv->value);
          break;
        }

K
kailixu 已提交
358
        hbProcessUserPassInfoRsp(kv->value, kv->valueLen, &pRsp->connKey, pAppHbMgr);
K
kailixu 已提交
359 360
        break;
      }
D
dapan1121 已提交
361 362 363 364 365 366
      default:
        tscError("invalid hb key type:%d", kv->key);
        break;
    }
  }

D
dapan1121 已提交
367 368
  taosHashRelease(pAppHbMgr->activeInfo, pReq);

D
dapan1121 已提交
369 370 371
  return TSDB_CODE_SUCCESS;
}

D
dapan1121 已提交
372
static int32_t hbAsyncCallBack(void *param, SDataBuf *pMsg, int32_t code) {
D
dapan1121 已提交
373 374 375 376
  if (0 == atomic_load_8(&clientHbMgr.inited)) {
    goto _return;
  }

377
  static int32_t    emptyRspNum = 0;
378
  int32_t           idx = *(int32_t *)param;
D
dapan1121 已提交
379
  SClientHbBatchRsp pRsp = {0};
D
dapan1121 已提交
380 381
  if (TSDB_CODE_SUCCESS == code) {
    tDeserializeSClientHbBatchRsp(pMsg->pData, pMsg->len, &pRsp);
382

dengyihao's avatar
dengyihao 已提交
383 384 385 386 387 388
    int32_t now = taosGetTimestampSec();
    int32_t delta = abs(now - pRsp.svrTimestamp);
    if (delta > timestampDeltaLimit) {
      code = TSDB_CODE_TIME_UNSYNCED;
      tscError("time diff: %ds is too big", delta);
    }
dengyihao's avatar
dengyihao 已提交
389 390
  }

D
dapan1121 已提交
391
  int32_t rspNum = taosArrayGetSize(pRsp.rsps);
D
dapan1121 已提交
392

D
dapan1121 已提交
393
  taosThreadMutexLock(&clientHbMgr.lock);
D
dapan1121 已提交
394

D
dapan1121 已提交
395 396 397 398
  SAppHbMgr *pAppHbMgr = taosArrayGetP(clientHbMgr.appHbMgrs, idx);
  if (pAppHbMgr == NULL) {
    taosThreadMutexUnlock(&clientHbMgr.lock);
    tscError("appHbMgr not exist, idx:%d", idx);
D
dapan1121 已提交
399
    taosMemoryFree(pMsg->pData);
dengyihao's avatar
dengyihao 已提交
400
    taosMemoryFree(pMsg->pEpSet);
D
dapan1121 已提交
401
    tFreeClientHbBatchRsp(&pRsp);
D
dapan1121 已提交
402 403 404
    return -1;
  }

D
dapan1121 已提交
405 406
  SAppInstInfo *pInst = pAppHbMgr->pAppInstInfo;

D
dapan1121 已提交
407
  if (code != 0) {
D
dapan1121 已提交
408
    pInst->onlineDnodes = pInst->totalDnodes ? 0 : -1;
409
    tscDebug("hb rsp error %s, update server status %d/%d", tstrerror(code), pInst->onlineDnodes, pInst->totalDnodes);
D
dapan1121 已提交
410 411
  }

D
dapan1121 已提交
412
  if (rspNum) {
L
fix  
Liu Jicong 已提交
413 414
    tscDebug("hb got %d rsp, %d empty rsp received before", rspNum,
             atomic_val_compare_exchange_32(&emptyRspNum, emptyRspNum, 0));
D
dapan1121 已提交
415 416 417 418 419
  } else {
    atomic_add_fetch_32(&emptyRspNum, 1);
  }

  for (int32_t i = 0; i < rspNum; ++i) {
L
fix  
Liu Jicong 已提交
420
    SClientHbRsp *rsp = taosArrayGet(pRsp.rsps, i);
D
dapan1121 已提交
421
    code = (*clientHbMgr.rspHandle[rsp->connKey.connType])(pAppHbMgr, rsp);
D
dapan1121 已提交
422 423 424 425
    if (code) {
      break;
    }
  }
D
dapan1121 已提交
426

D
dapan1121 已提交
427
  taosThreadMutexUnlock(&clientHbMgr.lock);
D
dapan1121 已提交
428

D
dapan1121 已提交
429
  tFreeClientHbBatchRsp(&pRsp);
D
dapan1121 已提交
430 431

_return:
H
Haojun Liao 已提交
432
  taosMemoryFree(pMsg->pData);
dengyihao's avatar
dengyihao 已提交
433
  taosMemoryFree(pMsg->pEpSet);
D
dapan1121 已提交
434
  return code;
L
Liu Jicong 已提交
435 436
}

D
dapan1121 已提交
437
int32_t hbBuildQueryDesc(SQueryHbReqBasic *hbBasic, STscObj *pObj) {
L
Liu Jicong 已提交
438
  int64_t    now = taosGetTimestampUs();
D
dapan1121 已提交
439
  SQueryDesc desc = {0};
L
Liu Jicong 已提交
440
  int32_t    code = 0;
D
dapan1121 已提交
441

L
Liu Jicong 已提交
442
  void *pIter = taosHashIterate(pObj->pRequests, NULL);
D
dapan1121 已提交
443
  while (pIter != NULL) {
L
Liu Jicong 已提交
444
    int64_t     *rid = pIter;
D
dapan1121 已提交
445
    SRequestObj *pRequest = acquireRequest(*rid);
D
dapan1121 已提交
446 447 448 449 450
    if (NULL == pRequest) {
      pIter = taosHashIterate(pObj->pRequests, pIter);
      continue;
    }

451
    if (pRequest->killed || 0 == pRequest->body.queryJob) {
D
dapan1121 已提交
452
      releaseRequest(*rid);
D
dapan1121 已提交
453
      pIter = taosHashIterate(pObj->pRequests, pIter);
D
dapan1121 已提交
454 455 456 457
      continue;
    }

    tstrncpy(desc.sql, pRequest->sqlstr, sizeof(desc.sql));
458
    desc.stime = pRequest->metric.start / 1000;
L
Liu Jicong 已提交
459
    desc.queryId = pRequest->requestId;
D
dapan1121 已提交
460
    desc.useconds = now - pRequest->metric.start;
L
Liu Jicong 已提交
461
    desc.reqRid = pRequest->self;
462
    desc.stableQuery = pRequest->stableQuery;
D
dapan1121 已提交
463
    taosGetFqdn(desc.fqdn);
D
dapan1121 已提交
464
    desc.subPlanNum = pRequest->body.subplanNum;
D
dapan1121 已提交
465 466 467 468 469

    if (desc.subPlanNum) {
      desc.subDesc = taosArrayInit(desc.subPlanNum, sizeof(SQuerySubDesc));
      if (NULL == desc.subDesc) {
        releaseRequest(*rid);
S
Shengliang Guan 已提交
470
        return TSDB_CODE_OUT_OF_MEMORY;
D
dapan1121 已提交
471 472 473 474 475 476
      }

      code = schedulerGetTasksStatus(pRequest->body.queryJob, desc.subDesc);
      if (code) {
        taosArrayDestroy(desc.subDesc);
        desc.subDesc = NULL;
477
        desc.subPlanNum = 0;
D
dapan1121 已提交
478
      }
D
dapan1121 已提交
479
      desc.subPlanNum = taosArrayGetSize(desc.subDesc);
D
dapan1121 已提交
480 481
    } else {
      desc.subDesc = NULL;
D
dapan1121 已提交
482 483
    }

L
Liu Jicong 已提交
484
    releaseRequest(*rid);
D
dapan1121 已提交
485
    taosArrayPush(hbBasic->queryDesc, &desc);
L
Liu Jicong 已提交
486

D
dapan1121 已提交
487 488 489 490 491 492 493 494 495 496
    pIter = taosHashIterate(pObj->pRequests, pIter);
  }

  return TSDB_CODE_SUCCESS;
}

int32_t hbGetQueryBasicInfo(SClientHbKey *connKey, SClientHbReq *req) {
  STscObj *pTscObj = (STscObj *)acquireTscObj(connKey->tscRid);
  if (NULL == pTscObj) {
    tscWarn("tscObj rid %" PRIx64 " not exist", connKey->tscRid);
S
Shengliang Guan 已提交
497
    return TSDB_CODE_APP_ERROR;
D
dapan1121 已提交
498
  }
L
Liu Jicong 已提交
499

D
dapan1121 已提交
500 501 502 503
  SQueryHbReqBasic *hbBasic = (SQueryHbReqBasic *)taosMemoryCalloc(1, sizeof(SQueryHbReqBasic));
  if (NULL == hbBasic) {
    tscError("calloc %d failed", (int32_t)sizeof(SQueryHbReqBasic));
    releaseTscObj(connKey->tscRid);
S
Shengliang Guan 已提交
504
    return TSDB_CODE_OUT_OF_MEMORY;
D
dapan1121 已提交
505
  }
506

507 508 509 510 511 512 513 514 515
  hbBasic->connId = pTscObj->connId;

  int32_t numOfQueries = pTscObj->pRequests ? taosHashGetSize(pTscObj->pRequests) : 0;
  if (numOfQueries <= 0) {
    req->query = hbBasic;
    releaseTscObj(connKey->tscRid);
    tscDebug("no queries on connection");
    return TSDB_CODE_SUCCESS;
  }
D
dapan1121 已提交
516 517 518 519 520 521

  hbBasic->queryDesc = taosArrayInit(numOfQueries, sizeof(SQueryDesc));
  if (NULL == hbBasic->queryDesc) {
    tscWarn("taosArrayInit %d queryDesc failed", numOfQueries);
    releaseTscObj(connKey->tscRid);
    taosMemoryFree(hbBasic);
S
Shengliang Guan 已提交
522
    return TSDB_CODE_OUT_OF_MEMORY;
D
dapan1121 已提交
523
  }
L
Liu Jicong 已提交
524

D
dapan1121 已提交
525 526 527
  int32_t code = hbBuildQueryDesc(hbBasic, pTscObj);
  if (code) {
    releaseTscObj(connKey->tscRid);
D
dapan1121 已提交
528 529 530
    if (hbBasic->queryDesc) {
      taosArrayDestroyEx(hbBasic->queryDesc, tFreeClientHbQueryDesc);
    }
D
dapan1121 已提交
531 532 533 534 535 536 537 538 539 540
    taosMemoryFree(hbBasic);
    return code;
  }

  req->query = hbBasic;
  releaseTscObj(connKey->tscRid);

  return TSDB_CODE_SUCCESS;
}

541
static int32_t hbGetUserBasicInfo(SClientHbKey *connKey, SHbParam *param, SClientHbReq *req) {
K
kailixu 已提交
542 543 544 545 546 547
  STscObj *pTscObj = (STscObj *)acquireTscObj(connKey->tscRid);
  if (!pTscObj) {
    tscWarn("tscObj rid %" PRIx64 " not exist", connKey->tscRid);
    return TSDB_CODE_APP_ERROR;
  }

548 549
  int32_t code = 0;

K
kailixu 已提交
550
  if (param && (param->passVer != INT32_MIN) && (param->passVer <= pTscObj->passInfo.ver)) {
551 552 553 554
    tscDebug("hb got user basic info, no need since passVer %d <= %d", param->passVer, pTscObj->passInfo.ver);
    goto _return;
  }

K
kailixu 已提交
555 556 557 558 559 560 561 562 563 564 565 566 567 568
  SUserPassVersion *user = taosMemoryMalloc(sizeof(SUserPassVersion));
  if (!user) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _return;
  }
  strncpy(user->user, pTscObj->user, TSDB_USER_LEN);
  user->version = htonl(pTscObj->passInfo.ver);

  SKv kv = {
      .key = HEARTBEAT_KEY_USER_PASSINFO,
      .valueLen = sizeof(SUserPassVersion),
      .value = user,
  };

K
kailixu 已提交
569 570
  tscDebug("hb got user basic info, valueLen:%d, user:%s, passVer:%d, tscRid:%" PRIi64, kv.valueLen, user->user,
           pTscObj->passInfo.ver, connKey->tscRid);
K
kailixu 已提交
571 572 573 574 575 576 577 578 579 580

  if (!req->info) {
    req->info = taosHashInit(64, hbKeyHashFunc, 1, HASH_ENTRY_LOCK);
  }

  if (taosHashPut(req->info, &kv.key, sizeof(kv.key), &kv, sizeof(kv)) < 0) {
    code = terrno ? terrno : TSDB_CODE_APP_ERROR;
    goto _return;
  }

581
  // assign the passVer
K
kailixu 已提交
582 583 584
  if (param) {
    param->passVer = pTscObj->passInfo.ver;
  }
585

K
kailixu 已提交
586 587 588 589 590 591 592 593 594
_return:
  releaseTscObj(connKey->tscRid);
  if (code) {
    tscError("hb got user basic info failed since %s", terrstr(code));
  }

  return code;
}

D
dapan 已提交
595 596 597 598 599 600 601 602 603 604 605
int32_t hbGetExpiredUserInfo(SClientHbKey *connKey, struct SCatalog *pCatalog, SClientHbReq *req) {
  SUserAuthVersion *users = NULL;
  uint32_t          userNum = 0;
  int32_t           code = 0;

  code = catalogGetExpiredUsers(pCatalog, &users, &userNum);
  if (TSDB_CODE_SUCCESS != code) {
    return code;
  }

  if (userNum <= 0) {
D
dapan1121 已提交
606
    taosMemoryFree(users);
D
dapan 已提交
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
    return TSDB_CODE_SUCCESS;
  }

  for (int32_t i = 0; i < userNum; ++i) {
    SUserAuthVersion *user = &users[i];
    user->version = htonl(user->version);
  }

  SKv kv = {
      .key = HEARTBEAT_KEY_USER_AUTHINFO,
      .valueLen = sizeof(SUserAuthVersion) * userNum,
      .value = users,
  };

  tscDebug("hb got %d expired users, valueLen:%d", userNum, kv.valueLen);

D
dapan1121 已提交
623 624 625
  if (NULL == req->info) {
    req->info = taosHashInit(64, hbKeyHashFunc, 1, HASH_ENTRY_LOCK);
  }
626

D
dapan 已提交
627 628 629 630 631
  taosHashPut(req->info, &kv.key, sizeof(kv.key), &kv, sizeof(kv));

  return TSDB_CODE_SUCCESS;
}

D
dapan1121 已提交
632 633
int32_t hbGetExpiredDBInfo(SClientHbKey *connKey, struct SCatalog *pCatalog, SClientHbReq *req) {
  SDbVgVersion *dbs = NULL;
L
fix  
Liu Jicong 已提交
634 635
  uint32_t      dbNum = 0;
  int32_t       code = 0;
D
dapan1121 已提交
636 637 638 639 640 641

  code = catalogGetExpiredDBs(pCatalog, &dbs, &dbNum);
  if (TSDB_CODE_SUCCESS != code) {
    return code;
  }

D
dapan1121 已提交
642
  if (dbNum <= 0) {
D
dapan1121 已提交
643
    taosMemoryFree(dbs);
D
dapan1121 已提交
644 645 646
    return TSDB_CODE_SUCCESS;
  }

D
dapan1121 已提交
647 648
  for (int32_t i = 0; i < dbNum; ++i) {
    SDbVgVersion *db = &dbs[i];
649 650
    tscDebug("the %dth expired dbFName:%s, dbId:%" PRId64 ", vgVersion:%d, numOfTable:%d, startTs:%" PRId64, i,
             db->dbFName, db->dbId, db->vgVersion, db->numOfTable, db->stateTs);
D
dapan1121 已提交
651

D
dapan1121 已提交
652 653
    db->dbId = htobe64(db->dbId);
    db->vgVersion = htonl(db->vgVersion);
D
dapan 已提交
654
    db->numOfTable = htonl(db->numOfTable);
D
dapan1121 已提交
655
    db->stateTs = htobe64(db->stateTs);
D
dapan1121 已提交
656 657
  }

L
Liu Jicong 已提交
658 659 660 661 662
  SKv kv = {
      .key = HEARTBEAT_KEY_DBINFO,
      .valueLen = sizeof(SDbVgVersion) * dbNum,
      .value = dbs,
  };
D
dapan1121 已提交
663 664 665

  tscDebug("hb got %d expired db, valueLen:%d", dbNum, kv.valueLen);

D
dapan1121 已提交
666 667 668 669
  if (NULL == req->info) {
    req->info = taosHashInit(64, hbKeyHashFunc, 1, HASH_ENTRY_LOCK);
  }

D
dapan1121 已提交
670 671 672 673 674
  taosHashPut(req->info, &kv.key, sizeof(kv.key), &kv, sizeof(kv));

  return TSDB_CODE_SUCCESS;
}

D
dapan 已提交
675
int32_t hbGetExpiredStbInfo(SClientHbKey *connKey, struct SCatalog *pCatalog, SClientHbReq *req) {
D
dapan1121 已提交
676
  SSTableVersion *stbs = NULL;
677 678
  uint32_t        stbNum = 0;
  int32_t         code = 0;
D
dapan 已提交
679 680 681 682 683 684 685

  code = catalogGetExpiredSTables(pCatalog, &stbs, &stbNum);
  if (TSDB_CODE_SUCCESS != code) {
    return code;
  }

  if (stbNum <= 0) {
D
dapan1121 已提交
686
    taosMemoryFree(stbs);
D
dapan 已提交
687 688 689 690
    return TSDB_CODE_SUCCESS;
  }

  for (int32_t i = 0; i < stbNum; ++i) {
D
dapan1121 已提交
691
    SSTableVersion *stb = &stbs[i];
D
dapan 已提交
692 693
    stb->suid = htobe64(stb->suid);
    stb->sversion = htons(stb->sversion);
L
fix  
Liu Jicong 已提交
694
    stb->tversion = htons(stb->tversion);
D
dapan1121 已提交
695
    stb->smaVer = htonl(stb->smaVer);
D
dapan 已提交
696 697
  }

L
Liu Jicong 已提交
698 699
  SKv kv = {
      .key = HEARTBEAT_KEY_STBINFO,
D
dapan1121 已提交
700
      .valueLen = sizeof(SSTableVersion) * stbNum,
L
Liu Jicong 已提交
701 702
      .value = stbs,
  };
D
dapan 已提交
703 704 705

  tscDebug("hb got %d expired stb, valueLen:%d", stbNum, kv.valueLen);

D
dapan1121 已提交
706 707 708 709
  if (NULL == req->info) {
    req->info = taosHashInit(64, hbKeyHashFunc, 1, HASH_ENTRY_LOCK);
  }

D
dapan 已提交
710 711 712 713 714
  taosHashPut(req->info, &kv.key, sizeof(kv.key), &kv, sizeof(kv));

  return TSDB_CODE_SUCCESS;
}

D
dapan1121 已提交
715
int32_t hbGetAppInfo(int64_t clusterId, SClientHbReq *req) {
716
  SAppHbReq *pApp = taosHashGet(clientHbMgr.appSummary, &clusterId, sizeof(clusterId));
D
dapan1121 已提交
717 718 719 720 721 722
  if (NULL != pApp) {
    memcpy(&req->app, pApp, sizeof(*pApp));
  } else {
    memset(&req->app.summary, 0, sizeof(req->app.summary));
    req->app.pid = taosGetPId();
    req->app.appId = clientHbMgr.appId;
723
    taosGetAppName(req->app.name, NULL);
D
dapan1121 已提交
724 725 726 727 728
  }

  return TSDB_CODE_SUCCESS;
}

L
fix  
Liu Jicong 已提交
729
int32_t hbQueryHbReqHandle(SClientHbKey *connKey, void *param, SClientHbReq *req) {
730 731 732 733 734 735 736 737 738 739
  int32_t   code = 0;
  SHbParam *hbParam = (SHbParam *)param;
  SCatalog *pCatalog = NULL;

  if (hbParam->reqCnt == 0) {
    code = catalogGetHandle(hbParam->clusterId, &pCatalog);
    if (code != TSDB_CODE_SUCCESS) {
      tscWarn("catalogGetHandle failed, clusterId:%" PRIx64 ", error:%s", hbParam->clusterId, tstrerror(code));
      return code;
    }
D
dapan1121 已提交
740
  }
L
fix  
Liu Jicong 已提交
741

K
kailixu 已提交
742
  hbGetAppInfo(hbParam->clusterId, req);
D
dapan1121 已提交
743

D
dapan1121 已提交
744
  hbGetQueryBasicInfo(connKey, req);
L
Liu Jicong 已提交
745

K
kailixu 已提交
746
  if (hbParam->passKeyCnt > 0) {
747
    hbGetUserBasicInfo(connKey, hbParam, req);
K
kailixu 已提交
748
  }
K
kailixu 已提交
749

750 751 752 753 754
  if (hbParam->reqCnt == 0) {
    code = hbGetExpiredUserInfo(connKey, pCatalog, req);
    if (TSDB_CODE_SUCCESS != code) {
      return code;
    }
D
dapan 已提交
755

756 757 758 759
    code = hbGetExpiredDBInfo(connKey, pCatalog, req);
    if (TSDB_CODE_SUCCESS != code) {
      return code;
    }
D
dapan1121 已提交
760

761 762 763 764
    code = hbGetExpiredStbInfo(connKey, pCatalog, req);
    if (TSDB_CODE_SUCCESS != code) {
      return code;
    }
D
dapan 已提交
765 766
  }

767 768
  ++hbParam->reqCnt; // success to get catalog info

D
dapan1121 已提交
769 770 771
  return TSDB_CODE_SUCCESS;
}

772 773
static FORCE_INLINE void hbMgrInitHandle() {
  // init all handle
D
dapan1121 已提交
774 775
  clientHbMgr.reqHandle[CONN_TYPE__QUERY] = hbQueryHbReqHandle;
  clientHbMgr.reqHandle[CONN_TYPE__TMQ] = hbMqHbReqHandle;
L
Liu Jicong 已提交
776

D
dapan1121 已提交
777 778
  clientHbMgr.rspHandle[CONN_TYPE__QUERY] = hbQueryHbRspHandle;
  clientHbMgr.rspHandle[CONN_TYPE__TMQ] = hbMqHbRspHandle;
L
Liu Jicong 已提交
779 780
}

L
fix  
Liu Jicong 已提交
781
SClientHbBatchReq *hbGatherAllInfo(SAppHbMgr *pAppHbMgr) {
wafwerar's avatar
wafwerar 已提交
782
  SClientHbBatchReq *pBatchReq = taosMemoryCalloc(1, sizeof(SClientHbBatchReq));
L
Liu Jicong 已提交
783
  if (pBatchReq == NULL) {
S
Shengliang Guan 已提交
784
    terrno = TSDB_CODE_OUT_OF_MEMORY;
L
Liu Jicong 已提交
785 786
    return NULL;
  }
L
Liu Jicong 已提交
787
  int32_t connKeyCnt = atomic_load_32(&pAppHbMgr->connKeyCnt);
L
Liu Jicong 已提交
788
  pBatchReq->reqs = taosArrayInit(connKeyCnt, sizeof(SClientHbReq));
789 790 791 792
  if (!pBatchReq->reqs) {
    tFreeClientHbBatchReq(pBatchReq);
    return NULL;
  }
L
Liu Jicong 已提交
793

dengyihao's avatar
dengyihao 已提交
794
  int64_t rid = -1;
D
dapan1121 已提交
795 796
  int32_t code = 0;

dengyihao's avatar
dengyihao 已提交
797 798 799 800 801 802 803 804 805 806 807
  void *pIter = taosHashIterate(pAppHbMgr->activeInfo, NULL);

  SClientHbReq *pOneReq = pIter;
  SClientHbKey *connKey = pOneReq ? &pOneReq->connKey : NULL;
  if (connKey != NULL) rid = connKey->tscRid;

  STscObj *pTscObj = (STscObj *)acquireTscObj(rid);
  if (pTscObj == NULL) {
    tFreeClientHbBatchReq(pBatchReq);
    return NULL;
  }
D
dapan1121 已提交
808

809 810
  SHbParam param = {0};

dengyihao's avatar
dengyihao 已提交
811 812
  while (pIter != NULL) {
    pOneReq = taosArrayPush(pBatchReq->reqs, pOneReq);
813

K
kailixu 已提交
814 815
    switch (pOneReq->connKey.connType) {
      case CONN_TYPE__QUERY: {
816 817 818 819 820
        if (param.clusterId == 0) {
          // init
          param.clusterId = pOneReq->clusterId;
          param.passVer = INT32_MIN;
        }
K
kailixu 已提交
821 822 823 824 825 826
        param.passKeyCnt = atomic_load_32(&pAppHbMgr->passKeyCnt);
        break;
      }
      default:
        break;
    }
K
kailixu 已提交
827 828 829 830 831 832 833
    if (clientHbMgr.reqHandle[pOneReq->connKey.connType]) {
      code = (*clientHbMgr.reqHandle[pOneReq->connKey.connType])(&pOneReq->connKey, &param, pOneReq);
      if (code) {
        tscWarn("hbGatherAllInfo failed since %s, tscRid:%" PRIi64 ", connType:%" PRIi8, tstrerror(code),
                pOneReq->connKey.tscRid, pOneReq->connKey.connType);
      }
    }
K
kailixu 已提交
834

D
dapan1121 已提交
835 836
    if (code) {
      pIter = taosHashIterate(pAppHbMgr->activeInfo, pIter);
dengyihao's avatar
dengyihao 已提交
837
      pOneReq = pIter;
D
dapan1121 已提交
838
      continue;
D
dapan1121 已提交
839 840
    }

L
Liu Jicong 已提交
841
    pIter = taosHashIterate(pAppHbMgr->activeInfo, pIter);
dengyihao's avatar
dengyihao 已提交
842
    pOneReq = pIter;
L
Liu Jicong 已提交
843
  }
dengyihao's avatar
dengyihao 已提交
844
  releaseTscObj(rid);
L
Liu Jicong 已提交
845

L
Liu Jicong 已提交
846
  return pBatchReq;
L
Liu Jicong 已提交
847 848
}

849
void hbThreadFuncUnexpectedStopped(void) { atomic_store_8(&clientHbMgr.threadStop, 2); }
wafwerar's avatar
wafwerar 已提交
850

851
void hbMergeSummary(SAppClusterSummary *dst, SAppClusterSummary *src) {
D
dapan1121 已提交
852 853 854 855 856 857 858 859 860 861 862 863 864
  dst->numOfInsertsReq += src->numOfInsertsReq;
  dst->numOfInsertRows += src->numOfInsertRows;
  dst->insertElapsedTime += src->insertElapsedTime;
  dst->insertBytes += src->insertBytes;
  dst->fetchBytes += src->fetchBytes;
  dst->queryElapsedTime += src->queryElapsedTime;
  dst->numOfSlowQueries += src->numOfSlowQueries;
  dst->totalRequests += src->totalRequests;
  dst->currentRequests += src->currentRequests;
}

int32_t hbGatherAppInfo(void) {
  SAppHbReq req = {0};
865
  int       sz = taosArrayGetSize(clientHbMgr.appHbMgrs);
D
dapan1121 已提交
866 867 868 869 870
  if (sz > 0) {
    req.pid = taosGetPId();
    req.appId = clientHbMgr.appId;
    taosGetAppName(req.name, NULL);
  }
D
dapan1121 已提交
871 872

  taosHashClear(clientHbMgr.appSummary);
873

D
dapan1121 已提交
874 875
  for (int32_t i = 0; i < sz; ++i) {
    SAppHbMgr *pAppHbMgr = taosArrayGetP(clientHbMgr.appHbMgrs, i);
dengyihao's avatar
dengyihao 已提交
876 877
    if (pAppHbMgr == NULL) continue;

878 879
    uint64_t   clusterId = pAppHbMgr->pAppInstInfo->clusterId;
    SAppHbReq *pApp = taosHashGet(clientHbMgr.appSummary, &clusterId, sizeof(clusterId));
D
dapan1121 已提交
880 881
    if (NULL == pApp) {
      memcpy(&req.summary, &pAppHbMgr->pAppInstInfo->summary, sizeof(req.summary));
D
dapan1121 已提交
882
      req.startTime = pAppHbMgr->startTime;
D
dapan1121 已提交
883 884 885 886 887
      taosHashPut(clientHbMgr.appSummary, &clusterId, sizeof(clusterId), &req, sizeof(req));
    } else {
      if (pAppHbMgr->startTime < pApp->startTime) {
        pApp->startTime = pAppHbMgr->startTime;
      }
888

D
dapan1121 已提交
889 890 891 892 893 894 895
      hbMergeSummary(&pApp->summary, &pAppHbMgr->pAppInstInfo->summary);
    }
  }

  return TSDB_CODE_SUCCESS;
}

L
fix  
Liu Jicong 已提交
896
static void *hbThreadFunc(void *param) {
L
Liu Jicong 已提交
897
  setThreadName("hb");
wafwerar's avatar
wafwerar 已提交
898
#ifdef WINDOWS
wafwerar's avatar
wafwerar 已提交
899 900 901
  if (taosCheckCurrentInDll()) {
    atexit(hbThreadFuncUnexpectedStopped);
  }
wafwerar's avatar
wafwerar 已提交
902
#endif
L
Liu Jicong 已提交
903
  while (1) {
904
    if (1 == clientHbMgr.threadStop) {
L
Liu Jicong 已提交
905 906 907
      break;
    }

wafwerar's avatar
wafwerar 已提交
908
    taosThreadMutexLock(&clientHbMgr.lock);
909

L
Liu Jicong 已提交
910
    int sz = taosArrayGetSize(clientHbMgr.appHbMgrs);
D
dapan1121 已提交
911 912 913
    if (sz > 0) {
      hbGatherAppInfo();
    }
914

L
fix  
Liu Jicong 已提交
915 916
    for (int i = 0; i < sz; i++) {
      SAppHbMgr *pAppHbMgr = taosArrayGetP(clientHbMgr.appHbMgrs, i);
dengyihao's avatar
dengyihao 已提交
917 918 919
      if (pAppHbMgr == NULL) {
        continue;
      }
L
Liu Jicong 已提交
920

L
Liu Jicong 已提交
921 922 923 924
      int32_t connCnt = atomic_load_32(&pAppHbMgr->connKeyCnt);
      if (connCnt == 0) {
        continue;
      }
L
fix  
Liu Jicong 已提交
925
      SClientHbBatchReq *pReq = hbGatherAllInfo(pAppHbMgr);
dengyihao's avatar
dengyihao 已提交
926 927
      if (pReq == NULL || taosArrayGetP(clientHbMgr.appHbMgrs, i) == NULL) {
        tFreeClientHbBatchReq(pReq);
L
Liu Jicong 已提交
928 929
        continue;
      }
L
fix  
Liu Jicong 已提交
930
      int   tlen = tSerializeSClientHbBatchReq(NULL, 0, pReq);
wafwerar's avatar
wafwerar 已提交
931
      void *buf = taosMemoryMalloc(tlen);
L
Liu Jicong 已提交
932
      if (buf == NULL) {
S
Shengliang Guan 已提交
933
        terrno = TSDB_CODE_OUT_OF_MEMORY;
D
dapan1121 已提交
934
        tFreeClientHbBatchReq(pReq);
dengyihao's avatar
dengyihao 已提交
935
        // hbClearReqInfo(pAppHbMgr);
L
Liu Jicong 已提交
936 937
        break;
      }
L
fix  
Liu Jicong 已提交
938

S
Shengliang Guan 已提交
939
      tSerializeSClientHbBatchReq(buf, tlen, pReq);
wafwerar's avatar
wafwerar 已提交
940
      SMsgSendInfo *pInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
941

L
Liu Jicong 已提交
942
      if (pInfo == NULL) {
S
Shengliang Guan 已提交
943
        terrno = TSDB_CODE_OUT_OF_MEMORY;
D
dapan1121 已提交
944
        tFreeClientHbBatchReq(pReq);
dengyihao's avatar
dengyihao 已提交
945
        // hbClearReqInfo(pAppHbMgr);
wafwerar's avatar
wafwerar 已提交
946
        taosMemoryFree(buf);
L
Liu Jicong 已提交
947 948
        break;
      }
L
Liu Jicong 已提交
949
      pInfo->fp = hbAsyncCallBack;
L
Liu Jicong 已提交
950 951 952
      pInfo->msgInfo.pData = buf;
      pInfo->msgInfo.len = tlen;
      pInfo->msgType = TDMT_MND_HEARTBEAT;
D
dapan1121 已提交
953 954
      pInfo->param = taosMemoryMalloc(sizeof(int32_t));
      *(int32_t *)pInfo->param = i;
dengyihao's avatar
dengyihao 已提交
955
      pInfo->paramFreeFp = taosMemoryFree;
L
Liu Jicong 已提交
956 957
      pInfo->requestId = generateRequestId();
      pInfo->requestObjRefId = 0;
L
Liu Jicong 已提交
958 959

      SAppInstInfo *pAppInstInfo = pAppHbMgr->pAppInstInfo;
L
fix  
Liu Jicong 已提交
960 961
      int64_t       transporterId = 0;
      SEpSet        epSet = getEpSet_s(&pAppInstInfo->mgmtEp);
L
Liu Jicong 已提交
962
      asyncSendMsgToServer(pAppInstInfo->pTransporter, &epSet, &transporterId, pInfo);
D
dapan1121 已提交
963
      tFreeClientHbBatchReq(pReq);
dengyihao's avatar
dengyihao 已提交
964
      // hbClearReqInfo(pAppHbMgr);
L
Liu Jicong 已提交
965 966 967

      atomic_add_fetch_32(&pAppHbMgr->reportCnt, 1);
    }
968

wafwerar's avatar
wafwerar 已提交
969
    taosThreadMutexUnlock(&clientHbMgr.lock);
L
fix  
Liu Jicong 已提交
970

L
Liu Jicong 已提交
971
    taosMsleep(HEARTBEAT_INTERVAL);
L
Liu Jicong 已提交
972 973 974 975 976
  }
  return NULL;
}

static int32_t hbCreateThread() {
wafwerar's avatar
wafwerar 已提交
977 978 979
  TdThreadAttr thAttr;
  taosThreadAttrInit(&thAttr);
  taosThreadAttrSetDetachState(&thAttr, PTHREAD_CREATE_JOINABLE);
L
Liu Jicong 已提交
980

D
dapan1121 已提交
981 982 983
  if (taosThreadCreate(&clientHbMgr.thread, &thAttr, hbThreadFunc, NULL) != 0) {
    terrno = TAOS_SYSTEM_ERROR(errno);
    return -1;
L
Liu Jicong 已提交
984
  }
D
dapan1121 已提交
985
  taosThreadAttrDestroy(&thAttr);
L
Liu Jicong 已提交
986 987 988
  return 0;
}

L
Liu Jicong 已提交
989
static void hbStopThread() {
D
dapan1121 已提交
990 991 992
  if (0 == atomic_load_8(&clientHbMgr.inited)) {
    return;
  }
993
  if (atomic_val_compare_exchange_8(&clientHbMgr.threadStop, 0, 1)) {
D
dapan1121 已提交
994
    tscDebug("hb thread already stopped");
995 996
    return;
  }
L
fix  
Liu Jicong 已提交
997

998 999 1000 1001 1002 1003
  // thread quit mode kill or inner exit from self-thread
  if (clientHbMgr.quitByKill) {
    taosThreadKill(clientHbMgr.thread, 0);
  } else {
    taosThreadJoin(clientHbMgr.thread, NULL);
  }
D
dapan1121 已提交
1004

L
fix  
Liu Jicong 已提交
1005
  tscDebug("hb thread stopped");
L
Liu Jicong 已提交
1006 1007
}

L
fix  
Liu Jicong 已提交
1008
SAppHbMgr *appHbMgrInit(SAppInstInfo *pAppInstInfo, char *key) {
1009
  if (hbMgrInit() != 0) {
1010 1011 1012
    terrno = TSDB_CODE_TSC_INTERNAL_ERROR;
    return NULL;
  }
wafwerar's avatar
wafwerar 已提交
1013
  SAppHbMgr *pAppHbMgr = taosMemoryMalloc(sizeof(SAppHbMgr));
L
Liu Jicong 已提交
1014 1015 1016 1017 1018 1019
  if (pAppHbMgr == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }
  // init stat
  pAppHbMgr->startTime = taosGetTimestampMs();
L
Liu Jicong 已提交
1020
  pAppHbMgr->connKeyCnt = 0;
K
kailixu 已提交
1021
  pAppHbMgr->passKeyCnt = 0;
L
Liu Jicong 已提交
1022 1023
  pAppHbMgr->reportCnt = 0;
  pAppHbMgr->reportBytes = 0;
1024
  pAppHbMgr->key = taosStrdup(key);
L
Liu Jicong 已提交
1025

L
Liu Jicong 已提交
1026 1027
  // init app info
  pAppHbMgr->pAppInstInfo = pAppInstInfo;
L
Liu Jicong 已提交
1028 1029 1030

  // init hash info
  pAppHbMgr->activeInfo = taosHashInit(64, hbKeyHashFunc, 1, HASH_ENTRY_LOCK);
L
Liu Jicong 已提交
1031 1032 1033

  if (pAppHbMgr->activeInfo == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
wafwerar's avatar
wafwerar 已提交
1034
    taosMemoryFree(pAppHbMgr);
L
Liu Jicong 已提交
1035 1036
    return NULL;
  }
H
Haojun Liao 已提交
1037

1038
  // taosHashSetFreeFp(pAppHbMgr->activeInfo, tFreeClientHbReq);
L
Liu Jicong 已提交
1039

wafwerar's avatar
wafwerar 已提交
1040
  taosThreadMutexLock(&clientHbMgr.lock);
L
Liu Jicong 已提交
1041
  taosArrayPush(clientHbMgr.appHbMgrs, &pAppHbMgr);
D
dapan1121 已提交
1042
  pAppHbMgr->idx = taosArrayGetSize(clientHbMgr.appHbMgrs) - 1;
wafwerar's avatar
wafwerar 已提交
1043
  taosThreadMutexUnlock(&clientHbMgr.lock);
L
fix  
Liu Jicong 已提交
1044

L
Liu Jicong 已提交
1045 1046 1047
  return pAppHbMgr;
}

D
dapan1121 已提交
1048 1049 1050 1051 1052 1053 1054 1055 1056
void hbFreeAppHbMgr(SAppHbMgr *pTarget) {
  void *pIter = taosHashIterate(pTarget->activeInfo, NULL);
  while (pIter != NULL) {
    SClientHbReq *pOneReq = pIter;
    tFreeClientHbReq(pOneReq);
    pIter = taosHashIterate(pTarget->activeInfo, pIter);
  }
  taosHashCleanup(pTarget->activeInfo);
  pTarget->activeInfo = NULL;
1057

D
dapan1121 已提交
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
  taosMemoryFree(pTarget->key);
  taosMemoryFree(pTarget);
}

void hbRemoveAppHbMrg(SAppHbMgr **pAppHbMgr) {
  taosThreadMutexLock(&clientHbMgr.lock);
  int32_t mgrSize = taosArrayGetSize(clientHbMgr.appHbMgrs);
  for (int32_t i = 0; i < mgrSize; ++i) {
    SAppHbMgr *pItem = taosArrayGetP(clientHbMgr.appHbMgrs, i);
    if (pItem == *pAppHbMgr) {
      hbFreeAppHbMgr(*pAppHbMgr);
      *pAppHbMgr = NULL;
dengyihao's avatar
dengyihao 已提交
1070
      taosArraySet(clientHbMgr.appHbMgrs, i, pAppHbMgr);
D
dapan1121 已提交
1071 1072 1073 1074 1075 1076
      break;
    }
  }
  taosThreadMutexUnlock(&clientHbMgr.lock);
}

D
dapan1121 已提交
1077
void appHbMgrCleanup(void) {
L
Liu Jicong 已提交
1078 1079
  int sz = taosArrayGetSize(clientHbMgr.appHbMgrs);
  for (int i = 0; i < sz; i++) {
L
fix  
Liu Jicong 已提交
1080
    SAppHbMgr *pTarget = taosArrayGetP(clientHbMgr.appHbMgrs, i);
dengyihao's avatar
dengyihao 已提交
1081
    if (pTarget == NULL) continue;
D
dapan1121 已提交
1082
    hbFreeAppHbMgr(pTarget);
L
Liu Jicong 已提交
1083 1084 1085 1086
  }
}

int hbMgrInit() {
L
Liu Jicong 已提交
1087 1088 1089 1090
  // init once
  int8_t old = atomic_val_compare_exchange_8(&clientHbMgr.inited, 0, 1);
  if (old == 1) return 0;

D
dapan1121 已提交
1091 1092
  clientHbMgr.appId = tGenIdPI64();
  tscDebug("app %" PRIx64 " initialized", clientHbMgr.appId);
1093

D
dapan1121 已提交
1094
  clientHbMgr.appSummary = taosHashInit(10, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false, HASH_NO_LOCK);
L
fix  
Liu Jicong 已提交
1095
  clientHbMgr.appHbMgrs = taosArrayInit(0, sizeof(void *));
dengyihao's avatar
dengyihao 已提交
1096 1097

  TdThreadMutexAttr attr = {0};
dengyihao's avatar
dengyihao 已提交
1098

dengyihao's avatar
dengyihao 已提交
1099
  int ret = taosThreadMutexAttrInit(&attr);
1100 1101
  if (ret != 0) {
    uError("hbMgrInit:taosThreadMutexAttrInit error") return ret;
1102
  }
dengyihao's avatar
dengyihao 已提交
1103

dengyihao's avatar
dengyihao 已提交
1104
  ret = taosThreadMutexAttrSetType(&attr, PTHREAD_MUTEX_RECURSIVE);
1105 1106
  if (ret != 0) {
    uError("hbMgrInit:taosThreadMutexAttrSetType error") return ret;
1107
  }
dengyihao's avatar
dengyihao 已提交
1108 1109

  ret = taosThreadMutexInit(&clientHbMgr.lock, &attr);
1110 1111
  if (ret != 0) {
    uError("hbMgrInit:taosThreadMutexInit error") return ret;
1112
  }
dengyihao's avatar
dengyihao 已提交
1113 1114

  ret = taosThreadMutexAttrDestroy(&attr);
1115 1116
  if (ret != 0) {
    uError("hbMgrInit:taosThreadMutexAttrDestroy error") return ret;
1117
  }
L
Liu Jicong 已提交
1118 1119 1120 1121 1122

  // init handle funcs
  hbMgrInitHandle();

  // init backgroud thread
D
dapan1121 已提交
1123
  hbCreateThread();
L
Liu Jicong 已提交
1124

L
Liu Jicong 已提交
1125 1126 1127 1128
  return 0;
}

void hbMgrCleanUp() {
D
dapan1121 已提交
1129
  hbStopThread();
L
fix  
Liu Jicong 已提交
1130

L
Liu Jicong 已提交
1131
  // destroy all appHbMgr
L
Liu Jicong 已提交
1132 1133 1134
  int8_t old = atomic_val_compare_exchange_8(&clientHbMgr.inited, 1, 0);
  if (old == 0) return;

wafwerar's avatar
wafwerar 已提交
1135
  taosThreadMutexLock(&clientHbMgr.lock);
D
dapan1121 已提交
1136
  appHbMgrCleanup();
L
fix  
Liu Jicong 已提交
1137
  taosArrayDestroy(clientHbMgr.appHbMgrs);
wafwerar's avatar
wafwerar 已提交
1138
  taosThreadMutexUnlock(&clientHbMgr.lock);
L
fix  
Liu Jicong 已提交
1139

1140
  clientHbMgr.appHbMgrs = NULL;
L
Liu Jicong 已提交
1141 1142
}

D
dapan1121 已提交
1143
int hbRegisterConnImpl(SAppHbMgr *pAppHbMgr, SClientHbKey connKey, int64_t clusterId) {
L
Liu Jicong 已提交
1144
  // init hash in activeinfo
L
fix  
Liu Jicong 已提交
1145
  void *data = taosHashGet(pAppHbMgr->activeInfo, &connKey, sizeof(SClientHbKey));
L
Liu Jicong 已提交
1146 1147 1148
  if (data != NULL) {
    return 0;
  }
D
dapan1121 已提交
1149
  SClientHbReq hbReq = {0};
L
Liu Jicong 已提交
1150
  hbReq.connKey = connKey;
D
dapan1121 已提交
1151
  hbReq.clusterId = clusterId;
1152
  // hbReq.info = taosHashInit(64, hbKeyHashFunc, 1, HASH_ENTRY_LOCK);
L
fix  
Liu Jicong 已提交
1153

L
Liu Jicong 已提交
1154
  taosHashPut(pAppHbMgr->activeInfo, &connKey, sizeof(SClientHbKey), &hbReq, sizeof(SClientHbReq));
L
fix  
Liu Jicong 已提交
1155

L
Liu Jicong 已提交
1156
  atomic_add_fetch_32(&pAppHbMgr->connKeyCnt, 1);
L
Liu Jicong 已提交
1157 1158 1159
  return 0;
}

D
dapan1121 已提交
1160
int hbRegisterConn(SAppHbMgr *pAppHbMgr, int64_t tscRefId, int64_t clusterId, int8_t connType) {
L
Liu Jicong 已提交
1161
  SClientHbKey connKey = {
D
dapan1121 已提交
1162
      .tscRid = tscRefId,
D
dapan1121 已提交
1163
      .connType = connType,
L
Liu Jicong 已提交
1164
  };
D
dapan1121 已提交
1165

D
dapan1121 已提交
1166 1167
  switch (connType) {
    case CONN_TYPE__QUERY: {
D
dapan1121 已提交
1168
      return hbRegisterConnImpl(pAppHbMgr, connKey, clusterId);
D
dapan1121 已提交
1169
    }
D
dapan1121 已提交
1170
    case CONN_TYPE__TMQ: {
L
Liu Jicong 已提交
1171
      return 0;
D
dapan1121 已提交
1172 1173
    }
    default:
L
Liu Jicong 已提交
1174
      return 0;
D
dapan1121 已提交
1175 1176 1177
  }
}

K
kailixu 已提交
1178 1179
void hbDeregisterConn(STscObj *pTscObj, SClientHbKey connKey) {
  SAppHbMgr    *pAppHbMgr = pTscObj->pAppInfo->pAppHbMgr;
D
dapan1121 已提交
1180
  SClientHbReq *pReq = taosHashAcquire(pAppHbMgr->activeInfo, &connKey, sizeof(SClientHbKey));
D
dapan1121 已提交
1181
  if (pReq) {
D
dapan1121 已提交
1182
    tFreeClientHbReq(pReq);
D
dapan1121 已提交
1183
    taosHashRemove(pAppHbMgr->activeInfo, &connKey, sizeof(SClientHbKey));
D
dapan1121 已提交
1184
    taosHashRelease(pAppHbMgr->activeInfo, pReq);
D
dapan1121 已提交
1185 1186
  }

D
dapan1121 已提交
1187
  if (NULL == pReq) {
D
dapan1121 已提交
1188 1189
    return;
  }
L
Liu Jicong 已提交
1190

L
Liu Jicong 已提交
1191
  atomic_sub_fetch_32(&pAppHbMgr->connKeyCnt, 1);
K
kailixu 已提交
1192 1193 1194

  taosThreadMutexLock(&pTscObj->mutex);
  if (pTscObj->passInfo.fp) {
K
kailixu 已提交
1195
    atomic_sub_fetch_32(&pAppHbMgr->passKeyCnt, 1);
K
kailixu 已提交
1196
  }
K
kailixu 已提交
1197
  taosThreadMutexUnlock(&pTscObj->mutex);
L
Liu Jicong 已提交
1198
}
1199 1200

// set heart beat thread quit mode , if quicByKill 1 then kill thread else quit from inner
K
kailixu 已提交
1201 1202 1203
void taos_set_hb_quit(int8_t quitByKill) {
  clientHbMgr.quitByKill = quitByKill;
}