service_manager.py 29.5 KB
Newer Older
1 2 3 4 5 6 7 8 9
import os
import io
import sys
import threading
import signal
import logging
import time
import subprocess

10
from typing import IO, List
11 12 13 14 15 16 17 18

try:
    import psutil
except:
    print("Psutil module needed, please install: sudo pip3 install psutil")
    sys.exit(-1)

from queue import Queue, Empty
19

20
from .misc import Logging, Status, CrashGenError, Dice, Helper, Progress
21
from .db import DbConn, DbTarget
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49

class TdeInstance():
    """
    A class to capture the *static* information of a TDengine instance,
    including the location of the various files/directories, and basica
    configuration.
    """

    @classmethod
    def _getBuildPath(cls):
        selfPath = os.path.dirname(os.path.realpath(__file__))
        if ("community" in selfPath):
            projPath = selfPath[:selfPath.find("communit")]
        else:
            projPath = selfPath[:selfPath.find("tests")]

        buildPath = None
        for root, dirs, files in os.walk(projPath):
            if ("taosd" in files):
                rootRealPath = os.path.dirname(os.path.realpath(root))
                if ("packaging" not in rootRealPath):
                    buildPath = root[:len(root) - len("/build/bin")]
                    break
        if buildPath == None:
            raise RuntimeError("Failed to determine buildPath, selfPath={}, projPath={}"
                .format(selfPath, projPath))
        return buildPath

S
Steven Li 已提交
50 51 52 53
    @classmethod
    def prepareGcovEnv(cls, env):
        # Ref: https://gcc.gnu.org/onlinedocs/gcc/Cross-profiling.html
        bPath = cls._getBuildPath() # build PATH
54 55 56 57
        numSegments = len(bPath.split('/')) # "/x/TDengine/build" should yield 3
        # numSegments += 2 # cover "/src" after build
        # numSegments = numSegments - 1 # DEBUG only
        env['GCOV_PREFIX'] = bPath + '/src_s' # Server side source
S
Steven Li 已提交
58
        env['GCOV_PREFIX_STRIP'] = str(numSegments) # Strip every element, plus, ENV needs strings
59
        # VERY VERY important note: GCOV data collection NOT effective upon SIG_KILL
S
Steven Li 已提交
60 61 62
        Logging.info("Preparing GCOV environement to strip {} elements and use path: {}".format(
            numSegments, env['GCOV_PREFIX'] ))

63
    def __init__(self, subdir='test', tInstNum=0, port=6030, fepPort=6030):
64 65 66 67 68
        self._buildDir  = self._getBuildPath()
        self._subdir    = '/' + subdir # TODO: tolerate "/"
        self._port      = port # TODO: support different IP address too
        self._fepPort   = fepPort

69 70 71
        self._tInstNum    = tInstNum
        self._smThread    = ServiceManagerThread()

72 73 74 75 76
    def getDbTarget(self):
        return DbTarget(self.getCfgDir(), self.getHostAddr(), self._port)

    def getPort(self):
        return self._port
77 78

    def __repr__(self):
