clientHb.c 36.2 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
    struct {
K
kailixu 已提交
25 26 27 28
      SAppHbMgr *pAppHbMgr;
      int64_t    clusterId;
      int32_t    reqCnt;
      int8_t     connHbFlag;
K
kailixu 已提交
29
    };
K
kailixu 已提交
30 31 32
  };
} SHbParam;

K
kailixu 已提交
33 34 35 36
static SClientHbMgr clientHbMgr = {0};

static int32_t hbCreateThread();
static void    hbStopThread();
K
kailixu 已提交
37
static int32_t hbUpdateUserAuthInfo(SAppHbMgr *pAppHbMgr, SUserAuthBatchRsp *batchRsp);
K
kailixu 已提交
38

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

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

K
kailixu 已提交
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
static int32_t hbProcessUserAuthInfoRsp(void *value, int32_t valueLen, struct SCatalog *pCatalog,
                                        SAppHbMgr *pAppHbMgr) {
  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);
  }

  if (numOfBatchs > 0) hbUpdateUserAuthInfo(pAppHbMgr, &batchRsp);

  atomic_val_compare_exchange_8(&pAppHbMgr->connHbFlag, 1, 2);

  taosArrayDestroy(batchRsp.pArray);
  return TSDB_CODE_SUCCESS;
}

K
kailixu 已提交
69
static int32_t hbUpdateUserAuthInfo(SAppHbMgr *pAppHbMgr, SUserAuthBatchRsp *batchRsp) {
K
kailixu 已提交
70 71 72 73 74 75
  SClientHbReq *pReq = NULL;
  while ((pReq = taosHashIterate(pAppHbMgr->activeInfo, pReq))) {
    STscObj *pTscObj = (STscObj *)acquireTscObj(pReq->connKey.tscRid);
    if (!pTscObj) {
      continue;
    }
K
kailixu 已提交
76 77
    for (int32_t i = 0; i < TARRAY_SIZE(batchRsp->pArray); ++i) {
      SGetUserAuthRsp *rsp = taosArrayGet(batchRsp->pArray, i);
K
kailixu 已提交
78

K
kailixu 已提交
79
      if (0 == strncmp(rsp->user, pTscObj->user, TSDB_USER_LEN)) {
K
kailixu 已提交
80 81 82
        
        pTscObj->authVer = rsp->version;

K
kailixu 已提交
83
        if (pTscObj->sysInfo != rsp->sysInfo) {
K
kailixu 已提交
84 85
          tscDebug("update sysInfo of user %s from %" PRIi8 " to %" PRIi8 ", tscRid:%" PRIi64, rsp->user,
                   pTscObj->sysInfo, rsp->sysInfo, pTscObj->id);
K
kailixu 已提交
86 87
          pTscObj->sysInfo = rsp->sysInfo;
        }
D
dapan 已提交
88

K
kailixu 已提交
89 90 91
        if (pTscObj->passInfo.fp) {
          SPassInfo *passInfo = &pTscObj->passInfo;
          int32_t    oldVer = atomic_load_32(&passInfo->ver);
K
kailixu 已提交
92 93 94
          if (oldVer < rsp->passVer) {
            atomic_store_32(&passInfo->ver, rsp->passVer);
            if (passInfo->fp) {
K
kailixu 已提交
95
              (*passInfo->fp)(passInfo->param, &rsp->passVer, TAOS_NOTIFY_PASSVER);
K
kailixu 已提交
96
            }
K
kailixu 已提交
97 98
            tscDebug("update passVer of user %s from %d to %d, tscRid:%" PRIi64, rsp->user, oldVer,
                     atomic_load_32(&passInfo->ver), pTscObj->id);
K
kailixu 已提交
99
          }
K
kailixu 已提交
100
        }
K
kailixu 已提交
101

K
kailixu 已提交
102
        break;
K
kailixu 已提交
103 104
      }
    }
K
kailixu 已提交
105
    releaseTscObj(pReq->connKey.tscRid);
K
kailixu 已提交
106
  }
K
kailixu 已提交
107 108 109
  return 0;
}

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

D
dapan1121 已提交
118 119 120 121 122 123 124 125 126 127 128 129
  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;
  }
130

D
dapan1121 已提交
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
  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 已提交
