clientHb.c 29.1 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 22 23 24 25 26

static SClientHbMgr clientHbMgr = {0};

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

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

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

D
dapan 已提交
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
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 已提交
48
  taosArrayDestroy(batchRsp.pArray);
D
dapan 已提交
49 50 51
  return TSDB_CODE_SUCCESS;
}

D
dapan1121 已提交
52 53 54
static int32_t hbProcessDBInfoRsp(void *value, int32_t valueLen, struct SCatalog *pCatalog) {
  int32_t code = 0;

S
Shengliang Guan 已提交
55 56 57 58 59
  SUseDbBatchRsp batchUseRsp = {0};
  if (tDeserializeSUseDbBatchRsp(value, valueLen, &batchUseRsp) != 0) {
    terrno = TSDB_CODE_INVALID_MSG;
    return -1;
  }
D
dapan1121 已提交
60

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

D
dapan1121 已提交
67
    if (rsp->vgVersion < 0) {
D
dapan1121 已提交
68
      code = catalogRemoveDB(pCatalog, rsp->db, rsp->uid);
D
dapan1121 已提交
69
    } else {
D
dapan1121 已提交
70 71
      SDBVgInfo *vgInfo = taosMemoryCalloc(1, sizeof(SDBVgInfo));
      if (NULL == vgInfo) {
S
Shengliang Guan 已提交
72
        code = TSDB_CODE_OUT_OF_MEMORY;
D
dapan1121 已提交
73
        goto _return;
D
dapan1121 已提交
74
      }
75

D
dapan1121 已提交
76
      vgInfo->vgVersion = rsp->vgVersion;
D
dapan1121 已提交
77
      vgInfo->stateTs = rsp->stateTs;
D
dapan1121 已提交
78
      vgInfo->hashMethod = rsp->hashMethod;
79 80
      vgInfo->hashPrefix = rsp->hashPrefix;
      vgInfo->hashSuffix = rsp->hashSuffix;
D
dapan1121 已提交
81 82 83
      vgInfo->vgHash = taosHashInit(rsp->vgNum, taosGetDefaultHashFunction(TSDB_DATA_TYPE_INT), true, HASH_ENTRY_LOCK);
      if (NULL == vgInfo->vgHash) {
        taosMemoryFree(vgInfo);
D
dapan1121 已提交
84
        tscError("hash init[%d] failed", rsp->vgNum);
S
Shengliang Guan 已提交
85
        code = TSDB_CODE_OUT_OF_MEMORY;
D
dapan1121 已提交
86
        goto _return;
D
dapan1121 已提交
87 88
      }

S
Shengliang Guan 已提交
89 90
      for (int32_t j = 0; j < rsp->vgNum; ++j) {
        SVgroupInfo *pInfo = taosArrayGet(rsp->pVgroupInfos, j);
D
dapan1121 已提交
91
        if (taosHashPut(vgInfo->vgHash, &pInfo->vgId, sizeof(int32_t), pInfo, sizeof(SVgroupInfo)) != 0) {
D
dapan1121 已提交
92
          tscError("hash push failed, errno:%d", errno);
D
dapan1121 已提交
93 94
          taosHashCleanup(vgInfo->vgHash);
          taosMemoryFree(vgInfo);
S
Shengliang Guan 已提交
95
          code = TSDB_CODE_OUT_OF_MEMORY;
D
dapan1121 已提交
96
          goto _return;
D
dapan1121 已提交
97
        }
L
fix  
Liu Jicong 已提交
98 99
      }

D
dapan1121 已提交
100
      catalogUpdateDBVgInfo(pCatalog, rsp->db, rsp->uid, vgInfo);
D
dapan1121 已提交
101 102 103
    }

    if (code) {
D
dapan1121 已提交
104
      goto _return;
D
dapan1121 已提交
105 106 107
    }
  }

D
dapan1121 已提交
108 109
_return:

S
Shengliang Guan 已提交
110
  tFreeSUseDbBatchRsp(&batchUseRsp);
D
dapan1121 已提交
111
  return code;
D
dapan1121 已提交
112 113
}