79 80
        return "[TdeInstance: {}, subdir={}]".format(
            self._buildDir, Helper.getFriendlyPath(self._subdir))
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
    
    def generateCfgFile(self):       
        # print("Logger = {}".format(logger))
        # buildPath = self.getBuildPath()
        # taosdPath = self._buildPath + "/build/bin/taosd"

        cfgDir  = self.getCfgDir()
        cfgFile = cfgDir + "/taos.cfg" # TODO: inquire if this is fixed
        if os.path.exists(cfgFile):
            if os.path.isfile(cfgFile):
                Logging.warning("Config file exists already, skip creation: {}".format(cfgFile))
                return # cfg file already exists, nothing to do
            else:
                raise CrashGenError("Invalid config file: {}".format(cfgFile))
        # Now that the cfg file doesn't exist
        if os.path.exists(cfgDir):
            if not os.path.isdir(cfgDir):
                raise CrashGenError("Invalid config dir: {}".format(cfgDir))
            # else: good path
        else: 
            os.makedirs(cfgDir, exist_ok=True) # like "mkdir -p"
        # Now we have a good cfg dir
        cfgValues = {
104 105 106 107
            'runDir':   self.getRunDir(),
            'ip':       '127.0.0.1', # TODO: change to a network addressable ip
            'port':     self._port,
            'fepPort':  self._fepPort,
108 109 110 111 112 113 114
        }
        cfgTemplate = """
dataDir {runDir}/data
logDir  {runDir}/log

charset UTF-8

115
firstEp {ip}:{fepPort}
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
fqdn {ip}
serverPort {port}

# was all 135 below
dDebugFlag 135
cDebugFlag 135
rpcDebugFlag 135
qDebugFlag 135
# httpDebugFlag 143
# asyncLog 0
# tables 10
maxtablesPerVnode 10
rpcMaxTime 101
# cache 2
keep 36500
# walLevel 2
walLevel 1
#
# maxConnections 100
"""
        cfgContent = cfgTemplate.format_map(cfgValues)
        f = open(cfgFile, "w")
        f.write(cfgContent)
        f.close()

    def rotateLogs(self):
        logPath = self.getLogDir()
        # ref: https://stackoverflow.com/questions/1995373/deleting-all-files-in-a-directory-with-python/1995397
        if os.path.exists(logPath):
            logPathSaved = logPath + "_" + time.strftime('%Y-%m-%d-%H-%M-%S')
            Logging.info("Saving old log files to: {}".format(logPathSaved))
            os.rename(logPath, logPathSaved)
        # os.mkdir(logPath) # recreate, no need actually, TDengine will auto-create with proper perms


    def getExecFile(self): # .../taosd
        return self._buildDir + "/build/bin/taosd"

    def getRunDir(self): # TODO: rename to "root dir" ?!
        return self._buildDir + self._subdir

    def getCfgDir(self): # path, not file
        return self.getRunDir() + "/cfg"

    def getLogDir(self):
        return self.getRunDir() + "/log"

    def getHostAddr(self):
        return "127.0.0.1"

166
    def getServiceCmdLine(self): # to start the instance
167
        return [self.getExecFile(), '-c', self.getCfgDir()] # used in subproce.Popen()
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
    
    def _getDnodes(self, dbc):
        dbc.query("show dnodes")
        cols = dbc.getQueryResult() #  id,end_point,vnodes,cores,status,role,create_time,offline reason
        return {c[1]:c[4] for c in cols} # {'xxx:6030':'ready', 'xxx:6130':'ready'}

    def createDnode(self, dbt: DbTarget):
        """
        With a connection to the "first" EP, let's create a dnode for someone else who
        wants to join.
        """
        dbc = DbConn.createNative(self.getDbTarget())
        dbc.open()

        if dbt.getEp() in self._getDnodes(dbc):
            Logging.info("Skipping DNode creation for: {}".format(dbt))
            dbc.close()
            return

        sql = "CREATE DNODE \"{}\"".format(dbt.getEp())
        dbc.execute(sql)
        dbc.close()

    def getStatus(self):
        return self._smThread.getStatus()

    def getSmThread(self):
        return self._smThread

    def start(self):
        if not self.getStatus().isStopped():
            raise CrashGenError("Cannot start instance from status: {}".format(self.getStatus()))

        Logging.info("Starting TDengine instance: {}".format(self))
        self.generateCfgFile() # service side generates config file, client does not
        self.rotateLogs()

        self._smThread.start(self.getServiceCmdLine())

    def stop(self):
        self._smThread.stop()

    def isFirst(self):
        return self._tInstNum == 0
212 213 214 215 216 217 218 219 220 221 222