152 153 154
static int32_t hbProcessDBInfoRsp(void *value, int32_t valueLen, struct SCatalog *pCatalog) {
  int32_t code = 0;

D
dapan1121 已提交
155 156
  SDbHbBatchRsp batchRsp = {0};
  if (tDeserializeSDbHbBatchRsp(value, valueLen, &batchRsp) != 0) {
S
Shengliang Guan 已提交
157
    terrno = TSDB_CODE_INVALID_MSG;
158 159
    code = terrno;
    goto _return;
S
Shengliang Guan 已提交
160
  }
D
dapan1121 已提交
161

D
dapan1121 已提交
162
  int32_t numOfBatchs = taosArrayGetSize(batchRsp.pArray);
S
Shengliang Guan 已提交
163
  for (int32_t i = 0; i < numOfBatchs; ++i) {
D
dapan1121 已提交
164 165
    SDbHbRsp *rsp = taosArrayGet(batchRsp.pArray, i);
    if (rsp->useDbRsp) {
H
Haojun Liao 已提交
166
      tscDebug("hb use db rsp, db:%s, vgVersion:%d, stateTs:%" PRId64 ", uid:%" PRIx64,
D
dapan1121 已提交
167
        rsp->useDbRsp->db, rsp->useDbRsp->vgVersion, rsp->useDbRsp->stateTs, rsp->useDbRsp->uid);
H
Haojun Liao 已提交
168

D
dapan1121 已提交
169 170 171 172 173
      if (rsp->useDbRsp->vgVersion < 0) {
        code = catalogRemoveDB(pCatalog, rsp->useDbRsp->db, rsp->useDbRsp->uid);
      } else {
        SDBVgInfo *vgInfo = NULL;
        code = hbGenerateVgInfoFromRsp(&vgInfo, rsp->useDbRsp);
D
dapan1121 已提交
174
        if (TSDB_CODE_SUCCESS != code) {
D
dapan1121 已提交
175
          goto _return;
D
dapan1121 已提交
176
        }
L
fix  
Liu Jicong 已提交
177

D
dapan1121 已提交
178
        catalogUpdateDBVgInfo(pCatalog, rsp->useDbRsp->db, rsp->useDbRsp->uid, vgInfo);
H
Haojun Liao 已提交
179

D
dapan1121 已提交
180 181 182 183 184
        if (IS_SYS_DBNAME(rsp->useDbRsp->db)) {
          code = hbGenerateVgInfoFromRsp(&vgInfo, rsp->useDbRsp);
          if (TSDB_CODE_SUCCESS != code) {
            goto _return;
          }
H
Haojun Liao 已提交
185

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

D
dapan1121 已提交
191 192 193 194
    if (rsp->cfgRsp) {
      tscDebug("hb db cfg rsp, db:%s, cfgVersion:%d", rsp->cfgRsp->db, rsp->cfgRsp->cfgVersion);
      catalogUpdateDbCfg(pCatalog, rsp->cfgRsp->db, rsp->cfgRsp->dbId, rsp->cfgRsp);
      rsp->cfgRsp = NULL;
D
dapan1121 已提交
195 196 197
    }
  }

D
dapan1121 已提交
198 199
_return:

D
dapan1121 已提交
200
  tFreeSDbHbBatchRsp(&batchRsp);
D
dapan1121 已提交
201
  return code;
D
dapan1121 已提交
202 203
}

D
dapan 已提交
204 205 206
static int32_t hbProcessStbInfoRsp(void *value, int32_t valueLen, struct SCatalog *pCatalog) {
  int32_t code = 0;

D
dapan1121 已提交
207 208
  SSTbHbRsp hbRsp = {0};
  if (tDeserializeSSTbHbRsp(value, valueLen, &hbRsp) != 0) {
S
Shengliang Guan 已提交
209 210 211 212
    terrno = TSDB_CODE_INVALID_MSG;
    return -1;
  }

D
dapan1121 已提交
213 214 215
  int32_t numOfMeta = taosArrayGetSize(hbRsp.pMetaRsp);
  for (int32_t i = 0; i < numOfMeta; ++i) {
    STableMetaRsp *rsp = taosArrayGet(hbRsp.pMetaRsp, i);
S
Shengliang Guan 已提交
216

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

D
dapan1121 已提交
228
      catalogAsyncUpdateTableMeta(pCatalog, rsp);
D
dapan 已提交
229 230 231
    }
  }

D
dapan1121 已提交
232 233 234 235 236 237 238 239 240 241
  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 已提交
242
  tFreeSSTbHbRsp(&hbRsp);
D
dapan 已提交
243 244 245
  return TSDB_CODE_SUCCESS;
}

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

D
dapan1121 已提交
254 255 256 257
  if (pRsp->query) {
    STscObj *pTscObj = (STscObj *)acquireTscObj(pRsp->connKey.tscRid);
    if (NULL == pTscObj) {
      tscDebug("tscObj rid %" PRIx64 " not exist", pRsp->connKey.tscRid);
258
    } else {
D
dapan1121 已提交
259
      if (pRsp->query->totalDnodes > 1 && !isEpsetEqual(&pTscObj->pAppInfo->mgmtEp.epSet, &pRsp->query->epSet)) {
260 261 262 263 264 265 266
        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 已提交
267 268
        updateEpSet_s(&pTscObj->pAppInfo->mgmtEp, &pRsp->query->epSet);
      }
269

D
dapan1121 已提交
270 271
      pTscObj->pAppInfo->totalDnodes = pRsp->query->totalDnodes;
      pTscObj->pAppInfo->onlineDnodes = pRsp->query->onlineDnodes;
D
dapan1121 已提交
272
      pTscObj->connId = pRsp->query->connId;
wmmhello's avatar
wmmhello 已提交
273
      tscTrace("conn %u hb rsp, dnodes %d/%d", pTscObj->connId, pTscObj->pAppInfo->onlineDnodes,
dengyihao's avatar
dengyihao 已提交
274
               pTscObj->pAppInfo->totalDnodes);
L
Liu Jicong 已提交
275

D
dapan1121 已提交
276
      if (pRsp->query->killRid) {
D
dapan1121 已提交
277
        tscDebug("request rid %" PRIx64 " need to be killed now", pRsp->query->killRid);
D
dapan1121 已提交
278 279 280 281 282 283 284 285
        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 已提交
286

D
dapan1121 已提交
287
      if (pRsp->query->killConnection) {
288
        taos_close_internal(pTscObj);
D
dapan1121 已提交
289 290
      }

D
dapan1121 已提交
291 292 293 294
      if (pRsp->query->pQnodeList) {
        updateQnodeList(pTscObj->pAppInfo, pRsp->query->pQnodeList);
      }

D
dapan1121 已提交
295 296 297
      releaseTscObj(pRsp->connKey.tscRid);
    }
  }
L
Liu Jicong 已提交
298

D
dapan1121 已提交
299
  int32_t kvNum = pRsp->info ? taosArrayGetSize(pRsp->info) : 0;
D
dapan1121 已提交
300 301

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

D
dapan1121 已提交
303 304 305
  for (int32_t i = 0; i < kvNum; ++i) {
    SKv *kv = taosArrayGet(pRsp->info, i);
    switch (kv->key) {
D
dapan 已提交
306 307 308 309 310 311 312 313
      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 已提交
314
        int32_t code = catalogGetHandle(pReq->clusterId, &pCatalog);
D
dapan 已提交
315
        if (code != TSDB_CODE_SUCCESS) {
D
dapan1121 已提交
316
          tscWarn("catalogGetHandle failed, clusterId:%" PRIx64 ", error:%s", pReq->clusterId, tstrerror(code));
D
dapan 已提交
317 318 319
          break;
        }

K
kailixu 已提交
320
        hbProcessUserAuthInfoRsp(kv->value, kv->valueLen, pCatalog, pAppHbMgr);
D
dapan 已提交
321 322
        break;
      }
D
dapan1121 已提交
323 324 325 326 327 328 329
      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 已提交
330

D
dapan1121 已提交
331
        int32_t code = catalogGetHandle(pReq->clusterId, &pCatalog);
D
dapan1121 已提交
332
        if (code != TSDB_CODE_SUCCESS) {
D
dapan1121 已提交
333
          tscWarn("catalogGetHandle failed, clusterId:%" PRIx64 ", error:%s", pReq->clusterId, tstrerror(code));
D
dapan1121 已提交
334 335 336 337
          break;
        }

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

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

D
dapan1121 已提交
348
        int32_t code = catalogGetHandle(pReq->clusterId, &pCatalog);
D
dapan 已提交
349
        if (code != TSDB_CODE_SUCCESS) {
D
dapan1121 已提交
350
          tscWarn("catalogGetHandle failed, clusterId:%" PRIx64 ", error:%s", pReq->clusterId, tstrerror(code));
D
dapan 已提交
351 352 353 354
          break;
        }

        hbProcessStbInfoRsp(kv->value, kv->valueLen, pCatalog);
D
dapan1121 已提交
355
        break;
D
dapan 已提交
356
      }
D
dapan1121 已提交
357 358 359 360 361 362
      default:
        tscError("invalid hb key type:%d", kv->key);
        break;
    }
  }

D
dapan1121 已提交
363 364
  taosHashRelease(pAppHbMgr->activeInfo, pReq);

D
dapan1121 已提交
365 366 367
  return TSDB_CODE_SUCCESS;
}