D
dapan 已提交
114 115 116
static int32_t hbProcessStbInfoRsp(void *value, int32_t valueLen, struct SCatalog *pCatalog) {
  int32_t code = 0;

D
dapan1121 已提交
117 118
  SSTbHbRsp hbRsp = {0};
  if (tDeserializeSSTbHbRsp(value, valueLen, &hbRsp) != 0) {
S
Shengliang Guan 已提交
119 120 121 122
    terrno = TSDB_CODE_INVALID_MSG;
    return -1;
  }

D
dapan1121 已提交
123 124 125
  int32_t numOfMeta = taosArrayGetSize(hbRsp.pMetaRsp);
  for (int32_t i = 0; i < numOfMeta; ++i) {
    STableMetaRsp *rsp = taosArrayGet(hbRsp.pMetaRsp, i);
S
Shengliang Guan 已提交
126

D
dapan 已提交
127 128
    if (rsp->numOfColumns < 0) {
      tscDebug("hb remove stb, db:%s, stb:%s", rsp->dbFName, rsp->stbName);
D
dapan1121 已提交
129
      catalogRemoveStbMeta(pCatalog, rsp->dbFName, rsp->dbId, rsp->stbName, rsp->suid);
D
dapan 已提交
130
    } else {
D
dapan1121 已提交
131
      tscDebug("hb update stb, db:%s, stb:%s", rsp->dbFName, rsp->stbName);
S
Shengliang Guan 已提交
132
      if (rsp->pSchemas[0].colId != PRIMARYKEY_TIMESTAMP_COL_ID) {
133
        tscError("invalid colId[%" PRIi16 "] for the first column in table meta rsp msg", rsp->pSchemas[0].colId);
D
dapan1121 已提交
134
        tFreeSSTbHbRsp(&hbRsp);
D
dapan1121 已提交
135
        return TSDB_CODE_TSC_INVALID_VALUE;
D
dapan 已提交
136 137
      }

D
dapan1121 已提交
138
      catalogUpdateTableMeta(pCatalog, rsp);
D
dapan 已提交
139 140 141
    }
  }

D
dapan1121 已提交
142 143 144 145 146 147 148 149 150 151
  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 已提交
152
  tFreeSSTbHbRsp(&hbRsp);
D
dapan 已提交
153 154 155
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
156
static int32_t hbQueryHbRspHandle(SAppHbMgr *pAppHbMgr, SClientHbRsp *pRsp) {
D
dapan1121 已提交
157
  SClientHbReq *pReq = taosHashAcquire(pAppHbMgr->activeInfo, &pRsp->connKey, sizeof(SClientHbKey));
D
dapan1121 已提交
158 159
  if (NULL == pReq) {
    tscWarn("pReq to get activeInfo, may be dropped, refId:%" PRIx64 ", type:%d", pRsp->connKey.tscRid,
L
Liu Jicong 已提交
160
            pRsp->connKey.connType);
D
dapan1121 已提交
161 162 163
    return TSDB_CODE_SUCCESS;
  }

D
dapan1121 已提交
164 165 166 167
  if (pRsp->query) {
    STscObj *pTscObj = (STscObj *)acquireTscObj(pRsp->connKey.tscRid);
    if (NULL == pTscObj) {
      tscDebug("tscObj rid %" PRIx64 " not exist", pRsp->connKey.tscRid);
168
    } else {
D
dapan1121 已提交
169
      if (pRsp->query->totalDnodes > 1 && !isEpsetEqual(&pTscObj->pAppInfo->mgmtEp.epSet, &pRsp->query->epSet)) {
170 171 172 173 174 175 176
        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 已提交
177 178
        updateEpSet_s(&pTscObj->pAppInfo->mgmtEp, &pRsp->query->epSet);
      }
179

D
dapan1121 已提交
180 181
      pTscObj->pAppInfo->totalDnodes = pRsp->query->totalDnodes;
      pTscObj->pAppInfo->onlineDnodes = pRsp->query->onlineDnodes;
D
dapan1121 已提交
182
      pTscObj->connId = pRsp->query->connId;
wmmhello's avatar
wmmhello 已提交
183
      tscTrace("conn %u hb rsp, dnodes %d/%d", pTscObj->connId, pTscObj->pAppInfo->onlineDnodes,
dengyihao's avatar
dengyihao 已提交
184
               pTscObj->pAppInfo->totalDnodes);
L
Liu Jicong 已提交
185

D
dapan1121 已提交
186
      if (pRsp->query->killRid) {
D
dapan1121 已提交
187
        tscDebug("request rid %" PRIx64 " need to be killed now", pRsp->query->killRid);
D
dapan1121 已提交
188 189 190 191 192 193 194 195
        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 已提交
196

D
dapan1121 已提交
197
      if (pRsp->query->killConnection) {
198
        taos_close_internal(pTscObj);
D
dapan1121 已提交
199 200
      }

D
dapan1121 已提交
201 202 203 204
      if (pRsp->query->pQnodeList) {
        updateQnodeList(pTscObj->pAppInfo, pRsp->query->pQnodeList);
      }

D
dapan1121 已提交
205 206 207
      releaseTscObj(pRsp->connKey.tscRid);
    }
  }
L
Liu Jicong 已提交
208

D
dapan1121 已提交
209
  int32_t kvNum = pRsp->info ? taosArrayGetSize(pRsp->info) : 0;
D
dapan1121 已提交
210 211

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

D
dapan1121 已提交
213 214 215
  for (int32_t i = 0; i < kvNum; ++i) {
    SKv *kv = taosArrayGet(pRsp->info, i);
    switch (kv->key) {
D
dapan 已提交
216 217 218 219 220 221 222 223
      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 已提交
224
        int32_t code = catalogGetHandle(pReq->clusterId, &pCatalog);
D
dapan 已提交
225
        if (code != TSDB_CODE_SUCCESS) {
D
dapan1121 已提交
226
          tscWarn("catalogGetHandle failed, clusterId:%" PRIx64 ", error:%s", pReq->clusterId, tstrerror(code));
D
dapan 已提交
227 228 229 230 231 232
          break;
        }

        hbProcessUserAuthInfoRsp(kv->value, kv->valueLen, pCatalog);
        break;
      }
D
dapan1121 已提交
233 234 235 236 237 238 239
      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 已提交
240

D
dapan1121 已提交
241
        int32_t code = catalogGetHandle(pReq->clusterId, &pCatalog);
D
dapan1121 已提交
242
        if (code != TSDB_CODE_SUCCESS) {
D
dapan1121 已提交
243
          tscWarn("catalogGetHandle failed, clusterId:%" PRIx64 ", error:%s", pReq->clusterId, tstrerror(code));
D
dapan1121 已提交
244 245 246 247
          break;
        }

        hbProcessDBInfoRsp(kv->value, kv->valueLen, pCatalog);
D
dapan1121 已提交
248
        break;
D
dapan1121 已提交
249
      }
L
fix  
Liu Jicong 已提交
250
      case HEARTBEAT_KEY_STBINFO: {
D
dapan 已提交
251 252 253 254
        if (kv->valueLen <= 0 || NULL == kv->value) {
          tscError("invalid hb stb info, len:%d, value:%p", kv->valueLen, kv->value);
          break;
        }
D
dapan1121 已提交
255

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

D
dapan1121 已提交
258
        int32_t code = catalogGetHandle(pReq->clusterId, &pCatalog);
D
dapan 已提交
259
        if (code != TSDB_CODE_SUCCESS) {
D
dapan1121 已提交
260
          tscWarn("catalogGetHandle failed, clusterId:%" PRIx64 ", error:%s", pReq->clusterId, tstrerror(code));
D
dapan 已提交
261 262 263 264
          break;
        }

        hbProcessStbInfoRsp(kv->value, kv->valueLen, pCatalog);
D
dapan1121 已提交
265
        break;
D
dapan 已提交
266
      }
D
dapan1121 已提交
267 268 269 270 271 272
      default:
        tscError("invalid hb key type:%d", kv->key);
        break;
    }
  }

D
dapan1121 已提交
273 274
  taosHashRelease(pAppHbMgr->activeInfo, pReq);

D
dapan1121 已提交
275 276 277
  return TSDB_CODE_SUCCESS;
}

