service_manager.py 38.3 KB
Newer Older
1 2
from __future__ import annotations

3 4 5
import os
import io
import sys
6
from enum import Enum
7 8 9 10
import threading
import signal
import logging
import time
11
from subprocess import PIPE, Popen, TimeoutExpired
12 13
from typing import BinaryIO, Generator, IO, List, NewType, Optional
import typing
14 15 16 17 18 19 20

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

22 23 24 25
from crash_gen.misc import CrashGenError, Dice, Helper, Logging, Progress, Status
from crash_gen.db import DbConn, DbTarget
from crash_gen.settings import Settings
from crash_gen.types import DirPath
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53

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 已提交
54 55 56 57
    @classmethod
    def prepareGcovEnv(cls, env):
        # Ref: https://gcc.gnu.org/onlinedocs/gcc/Cross-profiling.html
        bPath = cls._getBuildPath() # build PATH
58 59 60 61
        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 已提交
62
        env['GCOV_PREFIX_STRIP'] = str(numSegments) # Strip every element, plus, ENV needs strings
63
        # VERY VERY important note: GCOV data collection NOT effective upon SIG_KILL
S
Steven Li 已提交
64 65 66
        Logging.info("Preparing GCOV environement to strip {} elements and use path: {}".format(
            numSegments, env['GCOV_PREFIX'] ))

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

73
        self._tInstNum    = tInstNum
74 75 76 77

        # An "Tde Instance" will *contain* a "sub process" object, with will/may use a thread internally
        # self._smThread    = ServiceManagerThread()
        self._subProcess  = None # type: Optional[TdeSubProcess]
78

79 80 81 82 83
    def getDbTarget(self):
        return DbTarget(self.getCfgDir(), self.getHostAddr(), self._port)

    def getPort(self):
        return self._port
84 85

    def __repr__(self):
86 87
        return "[TdeInstance: {}, subdir={}]".format(
            self._buildDir, Helper.getFriendlyPath(self._subdir))
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
    
    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 = {
111 112 113 114
            'runDir':   self.getRunDir(),
            'ip':       '127.0.0.1', # TODO: change to a network addressable ip
            'port':     self._port,
            'fepPort':  self._fepPort,
115 116 117 118 119 120 121
        }
        cfgTemplate = """
dataDir {runDir}/data
logDir  {runDir}/log

charset UTF-8

122
firstEp {ip}:{fepPort}
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
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
142
quorum 2
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
"""
        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"

162 163
    def getRunDir(self) -> DirPath : # TODO: rename to "root dir" ?!
        return DirPath(self._buildDir + self._subdir)
164

165 166
    def getCfgDir(self) -> DirPath : # path, not file
        return DirPath(self.getRunDir() + "/cfg")
167

168 169
    def getLogDir(self) -> DirPath :
        return DirPath(self.getRunDir() + "/log")
170 171 172 173

    def getHostAddr(self):
        return "127.0.0.1"

174
    def getServiceCmdLine(self): # to start the instance
175
        cmdLine = []
176
        if Settings.getConfig().track_memory_leaks:
177 178
            Logging.info("Invoking VALGRIND on service...")
            cmdLine = ['valgrind', '--leak-check=yes']
179
        # TODO: move "exec -c" into Popen(), we can both "use shell" and NOT fork so ask to lose kill control
180 181
        cmdLine += ["exec " + self.getExecFile(), '-c', self.getCfgDir()] # used in subproce.Popen()        
        return cmdLine
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
    
    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):
206 207 208 209
        # return self._smThread.getStatus()
        if self._subProcess is None:
            return Status(Status.STATUS_EMPTY)
        return self._subProcess.getStatus()
210

211 212
    # def getSmThread(self):
    #     return self._smThread
213 214

    def start(self):
215
        if self.getStatus().isActive():
216 217 218 219 220 221
            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()