D
dapan1121 已提交
368
static int32_t hbAsyncCallBack(void *param, SDataBuf *pMsg, int32_t code) {
D
dapan1121 已提交
369 370 371 372
  if (0 == atomic_load_8(&clientHbMgr.inited)) {
    goto _return;
  }

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

dengyihao's avatar
dengyihao 已提交
379 380 381 382 383 384
    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 已提交
385 386
  }

D
dapan1121 已提交
387
  int32_t rspNum = taosArrayGetSize(pRsp.rsps);
D
dapan1121 已提交
388

D
dapan1121 已提交
389
  taosThreadMutexLock(&clientHbMgr.lock);
D
dapan1121 已提交
390

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

D
dapan1121 已提交
401 402
  SAppInstInfo *pInst = pAppHbMgr->pAppInstInfo;

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

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

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

D
dapan1121 已提交
423
  taosThreadMutexUnlock(&clientHbMgr.lock);
D
dapan1121 已提交
424

D
dapan1121 已提交
425
  tFreeClientHbBatchRsp(&pRsp);
D
dapan1121 已提交
426 427

_return:
H
Haojun Liao 已提交
428
  taosMemoryFree(pMsg->pData);
dengyihao's avatar
dengyihao 已提交
429
  taosMemoryFree(pMsg->pEpSet);
D
dapan1121 已提交
430
  return code;
L
Liu Jicong 已提交
431 432
}

D
dapan1121 已提交
433
int32_t hbBuildQueryDesc(SQueryHbReqBasic *hbBasic, STscObj *pObj) {
L
Liu Jicong 已提交
434
  int64_t    now = taosGetTimestampUs();
D
dapan1121 已提交
435
  SQueryDesc desc = {0};
L
Liu Jicong 已提交
436
  int32_t    code = 0;
D
dapan1121 已提交
437

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

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

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

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

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

L
Liu Jicong 已提交
480
    releaseRequest(*rid);
D
dapan1121 已提交
481
    taosArrayPush(hbBasic->queryDesc, &desc);
L
Liu Jicong 已提交
482

D
dapan1121 已提交
483 484 485 486 487 488 489 490 491 492
    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 已提交
493
    return TSDB_CODE_APP_ERROR;
D
dapan1121 已提交
494
  }
L
Liu Jicong 已提交
495

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

503 504 505 506 507 508 509 510 511
  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 已提交