class TdeSubProcess:
    """
    A class to to represent the actual sub process that is the run-time
    of a TDengine instance. 

    It takes a TdeInstance object as its parameter, with the rationale being
    "a sub process runs an instance".
    """

223 224 225 226 227
    # RET_ALREADY_STOPPED = -1
    # RET_TIME_OUT = -3
    # RET_SUCCESS = -4

    def __init__(self):
228
        self.subProcess = None
229 230 231
        # if tInst is None:
        #     raise CrashGenError("Empty instance not allowed in TdeSubProcess")
        # self._tInst = tInst # Default create at ServiceManagerThread
232

S
Steven Li 已提交
233 234 235 236 237
    def __repr__(self):
        if self.subProcess is None:
            return '[TdeSubProc: Empty]'
        return '[TdeSubProc: pid = {}]'.format(self.getPid())

238 239 240 241 242 243 244 245 246 247 248 249
    def getStdOut(self):
        return self.subProcess.stdout

    def getStdErr(self):
        return self.subProcess.stderr

    def isRunning(self):
        return self.subProcess is not None

    def getPid(self):
        return self.subProcess.pid

250
    def start(self, cmdLine):
251 252 253 254 255
        ON_POSIX = 'posix' in sys.builtin_module_names

        # Sanity check
        if self.subProcess:  # already there
            raise RuntimeError("Corrupt process state")
S
Steven Li 已提交
256 257 258 259 260 261 262

        # Prepare environment variables for coverage information
        # Ref: https://stackoverflow.com/questions/2231227/python-subprocess-popen-with-a-modified-environment
        myEnv = os.environ.copy()
        TdeInstance.prepareGcovEnv(myEnv)

        # print(myEnv)
263
        # print("Starting TDengine with env: ", myEnv.items())
S
Steven Li 已提交
264 265 266
        # print("Starting TDengine via Shell: {}".format(cmdLineStr))

        useShell = True    
267
        self.subProcess = subprocess.Popen(
268 269 270 271
            # ' '.join(cmdLine) if useShell else cmdLine,
            # shell=useShell,
            ' '.join(cmdLine),
            shell=True,
272 273 274
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            # bufsize=1, # not supported in binary mode
S
Steven Li 已提交
275 276
            close_fds=ON_POSIX,
            env=myEnv
277 278
            )  # had text=True, which interferred with reading EOF

279 280
    STOP_SIGNAL = signal.SIGKILL # signal.SIGKILL/SIGINT # What signal to use (in kill) to stop a taosd process?
    SIG_KILL_RETCODE = 137 # ref: https://stackoverflow.com/questions/43268156/process-finished-with-exit-code-137-in-pycharm
S
Steven Li 已提交
281

282
    def stop(self):
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
        """
        Stop a sub process, and try to return a meaningful return code.

        Common POSIX signal values (from man -7 signal):
        SIGHUP           1
        SIGINT           2 
        SIGQUIT          3 
        SIGILL           4
        SIGTRAP          5
        SIGABRT          6 
        SIGIOT           6 
        SIGBUS           7 
        SIGEMT           - 
        SIGFPE           8  
        SIGKILL          9  
        SIGUSR1         10 
        SIGSEGV         11
        SIGUSR2         12
        """
302
        if not self.subProcess:
S
Steven Li 已提交
303
            Logging.error("Sub process already stopped")
304
            return  # -1
305

306
        retCode = self.subProcess.poll() # ret -N means killed with signal N, otherwise it's from exit(N)
307
        if retCode:  # valid return code, process ended
308 309
            retCode = -retCode # only if valid
            Logging.warning("TSP.stop(): process ended itself")
310
            self.subProcess = None
311 312 313
            return retCode

        # process still alive, let's interrupt it