D
dapan1121 已提交
278
static int32_t hbAsyncCallBack(void *param, SDataBuf *pMsg, int32_t code) {
279
  static int32_t    emptyRspNum = 0;
L
fix  
Liu Jicong 已提交
280
  char             *key = (char *)param;
D
dapan1121 已提交
281
  SClientHbBatchRsp pRsp = {0};
D
dapan1121 已提交
282 283
  if (TSDB_CODE_SUCCESS == code) {
    tDeserializeSClientHbBatchRsp(pMsg->pData, pMsg->len, &pRsp);
284

dengyihao's avatar
dengyihao 已提交
285 286 287 288 289 290
    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 已提交
291 292
  }

D
dapan1121 已提交
293
  int32_t rspNum = taosArrayGetSize(pRsp.rsps);
D
dapan1121 已提交
294

D
dapan1121 已提交
295 296
  taosThreadMutexLock(&appInfo.mutex);

L
fix  
Liu Jicong 已提交
297
  SAppInstInfo **pInst = taosHashGet(appInfo.pInstMap, key, strlen(key));
D
dapan1121 已提交
298
  if (pInst == NULL || NULL == *pInst) {
D
dapan1121 已提交
299
    taosThreadMutexUnlock(&appInfo.mutex);
L
fix  
Liu Jicong 已提交
300
    tscError("cluster not exist, key:%s", key);
D
dapan1121 已提交
301
    taosMemoryFree(pMsg->pData);
dengyihao's avatar
dengyihao 已提交
302
    taosMemoryFree(pMsg->pEpSet);
D
dapan1121 已提交
303
    tFreeClientHbBatchRsp(&pRsp);
D
dapan1121 已提交
304 305 306
    return -1;
  }

D
dapan1121 已提交
307
  if (code != 0) {
dengyihao's avatar
dengyihao 已提交
308
    (*pInst)->onlineDnodes = ((*pInst)->totalDnodes ? 0 : -1);
dengyihao's avatar
dengyihao 已提交
309 310
    tscDebug("hb rsp error %s, update server status %d/%d", tstrerror(code), (*pInst)->onlineDnodes,
             (*pInst)->totalDnodes);
D
dapan1121 已提交
311 312
  }

D
dapan1121 已提交
313
  if (rspNum) {
L
fix  
Liu Jicong 已提交
314 315
    tscDebug("hb got %d rsp, %d empty rsp received before", rspNum,
             atomic_val_compare_exchange_32(&emptyRspNum, emptyRspNum, 0));
D
dapan1121 已提交
316 317 318 319 320
  } else {
    atomic_add_fetch_32(&emptyRspNum, 1);
  }

  for (int32_t i = 0; i < rspNum; ++i) {
L
fix  
Liu Jicong 已提交
321
    SClientHbRsp *rsp = taosArrayGet(pRsp.rsps, i);
D
dapan1121 已提交
322
    code = (*clientHbMgr.rspHandle[rsp->connKey.connType])((*pInst)->pAppHbMgr, rsp);
D
dapan1121 已提交
323 324 325 326
    if (code) {
      break;
    }
  }
D
dapan1121 已提交
327

D
dapan1121 已提交
328 329
  taosThreadMutexUnlock(&appInfo.mutex);

D
dapan1121 已提交
330
  tFreeClientHbBatchRsp(&pRsp);
H
Haojun Liao 已提交
331
  taosMemoryFree(pMsg->pData);
dengyihao's avatar
dengyihao 已提交
332
  taosMemoryFree(pMsg->pEpSet);
D
dapan1121 已提交
333
  return code;
L
Liu Jicong 已提交
334 335
}

