test.py 12.8 KB
Newer Older
P
plum-lihui 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#!/usr/bin/python
###################################################################
#           Copyright (c) 2016 by TAOS Technologies, Inc.
#                     All rights reserved.
#
#  This file is proprietary and confidential to TAOS Technologies.
#  No part of this file may be reproduced, stored, transmitted,
#  disclosed or used in any form or by any means other than as
#  expressly provided by the written permission from Jianhui Tao
#
###################################################################
# install pip
# pip install src/connector/python/

# -*- coding: utf-8 -*-
import sys
import getopt
import subprocess
import time
wafwerar's avatar
wafwerar 已提交
20 21
import base64
import json
wafwerar's avatar
wafwerar 已提交
22
import platform
wafwerar's avatar
wafwerar 已提交
23
import socket
wafwerar's avatar
wafwerar 已提交
24
import threading
P
plum-lihui 已提交
25 26 27 28
sys.path.append("../pytest")
from util.log import *
from util.dnodes import *
from util.cases import *
haoranc's avatar
haoranc 已提交
29
from util.cluster import *
P
plum-lihui 已提交
30 31 32

import taos

wafwerar's avatar
wafwerar 已提交
33 34
def checkRunTimeError():
    import win32gui
wafwerar's avatar
wafwerar 已提交
35
    timeCount = 0
wafwerar's avatar
wafwerar 已提交
36 37
    while 1:
        time.sleep(1)
wafwerar's avatar
wafwerar 已提交
38
        timeCount = timeCount + 1
wafwerar's avatar
wafwerar 已提交
39
        print("checkRunTimeError",timeCount)
wafwerar's avatar
wafwerar 已提交
40
        if (timeCount>900):
wafwerar's avatar
wafwerar 已提交
41
            print("stop the test.")
wafwerar's avatar
wafwerar 已提交
42 43 44
            os.system("TASKKILL /F /IM taosd.exe")
            os.system("TASKKILL /F /IM taos.exe")
            os.system("TASKKILL /F /IM tmq_sim.exe")
wafwerar's avatar
wafwerar 已提交
45
            os.system("TASKKILL /F /IM mintty.exe")
wafwerar's avatar
wafwerar 已提交
46
            quit(0)
wafwerar's avatar
wafwerar 已提交
47 48 49
        hwnd = win32gui.FindWindow(None, "Microsoft Visual C++ Runtime Library")
        if hwnd:
            os.system("TASKKILL /F /IM taosd.exe")
P
plum-lihui 已提交
50 51 52 53 54 55 56 57

if __name__ == "__main__":
    
    fileName = "all"
    deployPath = ""
    masterIp = ""
    testCluster = False
    valgrind = 0
58
    killValgrind = 1
P
plum-lihui 已提交
59 60 61
    logSql = True
    stop = 0
    restart = False
62
    dnodeNums = 1
haoranc's avatar
haoranc 已提交
63
    mnodeNums = 0
wafwerar's avatar
wafwerar 已提交
64
    updateCfgDict = {}
wafwerar's avatar
wafwerar 已提交
65
    execCmd = ""
haoranc's avatar
haoranc 已提交
66 67 68
    queryPolicy = 1
    opts, args = getopt.gnu_getopt(sys.argv[1:], 'f:p:m:l:scghrd:k:e:N:M:Q:', [
        'file=', 'path=', 'master', 'logSql', 'stop', 'cluster', 'valgrind', 'help', 'restart', 'updateCfgDict', 'killv', 'execCmd','dnodeNums','mnodeNums','queryPolicy'])
P
plum-lihui 已提交
69 70 71 72 73 74 75 76 77 78 79 80
    for key, value in opts:
        if key in ['-h', '--help']:
            tdLog.printNoPrefix(
                'A collection of test cases written using Python')
            tdLog.printNoPrefix('-f Name of test case file written by Python')
            tdLog.printNoPrefix('-p Deploy Path for Simulator')
            tdLog.printNoPrefix('-m Master Ip for Simulator')
            tdLog.printNoPrefix('-l <True:False> logSql Flag')
            tdLog.printNoPrefix('-s stop All dnodes')
            tdLog.printNoPrefix('-c Test Cluster Flag')
            tdLog.printNoPrefix('-g valgrind Test Flag')
            tdLog.printNoPrefix('-r taosd restart test')