S
Steven Li 已提交
314 315 316 317 318 319 320 321 322
        Logging.info("Terminate running process, send SIG_{} and wait...".format(self.STOP_SIGNAL))
        # sub process should end, then IPC queue should end, causing IO thread to end        
        topSubProc = psutil.Process(self.subProcess.pid)
        for child in topSubProc.children(recursive=True):  # or parent.children() for recursive=False
            child.send_signal(self.STOP_SIGNAL)
            time.sleep(0.2) # 200 ms
        # topSubProc.send_signal(sig) # now kill the main sub process (likely the Shell)

        self.subProcess.send_signal(self.STOP_SIGNAL) # main sub process (likely the Shell)
323 324 325 326
        self.subProcess.wait(20)
        retCode = self.subProcess.returncode # should always be there
        # May throw subprocess.TimeoutExpired exception above, therefore
        # The process is guranteed to have ended by now
327 328 329 330 331 332
        self.subProcess = None       
        if retCode == self.SIG_KILL_RETCODE:
            Logging.info("TSP.stop(): sub proc KILLED, as expected")
        elif retCode == (- self.STOP_SIGNAL):
            Logging.info("TSP.stop(), sub process STOPPED, as expected")
        elif retCode != 0: # != (- signal.SIGINT):
S
Steven Li 已提交
333 334
            Logging.error("TSP.stop(): Failed to stop sub proc properly w/ SIG {}, retCode={}".format(
                self.STOP_SIGNAL, retCode))
335
        else:
S
Steven Li 已提交
336
            Logging.info("TSP.stop(): sub proc successfully terminated with SIG {}".format(self.STOP_SIGNAL))
337
        return - retCode
338 339 340 341

class ServiceManager:
    PAUSE_BETWEEN_IPC_CHECK = 1.2  # seconds between checks on STDOUT of sub process

342
    def __init__(self, numDnodes): # >1 when we run a cluster
343 344
        Logging.info("TDengine Service Manager (TSM) created")
        self._numDnodes = numDnodes # >1 means we have a cluster
345
        self._lock = threading.Lock()
346 347 348 349 350 351 352
        # signal.signal(signal.SIGTERM, self.sigIntHandler) # Moved to MainExec
        # signal.signal(signal.SIGINT, self.sigIntHandler)
        # signal.signal(signal.SIGUSR1, self.sigUsrHandler)  # different handler!

        self.inSigHandler = False
        # self._status = MainExec.STATUS_RUNNING # set inside
        # _startTaosService()
353
        self._runCluster = (numDnodes > 1)
354
        self._tInsts : List[TdeInstance] = []
355
        for i in range(0, numDnodes):
356 357 358 359 360 361 362
            ti = self._createTdeInstance(i) # construct tInst
            self._tInsts.append(ti)

        # self.svcMgrThreads : List[ServiceManagerThread] = []
        # for i in range(0, numDnodes):
        #     thread = self._createThread(i) # construct tInst
        #     self.svcMgrThreads.append(thread)
363

364
    def _createTdeInstance(self, dnIndex):
365 366 367 368
        if not self._runCluster: # single instance 
            subdir = 'test'
        else:        # Create all threads in a cluster
            subdir = 'cluster_dnode_{}'.format(dnIndex)
369 370
        fepPort= 6030 # firstEP Port
        port   = fepPort + dnIndex * 100