222 223
        # self._smThread.start(self.getServiceCmdLine(), self.getLogDir()) # May raise exceptions
        self._subProcess = TdeSubProcess(self.getServiceCmdLine(),  self.getLogDir())
224 225

    def stop(self):
226 227
        self._subProcess.stop()
        self._subProcess = None
228 229 230

    def isFirst(self):
        return self._tInstNum == 0
231

232 233 234 235 236 237 238 239 240 241 242 243 244 245
    def printFirst10Lines(self):
        if self._subProcess is None:
            Logging.warning("Incorrect TI status for procIpcBatch-10 operation")
            return
        self._subProcess.procIpcBatch(trimToTarget=10, forceOutput=True)  

    def procIpcBatch(self):
        if self._subProcess is None:
            Logging.warning("Incorrect TI status for procIpcBatch operation")
            return
        self._subProcess.procIpcBatch() # may enounter EOF and change status to STOPPED
        if self._subProcess.getStatus().isStopped():
            self._subProcess.stop()
            self._subProcess = None
246 247 248 249 250 251 252 253

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".
254 255 256

    We aim to ensure that this object has exactly the same life-cycle as the 
    underlying sub process.
257 258
    """

259 260 261 262
    # RET_ALREADY_STOPPED = -1
    # RET_TIME_OUT = -3
    # RET_SUCCESS = -4

263 264 265 266 267 268 269 270 271
    def __init__(self, cmdLine: List[str], logDir: DirPath):
        # Create the process + managing thread immediately

        Logging.info("Attempting to start TAOS sub process...")
        self._popen     = self._start(cmdLine) # the actual sub process
        self._smThread  = ServiceManagerThread(self, logDir)  # A thread to manage the sub process, mostly to process the IO
        Logging.info("Successfully started TAOS process: {}".format(self))


272

S
Steven Li 已提交
273
    def __repr__(self):
274 275
        # if self.subProcess is None:
        #     return '[TdeSubProc: Empty]'
276 277
        return '[TdeSubProc: pid = {}, status = {}]'.format(
            self.getPid(), self.getStatus() )
S
Steven Li 已提交
278

279 280 281 282 283
    def getStdOut(self) -> BinaryIO :
        if self._popen.universal_newlines : # alias of text_mode
            raise CrashGenError("We need binary mode for STDOUT IPC")
        # Logging.info("Type of stdout is: {}".format(type(self._popen.stdout)))
        return typing.cast(BinaryIO, self._popen.stdout)
284

285 286 287 288
    def getStdErr(self) -> BinaryIO :
        if self._popen.universal_newlines : # alias of text_mode
            raise CrashGenError("We need binary mode for STDERR IPC")
        return typing.cast(BinaryIO, self._popen.stderr)
289

290 291 292
    # Now it's always running, since we matched the life cycle
    # def isRunning(self):
    #     return self.subProcess is not None
293 294

    def getPid(self):
295
        return self._popen.pid
296

297
    def _start(self, cmdLine) -> Popen :
298 299 300
        ON_POSIX = 'posix' in sys.builtin_module_names

        # Sanity check
301 302
        # if self.subProcess:  # already there
        #     raise RuntimeError("Corrupt process state")
S
Steven Li 已提交
303

304
        
S
Steven Li 已提交
305 306 307 308 309 310
        # 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)
311
        # print("Starting TDengine with env: ", myEnv.items())
S
Steven Li 已提交
312 313
        # print("Starting TDengine via Shell: {}".format(cmdLineStr))

314
        # useShell = True # Needed to pass environments into it
315
        return Popen(            
316 317 318 319
            ' '.join(cmdLine), # ' '.join(cmdLine) if useShell else cmdLine,
            shell=True, # Always use shell, since we need to pass ENV vars
            stdout=PIPE,
            stderr=PIPE,
S
Steven Li 已提交
320 321
            close_fds=ON_POSIX,
            env=myEnv
322 323
            )  # had text=True, which interferred with reading EOF

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

327
    def stop(self):
328
        """