wafwerar's avatar
wafwerar 已提交
81
            tdLog.printNoPrefix('-d update cfg dict, base64 json str')
82
            tdLog.printNoPrefix('-k not kill valgrind processer')
wafwerar's avatar
wafwerar 已提交
83
            tdLog.printNoPrefix('-e eval str to run')
haoranc's avatar
haoranc 已提交
84 85
            tdLog.printNoPrefix('-N create dnodes numbers in clusters')
            tdLog.printNoPrefix('-M create mnode numbers in clusters')
haoranc's avatar
haoranc 已提交
86
            tdLog.printNoPrefix('-Q set queryPolicy in one dnode')
haoranc's avatar
haoranc 已提交
87

P
plum-lihui 已提交
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 118 119
            sys.exit(0)

        if key in ['-r', '--restart']: 
            restart = True

        if key in ['-f', '--file']:
            fileName = value

        if key in ['-p', '--path']:
            deployPath = value

        if key in ['-m', '--master']:
            masterIp = value

        if key in ['-l', '--logSql']:
            if (value.upper() == "TRUE"):
                logSql = True
            elif (value.upper() == "FALSE"):
                logSql = False
            else:
                tdLog.printNoPrefix("logSql value %s is invalid" % logSql)
                sys.exit(0)

        if key in ['-c', '--cluster']:
            testCluster = True

        if key in ['-g', '--valgrind']:
            valgrind = 1

        if key in ['-s', '--stop']:
            stop = 1

wafwerar's avatar
wafwerar 已提交
120 121 122 123 124 125
        if key in ['-d', '--updateCfgDict']:
            try:
                updateCfgDict = eval(base64.b64decode(value.encode()).decode())
            except:
                print('updateCfgDict convert fail.')
                sys.exit(0)
wafwerar's avatar
wafwerar 已提交
126

127 128 129
        if key in ['-k', '--killValgrind']:
            killValgrind = 0

wafwerar's avatar
wafwerar 已提交
130 131 132 133 134 135 136
        if key in ['-e', '--execCmd']:
            try:
                execCmd = base64.b64decode(value.encode()).decode()
            except:
                print('updateCfgDict convert fail.')
                sys.exit(0)

haoranc's avatar
haoranc 已提交
137 138 139
        if key in ['-N', '--dnodeNums']:
            dnodeNums = value

haoranc's avatar
haoranc 已提交
140 141 142
        if key in ['-M', '--mnodeNums']:
            mnodeNums = value

haoranc's avatar
haoranc 已提交
143 144 145
        if key in ['-Q', '--queryPolicy']:
            queryPolicy = value

wafwerar's avatar
wafwerar 已提交
146 147
    if not execCmd == "":
        tdDnodes.init(deployPath)
wafwerar's avatar
wafwerar 已提交
148
        print(execCmd)
wafwerar's avatar
wafwerar 已提交
149 150 151
        exec(execCmd)
        quit()

P
plum-lihui 已提交
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
    if (stop != 0):
        if (valgrind == 0):
            toBeKilled = "taosd"
        else:
            toBeKilled = "valgrind.bin"

        killCmd = "ps -ef|grep -w %s| grep -v grep | awk '{print $2}' | xargs kill -TERM > /dev/null 2>&1" % toBeKilled

        psCmd = "ps -ef|grep -w %s| grep -v grep | awk '{print $2}'" % toBeKilled
        processID = subprocess.check_output(psCmd, shell=True)

        while(processID):
            os.system(killCmd)
            time.sleep(1)
            processID = subprocess.check_output(psCmd, shell=True)

        for port in range(6030, 6041):
            usePortPID = "lsof -i tcp:%d | grep LISTEn | awk '{print $2}'" % port
            processID = subprocess.check_output(usePortPID, shell=True)

            if processID:
                killCmd = "kill -TERM %s" % processID
                os.system(killCmd)
            fuserCmd = "fuser -k -n tcp %d" % port
            os.system(fuserCmd)
        if valgrind:
            time.sleep(2)

        tdLog.info('stop All dnodes')
    
    if masterIp == "":
wafwerar's avatar
wafwerar 已提交
183
        host = socket.gethostname()
P
plum-lihui 已提交
184
    else:
wafwerar's avatar
wafwerar 已提交
185 186 187 188 189
        try:
            config = eval(masterIp)
            host = config["host"]
        except Exception as r:
            host = masterIp