512 513 514 515 516 517

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

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

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

  return TSDB_CODE_SUCCESS;
}

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

  int32_t code = 0;

  SKv  kv = {.key = HEARTBEAT_KEY_USER_AUTHINFO};
  SKv *pKv = NULL;
  if ((pKv = taosHashGet(req->info, &kv.key, sizeof(kv.key)))) {
    int32_t           userNum = pKv->valueLen / sizeof(SUserAuthVersion);
K
kailixu 已提交
550
    SUserAuthVersion *userAuths = (SUserAuthVersion *)pKv->value;
K
kailixu 已提交
551
    for (int32_t i = 0; i < userNum; ++i) {
K
kailixu 已提交
552 553
      SUserAuthVersion *pUserAuth = userAuths + i;
      // both key and user exist, update version
K
kailixu 已提交
554
      if (strncmp(pUserAuth->user, pTscObj->user, TSDB_USER_LEN) == 0) {
K
kailixu 已提交
555
        pUserAuth->version = htonl(-1);  // force get userAuthInfo
K
kailixu 已提交
556 557 558
        goto _return;
      }
    }
K
kailixu 已提交
559
    // key exists, user not exist, append user
K
kailixu 已提交
560 561 562 563
    SUserAuthVersion *qUserAuth =
        (SUserAuthVersion *)taosMemoryRealloc(pKv->value, (userNum + 1) * sizeof(SUserAuthVersion));
    if (qUserAuth) {
      strncpy((qUserAuth + userNum)->user, pTscObj->user, TSDB_USER_LEN);
K
kailixu 已提交
564
      (qUserAuth + userNum)->version = htonl(-1);  // force get userAuthInfo
K
kailixu 已提交
565 566 567 568 569 570 571 572
      pKv->value = qUserAuth;
      pKv->valueLen += sizeof(SUserAuthVersion);
    } else {
      code = TSDB_CODE_OUT_OF_MEMORY;
    }
    goto _return;
  }

K
kailixu 已提交
573
  // key/user not exist, add user
K
kailixu 已提交
574 575 576 577 578 579
  SUserAuthVersion *user = taosMemoryMalloc(sizeof(SUserAuthVersion));
  if (!user) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _return;
  }
  strncpy(user->user, pTscObj->user, TSDB_USER_LEN);
K
kailixu 已提交
580
  user->version = htonl(-1);  // force get userAuthInfo
K
kailixu 已提交
581 582 583 584 585 586 587 588 589 590 591
  kv.valueLen = sizeof(SUserAuthVersion);
  kv.value = user;

  tscDebug("hb got user auth info, valueLen:%d, user:%s, authVer:%d, tscRid:%" PRIi64, kv.valueLen, user->user,
           pTscObj->authVer, connKey->tscRid);

  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) {
K
kailixu 已提交
592
    taosMemoryFree(user);
K
kailixu 已提交
593 594 595 596 597 598 599 600 601 602 603 604 605
    code = terrno ? terrno : TSDB_CODE_APP_ERROR;
    goto _return;
  }

_return:
  releaseTscObj(connKey->tscRid);
  if (code) {
    tscError("hb got user auth info failed since %s", terrstr(code));
  }

  return code;
}

D
dapan 已提交
606 607 608 609 610 611 612 613 614 615 616
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 已提交
617
    taosMemoryFree(users);
D
dapan 已提交
618
    return TSDB_CODE_SUCCESS;
K
kailixu 已提交
619 620
  } 

D
dapan 已提交
621 622 623 624 625 626 627 628 629 630 631 632 633
  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 已提交
634 635 636
  if (NULL == req->info) {
    req->info = taosHashInit(64, hbKeyHashFunc, 1, HASH_ENTRY_LOCK);
  }
637

D
dapan 已提交
638 639 640 641 642
  taosHashPut(req->info, &kv.key, sizeof(kv.key), &kv, sizeof(kv));

  return TSDB_CODE_SUCCESS;
}

D
dapan1121 已提交
643
int32_t hbGetExpiredDBInfo(SClientHbKey *connKey, struct SCatalog *pCatalog, SClientHbReq *req) {
D
dapan1121 已提交
644
  SDbCacheInfo *dbs = NULL;
L
fix  
Liu Jicong 已提交
645 646
  uint32_t      dbNum = 0;
  int32_t       code = 0;
D
dapan1121 已提交
647 648 649 650 651 652

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

D
dapan1121 已提交
653
  if (dbNum <= 0) {
D
dapan1121 已提交
654
    taosMemoryFree(dbs);
D
dapan1121 已提交
655 656 657
    return TSDB_CODE_SUCCESS;
  }

D
dapan1121 已提交
658
  for (int32_t i = 0; i < dbNum; ++i) {
D
dapan1121 已提交
659
    SDbCacheInfo *db = &dbs[i];
H
Haojun Liao 已提交
660
    tscDebug("the %dth expired dbFName:%s, dbId:%" PRId64 ", vgVersion:%d, cfgVersion:%d, numOfTable:%d, startTs:%" PRId64,
D
dapan1121 已提交
661
      i, db->dbFName, db->dbId, db->vgVersion, db->cfgVersion, db->numOfTable, db->stateTs);
D
dapan1121 已提交
662

D
dapan1121 已提交
663 664
    db->dbId = htobe64(db->dbId);
    db->vgVersion = htonl(db->vgVersion);
D
dapan1121 已提交
665
    db->cfgVersion = htonl(db->cfgVersion);
D
dapan 已提交
666
    db->numOfTable = htonl(db->numOfTable);
D
dapan1121 已提交
667
    db->stateTs = htobe64(db->stateTs);
D
dapan1121 已提交
668 669
  }

L
Liu Jicong 已提交
670 671
  SKv kv = {
      .key = HEARTBEAT_KEY_DBINFO,
D
dapan1121 已提交
672
      .valueLen = sizeof(SDbCacheInfo) * dbNum,
L
Liu Jicong 已提交
673 674
      .value = dbs,
  };
D
dapan1121 已提交
675 676 677

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

D
dapan1121 已提交
678 679 680 681
  if (NULL == req->info) {
    req->info = taosHashInit(64, hbKeyHashFunc, 1, HASH_ENTRY_LOCK);
  }

D
dapan1121 已提交
682 683 684 685 686
  taosHashPut(req->info, &kv.key, sizeof(kv.key), &kv, sizeof(kv));

  return TSDB_CODE_SUCCESS;
}