D
dapan1121 已提交
336
int32_t hbBuildQueryDesc(SQueryHbReqBasic *hbBasic, STscObj *pObj) {
L
Liu Jicong 已提交
337
  int64_t    now = taosGetTimestampUs();
D
dapan1121 已提交
338
  SQueryDesc desc = {0};
L
Liu Jicong 已提交
339
  int32_t    code = 0;
D
dapan1121 已提交
340

L
Liu Jicong 已提交
341
  void *pIter = taosHashIterate(pObj->pRequests, NULL);
D
dapan1121 已提交
342
  while (pIter != NULL) {
L
Liu Jicong 已提交
343
    int64_t     *rid = pIter;
D
dapan1121 已提交
344
    SRequestObj *pRequest = acquireRequest(*rid);
D
dapan1121 已提交
345 346 347 348 349 350 351
    if (NULL == pRequest) {
      pIter = taosHashIterate(pObj->pRequests, pIter);
      continue;
    }

    if (pRequest->killed) {
      releaseRequest(*rid);
D
dapan1121 已提交
352
      pIter = taosHashIterate(pObj->pRequests, pIter);
D
dapan1121 已提交
353 354 355 356
      continue;
    }

    tstrncpy(desc.sql, pRequest->sqlstr, sizeof(desc.sql));
357
    desc.stime = pRequest->metric.start / 1000;
L
Liu Jicong 已提交
358
    desc.queryId = pRequest->requestId;
D
dapan1121 已提交
359
    desc.useconds = now - pRequest->metric.start;
L
Liu Jicong 已提交
360
    desc.reqRid = pRequest->self;
361
    desc.stableQuery = pRequest->stableQuery;
D
dapan1121 已提交
362
    taosGetFqdn(desc.fqdn);
D
dapan1121 已提交
363
    desc.subPlanNum = pRequest->body.subplanNum;
D
dapan1121 已提交
364 365 366 367 368

    if (desc.subPlanNum) {
      desc.subDesc = taosArrayInit(desc.subPlanNum, sizeof(SQuerySubDesc));
      if (NULL == desc.subDesc) {
        releaseRequest(*rid);
S
Shengliang Guan 已提交
369
        return TSDB_CODE_OUT_OF_MEMORY;
D
dapan1121 已提交
370 371 372 373 374 375
      }

      code = schedulerGetTasksStatus(pRequest->body.queryJob, desc.subDesc);
      if (code) {
        taosArrayDestroy(desc.subDesc);
        desc.subDesc = NULL;
376
        desc.subPlanNum = 0;
D
dapan1121 已提交
377
      }
D
dapan1121 已提交
378
      desc.subPlanNum = taosArrayGetSize(desc.subDesc);
D
dapan1121 已提交
379 380
    } else {
      desc.subDesc = NULL;
D
dapan1121 已提交
381 382
    }

L
Liu Jicong 已提交
383
    releaseRequest(*rid);
D
dapan1121 已提交
384
    taosArrayPush(hbBasic->queryDesc, &desc);
L
Liu Jicong 已提交
385

D
dapan1121 已提交
386 387 388 389 390 391 392 393 394 395
    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 已提交
396
    return TSDB_CODE_APP_ERROR;
D
dapan1121 已提交
397
  }
L
Liu Jicong 已提交
398

D
dapan1121 已提交
399 400 401 402
  SQueryHbReqBasic *hbBasic = (SQueryHbReqBasic *)taosMemoryCalloc(1, sizeof(SQueryHbReqBasic));
  if (NULL == hbBasic) {
    tscError("calloc %d failed", (int32_t)sizeof(SQueryHbReqBasic));
    releaseTscObj(connKey->tscRid);
S
Shengliang Guan 已提交
403
    return TSDB_CODE_OUT_OF_MEMORY;
D
dapan1121 已提交
404
  }
405

406 407 408 409 410 411 412 413 414
  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 已提交
415 416 417 418 419 420

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

D
dapan1121 已提交
424 425 426
  int32_t code = hbBuildQueryDesc(hbBasic, pTscObj);
  if (code) {
    releaseTscObj(connKey->tscRid);
D
dapan1121 已提交
427 428 429
    if (hbBasic->queryDesc) {
      taosArrayDestroyEx(hbBasic->queryDesc, tFreeClientHbQueryDesc);
    }
D
dapan1121 已提交
430 431 432 433 434 435 436 437 438 439
    taosMemoryFree(hbBasic);
    return code;
  }

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

  return TSDB_CODE_SUCCESS;
}

D
dapan 已提交
440 441 442 443 444 445 446 447 448 449 450
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 已提交
451
    taosMemoryFree(users);
D
dapan 已提交
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
    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 已提交
468 469 470
  if (NULL == req->info) {
    req->info = taosHashInit(64, hbKeyHashFunc, 1, HASH_ENTRY_LOCK);
  }
471

D
dapan 已提交
472 473 474 475 476
  taosHashPut(req->info, &kv.key, sizeof(kv.key), &kv, sizeof(kv));

  return TSDB_CODE_SUCCESS;
}

D
dapan1121 已提交
477 478
int32_t hbGetExpiredDBInfo(SClientHbKey *connKey, struct SCatalog *pCatalog, SClientHbReq *req) {
  SDbVgVersion *dbs = NULL;
L
fix  
Liu Jicong 已提交
479 480
  uint32_t      dbNum = 0;
  int32_t       code = 0;
D
dapan1121 已提交
481 482 483 484 485 486

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

D
dapan1121 已提交
487
  if (dbNum <= 0) {
D
dapan1121 已提交
488
    taosMemoryFree(dbs);
D
dapan1121 已提交
489 490 491
    return TSDB_CODE_SUCCESS;
  }

D
dapan1121 已提交
492 493 494 495
  for (int32_t i = 0; i < dbNum; ++i) {
    SDbVgVersion *db = &dbs[i];
    db->dbId = htobe64(db->dbId);
    db->vgVersion = htonl(db->vgVersion);
D
dapan 已提交
496
    db->numOfTable = htonl(db->numOfTable);
D
dapan1121 已提交
497
    db->stateTs = htobe64(db->stateTs);
D
dapan1121 已提交
498 499
  }

L
Liu Jicong 已提交
500 501 502 503 504
  SKv kv = {
      .key = HEARTBEAT_KEY_DBINFO,
      .valueLen = sizeof(SDbVgVersion) * dbNum,
      .value = dbs,
  };
D
dapan1121 已提交
505 506 507

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

D
dapan1121 已提交
508 509 510 511
  if (NULL == req->info) {
    req->info = taosHashInit(64, hbKeyHashFunc, 1, HASH_ENTRY_LOCK);
  }

D
dapan1121 已提交
512 513 514 515 516
  taosHashPut(req->info, &kv.key, sizeof(kv.key), &kv, sizeof(kv));

  return TSDB_CODE_SUCCESS;
}

D
dapan 已提交
517
int32_t hbGetExpiredStbInfo(SClientHbKey *connKey, struct SCatalog *pCatalog, SClientHbReq *req) {
D
dapan1121 已提交
518
  SSTableVersion *stbs = NULL;
519 520
  uint32_t        stbNum = 0;
  int32_t         code = 0;
D
dapan 已提交
521 522 523 524 525 526 527

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

  if (stbNum <= 0) {
D
dapan1121 已提交
528
    taosMemoryFree(stbs);
D
dapan 已提交
529 530 531 532
    return TSDB_CODE_SUCCESS;
  }

  for (int32_t i = 0; i < stbNum; ++i) {
D
dapan1121 已提交
533
    SSTableVersion *stb = &stbs[i];
D
dapan 已提交
534 535
    stb->suid = htobe64(stb->suid);
    stb->sversion = htons(stb->sversion);
L
fix  
Liu Jicong 已提交
536
    stb->tversion = htons(stb->tversion);
D
dapan1121 已提交
537
    stb->smaVer = htonl(stb->smaVer);
D
dapan 已提交
538 539
  }

L
Liu Jicong 已提交
540 541
  SKv kv = {
      .key = HEARTBEAT_KEY_STBINFO,
D
dapan1121 已提交
542
      .valueLen = sizeof(SSTableVersion) * stbNum,
L
Liu Jicong 已提交
543 544
      .value = stbs,
  };
D
dapan 已提交
545 546 547

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

D
dapan1121 已提交
548 549 550 551
  if (NULL == req->info) {
    req->info = taosHashInit(64, hbKeyHashFunc, 1, HASH_ENTRY_LOCK);
  }

D
dapan 已提交
552 553 554 555 556
  taosHashPut(req->info, &kv.key, sizeof(kv.key), &kv, sizeof(kv));

  return TSDB_CODE_SUCCESS;
}

