4dnode1mnode_basic_replica3_insertdatas_stop_leader.py 14.7 KB
Newer Older
1 2 3 4 5
# author : wenzhouwww
from ssl import ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE
import taos
import sys
import time
G
Ganlin Zhao 已提交
6
import os
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

from util.log import *
from util.sql import *
from util.cases import *
from util.dnodes import TDDnodes
from util.dnodes import TDDnode
from util.cluster import *

import time
import socket
import subprocess
import threading
sys.path.append(os.path.dirname(__file__))

class TDTestCase:
22
    def init(self, conn, logSql, replicaVar=1):
23
        self.replicaVar = int(replicaVar)
24 25 26 27 28 29 30 31
        tdLog.debug(f"start to excute {__file__}")
        tdSql.init(conn.cursor())
        self.host = socket.gethostname()
        self.mnode_list = {}
        self.dnode_list = {}
        self.ts = 1483200000000
        self.ts_step =1000
        self.db_name ='testdb'
G
Ganlin Zhao 已提交
32
        self.replica = 3
33
        self.vgroups = 1
G
Ganlin Zhao 已提交
34
        self.tb_nums = 10
35 36
        self.row_nums = 100
        self.stop_dnode_id = None
37
        self.loop_restart_times = 10
38
        self.current_thread = None
39
        self.max_restart_time = 5
40 41 42 43 44 45 46 47 48

    def getBuildPath(self):
        selfPath = os.path.dirname(os.path.realpath(__file__))
        if ("community" in selfPath):
            projPath = selfPath[:selfPath.find("community")]
        else:
            projPath = selfPath[:selfPath.find("tests")]

        for root, dirs, files in os.walk(projPath):
haoranc's avatar
haoranc 已提交
49
            if ("taosd" in files or "taosd.exe" in files):
50 51 52 53 54 55
                rootRealPath = os.path.dirname(os.path.realpath(root))
                if ("packaging" not in rootRealPath):
                    buildPath = root[:len(root) - len("/build/bin")]
                    break
        return buildPath

56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
    def _parse_datetime(self,timestr):
        try:
            return datetime.datetime.strptime(timestr, '%Y-%m-%d %H:%M:%S.%f')
        except ValueError:
            pass
        try:
            return datetime.datetime.strptime(timestr, '%Y-%m-%d %H:%M:%S')
        except ValueError:
            pass

    def mycheckRowCol(self, sql, row, col):
        caller = inspect.getframeinfo(inspect.stack()[2][0])
        if row < 0:
            args = (caller.filename, caller.lineno, sql, row)
            tdLog.exit("%s(%d) failed: sql:%s, row:%d is smaller than zero" % args)
        if col < 0:
            args = (caller.filename, caller.lineno, sql, row)
            tdLog.exit("%s(%d) failed: sql:%s, col:%d is smaller than zero" % args)
        if row > tdSql.queryRows:
            args = (caller.filename, caller.lineno, sql, row, tdSql.queryRows)
            tdLog.exit("%s(%d) failed: sql:%s, row:%d is larger than queryRows:%d" % args)
        if col > tdSql.queryCols:
            args = (caller.filename, caller.lineno, sql, col, tdSql.queryCols)
            tdLog.exit("%s(%d) failed: sql:%s, col:%d is larger than queryCols:%d" % args)

    def mycheckData(self, sql ,row, col, data):
        check_status = True
        self.mycheckRowCol(sql ,row, col)
        if tdSql.queryResult[row][col] != data:
            if tdSql.cursor.istype(col, "TIMESTAMP"):
                # suppose user want to check nanosecond timestamp if a longer data passed
                if (len(data) >= 28):
                    if pd.to_datetime(tdSql.queryResult[row][col]) == pd.to_datetime(data):
                        tdLog.info("sql:%s, row:%d col:%d data:%d == expect:%s" %
                            (sql, row, col, tdSql.queryResult[row][col], data))
                else:
                    if tdSql.queryResult[row][col] == self._parse_datetime(data):
                        tdLog.info("sql:%s, row:%d col:%d data:%s == expect:%s" %
                            (sql, row, col, tdSql.queryResult[row][col], data))
                return

            if str(tdSql.queryResult[row][col]) == str(data):
                tdLog.info("sql:%s, row:%d col:%d data:%s == expect:%s" %
                            (sql, row, col, tdSql.queryResult[row][col], data))
                return
            elif isinstance(data, float) and abs(tdSql.queryResult[row][col] - data) <= 0.000001:
                tdLog.info("sql:%s, row:%d col:%d data:%f == expect:%f" %
                            (sql, row, col, tdSql.queryResult[row][col], data))
                return
            else:
                caller = inspect.getframeinfo(inspect.stack()[1][0])
                args = (caller.filename, caller.lineno, sql, row, col, tdSql.queryResult[row][col], data)
                tdLog.info("%s(%d) failed: sql:%s row:%d col:%d data:%s != expect:%s" % args)

                check_status = False

        if data is None:
            tdLog.info("sql:%s, row:%d col:%d data:%s == expect:%s" %
                       (sql, row, col, tdSql.queryResult[row][col], data))
        elif isinstance(data, str):
            tdLog.info("sql:%s, row:%d col:%d data:%s == expect:%s" %
                       (sql, row, col, tdSql.queryResult[row][col], data))