P
plum-lihui 已提交
190 191

    tdLog.info("Procedures for tdengine deployed in %s" % (host))
wafwerar's avatar
wafwerar 已提交
192
    if platform.system().lower() == 'windows':
wafwerar's avatar
wafwerar 已提交
193
        fileName = fileName.replace("/", os.sep)
wafwerar's avatar
wafwerar 已提交
194
        if (masterIp == "" and not fileName == "0-others\\udf_create.py"):
wafwerar's avatar
wafwerar 已提交
195
            threading.Thread(target=checkRunTimeError,daemon=True).start()
P
plum-lihui 已提交
196
        tdLog.info("Procedures for testing self-deployment")
wafwerar's avatar
wafwerar 已提交
197
        tdDnodes.init(deployPath, masterIp)
wafwerar's avatar
wafwerar 已提交
198 199 200 201 202 203
        tdDnodes.setTestCluster(testCluster)
        tdDnodes.setValgrind(valgrind)
        tdDnodes.stopAll()
        key_word = 'tdCases.addWindows'
        is_test_framework = 0
        try:
wafwerar's avatar
wafwerar 已提交
204
            if key_word in open(fileName, encoding='UTF-8').read():
wafwerar's avatar
wafwerar 已提交
205
                is_test_framework = 1
wafwerar's avatar
wafwerar 已提交
206 207
        except Exception as r:
            print(r)
wafwerar's avatar
wafwerar 已提交
208 209 210 211 212 213
        updateCfgDictStr = ''
        if is_test_framework:
            moduleName = fileName.replace(".py", "").replace(os.sep, ".")
            uModule = importlib.import_module(moduleName)
            try:
                ucase = uModule.TDTestCase()
wafwerar's avatar
wafwerar 已提交
214
                if ((json.dumps(updateCfgDict) == '{}') and hasattr(ucase, 'updatecfgDict')):
wafwerar's avatar
wafwerar 已提交
215 216
                    updateCfgDict = ucase.updatecfgDict
                    updateCfgDictStr = "-d %s"%base64.b64encode(json.dumps(updateCfgDict).encode()).decode()
wafwerar's avatar
wafwerar 已提交
217 218
            except Exception as r:
                print(r)
wafwerar's avatar
wafwerar 已提交
219 220
        else:
            pass
wafwerar's avatar
wafwerar 已提交
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
        if dnodeNums == 1 :
            tdDnodes.deploy(1,updateCfgDict)
            tdDnodes.start(1)
            tdCases.logSql(logSql)
        else :
            tdLog.debug("create an cluster  with %s nodes and make %s dnode as independent mnode"%(dnodeNums,mnodeNums))
            dnodeslist = cluster.configure_cluster(dnodeNums=dnodeNums,mnodeNums=mnodeNums)
            tdDnodes = ClusterDnodes(dnodeslist)
            tdDnodes.init(deployPath, masterIp)
            tdDnodes.setTestCluster(testCluster)
            tdDnodes.setValgrind(valgrind)
            tdDnodes.stopAll()
            for dnode in tdDnodes.dnodes:
                tdDnodes.deploy(dnode.index,{})
            for dnode in tdDnodes.dnodes:
                tdDnodes.starttaosd(dnode.index)
            tdCases.logSql(logSql)
            conn = taos.connect(
                host,
                config=tdDnodes.getSimCfgPath())
            print(tdDnodes.getSimCfgPath(),host)
            cluster.create_dnode(conn)
            try:
                if cluster.check_dnode(conn) :
                    print("check dnode ready")
            except Exception as r:
                print(r)
        if ucase is not None and hasattr(ucase, 'noConn') and ucase.noConn == True:
            conn = None
        else:
            conn = taos.connect(
                host="%s"%(host),
                config=tdDnodes.sim.getCfgDir())
wafwerar's avatar
wafwerar 已提交
254 255 256 257
        if is_test_framework:
            tdCases.runOneWindows(conn, fileName)
        else:
            tdCases.runAllWindows(conn)
P
plum-lihui 已提交
258
    else:
259
        tdDnodes.setKillValgrind(killValgrind)
wafwerar's avatar
wafwerar 已提交
260
        tdDnodes.init(deployPath, masterIp)