D
dapan1121 已提交
557
int32_t hbGetAppInfo(int64_t clusterId, SClientHbReq *req) {
558
  SAppHbReq *pApp = taosHashGet(clientHbMgr.appSummary, &clusterId, sizeof(clusterId));
D
dapan1121 已提交
559 560 561 562 563 564
  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;
565
    taosGetAppName(req->app.name, NULL);
D
dapan1121 已提交
566 567 568 569 570
  }

  return TSDB_CODE_SUCCESS;
}

L
fix  
Liu Jicong 已提交
571 572
int32_t hbQueryHbReqHandle(SClientHbKey *connKey, void *param, SClientHbReq *req) {
  int64_t         *clusterId = (int64_t *)param;
D
dapan1121 已提交
573 574 575 576
  struct SCatalog *pCatalog = NULL;

  int32_t code = catalogGetHandle(*clusterId, &pCatalog);
  if (code != TSDB_CODE_SUCCESS) {
L
fix  
Liu Jicong 已提交
577
    tscWarn("catalogGetHandle failed, clusterId:%" PRIx64 ", error:%s", *clusterId, tstrerror(code));
D
dapan1121 已提交
578 579
    return code;
  }
L
fix  
Liu Jicong 已提交
580

D
dapan1121 已提交
581 582
  hbGetAppInfo(*clusterId, req);

D
dapan1121 已提交
583
  hbGetQueryBasicInfo(connKey, req);
L
Liu Jicong 已提交
584

D
dapan 已提交
585 586 587 588 589
  code = hbGetExpiredUserInfo(connKey, pCatalog, req);
  if (TSDB_CODE_SUCCESS != code) {
    return code;
  }

D
dapan1121 已提交
590 591 592 593 594
  code = hbGetExpiredDBInfo(connKey, pCatalog, req);
  if (TSDB_CODE_SUCCESS != code) {
    return code;
  }

D
dapan 已提交
595 596 597 598 599
  code = hbGetExpiredStbInfo(connKey, pCatalog, req);
  if (TSDB_CODE_SUCCESS != code) {
    return code;
  }

D
dapan1121 已提交
600 601 602
  return TSDB_CODE_SUCCESS;
}

603 604
static FORCE_INLINE void hbMgrInitHandle() {
  // init all handle
D
dapan1121 已提交
605 606
  clientHbMgr.reqHandle[CONN_TYPE__QUERY] = hbQueryHbReqHandle;
  clientHbMgr.reqHandle[CONN_TYPE__TMQ] = hbMqHbReqHandle;
L
Liu Jicong 已提交
607

D
dapan1121 已提交
608 609
  clientHbMgr.rspHandle[CONN_TYPE__QUERY] = hbQueryHbRspHandle;
  clientHbMgr.rspHandle[CONN_TYPE__TMQ] = hbMqHbRspHandle;
L
Liu Jicong 已提交
610 611
}

L
fix  
Liu Jicong 已提交
612
SClientHbBatchReq *hbGatherAllInfo(SAppHbMgr *pAppHbMgr) {
wafwerar's avatar
wafwerar 已提交
613
  SClientHbBatchReq *pBatchReq = taosMemoryCalloc(1, sizeof(SClientHbBatchReq));
L
Liu Jicong 已提交
614
  if (pBatchReq == NULL) {
S
Shengliang Guan 已提交
615
    terrno = TSDB_CODE_OUT_OF_MEMORY;
L
Liu Jicong 已提交
616 617
    return NULL;
  }
L
Liu Jicong 已提交
618
  int32_t connKeyCnt = atomic_load_32(&pAppHbMgr->connKeyCnt);
L
Liu Jicong 已提交
619
  pBatchReq->reqs = taosArrayInit(connKeyCnt, sizeof(SClientHbReq));
L
Liu Jicong 已提交
620

dengyihao's avatar
dengyihao 已提交
621
  int64_t rid = -1;
D
dapan1121 已提交
622 623
  int32_t code = 0;

dengyihao's avatar
dengyihao 已提交
624 625 626 627 628 629 630 631 632 633 634
  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 已提交
635

dengyihao's avatar
dengyihao 已提交
636 637
  while (pIter != NULL) {
    pOneReq = taosArrayPush(pBatchReq->reqs, pOneReq);
D
dapan1121 已提交
638 639 640
    code = (*clientHbMgr.reqHandle[pOneReq->connKey.connType])(&pOneReq->connKey, &pOneReq->clusterId, pOneReq);
    if (code) {
      pIter = taosHashIterate(pAppHbMgr->activeInfo, pIter);
dengyihao's avatar
dengyihao 已提交
641
      pOneReq = pIter;
D
dapan1121 已提交
642
      continue;
D
dapan1121 已提交
643 644
    }

L
Liu Jicong 已提交
645
    pIter = taosHashIterate(pAppHbMgr->activeInfo, pIter);
dengyihao's avatar
dengyihao 已提交
646
    pOneReq = pIter;
L
Liu Jicong 已提交
647
  }
dengyihao's avatar
dengyihao 已提交
648
  releaseTscObj(rid);
L
Liu Jicong 已提交
649

L
Liu Jicong 已提交
650
  return pBatchReq;
L
Liu Jicong 已提交
651 652
}

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