118 119 120
        # elif isinstance(data, datetime.date):
        #     tdLog.info("sql:%s, row:%d col:%d data:%s == expect:%s" %
        #                (sql, row, col, tdSql.queryResult[row][col], data))
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
        elif isinstance(data, float):
            tdLog.info("sql:%s, row:%d col:%d data:%s == expect:%s" %
                       (sql, row, col, tdSql.queryResult[row][col], data))
        else:
            tdLog.info("sql:%s, row:%d col:%d data:%s == expect:%d" %
                       (sql, row, col, tdSql.queryResult[row][col], data))

        return check_status

    def mycheckRows(self, sql, expectRows):
        check_status = True
        if len(tdSql.queryResult) == expectRows:
            tdLog.info("sql:%s, queryRows:%d == expect:%d" % (sql, len(tdSql.queryResult), expectRows))
            return True
        else:
            caller = inspect.getframeinfo(inspect.stack()[1][0])
            args = (caller.filename, caller.lineno, sql, len(tdSql.queryResult), expectRows)
            tdLog.info("%s(%d) failed: sql:%s, queryRows:%d != expect:%d" % args)
            check_status = False
        return check_status

142
    def check_setup_cluster_status(self):
X
Xiaoyu Wang 已提交
143
        tdSql.query("select * from information_schema.ins_mnodes")
144 145 146 147 148
        for mnode in tdSql.queryResult:
            name = mnode[1]
            info = mnode
            self.mnode_list[name] = info

X
Xiaoyu Wang 已提交
149
        tdSql.query("select * from information_schema.ins_dnodes")
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
        for dnode in tdSql.queryResult:
            name = dnode[1]
            info = dnode
            self.dnode_list[name] = info

        count = 0
        is_leader = False
        mnode_name = ''
        for k,v in self.mnode_list.items():
            count +=1
            # only for 1 mnode
            mnode_name = k

            if v[2] =='leader':
                is_leader=True

        if count==1 and is_leader:
167
            tdLog.notice("===== depoly cluster success with 1 mnode as leader =====")
168
        else:
W
wenzhouwww 已提交
169
            tdLog.notice("===== depoly cluster fail with 1 mnode as leader =====")
170 171 172 173

        for k ,v in self.dnode_list.items():
            if k == mnode_name:
                if v[3]==0:
174
                    tdLog.notice("===== depoly cluster mnode only success at {} , support_vnodes is {} ".format(mnode_name,v[3]))
175
                else:
W
wenzhouwww 已提交
176
                    tdLog.notice("===== depoly cluster mnode only fail at {} , support_vnodes is {} ".format(mnode_name,v[3]))
177 178 179
            else:
                continue

180

181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
    def _get_stop_dnode_id(self,dbname ,dnode_role):
        tdSql.query("show {}.vgroups".format(dbname))
        vgroup_infos = tdSql.queryResult
        status = False
        for vgroup_info in vgroup_infos:
            if "error" not in vgroup_info:
                status = True
            else:
                status = False
        while status!=True :
            time.sleep(0.1)
            tdSql.query("show {}.vgroups".format(dbname))
            vgroup_infos = tdSql.queryResult
            for vgroup_info in vgroup_infos:
                if "error" not in vgroup_info:
                    status = True
                else:
                    status = False
            # print(status)
200
        for vgroup_info in vgroup_infos:
G
Ganlin Zhao 已提交
201
            leader_infos = vgroup_info[3:-4]
202 203
            # print(vgroup_info)
            for ind ,role in enumerate(leader_infos):
204
                if role == dnode_role:
205 206 207 208 209 210
                    # print(ind,leader_infos)
                    self.stop_dnode_id = leader_infos[ind-1]
                    break

        return self.stop_dnode_id

211
    def wait_stop_dnode_OK(self , newTdSql):
212 213
    
        def _get_status():
214
            # newTdSql=tdCom.newTdSql()
215 216

            status =  ""
X
Xiaoyu Wang 已提交
217
            newTdSql.query("select * from information_schema.ins_dnodes")
218 219 220 221 222 223 224
            dnode_infos = newTdSql.queryResult
            for dnode_info in dnode_infos:
                id = dnode_info[0]
                dnode_status = dnode_info[4]
                if id == self.stop_dnode_id:
                    status = dnode_status
                    break
G
Ganlin Zhao 已提交
225
            return status
226 227 228 229 230

        status = _get_status()
        while status !="offline":
            time.sleep(0.1)
            status = _get_status()
231 232
            # tdLog.notice("==== stop dnode has not been stopped , endpoint is {}".format(self.stop_dnode))
        tdLog.notice("==== stop_dnode has stopped , id is {}".format(self.stop_dnode_id))
233

234
    def wait_start_dnode_OK(self,newTdSql):
235 236
    
        def _get_status():
237
            # newTdSql=tdCom.newTdSql()
238
            status =  ""
X
Xiaoyu Wang 已提交
239
            newTdSql.query("select * from information_schema.ins_dnodes")
240 241 242 243 244 245 246
            dnode_infos = newTdSql.queryResult
            for dnode_info in dnode_infos:
                id = dnode_info[0]
                dnode_status = dnode_info[4]
                if id == self.stop_dnode_id:
                    status = dnode_status
                    break
G
Ganlin Zhao 已提交
247
            return status
248 249 250 251 252

        status = _get_status()
        while status !="ready":
            time.sleep(0.1)
            status = _get_status()
253 254
            # tdLog.notice("==== stop dnode has not been stopped , endpoint is {}".format(self.stop_dnode))
        tdLog.notice("==== stop_dnode has restart , id is {}".format(self.stop_dnode_id))
255

256
    def get_leader_infos(self ,dbname):
G
Ganlin Zhao 已提交
257

258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
        newTdSql=tdCom.newTdSql()
        newTdSql.query("show {}.vgroups".format(dbname))
        vgroup_infos = newTdSql.queryResult

        leader_infos = set()
        for vgroup_info in vgroup_infos:
            leader_infos.add(vgroup_info[3:-4])

        return leader_infos

    def check_revote_leader_success(self, dbname, before_leader_infos , after_leader_infos):
        check_status = False
        vote_act = set(set(after_leader_infos)-set(before_leader_infos))
        if not vote_act:
            print("=======before_revote_leader_infos ======\n" , before_leader_infos)
            print("=======after_revote_leader_infos ======\n" , after_leader_infos)
W
wenzhouwww@live.cn 已提交
274
            tdLog.info(" ===maybe revote not occured , there is no dnode offline ====")
275 276
        else:
            for vgroup_info in vote_act:
G
Ganlin Zhao 已提交
277
                for ind , role in enumerate(vgroup_info):
278 279 280
                    if role==self.stop_dnode_id:

                        if vgroup_info[ind+1] =="offline" and "leader" in vgroup_info:
281
                            tdLog.notice(" === revote leader ok , leader is {} now   ====".format(vgroup_info[list(vgroup_info).index("leader")-1]))
282 283
                            check_status = True
                        elif vgroup_info[ind+1] !="offline":
284
                            tdLog.notice(" === dnode {} should be offline ".format(self.stop_dnode_id))
285 286 287 288 289
                        else:
                            continue
                        break
        return check_status

W
wenzhouwww 已提交
290
    def start_benchmark_inserts(self):
291
        benchmark_build_path = self.getBuildPath() + '/build/bin/taosBenchmark'
W
wenzhouwww 已提交
292 293
        tdLog.notice("==== start taosBenchmark insert datas of database test ==== ")
        os.system(" {} -y -n 10000 -t 100  ".format(benchmark_build_path))