371 372
        return TdeInstance(subdir, dnIndex, port, fepPort)
        # return ServiceManagerThread(dnIndex, ti)
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436

    def _doMenu(self):
        choice = ""
        while True:
            print("\nInterrupting Service Program, Choose an Action: ")
            print("1: Resume")
            print("2: Terminate")
            print("3: Restart")
            # Remember to update the if range below
            # print("Enter Choice: ", end="", flush=True)
            while choice == "":
                choice = input("Enter Choice: ")
                if choice != "":
                    break  # done with reading repeated input
            if choice in ["1", "2", "3"]:
                break  # we are done with whole method
            print("Invalid choice, please try again.")
            choice = ""  # reset
        return choice

    def sigUsrHandler(self, signalNumber, frame):
        print("Interrupting main thread execution upon SIGUSR1")
        if self.inSigHandler:  # already
            print("Ignoring repeated SIG...")
            return  # do nothing if it's already not running
        self.inSigHandler = True

        choice = self._doMenu()
        if choice == "1":            
            self.sigHandlerResume() # TODO: can the sub-process be blocked due to us not reading from queue?
        elif choice == "2":
            self.stopTaosServices()
        elif choice == "3": # Restart
            self.restart()
        else:
            raise RuntimeError("Invalid menu choice: {}".format(choice))

        self.inSigHandler = False

    def sigIntHandler(self, signalNumber, frame):
        print("ServiceManager: INT Signal Handler starting...")
        if self.inSigHandler:
            print("Ignoring repeated SIG_INT...")
            return
        self.inSigHandler = True

        self.stopTaosServices()
        print("ServiceManager: INT Signal Handler returning...")
        self.inSigHandler = False

    def sigHandlerResume(self):
        print("Resuming TDengine service manager (main thread)...\n\n")

    # def _updateThreadStatus(self):
    #     if self.svcMgrThread:  # valid svc mgr thread
    #         if self.svcMgrThread.isStopped():  # done?
    #             self.svcMgrThread.procIpcBatch()  # one last time. TODO: appropriate?
    #             self.svcMgrThread = None  # no more

    def isActive(self):
        """
        Determine if the service/cluster is active at all, i.e. at least
        one thread is not "stopped".
        """
437 438
        for ti in self._tInsts:
            if not ti.getStatus().isStopped():
439 440 441
                return True
        return False

442 443 444 445 446 447 448
    def isRunning(self):
        for ti in self._tInsts:
            if not ti.getStatus().isRunning():
                return False
        return True


449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
    # def isRestarting(self):
    #     """
    #     Determine if the service/cluster is being "restarted", i.e., at least
    #     one thread is in "restarting" status
    #     """
    #     for thread in self.svcMgrThreads:
    #         if thread.isRestarting():
    #             return True
    #     return False

    def isStable(self):
        """
        Determine if the service/cluster is "stable", i.e. all of the
        threads are in "stable" status.
        """
464
        for ti in self._tInsts:
465
            if not ti.getStatus().isStable():
466 467 468 469 470
                return False
        return True

    def _procIpcAll(self):
        while self.isActive():
471 472
            Progress.emit(Progress.SERVICE_HEART_BEAT)
            for ti in self._tInsts: # all thread objects should always be valid
473
            # while self.isRunning() or self.isRestarting() :  # for as long as the svc mgr thread is still here
474 475 476 477 478 479
                status = ti.getStatus()
                if  status.isRunning():
                    th = ti.getSmThread()
                    th.procIpcBatch()  # regular processing,
                    if  status.isStopped():
                        th.procIpcBatch() # one last time?
480 481 482 483
                    # self._updateThreadStatus()
                    
            time.sleep(self.PAUSE_BETWEEN_IPC_CHECK)  # pause, before next round
        # raise CrashGenError("dummy")
S
Steven Li 已提交
484
        Logging.info("Service Manager Thread (with subprocess) ended, main thread exiting...")
485

486 487 488
    def _getFirstInstance(self):
        return self._tInsts[0]

489 490 491 492 493 494 495 496
    def startTaosServices(self):
        with self._lock:
            if self.isActive():
                raise RuntimeError("Cannot start TAOS service(s) when one/some may already be running")

            # Find if there's already a taosd service, and then kill it
            for proc in psutil.process_iter():
                if proc.name() == 'taosd':
S
Steven Li 已提交
497
                    Logging.info("Killing an existing TAOSD process in 2 seconds... press CTRL-C to interrupt")
498 499 500 501 502
                    time.sleep(2.0)
                    proc.kill()
                # print("Process: {}".format(proc.name()))
            
            # self.svcMgrThread = ServiceManagerThread()  # create the object