655
void hbMergeSummary(SAppClusterSummary *dst, SAppClusterSummary *src) {
D
dapan1121 已提交
656 657 658 659 660 661 662 663 664 665 666 667 668
  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};
669
  int       sz = taosArrayGetSize(clientHbMgr.appHbMgrs);
D
dapan1121 已提交
670 671 672 673 674
  if (sz > 0) {
    req.pid = taosGetPId();
    req.appId = clientHbMgr.appId;
    taosGetAppName(req.name, NULL);
  }
D
dapan1121 已提交
675 676

  taosHashClear(clientHbMgr.appSummary);
677

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

682 683
    uint64_t   clusterId = pAppHbMgr->pAppInstInfo->clusterId;
    SAppHbReq *pApp = taosHashGet(clientHbMgr.appSummary, &clusterId, sizeof(clusterId));
D
dapan1121 已提交
684 685
    if (NULL == pApp) {
      memcpy(&req.summary, &pAppHbMgr->pAppInstInfo->summary, sizeof(req.summary));
D
dapan1121 已提交
686
      req.startTime = pAppHbMgr->startTime;
D
dapan1121 已提交
687 688 689 690 691
      taosHashPut(clientHbMgr.appSummary, &clusterId, sizeof(clusterId), &req, sizeof(req));
    } else {
      if (pAppHbMgr->startTime < pApp->startTime) {
        pApp->startTime = pAppHbMgr->startTime;
      }
692

D
dapan1121 已提交
693 694 695 696 697 698 699
      hbMergeSummary(&pApp->summary, &pAppHbMgr->pAppInstInfo->summary);
    }
  }

  return TSDB_CODE_SUCCESS;
}

L
fix  
Liu Jicong 已提交
700
static void *hbThreadFunc(void *param) {
L
Liu Jicong 已提交
701
  setThreadName("hb");
wafwerar's avatar
wafwerar 已提交
702
#ifdef WINDOWS
wafwerar's avatar
wafwerar 已提交
703 704 705
  if (taosCheckCurrentInDll()) {
    atexit(hbThreadFuncUnexpectedStopped);
  }
wafwerar's avatar
wafwerar 已提交
706
#endif
L
Liu Jicong 已提交
707
  while (1) {
708
    if (1 == clientHbMgr.threadStop) {
L
Liu Jicong 已提交
709 710 711
      break;
    }

wafwerar's avatar
wafwerar 已提交
712
    taosThreadMutexLock(&clientHbMgr.lock);
713

L
Liu Jicong 已提交
714
    int sz = taosArrayGetSize(clientHbMgr.appHbMgrs);
D
dapan1121 已提交
715 716 717
    if (sz > 0) {
      hbGatherAppInfo();
    }
718

dengyihao's avatar
dengyihao 已提交
719
    SArray *mgr = taosArrayInit(sz, sizeof(void *));
L
fix  
Liu Jicong 已提交
720 721
    for (int i = 0; i < sz; i++) {
      SAppHbMgr *pAppHbMgr = taosArrayGetP(clientHbMgr.appHbMgrs, i);
dengyihao's avatar
dengyihao 已提交
722 723 724
      if (pAppHbMgr == NULL) {
        continue;
      }
L
Liu Jicong 已提交
725

L
Liu Jicong 已提交
726 727
      int32_t connCnt = atomic_load_32(&pAppHbMgr->connKeyCnt);
      if (connCnt == 0) {
dengyihao's avatar
dengyihao 已提交
728
        taosArrayPush(mgr, &pAppHbMgr);
L
Liu Jicong 已提交
729 730
        continue;
      }
L
fix  
Liu Jicong 已提交
731
      SClientHbBatchReq *pReq = hbGatherAllInfo(pAppHbMgr);
dengyihao's avatar
dengyihao 已提交
732 733
      if (pReq == NULL || taosArrayGetP(clientHbMgr.appHbMgrs, i) == NULL) {
        tFreeClientHbBatchReq(pReq);
L
Liu Jicong 已提交
734 735
        continue;
      }
L
fix  
Liu Jicong 已提交
736
      int   tlen = tSerializeSClientHbBatchReq(NULL, 0, pReq);
wafwerar's avatar
wafwerar 已提交
737
      void *buf = taosMemoryMalloc(tlen);
L
Liu Jicong 已提交
738
      if (buf == NULL) {
S
Shengliang Guan 已提交
739
        terrno = TSDB_CODE_OUT_OF_MEMORY;
D
dapan1121 已提交
740
        tFreeClientHbBatchReq(pReq);
dengyihao's avatar
dengyihao 已提交
741
        // hbClearReqInfo(pAppHbMgr);
dengyihao's avatar
dengyihao 已提交
742
        taosArrayPush(mgr, &pAppHbMgr);
L
Liu Jicong 已提交
743 744
        break;
      }
L
fix  
Liu Jicong 已提交
745

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

L
Liu Jicong 已提交
749
      if (pInfo == NULL) {
S
Shengliang Guan 已提交
750
        terrno = TSDB_CODE_OUT_OF_MEMORY;
D
dapan1121 已提交
751
        tFreeClientHbBatchReq(pReq);
dengyihao's avatar
dengyihao 已提交
752
        // hbClearReqInfo(pAppHbMgr);
wafwerar's avatar
wafwerar 已提交
753
        taosMemoryFree(buf);
dengyihao's avatar
dengyihao 已提交
754
        taosArrayPush(mgr, &pAppHbMgr);
L
Liu Jicong 已提交
755 756
        break;
      }
L
Liu Jicong 已提交
757
      pInfo->fp = hbAsyncCallBack;
L
Liu Jicong 已提交
758 759 760
      pInfo->msgInfo.pData = buf;
      pInfo->msgInfo.len = tlen;
      pInfo->msgType = TDMT_MND_HEARTBEAT;
D
dapan1121 已提交
761
      pInfo->param = strdup(pAppHbMgr->key);
dengyihao's avatar
dengyihao 已提交
762
      pInfo->paramFreeFp = taosMemoryFree;
L
Liu Jicong 已提交
763 764
      pInfo->requestId = generateRequestId();
      pInfo->requestObjRefId = 0;
L
Liu Jicong 已提交
765 766

      SAppInstInfo *pAppInstInfo = pAppHbMgr->pAppInstInfo;
L
fix  
Liu Jicong 已提交
767 768
      int64_t       transporterId = 0;
      SEpSet        epSet = getEpSet_s(&pAppInstInfo->mgmtEp);
L
Liu Jicong 已提交
769
      asyncSendMsgToServer(pAppInstInfo->pTransporter, &epSet, &transporterId, pInfo);
D
dapan1121 已提交
770
      tFreeClientHbBatchReq(pReq);
dengyihao's avatar
dengyihao 已提交
771
      // hbClearReqInfo(pAppHbMgr);
L
Liu Jicong 已提交
772 773

      atomic_add_fetch_32(&pAppHbMgr->reportCnt, 1);
dengyihao's avatar
dengyihao 已提交
774
      taosArrayPush(mgr, &pAppHbMgr);
L
Liu Jicong 已提交
775
    }
776

dengyihao's avatar
dengyihao 已提交
777 778 779
    taosArrayDestroy(clientHbMgr.appHbMgrs);
    clientHbMgr.appHbMgrs = mgr;

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

L
Liu Jicong 已提交
782
    taosMsleep(HEARTBEAT_INTERVAL);
L
Liu Jicong 已提交
783 784 785 786 787
  }
  return NULL;
}