329 330 331
        Stop a sub process, DO NOT return anything, process all conditions INSIDE.

        Calling function should immediately delete/unreference the object
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348

        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
        """
349 350
        # self._popen should always be valid.

351 352 353 354 355 356 357 358 359
        Logging.info("Terminating TDengine service running as the sub process...")
        if self.getStatus().isStopped():
            Logging.info("Service already stopped")
            return
        if self.getStatus().isStopping():
            Logging.info("Service is already being stopped, pid: {}".format(self.getPid()))
            return

        self.setStatus(Status.STATUS_STOPPING)
360

361
        retCode = self._popen.poll() # ret -N means killed with signal N, otherwise it's from exit(N)
362
        if retCode:  # valid return code, process ended
363
            # retCode = -retCode # only if valid
364
            Logging.warning("TSP.stop(): process ended itself")
365
            # self.subProcess = None
366
            return
367 368

        # process still alive, let's interrupt it
369
        self._stopForSure(self._popen, self.STOP_SIGNAL) # success if no exception
370

371 372 373 374
        # sub process should end, then IPC queue should end, causing IO thread to end  
        self._smThread.stop() # stop for sure too

        self.setStatus(Status.STATUS_STOPPED)
375 376

    @classmethod
377
    def _stopForSure(cls, proc: Popen, sig: int):
378 379 380
        ''' 
        Stop a process and all sub processes with a singal, and SIGKILL if necessary
        '''
381
        def doKillTdService(proc: Popen, sig: int):
382 383 384 385 386 387 388 389 390 391 392
            Logging.info("Killing sub-sub process {} with signal {}".format(proc.pid, sig))
            proc.send_signal(sig)
            try:            
                retCode = proc.wait(20)
                if (- retCode) == signal.SIGSEGV: # Crashed
                    Logging.warning("Process {} CRASHED, please check CORE file!".format(proc.pid))
                elif (- retCode) == sig : 
                    Logging.info("TD service terminated with expected return code {}".format(sig))
                else:
                    Logging.warning("TD service terminated, EXPECTING ret code {}, got {}".format(sig, -retCode))
                return True # terminated successfully
393
            except TimeoutExpired as err:
394 395 396 397 398 399 400 401
                Logging.warning("Failed to kill sub-sub process {} with signal {}".format(proc.pid, sig))
            return False # failed to terminate


        def doKillChild(child: psutil.Process, sig: int):
            Logging.info("Killing sub-sub process {} with signal {}".format(child.pid, sig))
            child.send_signal(sig)
            try:            
402 403
                retCode = child.wait(20) # type: ignore
                if (- retCode) == signal.SIGSEGV: # type: ignore # Crashed
404
                    Logging.warning("Process {} CRASHED, please check CORE file!".format(child.pid))
405
                elif (- retCode) == sig : # type: ignore
406 407
                    Logging.info("Sub-sub process terminated with expected return code {}".format(sig))
                else:
408
                    Logging.warning("Process terminated, EXPECTING ret code {}, got {}".format(sig, -retCode)) # type: ignore
409 410 411 412 413
                return True # terminated successfully
            except psutil.TimeoutExpired as err:
                Logging.warning("Failed to kill sub-sub process {} with signal {}".format(child.pid, sig))
            return False # did not terminate

414
        def doKill(proc: Popen, sig: int):
415 416
            pid = proc.pid
            try:
417
                topSubProc = psutil.Process(pid) # Now that we are doing "exec -c", should not have children any more
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
                for child in topSubProc.children(recursive=True):  # or parent.children() for recursive=False
                    Logging.warning("Unexpected child to be killed")
                    doKillChild(child, sig)
            except psutil.NoSuchProcess as err:
                Logging.info("Process not found, can't kill, pid = {}".format(pid))
            
            return doKillTdService(proc, sig)
            # TODO: re-examine if we need to kill the top process, which is always the SHELL for now
            # try:
            #     proc.wait(1) # SHELL process here, may throw subprocess.TimeoutExpired exception
            #     # expRetCode = self.SIG_KILL_RETCODE if sig==signal.SIGKILL else (-sig)
            #     # if retCode == expRetCode:
            #     #     Logging.info("Process terminated with expected return code {}".format(retCode))
            #     # else:
            #     #     Logging.warning("Process terminated, EXPECTING ret code {}, got {}".format(expRetCode, retCode))
            #     # return True # success
            # except subprocess.TimeoutExpired as err:
            #     Logging.warning("Failed to kill process {} with signal {}".format(pid, sig))
            # return False # failed to kill

        def softKill(proc, sig):
            return doKill(proc, sig)

        def hardKill(proc):
442
            return doKill(proc, signal.SIGKILL) 
443 444 445 446

        pid = proc.pid
        Logging.info("Terminate running processes under {}, with SIG #{} and wait...".format(pid, sig))
        if softKill(proc, sig):            
447
            return # success
448 449
        if sig != signal.SIGKILL: # really was soft above            
            if hardKill(proc):
450
                return 
451
        raise CrashGenError("Failed to stop process, pid={}".format(pid))
452

453 454 455 456 457 458 459 460 461
    def getStatus(self):
        return self._smThread.getStatus()

    def setStatus(self, status):
        self._smThread.setStatus(status)

    def procIpcBatch(self, trimToTarget=0, forceOutput=False):
        self._smThread.procIpcBatch(trimToTarget, forceOutput)

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

465
    def __init__(self, numDnodes): # >1 when we run a cluster
466 467
        Logging.info("TDengine Service Manager (TSM) created")
        self._numDnodes = numDnodes # >1 means we have a cluster
468
        self._lock = threading.Lock()
469 470 471 472 473 474 475
        # 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()
476
        self._runCluster = (numDnodes > 1)
477
        self._tInsts : List[TdeInstance] = []
478
        for i in range(0, numDnodes):
479 480 481 482 483 484 485
            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)
486

487
    def _createTdeInstance(self, dnIndex):
488 489 490 491
        if not self._runCluster: # single instance 
            subdir = 'test'
        else:        # Create all threads in a cluster
            subdir = 'cluster_dnode_{}'.format(dnIndex)
492 493
        fepPort= 6030 # firstEP Port
        port   = fepPort + dnIndex * 100
494 495
        return TdeInstance(subdir, dnIndex, port, fepPort)
        # return ServiceManagerThread(dnIndex, ti)
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557

    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
558
        one instance is active
559
        """