D
dapan 已提交
687
int32_t hbGetExpiredStbInfo(SClientHbKey *connKey, struct SCatalog *pCatalog, SClientHbReq *req) {
D
dapan1121 已提交
688
  SSTableVersion *stbs = NULL;
689 690
  uint32_t        stbNum = 0;
  int32_t         code = 0;
D
dapan 已提交
691 692 693 694 695 696 697

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

  if (stbNum <= 0) {
D
dapan1121 已提交
698
    taosMemoryFree(stbs);
D
dapan 已提交
699 700 701 702
    return TSDB_CODE_SUCCESS;
  }

  for (int32_t i = 0; i < stbNum; ++i) {
D
dapan1121 已提交
703
    SSTableVersion *stb = &stbs[i];
D
dapan 已提交
704 705
    stb->suid = htobe64(stb->suid);
    stb->sversion = htons(stb->sversion);
L
fix  
Liu Jicong 已提交
706
    stb->tversion = htons(stb->tversion);
D
dapan1121 已提交
707
    stb->smaVer = htonl(stb->smaVer);
D
dapan 已提交
708 709
  }

L
Liu Jicong 已提交
710 711
  SKv kv = {
      .key = HEARTBEAT_KEY_STBINFO,
D
dapan1121 已提交
712
      .valueLen = sizeof(SSTableVersion) * stbNum,
L
Liu Jicong 已提交
713 714
      .value = stbs,
  };
D
dapan 已提交
715 716 717

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

D
dapan1121 已提交
718 719 720 721
  if (NULL == req->info) {
    req->info = taosHashInit(64, hbKeyHashFunc, 1, HASH_ENTRY_LOCK);
  }

D
dapan 已提交
722 723 724 725 726
  taosHashPut(req->info, &kv.key, sizeof(kv.key), &kv, sizeof(kv));

  return TSDB_CODE_SUCCESS;
}

D
dapan1121 已提交
727
int32_t hbGetAppInfo(int64_t clusterId, SClientHbReq *req) {
728
  SAppHbReq *pApp = taosHashGet(clientHbMgr.appSummary, &clusterId, sizeof(clusterId));
D
dapan1121 已提交
729 730 731 732 733 734
  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;
735
    taosGetAppName(req->app.name, NULL);
D
dapan1121 已提交
736 737 738 739 740
  }

  return TSDB_CODE_SUCCESS;
}

K
kailixu 已提交
741
int32_t hbQueryHbReqHandle(SClientHbKey *connKey, void *param, SClientHbReq *req) {
742 743 744 745 746 747 748 749 750 751
  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 已提交
752
  }
L
fix  
Liu Jicong 已提交
753

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

D
dapan1121 已提交
756
  hbGetQueryBasicInfo(connKey, req);
L
Liu Jicong 已提交
757

K
kailixu 已提交
758
  if (hbParam->reqCnt == 0) {
K
kailixu 已提交
759
    if (!taosHashGet(clientHbMgr.appHbHash, &hbParam->clusterId, sizeof(hbParam->clusterId))) {
K
kailixu 已提交
760 761 762 763 764
      code = hbGetExpiredUserInfo(connKey, pCatalog, req);
      if (TSDB_CODE_SUCCESS != code) {
        return code;
      }
    }
K
kailixu 已提交
765

K
kailixu 已提交
766
    // invoke after hbGetExpiredUserInfo
K
kailixu 已提交
767
    if (2 != atomic_load_8(&hbParam->pAppHbMgr->connHbFlag)) {
K
kailixu 已提交
768 769 770 771
      code = hbGetUserAuthInfo(connKey, hbParam, req);
      if (TSDB_CODE_SUCCESS != code) {
        return code;
      }
K
kailixu 已提交
772
      atomic_store_8(&hbParam->pAppHbMgr->connHbFlag, 1);
773
    }
D
dapan 已提交
774

775 776 777 778
    code = hbGetExpiredDBInfo(connKey, pCatalog, req);
    if (TSDB_CODE_SUCCESS != code) {
      return code;
    }
D
dapan1121 已提交
779

780 781 782 783
    code = hbGetExpiredStbInfo(connKey, pCatalog, req);
    if (TSDB_CODE_SUCCESS != code) {
      return code;
    }
D
dapan 已提交
784
  }
K
kailixu 已提交
785
  ++hbParam->reqCnt;  // success to get catalog info
K
kailixu 已提交
786

D
dapan1121 已提交
787 788 789
  return TSDB_CODE_SUCCESS;
}

790 791
static FORCE_INLINE void hbMgrInitHandle() {
  // init all handle
D
dapan1121 已提交
792 793
  clientHbMgr.reqHandle[CONN_TYPE__QUERY] = hbQueryHbReqHandle;
  clientHbMgr.reqHandle[CONN_TYPE__TMQ] = hbMqHbReqHandle;
L
Liu Jicong 已提交
794

D
dapan1121 已提交
795 796
  clientHbMgr.rspHandle[CONN_TYPE__QUERY] = hbQueryHbRspHandle;
  clientHbMgr.rspHandle[CONN_TYPE__TMQ] = hbMqHbRspHandle;
L
Liu Jicong 已提交
797 798
}