P
plum-lihui 已提交
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
        tdDnodes.setTestCluster(testCluster)
        tdDnodes.setValgrind(valgrind)
        tdDnodes.stopAll()
        is_test_framework = 0
        key_word = 'tdCases.addLinux'
        try:
            if key_word in open(fileName).read():
                is_test_framework = 1
        except:
            pass
        if is_test_framework:
            moduleName = fileName.replace(".py", "").replace("/", ".")
            uModule = importlib.import_module(moduleName)
            try:
                ucase = uModule.TDTestCase()
wafwerar's avatar
wafwerar 已提交
276 277 278 279
                if (json.dumps(updateCfgDict) == '{}'):
                    updateCfgDict = ucase.updatecfgDict
            except:
                pass
haoranc's avatar
haoranc 已提交
280 281 282 283
        if dnodeNums == 1 :
            tdDnodes.deploy(1,updateCfgDict)
            tdDnodes.start(1)
            tdCases.logSql(logSql)
haoranc's avatar
haoranc 已提交
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
            if queryPolicy != 1:
                queryPolicy=int(queryPolicy)
                conn = taos.connect(
                host,
                config=tdDnodes.getSimCfgPath())
                tdSql.init(conn.cursor())
                tdSql.execute("create qnode on dnode 1")
                tdSql.execute('alter local "queryPolicy" "%d"'%queryPolicy)     
                tdSql.query("show local variables;")
                for i in range(tdSql.queryRows):
                    if tdSql.queryResult[i][0] == "queryPolicy" :
                        if int(tdSql.queryResult[i][1]) == int(queryPolicy):
                            tdLog.success('alter queryPolicy to %d successfully'%queryPolicy)
                        else :
                            tdLog.debug(tdSql.queryResult)
                            tdLog.exit("alter queryPolicy to  %d failed"%queryPolicy)      
haoranc's avatar
haoranc 已提交
300
        else :
haoranc's avatar
haoranc 已提交
301 302
            tdLog.debug("create an cluster  with %s nodes and make %s dnode as independent mnode"%(dnodeNums,mnodeNums))
            dnodeslist = cluster.configure_cluster(dnodeNums=dnodeNums,mnodeNums=mnodeNums)
haoranc's avatar
haoranc 已提交
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
            tdDnodes = ClusterDnodes(dnodeslist)
            tdDnodes.init(deployPath, masterIp)
            tdDnodes.setTestCluster(testCluster)
            tdDnodes.setValgrind(valgrind)
            tdDnodes.stopAll()
            for dnode in tdDnodes.dnodes:
                tdDnodes.deploy(dnode.index,{})
            for dnode in tdDnodes.dnodes:
                tdDnodes.starttaosd(dnode.index)
            tdCases.logSql(logSql)
            conn = taos.connect(
                host,
                config=tdDnodes.getSimCfgPath())
            print(tdDnodes.getSimCfgPath(),host)
            cluster.create_dnode(conn)
            try:
                if cluster.check_dnode(conn) :
                    print("check dnode ready")
            except Exception as r:
                print(r)
            
            
P
plum-lihui 已提交
325 326 327 328 329 330 331 332 333 334 335
        if testCluster:
            tdLog.info("Procedures for testing cluster")
            if fileName == "all":
                tdCases.runAllCluster()
            else:
                tdCases.runOneCluster(fileName)
        else:
            tdLog.info("Procedures for testing self-deployment")
            conn = taos.connect(
                host,
                config=tdDnodes.getSimCfgPath())
haoranc's avatar
haoranc 已提交
336
                
P
plum-lihui 已提交
337 338 339 340
            if fileName == "all":
                tdCases.runAllLinux(conn)
            else:
                tdCases.runOneLinux(conn, fileName)
haoranc's avatar
haoranc 已提交
341
            
P
plum-lihui 已提交
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
        if restart:
            if fileName == "all":
                tdLog.info("not need to query ")
            else:    
                sp = fileName.rsplit(".", 1)
                if len(sp) == 2 and sp[1] == "py":
                    tdDnodes.stopAll()
                    tdDnodes.start(1)
                    time.sleep(1)            
                    conn = taos.connect( host, config=tdDnodes.getSimCfgPath())
                    tdLog.info("Procedures for tdengine deployed in %s" % (host))
                    tdLog.info("query test after taosd restart")
                    tdCases.runOneLinux(conn, sp[0] + "_" + "restart.py")
                else:
                    tdLog.info("not need to query")
wafwerar's avatar
wafwerar 已提交
357 358
    if conn is not None:
        conn.close()