560
        for ti in self._tInsts:
561
            if ti.getStatus().isActive():
562 563 564
                return True
        return False

565 566 567 568 569 570 571
    def isRunning(self):
        for ti in self._tInsts:
            if not ti.getStatus().isRunning():
                return False
        return True


572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
    # 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.
        """
587
        for ti in self._tInsts:
588
            if not ti.getStatus().isStable():
589 590 591 592 593
                return False
        return True

    def _procIpcAll(self):
        while self.isActive():
594 595
            Progress.emit(Progress.SERVICE_HEART_BEAT)
            for ti in self._tInsts: # all thread objects should always be valid
596
            # while self.isRunning() or self.isRestarting() :  # for as long as the svc mgr thread is still here
597 598
                status = ti.getStatus()
                if  status.isRunning():
599 600
                    # th = ti.getSmThread()
                    ti.procIpcBatch()  # regular processing,
601
                    if  status.isStopped():
602
                        ti.procIpcBatch() # one last time?
603 604 605 606
                    # self._updateThreadStatus()
                    
            time.sleep(self.PAUSE_BETWEEN_IPC_CHECK)  # pause, before next round
        # raise CrashGenError("dummy")
S
Steven Li 已提交
607
        Logging.info("Service Manager Thread (with subprocess) ended, main thread exiting...")
608

609 610 611
    def _getFirstInstance(self):
        return self._tInsts[0]

612 613 614 615 616 617 618 619
    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 已提交
620
                    Logging.info("Killing an existing TAOSD process in 2 seconds... press CTRL-C to interrupt")
621 622 623 624 625
                    time.sleep(2.0)
                    proc.kill()
                # print("Process: {}".format(proc.name()))
            
            # self.svcMgrThread = ServiceManagerThread()  # create the object
626 627 628 629 630 631
            
            for ti in self._tInsts:
                ti.start()  
                if not ti.isFirst():                                    
                    tFirst = self._getFirstInstance()
                    tFirst.createDnode(ti.getDbTarget())
632 633
                ti.printFirst10Lines()
                # ti.getSmThread().procIpcBatch(trimToTarget=10, forceOutput=True)  # for printing 10 lines                                     
634 635 636 637 638 639 640

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

641 642
            for ti in self._tInsts:
                ti.stop()
643 644 645 646 647 648 649 650
                
    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):
651
        if not self.isStable():
652 653 654 655 656 657 658 659 660
            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")

661
        self.startTaosServices()
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
        # 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

679
    def __init__(self, subProc: TdeSubProcess, logDir: str):
680
        # Set the sub process
681
        # self._tdeSubProcess = None # type: TdeSubProcess
682 683

        # Arrange the TDengine instance
684 685
        # self._tInstNum = tInstNum # instance serial number in cluster, ZERO based
        # self._tInst    = tInst or TdeInstance() # Need an instance
686

687 688
        # self._thread  = None # type: Optional[threading.Thread]  # The actual thread, # type: threading.Thread
        # self._thread2 = None # type: Optional[threading.Thread] Thread  # watching stderr
689
        self._status = Status(Status.STATUS_STOPPED) # The status of the underlying service, actually.
690

691 692
        self._start(subProc, logDir)

693
    def __repr__(self):
694 695 696
        raise CrashGenError("SMT status moved to TdeSubProcess")
        # return "[SvcMgrThread: status={}, subProc={}]".format(
        #     self.getStatus(), self._tdeSubProcess)
697 698

    def getStatus(self):
699 700 701
        '''
        Get the status of the process being managed. (misnomer alert!)
        '''
702 703
        return self._status

704 705 706
    def setStatus(self, statusVal: int):
        self._status.set(statusVal)

707 708
    # Start the thread (with sub process), and wait for the sub service
    # to become fully operational
709
    def _start(self, subProc :TdeSubProcess, logDir: str):
710 711 712 713 714 715
        '''
        Request the manager thread to start a new sub process, and manage it.

        :param cmdLine: the command line to invoke
        :param logDir: the logging directory, to hold stdout/stderr files
        '''
716 717 718 719
        # if self._thread:
        #     raise RuntimeError("Unexpected _thread")
        # if self._tdeSubProcess:
        #     raise RuntimeError("TDengine sub process already created/running")
720

721 722
        # Moved to TdeSubProcess
        # Logging.info("Attempting to start TAOS service: {}".format(self))
723

724
        self._status.set(Status.STATUS_STARTING)
725
        # self._tdeSubProcess = TdeSubProcess.start(cmdLine) # TODO: verify process is running
726

727
        self._ipcQueue = Queue() # type: Queue
728 729
        self._thread = threading.Thread( # First thread captures server OUTPUT
            target=self.svcOutputReader,
730
            args=(subProc.getStdOut(), self._ipcQueue, logDir))
731 732
        self._thread.daemon = True  # thread dies with the program
        self._thread.start()
733 734 735 736 737 738
        time.sleep(0.01)
        if not self._thread.is_alive(): # What happened?
            Logging.info("Failed to started process to monitor STDOUT")
            self.stop()
            raise CrashGenError("Failed to start thread to monitor STDOUT")
        Logging.info("Successfully started process to monitor STDOUT")
739 740 741

        self._thread2 = threading.Thread( # 2nd thread captures server ERRORs
            target=self.svcErrorReader,
742
            args=(subProc.getStdErr(), self._ipcQueue, logDir))
743 744
        self._thread2.daemon = True  # thread dies with the program
        self._thread2.start()
745 746 747 748
        time.sleep(0.01)
        if not self._thread2.is_alive():
            self.stop()
            raise CrashGenError("Failed to start thread to monitor STDERR")
749 750 751 752 753

        # 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 已提交
754 755
            Progress.emit(Progress.SERVICE_START_NAP)
            # print("_zz_", end="", flush=True)
756
            if self._status.isRunning():
757 758
                Logging.info("[] TDengine service READY to process requests: pid={}".format(subProc.getPid()))
                # Logging.info("[] TAOS service started: {}".format(self))
759 760
                # self._verifyDnode(self._tInst) # query and ensure dnode is ready
                # Logging.debug("[] TAOS Dnode verified: {}".format(self))
761 762 763
                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
764
        raise RuntimeError("TDengine service DID NOT achieve READY status: pid={}".format(subProc.getPid()))
765

766 767 768 769 770 771 772 773 774
    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:
775
            # print("col = {}".format(col))
776
            ep = col[1].split(':') # 10.1.30.2:6030
777
            print("Found ep={}".format(ep))
778
            if tInst.getPort() == int(ep[1]): # That's us
779
                # print("Valid Dnode matched!")
780 781 782
                isValid = True # now we are valid
                break
        if not isValid:
783
            print("Failed to start dnode, sleep for a while")
784
            time.sleep(10.0)
785 786
            raise RuntimeError("Failed to start Dnode, expected port not found: {}".
                format(tInst.getPort()))
787 788
        dbc.close()

789 790
    def stop(self):
        # can be called from both main thread or signal handler
791

792 793 794
        # 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
795 796
        # if not self._tdeSubProcess:
        #     raise RuntimeError("sub process object missing")
797

798 799 800
        # self._status.set(Status.STATUS_STOPPING)
        # TdeSubProcess.stop(self._tdeSubProcess) # must stop, no matter what
        # self._tdeSubProcess = None
801 802 803 804 805 806 807
        # if not self._tdeSubProcess.stop(): # everything withing
        #     if self._tdeSubProcess.isRunning():  # still running, should now never happen
        #         Logging.error("FAILED to stop sub process, it is still running... pid = {}".format(
        #             self._tdeSubProcess.getPid()))
        #     else:
        #         self._tdeSubProcess = None  # not running any more
        self.join()  # stop the thread, change the status, etc.
808 809

        # Check if it's really stopped
810 811
        outputLines = 10 # for last output
        if  self.getStatus().isStopped():
812
            self.procIpcBatch(outputLines)  # one last time
813
            Logging.debug("End of TDengine Service Output")
814
            Logging.info("----- TDengine Service (managed by SMT) is now terminated -----\n")
815
        else:
816
            print("WARNING: SMT did not terminate as expected")
817 818 819

    def join(self):
        # TODO: sanity check
820 821 822 823 824 825 826 827 828 829 830 831
        s = self.getStatus()
        if s.isStopping() or s.isStopped(): # we may be stopping ourselves, or have been stopped/killed by others
            if self._thread or self._thread2 :
                if self._thread:
                    self._thread.join()
                    self._thread = None
                if self._thread2: # STD ERR thread            
                    self._thread2.join()
                    self._thread2 = None
            else:
                Logging.warning("Joining empty thread, doing nothing")
        else:
832
            raise RuntimeError(
833
                "SMT.Join(): Unexpected status: {}".format(self._status))
834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852

    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):
853 854
        '''
        Process a batch of STDOUT/STDERR data, until we read EMPTY from
855
        the queue.
856
        '''
857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
        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 已提交
872
                    Logging.info('[TAOSD] ' + line)
873
                else:
S
Steven Li 已提交
874
                    Logging.debug('[TAOSD] ' + line)
875 876 877 878 879 880 881 882 883 884
        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)

885 886 887
    BinaryChunk = NewType('BinaryChunk', bytes) # line with binary data, directly from STDOUT, etc.
    TextChunk   = NewType('TextChunk', str) # properly decoded, suitable for printing, etc.
   
888
    @classmethod
889
    def _decodeBinaryChunk(cls, bChunk: bytes) -> Optional[TextChunk] :
890
        try:
891 892
            tChunk = bChunk.decode("utf-8").rstrip() 
            return cls.TextChunk(tChunk)
893
        except UnicodeError:
894
            print("\nNon-UTF8 server output: {}\n".format(bChunk.decode('cp437')))
895 896
            return None

897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915
    def _textChunkGenerator(self, streamIn: BinaryIO, logDir: str, logFile: str
            ) -> Generator[TextChunk, None, None]:
        '''
        Take an input stream with binary data, produced a generator of decoded
        "text chunks", and also save the original binary data in a log file.
        '''
        os.makedirs(logDir, exist_ok=True)
        logF = open(os.path.join(logDir, logFile), 'wb')
        for bChunk in iter(streamIn.readline, b''):
            logF.write(bChunk) # Write to log file immediately
            tChunk = self._decodeBinaryChunk(bChunk) # decode
            if tChunk is not None:
                yield tChunk # TODO: split into actual text lines

        # At the end...
        streamIn.close() # Close the stream
        logF.close() # Close the output file

    def svcOutputReader(self, stdOut: BinaryIO, queue, logDir: str):
916 917 918
        '''
        The infinite routine that processes the STDOUT stream for the sub process being managed.

919 920
        :param stdOut: the IO stream object used to fetch the data from
        :param queue: the queue where we dump the roughly parsed chunk-by-chunk text data
921 922
        :param logDir: where we should dump a verbatim output file
        '''
923
        
924 925
        # Important Reference: https://stackoverflow.com/questions/375427/non-blocking-read-on-a-subprocess-pipe-in-python
        # print("This is the svcOutput Reader...")
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
        # stdOut.readline() # Skip the first output? TODO: remove?
        for tChunk in self._textChunkGenerator(stdOut, logDir, 'stdout.log') :
            queue.put(tChunk) # tChunk garanteed not to be None
            self._printProgress("_i")

            if self._status.isStarting():  # we are starting, let's see if we have started
                if tChunk.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
                    Logging.info("Service is now FULLY READY") # TODO: more ID info here?
                    self._status.set(Status.STATUS_RUNNING)

            # 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

            if self._status.isStopping():  # TODO: use thread status instead
                # WAITING for stopping sub process to finish its outptu
                print("_w", end="", flush=True)
944 945

            # queue.put(line)
946
        # stdOut has no more data, meaning sub process must have died
947 948
        Logging.info("EOF found TDengine STDOUT, marking the process as terminated")
        self.setStatus(Status.STATUS_STOPPED)
949

950 951 952 953 954 955 956 957 958
    def svcErrorReader(self, stdErr: BinaryIO, queue, logDir: str):
        # os.makedirs(logDir, exist_ok=True)
        # logFile = os.path.join(logDir,'stderr.log')
        # fErr = open(logFile, 'wb')
        # for line in iter(err.readline, b''):
        for tChunk in self._textChunkGenerator(stdErr, logDir, 'stderr.log') :
            queue.put(tChunk) # tChunk garanteed not to be None
            # fErr.write(line)
            Logging.info("TDengine STDERR: {}".format(tChunk))
959
        Logging.info("EOF for TDengine STDERR")