503 504 505 506 507 508 509
            
            for ti in self._tInsts:
                ti.start()  
                if not ti.isFirst():                                    
                    tFirst = self._getFirstInstance()
                    tFirst.createDnode(ti.getDbTarget())
                ti.getSmThread().procIpcBatch(trimToTarget=10, forceOutput=True)  # for printing 10 lines                                     
510 511 512 513 514 515 516

    def stopTaosServices(self):
        with self._lock:
            if not self.isActive():
                Logging.warning("Cannot stop TAOS service(s), already not active")
                return

517 518
            for ti in self._tInsts:
                ti.stop()
519 520 521 522 523 524 525 526
                
    def run(self):
        self.startTaosServices()
        self._procIpcAll()  # pump/process all the messages, may encounter SIG + restart
        if  self.isActive():  # if sig handler hasn't destroyed it by now
            self.stopTaosServices()  # should have started already

    def restart(self):
527
        if not self.isStable():
528 529 530 531 532 533 534 535 536
            Logging.warning("Cannot restart service/cluster, when not stable")
            return

        # self._isRestarting = True
        if  self.isActive():
            self.stopTaosServices()
        else:
            Logging.warning("Service not active when restart requested")

537
        self.startTaosServices()
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
        # self._isRestarting = False

    # def isRunning(self):
    #     return self.svcMgrThread != None

    # def isRestarting(self):
    #     return self._isRestarting

class ServiceManagerThread:
    """
    A class representing a dedicated thread which manages the "sub process"
    of the TDengine service, interacting with its STDOUT/ERR.

    It takes a TdeInstance parameter at creation time, or create a default    
    """
    MAX_QUEUE_SIZE = 10000

555
    def __init__(self):
556 557 558 559
        # Set the sub process
        self._tdeSubProcess = None # type: TdeSubProcess

        # Arrange the TDengine instance
560 561
        # self._tInstNum = tInstNum # instance serial number in cluster, ZERO based
        # self._tInst    = tInst or TdeInstance() # Need an instance
562 563

        self._thread = None # The actual thread, # type: threading.Thread
564
        self._status = Status(Status.STATUS_STOPPED) # The status of the underlying service, actually.
565 566

    def __repr__(self):
567 568
        return "[SvcMgrThread: status={}, subProc={}]".format(
            self.getStatus(), self._tdeSubProcess)
569 570 571 572 573 574

    def getStatus(self):
        return self._status

    # Start the thread (with sub process), and wait for the sub service
    # to become fully operational
575
    def start(self, cmdLine):
576 577 578 579 580 581 582
        if self._thread:
            raise RuntimeError("Unexpected _thread")
        if self._tdeSubProcess:
            raise RuntimeError("TDengine sub process already created/running")

        Logging.info("Attempting to start TAOS service: {}".format(self))

583 584 585
        self._status.set(Status.STATUS_STARTING)
        self._tdeSubProcess = TdeSubProcess()
        self._tdeSubProcess.start(cmdLine)
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603

        self._ipcQueue = Queue()
        self._thread = threading.Thread( # First thread captures server OUTPUT
            target=self.svcOutputReader,
            args=(self._tdeSubProcess.getStdOut(), self._ipcQueue))
        self._thread.daemon = True  # thread dies with the program
        self._thread.start()

        self._thread2 = threading.Thread( # 2nd thread captures server ERRORs
            target=self.svcErrorReader,
            args=(self._tdeSubProcess.getStdErr(), self._ipcQueue))
        self._thread2.daemon = True  # thread dies with the program
        self._thread2.start()

        # wait for service to start
        for i in range(0, 100):
            time.sleep(1.0)
            # self.procIpcBatch() # don't pump message during start up
S
Steven Li 已提交
604 605
            Progress.emit(Progress.SERVICE_START_NAP)
            # print("_zz_", end="", flush=True)
606
            if self._status.isRunning():
607 608
                Logging.info("[] TDengine service READY to process requests")
                Logging.info("[] TAOS service started: {}".format(self))