static int32_t hbCreateThread() {
wafwerar's avatar
wafwerar 已提交
788 789 790
  TdThreadAttr thAttr;
  taosThreadAttrInit(&thAttr);
  taosThreadAttrSetDetachState(&thAttr, PTHREAD_CREATE_JOINABLE);
L
Liu Jicong 已提交
791

D
dapan1121 已提交
792 793 794
  if (taosThreadCreate(&clientHbMgr.thread, &thAttr, hbThreadFunc, NULL) != 0) {
    terrno = TAOS_SYSTEM_ERROR(errno);
    return -1;
L
Liu Jicong 已提交
795
  }
D
dapan1121 已提交
796
  taosThreadAttrDestroy(&thAttr);
L
Liu Jicong 已提交
797 798 799
  return 0;
}

L
Liu Jicong 已提交
800
static void hbStopThread() {
D
dapan1121 已提交
801 802 803
  if (0 == atomic_load_8(&clientHbMgr.inited)) {
    return;
  }
804
  if (atomic_val_compare_exchange_8(&clientHbMgr.threadStop, 0, 1)) {
D
dapan1121 已提交
805
    tscDebug("hb thread already stopped");
806 807
    return;
  }
L
fix  
Liu Jicong 已提交
808

809
  taosThreadJoin(clientHbMgr.thread, NULL);
D
dapan1121 已提交
810

L
fix  
Liu Jicong 已提交
811
  tscDebug("hb thread stopped");
L
Liu Jicong 已提交
812 813
}

L
fix  
Liu Jicong 已提交
814
SAppHbMgr *appHbMgrInit(SAppInstInfo *pAppInstInfo, char *key) {
815 816 817 818
  if(hbMgrInit() != 0){
    terrno = TSDB_CODE_TSC_INTERNAL_ERROR;
    return NULL;
  }
wafwerar's avatar
wafwerar 已提交
819
  SAppHbMgr *pAppHbMgr = taosMemoryMalloc(sizeof(SAppHbMgr));
L
Liu Jicong 已提交
820 821 822 823 824 825
  if (pAppHbMgr == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }
  // init stat
  pAppHbMgr->startTime = taosGetTimestampMs();
L
Liu Jicong 已提交
826 827 828
  pAppHbMgr->connKeyCnt = 0;
  pAppHbMgr->reportCnt = 0;
  pAppHbMgr->reportBytes = 0;
D
dapan1121 已提交
829
  pAppHbMgr->key = strdup(key);
L
Liu Jicong 已提交
830

L
Liu Jicong 已提交
831 832
  // init app info
  pAppHbMgr->pAppInstInfo = pAppInstInfo;
L
Liu Jicong 已提交
833 834 835

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

  if (pAppHbMgr->activeInfo == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
wafwerar's avatar
wafwerar 已提交
839
    taosMemoryFree(pAppHbMgr);
L
Liu Jicong 已提交
840 841
    return NULL;
  }
H
Haojun Liao 已提交
842

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

wafwerar's avatar
wafwerar 已提交
845
  taosThreadMutexLock(&clientHbMgr.lock);
L
Liu Jicong 已提交
846
  taosArrayPush(clientHbMgr.appHbMgrs, &pAppHbMgr);
wafwerar's avatar
wafwerar 已提交
847
  taosThreadMutexUnlock(&clientHbMgr.lock);
L
fix  
Liu Jicong 已提交
848

L
Liu Jicong 已提交
849 850 851
  return pAppHbMgr;
}

D
dapan1121 已提交
852 853 854 855 856 857 858 859 860
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;
861

D
dapan1121 已提交
862 863 864 865 866 867 868 869 870 871 872 873
  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 已提交
874
      taosArraySet(clientHbMgr.appHbMgrs, i, pAppHbMgr);
D
dapan1121 已提交
875 876 877 878 879 880
      break;
    }
  }
  taosThreadMutexUnlock(&clientHbMgr.lock);
}

D
dapan1121 已提交
881
void appHbMgrCleanup(void) {
L
Liu Jicong 已提交
882 883
  int sz = taosArrayGetSize(clientHbMgr.appHbMgrs);
  for (int i = 0; i < sz; i++) {
L
fix  
Liu Jicong 已提交
884
    SAppHbMgr *pTarget = taosArrayGetP(clientHbMgr.appHbMgrs, i);
dengyihao's avatar
dengyihao 已提交
885
    if (pTarget == NULL) continue;
D
dapan1121 已提交
886
    hbFreeAppHbMgr(pTarget);
L
Liu Jicong 已提交
887 888 889 890
  }
}