L
fix  
Liu Jicong 已提交
799
SClientHbBatchReq *hbGatherAllInfo(SAppHbMgr *pAppHbMgr) {
wafwerar's avatar
wafwerar 已提交
800
  SClientHbBatchReq *pBatchReq = taosMemoryCalloc(1, sizeof(SClientHbBatchReq));
L
Liu Jicong 已提交
801
  if (pBatchReq == NULL) {
S
Shengliang Guan 已提交
802
    terrno = TSDB_CODE_OUT_OF_MEMORY;
L
Liu Jicong 已提交
803 804
    return NULL;
  }
L
Liu Jicong 已提交
805
  int32_t connKeyCnt = atomic_load_32(&pAppHbMgr->connKeyCnt);
L
Liu Jicong 已提交
806
  pBatchReq->reqs = taosArrayInit(connKeyCnt, sizeof(SClientHbReq));
807
  if (!pBatchReq->reqs) {
dengyihao's avatar
dengyihao 已提交
808 809 810
    tFreeClientHbBatchReq(pBatchReq);
    return NULL;
  }
D
dapan1121 已提交
811

K
kailixu 已提交
812
  void    *pIter = NULL;
K
kailixu 已提交
813
  SHbParam param = {.pAppHbMgr = pAppHbMgr};
K
kailixu 已提交
814 815 816 817 818 819 820 821
  while ((pIter = taosHashIterate(pAppHbMgr->activeInfo, pIter))) {
    SClientHbReq *pOneReq = pIter;
    SClientHbKey *connKey = &pOneReq->connKey;
    STscObj      *pTscObj = (STscObj *)acquireTscObj(connKey->tscRid);

    if (!pTscObj) {
      continue;
    }
822

dengyihao's avatar
dengyihao 已提交
823
    pOneReq = taosArrayPush(pBatchReq->reqs, pOneReq);
824

K
kailixu 已提交
825
    switch (connKey->connType) {
K
kailixu 已提交
826
      case CONN_TYPE__QUERY: {
827 828 829
        if (param.clusterId == 0) {
          // init
          param.clusterId = pOneReq->clusterId;
K
kailixu 已提交
830
          param.connHbFlag = atomic_load_8(&pAppHbMgr->connHbFlag);
831
        }
K
kailixu 已提交
832 833 834 835 836
        break;
      }
      default:
        break;
    }
K
kailixu 已提交
837 838
    if (clientHbMgr.reqHandle[connKey->connType]) {
      int32_t code = (*clientHbMgr.reqHandle[connKey->connType])(connKey, &param, pOneReq);
K
kailixu 已提交
839 840
      if (code) {
        tscWarn("hbGatherAllInfo failed since %s, tscRid:%" PRIi64 ", connType:%" PRIi8, tstrerror(code),
K
kailixu 已提交
841
                connKey->tscRid, connKey->connType);
K
kailixu 已提交
842 843
      }
    }
K
kailixu 已提交
844

K
kailixu 已提交
845
    releaseTscObj(connKey->tscRid);
L
Liu Jicong 已提交
846
  }
L
Liu Jicong 已提交
847

L
Liu Jicong 已提交
848
  return pBatchReq;
L
Liu Jicong 已提交
849 850
}

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

853
void hbMergeSummary(SAppClusterSummary *dst, SAppClusterSummary *src) {
D
dapan1121 已提交
854 855 856 857 858 859 860 861 862 863 864 865 866
  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};
867
  int       sz = taosArrayGetSize(clientHbMgr.appHbMgrs);
D
dapan1121 已提交
868 869 870 871 872
  if (sz > 0) {
    req.pid = taosGetPId();
    req.appId = clientHbMgr.appId;
    taosGetAppName(req.name, NULL);
  }
D
dapan1121 已提交
873 874

  taosHashClear(clientHbMgr.appSummary);
875

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

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

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

  return TSDB_CODE_SUCCESS;
}

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

wafwerar's avatar
wafwerar 已提交
910
    taosThreadMutexLock(&clientHbMgr.lock);
911

L
Liu Jicong 已提交
912
    int sz = taosArrayGetSize(clientHbMgr.appHbMgrs);
D
dapan1121 已提交
913 914
    if (sz > 0) {
      hbGatherAppInfo();
K
kailixu 已提交
915
      if (sz > 1 && !clientHbMgr.appHbHash) {
K
kailixu 已提交
916
        clientHbMgr.appHbHash = taosHashInit(0, taosGetDefaultHashFunction(TSDB_DATA_TYPE_UBIGINT), false, HASH_NO_LOCK);
K
kailixu 已提交
917
      }
K
kailixu 已提交
918
      taosHashClear(clientHbMgr.appHbHash);
D
dapan1121 已提交
919
    }
920

L
fix  
Liu Jicong 已提交
921 922
    for (int i = 0; i < sz; i++) {
      SAppHbMgr *pAppHbMgr = taosArrayGetP(clientHbMgr.appHbMgrs, i);
dengyihao's avatar
dengyihao 已提交
923 924 925
      if (pAppHbMgr == NULL) {
        continue;
      }
L
Liu Jicong 已提交
926

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

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

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

      SAppInstInfo *pAppInstInfo = pAppHbMgr->pAppInstInfo;
L
fix  
Liu Jicong 已提交
966 967
      int64_t       transporterId = 0;
      SEpSet        epSet = getEpSet_s(&pAppInstInfo->mgmtEp);
L
Liu Jicong 已提交
968
      asyncSendMsgToServer(pAppInstInfo->pTransporter, &epSet, &transporterId, pInfo);
D
dapan1121 已提交
969
      tFreeClientHbBatchReq(pReq);
dengyihao's avatar
dengyihao 已提交
970
      // hbClearReqInfo(pAppHbMgr);
K
kailixu 已提交
971
      taosHashPut(clientHbMgr.appHbHash, &pAppHbMgr->pAppInstInfo->clusterId, sizeof(uint64_t), NULL, 0);
L
Liu Jicong 已提交
972 973
      atomic_add_fetch_32(&pAppHbMgr->reportCnt, 1);
    }