609 610
                # self._verifyDnode(self._tInst) # query and ensure dnode is ready
                # Logging.debug("[] TAOS Dnode verified: {}".format(self))
611 612 613 614 615
                return  # now we've started
        # TODO: handle failure-to-start  better?
        self.procIpcBatch(100, True) # display output before cronking out, trim to last 20 msgs, force output
        raise RuntimeError("TDengine service did not start successfully: {}".format(self))

616 617 618 619 620 621 622 623 624
    def _verifyDnode(self, tInst: TdeInstance):
        dbc = DbConn.createNative(tInst.getDbTarget())
        dbc.open()
        dbc.query("show dnodes")
        # dbc.query("DESCRIBE {}.{}".format(dbName, self._stName))
        cols = dbc.getQueryResult() #  id,end_point,vnodes,cores,status,role,create_time,offline reason
        # ret = {row[0]:row[1] for row in stCols if row[3]=='TAG'} # name:type
        isValid = False
        for col in cols:
625
            # print("col = {}".format(col))
626
            ep = col[1].split(':') # 10.1.30.2:6030
627
            print("Found ep={}".format(ep))
628
            if tInst.getPort() == int(ep[1]): # That's us
629
                # print("Valid Dnode matched!")
630 631 632
                isValid = True # now we are valid
                break
        if not isValid:
633 634 635 636
            print("Failed to start dnode, sleep for a while")
            time.sleep(600)
            raise RuntimeError("Failed to start Dnode, expected port not found: {}".
                format(tInst.getPort()))
637 638
        dbc.close()

639 640
    def stop(self):
        # can be called from both main thread or signal handler
S
Steven Li 已提交
641
        Logging.info("Terminating TDengine service running as the sub process...")
642
        if self.getStatus().isStopped():
S
Steven Li 已提交
643
            Logging.info("Service already stopped")
644
            return
645
        if self.getStatus().isStopping():
S
Steven Li 已提交
646
            Logging.info("Service is already being stopped")
647 648 649 650 651 652 653
            return
        # Linux will send Control-C generated SIGINT to the TDengine process
        # already, ref:
        # https://unix.stackexchange.com/questions/176235/fork-and-how-signals-are-delivered-to-processes
        if not self._tdeSubProcess:
            raise RuntimeError("sub process object missing")

654 655 656 657 658 659 660 661
        self._status.set(Status.STATUS_STOPPING)
        # retCode = self._tdeSubProcess.stop()
        try:
            retCode = self._tdeSubProcess.stop()
            # print("Attempted to stop sub process, got return code: {}".format(retCode))
            if retCode == signal.SIGSEGV : # SGV
                Logging.error("[[--ERROR--]]: TDengine service SEGV fault (check core file!)")
        except subprocess.TimeoutExpired as err:
S
Steven Li 已提交
662
            Logging.info("Time out waiting for TDengine service process to exit")
663 664
        else:    
            if self._tdeSubProcess.isRunning():  # still running, should now never happen
S
Steven Li 已提交
665
                Logging.error("FAILED to stop sub process, it is still running... pid = {}".format(
666
                    self._tdeSubProcess.getPid()))
667 668 669
            else:
                self._tdeSubProcess = None  # not running any more
                self.join()  # stop the thread, change the status, etc.
670 671

        # Check if it's really stopped
672 673
        outputLines = 10 # for last output
        if  self.getStatus().isStopped():
674
            self.procIpcBatch(outputLines)  # one last time
675 676
            Logging.debug("End of TDengine Service Output: {}".format(self))
            Logging.info("----- TDengine Service (managed by SMT) is now terminated -----\n")
677 678 679 680 681
        else:
            print("WARNING: SMT did not terminate as expected: {}".format(self))

    def join(self):
        # TODO: sanity check
682
        if not self.getStatus().isStopping():
683
            raise RuntimeError(
684
                "SMT.Join(): Unexpected status: {}".format(self._status))