int hbMgrInit() {
L
Liu Jicong 已提交
891 892 893 894
  // init once
  int8_t old = atomic_val_compare_exchange_8(&clientHbMgr.inited, 0, 1);
  if (old == 1) return 0;

D
dapan1121 已提交
895 896
  clientHbMgr.appId = tGenIdPI64();
  tscDebug("app %" PRIx64 " initialized", clientHbMgr.appId);
897

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

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

dengyihao's avatar
dengyihao 已提交
903
  int ret = taosThreadMutexAttrInit(&attr);
904 905 906 907
  if(ret != 0){
    uError("hbMgrInit:taosThreadMutexAttrInit error")
    return ret;
  }
dengyihao's avatar
dengyihao 已提交
908

dengyihao's avatar
dengyihao 已提交
909
  ret = taosThreadMutexAttrSetType(&attr, PTHREAD_MUTEX_RECURSIVE);
910 911 912 913
  if(ret != 0){
    uError("hbMgrInit:taosThreadMutexAttrSetType error")
    return ret;
  }
dengyihao's avatar
dengyihao 已提交
914 915

  ret = taosThreadMutexInit(&clientHbMgr.lock, &attr);
916 917 918 919
  if(ret != 0){
    uError("hbMgrInit:taosThreadMutexInit error")
    return ret;
  }
dengyihao's avatar
dengyihao 已提交
920 921

  ret = taosThreadMutexAttrDestroy(&attr);
922 923 924 925
  if(ret != 0){
    uError("hbMgrInit:taosThreadMutexAttrDestroy error")
    return ret;
  }
L
Liu Jicong 已提交
926 927 928 929 930

  // init handle funcs
  hbMgrInitHandle();

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

L
Liu Jicong 已提交
933 934 935 936
  return 0;
}

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

L
Liu Jicong 已提交
939
  // destroy all appHbMgr
L
Liu Jicong 已提交
940 941 942
  int8_t old = atomic_val_compare_exchange_8(&clientHbMgr.inited, 1, 0);
  if (old == 0) return;

wafwerar's avatar
wafwerar 已提交
943
  taosThreadMutexLock(&clientHbMgr.lock);
D
dapan1121 已提交
944
  appHbMgrCleanup();
L
fix  
Liu Jicong 已提交
945
  taosArrayDestroy(clientHbMgr.appHbMgrs);
wafwerar's avatar
wafwerar 已提交
946
  taosThreadMutexUnlock(&clientHbMgr.lock);
L
fix  
Liu Jicong 已提交
947

948
  clientHbMgr.appHbMgrs = NULL;
L
Liu Jicong 已提交
949 950
}

D
dapan1121 已提交
951
int hbRegisterConnImpl(SAppHbMgr *pAppHbMgr, SClientHbKey connKey, int64_t clusterId) {
L
Liu Jicong 已提交
952
  // init hash in activeinfo
L
fix  
Liu Jicong 已提交
953
  void *data = taosHashGet(pAppHbMgr->activeInfo, &connKey, sizeof(SClientHbKey));
L
Liu Jicong 已提交
954 955 956
  if (data != NULL) {
    return 0;
  }
D
dapan1121 已提交
957
  SClientHbReq hbReq = {0};
L
Liu Jicong 已提交
958
  hbReq.connKey = connKey;
D
dapan1121 已提交
959
  hbReq.clusterId = clusterId;
960
  // hbReq.info = taosHashInit(64, hbKeyHashFunc, 1, HASH_ENTRY_LOCK);
L
fix  
Liu Jicong 已提交
961

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

L
Liu Jicong 已提交
964
  atomic_add_fetch_32(&pAppHbMgr->connKeyCnt, 1);
L
Liu Jicong 已提交
965 966 967
  return 0;
}

D
dapan1121 已提交
968
int hbRegisterConn(SAppHbMgr *pAppHbMgr, int64_t tscRefId, int64_t clusterId, int8_t connType) {
L
Liu Jicong 已提交
969
  SClientHbKey connKey = {
D
dapan1121 已提交
970
      .tscRid = tscRefId,
D
dapan1121 已提交
971
      .connType = connType,
L
Liu Jicong 已提交
972
  };
D
dapan1121 已提交
973

D
dapan1121 已提交
974 975
  switch (connType) {
    case CONN_TYPE__QUERY: {
D
dapan1121 已提交
976
      return hbRegisterConnImpl(pAppHbMgr, connKey, clusterId);
D
dapan1121 已提交
977
    }
D
dapan1121 已提交
978
    case CONN_TYPE__TMQ: {
L
Liu Jicong 已提交
979
      return 0;
D
dapan1121 已提交
980 981
    }
    default:
L
Liu Jicong 已提交
982
      return 0;
D
dapan1121 已提交
983 984 985
  }
}

L
fix  
Liu Jicong 已提交
986
void hbDeregisterConn(SAppHbMgr *pAppHbMgr, SClientHbKey connKey) {
D
dapan1121 已提交
987
  SClientHbReq *pReq = taosHashAcquire(pAppHbMgr->activeInfo, &connKey, sizeof(SClientHbKey));
D
dapan1121 已提交
988
  if (pReq) {
D
dapan1121 已提交
989
    tFreeClientHbReq(pReq);
D
dapan1121 已提交
990
    taosHashRemove(pAppHbMgr->activeInfo, &connKey, sizeof(SClientHbKey));
D
dapan1121 已提交
991
    taosHashRelease(pAppHbMgr->activeInfo, pReq);
D
dapan1121 已提交
992 993
  }

D
dapan1121 已提交
994
  if (NULL == pReq) {
D
dapan1121 已提交
995 996
    return;
  }
L
Liu Jicong 已提交
997

L
Liu Jicong 已提交
998
  atomic_sub_fetch_32(&pAppHbMgr->connKeyCnt, 1);
L
Liu Jicong 已提交
999
}