974

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

L
Liu Jicong 已提交
977
    taosMsleep(HEARTBEAT_INTERVAL);
L
Liu Jicong 已提交
978 979 980 981 982
  }
  return NULL;
}

static int32_t hbCreateThread() {
wafwerar's avatar
wafwerar 已提交
983 984 985
  TdThreadAttr thAttr;
  taosThreadAttrInit(&thAttr);
  taosThreadAttrSetDetachState(&thAttr, PTHREAD_CREATE_JOINABLE);
L
Liu Jicong 已提交
986

D
dapan1121 已提交
987 988 989
  if (taosThreadCreate(&clientHbMgr.thread, &thAttr, hbThreadFunc, NULL) != 0) {
    terrno = TAOS_SYSTEM_ERROR(errno);
    return -1;
L
Liu Jicong 已提交
990
  }
D
dapan1121 已提交
991
  taosThreadAttrDestroy(&thAttr);
L
Liu Jicong 已提交
992 993 994
  return 0;
}

L
Liu Jicong 已提交
995
static void hbStopThread() {
D
dapan1121 已提交
996 997 998
  if (0 == atomic_load_8(&clientHbMgr.inited)) {
    return;
  }
999
  if (atomic_val_compare_exchange_8(&clientHbMgr.threadStop, 0, 1)) {
D
dapan1121 已提交
1000
    tscDebug("hb thread already stopped");
1001 1002
    return;
  }
L
fix  
Liu Jicong 已提交
1003

1004 1005 1006 1007 1008 1009
  // thread quit mode kill or inner exit from self-thread
  if (clientHbMgr.quitByKill) {
    taosThreadKill(clientHbMgr.thread, 0);
  } else {
    taosThreadJoin(clientHbMgr.thread, NULL);
  }
D
dapan1121 已提交
1010

L
fix  
Liu Jicong 已提交
1011
  tscDebug("hb thread stopped");
L
Liu Jicong 已提交
1012 1013
}

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

L
Liu Jicong 已提交
1032 1033
  // init app info
  pAppHbMgr->pAppInstInfo = pAppInstInfo;
L
Liu Jicong 已提交
1034 1035 1036

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

  if (pAppHbMgr->activeInfo == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
wafwerar's avatar
wafwerar 已提交
1040
    taosMemoryFree(pAppHbMgr);
L
Liu Jicong 已提交
1041 1042
    return NULL;
  }
H
Haojun Liao 已提交
1043

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

wafwerar's avatar
wafwerar 已提交
1046
  taosThreadMutexLock(&clientHbMgr.lock);
L
Liu Jicong 已提交
1047
  taosArrayPush(clientHbMgr.appHbMgrs, &pAppHbMgr);
D
dapan1121 已提交
1048
  pAppHbMgr->idx = taosArrayGetSize(clientHbMgr.appHbMgrs) - 1;
wafwerar's avatar
wafwerar 已提交
1049
  taosThreadMutexUnlock(&clientHbMgr.lock);
L
fix  
Liu Jicong 已提交
1050

L
Liu Jicong 已提交
1051 1052 1053
  return pAppHbMgr;
}

D
dapan1121 已提交
1054 1055 1056 1057 1058 1059 1060 1061 1062
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;
1063

D
dapan1121 已提交
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
  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 已提交
1076
      taosArraySet(clientHbMgr.appHbMgrs, i, pAppHbMgr);
D
dapan1121 已提交
1077 1078 1079 1080 1081 1082
      break;
    }
  }
  taosThreadMutexUnlock(&clientHbMgr.lock);
}

D
dapan1121 已提交
1083
void appHbMgrCleanup(void) {
L
Liu Jicong 已提交
1084 1085
  int sz = taosArrayGetSize(clientHbMgr.appHbMgrs);
  for (int i = 0; i < sz; i++) {
L
fix  
Liu Jicong 已提交
1086
    SAppHbMgr *pTarget = taosArrayGetP(clientHbMgr.appHbMgrs, i);
dengyihao's avatar
dengyihao 已提交
1087
    if (pTarget == NULL) continue;
D
dapan1121 已提交
1088
    hbFreeAppHbMgr(pTarget);
L
Liu Jicong 已提交
1089
  }
K
kailixu 已提交
1090 1091
  clientHbMgr.appHbMgrs = taosArrayDestroy(clientHbMgr.appHbMgrs);
  taosHashCleanup(clientHbMgr.appSummary);
K
kailixu 已提交
1092
  taosHashCleanup(clientHbMgr.appHbHash);
K
kailixu 已提交
1093
  clientHbMgr.appSummary = NULL;
K
kailixu 已提交
1094
  clientHbMgr.appHbHash = NULL;
L
Liu Jicong 已提交
1095 1096 1097
}