685 686 687 688

        if self._thread:
            self._thread.join()
            self._thread = None
689
            self._status.set(Status.STATUS_STOPPED)
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
            # STD ERR thread
            self._thread2.join()
            self._thread2 = None
        else:
            print("Joining empty thread, doing nothing")

    def _trimQueue(self, targetSize):
        if targetSize <= 0:
            return  # do nothing
        q = self._ipcQueue
        if (q.qsize() <= targetSize):  # no need to trim
            return

        Logging.debug("Triming IPC queue to target size: {}".format(targetSize))
        itemsToTrim = q.qsize() - targetSize
        for i in range(0, itemsToTrim):
            try:
                q.get_nowait()
            except Empty:
                break  # break out of for loop, no more trimming

    TD_READY_MSG = "TDengine is initialized successfully"

    def procIpcBatch(self, trimToTarget=0, forceOutput=False):
        self._trimQueue(trimToTarget)  # trim if necessary
        # Process all the output generated by the underlying sub process,
        # managed by IO thread
        print("<", end="", flush=True)
        while True:
            try:
                line = self._ipcQueue.get_nowait()  # getting output at fast speed
                self._printProgress("_o")
            except Empty:
                # time.sleep(2.3) # wait only if there's no output
                # no more output
                print(".>", end="", flush=True)
                return  # we are done with THIS BATCH
            else:  # got line, printing out
                if forceOutput:
S
Steven Li 已提交
729
                    Logging.info('[TAOSD] ' + line)
730
                else:
S
Steven Li 已提交
731
                    Logging.debug('[TAOSD] ' + line)
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
        print(">", end="", flush=True)

    _ProgressBars = ["--", "//", "||", "\\\\"]

    def _printProgress(self, msg):  # TODO: assuming 2 chars
        print(msg, end="", flush=True)
        pBar = self._ProgressBars[Dice.throw(4)]
        print(pBar, end="", flush=True)
        print('\b\b\b\b', end="", flush=True)

    def svcOutputReader(self, out: IO, queue):
        # Important Reference: https://stackoverflow.com/questions/375427/non-blocking-read-on-a-subprocess-pipe-in-python
        # print("This is the svcOutput Reader...")
        # for line in out :
        for line in iter(out.readline, b''):
            # print("Finished reading a line: {}".format(line))
            # print("Adding item to queue...")
            try:
                line = line.decode("utf-8").rstrip()
            except UnicodeError:
                print("\nNon-UTF8 server output: {}\n".format(line))

            # This might block, and then causing "out" buffer to block
            queue.put(line)
            self._printProgress("_i")

758
            if self._status.isStarting():  # we are starting, let's see if we have started
759 760 761
                if line.find(self.TD_READY_MSG) != -1:  # found
                    Logging.info("Waiting for the service to become FULLY READY")
                    time.sleep(1.0) # wait for the server to truly start. TODO: remove this
762 763
                    Logging.info("Service is now FULLY READY") # TODO: more ID info here?
                    self._status.set(Status.STATUS_RUNNING)
764 765 766 767

            # Trim the queue if necessary: TODO: try this 1 out of 10 times
            self._trimQueue(self.MAX_QUEUE_SIZE * 9 // 10)  # trim to 90% size

768
            if self._status.isStopping():  # TODO: use thread status instead
769 770 771 772 773
                # WAITING for stopping sub process to finish its outptu
                print("_w", end="", flush=True)

            # queue.put(line)
        # meaning sub process must have died
S
Steven Li 已提交
774
        Logging.info("EOF for TDengine STDOUT: {}".format(self))
775 776 777 778
        out.close()

    def svcErrorReader(self, err: IO, queue):
        for line in iter(err.readline, b''):
S
Steven Li 已提交
779 780
            Logging.info("TDengine STDERR: {}".format(line))
        Logging.info("EOF for TDengine STDERR: {}".format(self))
781
        err.close()