G
Ganlin Zhao 已提交
294

W
wenzhouwww 已提交
295
    def stop_leader_when_Benchmark_inserts(self,dbname , total_rows ):
W
wenzhouwww@live.cn 已提交
296 297 298

        newTdSql=tdCom.newTdSql()
        
299 300
        # stop follower and insert datas , update tables and create new stables
        tdDnodes=cluster.dnodes
301 302
        tdSql.execute(" drop database if exists {} ".format(dbname))
        tdSql.execute(" create database {} replica {} vgroups {}".format(dbname , self.replica , self.vgroups))
G
Ganlin Zhao 已提交
303 304

        # start insert datas using taosBenchmark ,expect insert 10000 rows
W
wenzhouwww 已提交
305 306
        time.sleep(3)
        self.current_thread = threading.Thread(target=self.start_benchmark_inserts, args=())
307
        self.current_thread.start()
X
Xiaoyu Wang 已提交
308
        tdSql.query(" select * from information_schema.ins_databases ")
G
Ganlin Zhao 已提交
309

W
wenzhouwww 已提交
310
        tdSql.query(" select count(*) from {}.{} ".format(dbname,"meters"))
311 312

        while not tdSql.queryResult:
W
wenzhouwww 已提交
313
            tdSql.query(" select count(*) from {}.{} ".format(dbname,"meters"))
314 315 316 317 318 319
        tdLog.debug(" === current insert  {} rows in database {} === ".format(tdSql.queryResult[0][0] , dbname))

        while (tdSql.queryResult[0][0] < total_rows/10):
            if tdSql.queryResult:
                tdLog.debug(" === current insert  {} rows in database {} === ".format(tdSql.queryResult[0][0] , dbname))
            time.sleep(0.01)
W
wenzhouwww 已提交
320
            tdSql.query(" select count(*) from {}.{} ".format(dbname,"meters"))
G
Ganlin Zhao 已提交
321

322 323
        tdLog.debug(" === database {} has write {} rows at least ====".format(dbname,total_rows/10))

324
        self.stop_dnode_id = self._get_stop_dnode_id(dbname ,"leader")
325

G
Ganlin Zhao 已提交
326
        # prepare stop leader of database
327
        before_leader_infos = self.get_leader_infos(dbname)
G
Ganlin Zhao 已提交
328

329
        tdDnodes[self.stop_dnode_id-1].stoptaosd()
W
wenzhouwww 已提交
330
        os.system("taos -s 'show dnodes;'")
331 332 333
        # self.current_thread.join()
        after_leader_infos = self.get_leader_infos(dbname)

W
wenzhouwww 已提交
334 335 336 337 338 339 340 341
        # start = time.time()
        # revote_status = self.check_revote_leader_success(dbname ,before_leader_infos , after_leader_infos)
        # while not revote_status:
        #     after_leader_infos = self.get_leader_infos(dbname)
        #     revote_status = self.check_revote_leader_success(dbname ,before_leader_infos , after_leader_infos)
        # end = time.time()
        # time_cost = end - start
        # tdLog.debug(" ==== revote leader of database {} cost time {}  ====".format(dbname , time_cost))
342 343

        self.current_thread.join()
W
wenzhouwww 已提交
344
        time.sleep(2)
345
        tdDnodes[self.stop_dnode_id-1].starttaosd()
W
wenzhouwww@live.cn 已提交
346
        self.wait_start_dnode_OK(newTdSql)
W
update  
wenzhouwww@live.cn 已提交
347
        
348

W
wenzhouwww 已提交
349
        tdSql.query(" select count(*) from {}.{} ".format(dbname,"meters"))
350 351
        tdLog.debug(" ==== expected insert  {} rows of database {}  , really is {}".format(total_rows, dbname , tdSql.queryResult[0][0]))

352 353


G
Ganlin Zhao 已提交
354
    def run(self):
355 356

        # basic insert and check of cluster
357
        # self.check_setup_cluster_status()
W
wenzhouwww 已提交
358 359
        self.stop_leader_when_Benchmark_inserts('test' , 1000000 )
      
360 361 362 363 364 365

    def stop(self):
        tdSql.close()
        tdLog.success(f"{__file__} successfully executed")

tdCases.addLinux(__file__, TDTestCase())
G
Ganlin Zhao 已提交
366
tdCases.addWindows(__file__, TDTestCase())