int hbMgrInit() {
L
Liu Jicong 已提交
1098 1099 1100 1101
  // init once
  int8_t old = atomic_val_compare_exchange_8(&clientHbMgr.inited, 0, 1);
  if (old == 1) return 0;

D
dapan1121 已提交
1102 1103
  clientHbMgr.appId = tGenIdPI64();
  tscDebug("app %" PRIx64 " initialized", clientHbMgr.appId);
1104

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

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

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

dengyihao's avatar
dengyihao 已提交
1115
  ret = taosThreadMutexAttrSetType(&attr, PTHREAD_MUTEX_RECURSIVE);
1116 1117
  if (ret != 0) {
    uError("hbMgrInit:taosThreadMutexAttrSetType error") return ret;
1118
  }
dengyihao's avatar
dengyihao 已提交
1119 1120

  ret = taosThreadMutexInit(&clientHbMgr.lock, &attr);
1121 1122
  if (ret != 0) {
    uError("hbMgrInit:taosThreadMutexInit error") return ret;
1123
  }
dengyihao's avatar
dengyihao 已提交
1124 1125

  ret = taosThreadMutexAttrDestroy(&attr);
1126 1127
  if (ret != 0) {
    uError("hbMgrInit:taosThreadMutexAttrDestroy error") return ret;
1128
  }
L
Liu Jicong 已提交
1129 1130 1131 1132 1133

  // init handle funcs
  hbMgrInitHandle();

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

L
Liu Jicong 已提交
1136 1137 1138 1139
  return 0;
}

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

L
Liu Jicong 已提交
1142
  // destroy all appHbMgr
L
Liu Jicong 已提交
1143 1144 1145
  int8_t old = atomic_val_compare_exchange_8(&clientHbMgr.inited, 1, 0);
  if (old == 0) return;

wafwerar's avatar
wafwerar 已提交
1146
  taosThreadMutexLock(&clientHbMgr.lock);
D
dapan1121 已提交
1147
  appHbMgrCleanup();
wafwerar's avatar
wafwerar 已提交
1148
  taosThreadMutexUnlock(&clientHbMgr.lock);
L
Liu Jicong 已提交
1149 1150
}

D
dapan1121 已提交
1151
int hbRegisterConnImpl(SAppHbMgr *pAppHbMgr, SClientHbKey connKey, int64_t clusterId) {
L
Liu Jicong 已提交
1152
  // init hash in activeinfo
L
fix  
Liu Jicong 已提交
1153
  void *data = taosHashGet(pAppHbMgr->activeInfo, &connKey, sizeof(SClientHbKey));
L
Liu Jicong 已提交
1154 1155 1156
  if (data != NULL) {
    return 0;
  }
D
dapan1121 已提交
1157
  SClientHbReq hbReq = {0};
L
Liu Jicong 已提交
1158
  hbReq.connKey = connKey;
D
dapan1121 已提交
1159
  hbReq.clusterId = clusterId;
1160
  // hbReq.info = taosHashInit(64, hbKeyHashFunc, 1, HASH_ENTRY_LOCK);
L
fix  
Liu Jicong 已提交
1161

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

L
Liu Jicong 已提交
1164
  atomic_add_fetch_32(&pAppHbMgr->connKeyCnt, 1);
L
Liu Jicong 已提交
1165 1166 1167
  return 0;
}

D
dapan1121 已提交
1168
int hbRegisterConn(SAppHbMgr *pAppHbMgr, int64_t tscRefId, int64_t clusterId, int8_t connType) {
L
Liu Jicong 已提交
1169
  SClientHbKey connKey = {
D
dapan1121 已提交
1170
      .tscRid = tscRefId,
D
dapan1121 已提交
1171
      .connType = connType,
L
Liu Jicong 已提交
1172
  };
D
dapan1121 已提交
1173

D
dapan1121 已提交
1174 1175
  switch (connType) {
    case CONN_TYPE__QUERY: {
D
dapan1121 已提交
1176
      return hbRegisterConnImpl(pAppHbMgr, connKey, clusterId);
D
dapan1121 已提交
1177
    }
D
dapan1121 已提交
1178
    case CONN_TYPE__TMQ: {
L
Liu Jicong 已提交
1179
      return 0;
D
dapan1121 已提交
1180 1181
    }
    default:
L
Liu Jicong 已提交
1182
      return 0;
D
dapan1121 已提交
1183 1184 1185
  }
}

K
kailixu 已提交
1186 1187
void hbDeregisterConn(STscObj *pTscObj, SClientHbKey connKey) {
  SAppHbMgr    *pAppHbMgr = pTscObj->pAppInfo->pAppHbMgr;
D
dapan1121 已提交
1188
  SClientHbReq *pReq = taosHashAcquire(pAppHbMgr->activeInfo, &connKey, sizeof(SClientHbKey));
D
dapan1121 已提交
1189
  if (pReq) {
D
dapan1121 已提交
1190
    tFreeClientHbReq(pReq);
D
dapan1121 已提交
1191
    taosHashRemove(pAppHbMgr->activeInfo, &connKey, sizeof(SClientHbKey));
D
dapan1121 已提交
1192
    taosHashRelease(pAppHbMgr->activeInfo, pReq);
D
dapan1121 已提交
1193 1194
  }

D
dapan1121 已提交
1195
  if (NULL == pReq) {
D
dapan1121 已提交
1196 1197
    return;
  }
L
Liu Jicong 已提交
1198

L
Liu Jicong 已提交
1199
  atomic_sub_fetch_32(&pAppHbMgr->connKeyCnt, 1);
L
Liu Jicong 已提交
1200
}
1201 1202 1203 1204 1205

// set heart beat thread quit mode , if quicByKill 1 then kill thread else quit from inner
void taos_set_hb_quit(int8_t quitByKill) {
  clientHbMgr.quitByKill = quitByKill;
}