misc.py 4.8 KB
Newer Older
1 2 3
import threading
import random
import logging
4
import os
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29


class CrashGenError(Exception):
    def __init__(self, msg=None, errno=None):
        self.msg = msg
        self.errno = errno

    def __str__(self):
        return self.msg


class LoggingFilter(logging.Filter):
    def filter(self, record: logging.LogRecord):
        if (record.levelno >= logging.INFO):
            return True  # info or above always log

        # Commenting out below to adjust...

        # if msg.startswith("[TRD]"):
        #     return False
        return True


class MyLoggingAdapter(logging.LoggerAdapter):
    def process(self, msg, kwargs):
S
Steven Li 已提交
30
        return "[{:04d}] {}".format(threading.get_ident() % 10000, msg), kwargs
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
        # return '[%s] %s' % (self.extra['connid'], msg), kwargs


class Logging:
    logger = None

    @classmethod
    def getLogger(cls):
        return logger

    @classmethod
    def clsInit(cls, gConfig): # TODO: refactor away gConfig
        if cls.logger:
            return
        
        # Logging Stuff
        # global misc.logger
        _logger = logging.getLogger('CrashGen')  # real logger
        _logger.addFilter(LoggingFilter())
        ch = logging.StreamHandler()
        _logger.addHandler(ch)

        # Logging adapter, to be used as a logger
S
Steven Li 已提交
54
        # print("setting logger variable")
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
        # global logger
        cls.logger = MyLoggingAdapter(_logger, [])

        if (gConfig.debug):
            cls.logger.setLevel(logging.DEBUG)  # default seems to be INFO
        else:
            cls.logger.setLevel(logging.INFO)

    @classmethod
    def info(cls, msg):
        cls.logger.info(msg)

    @classmethod
    def debug(cls, msg):
        cls.logger.debug(msg)

    @classmethod
    def warning(cls, msg):
        cls.logger.warning(msg)

75 76 77 78
    @classmethod
    def error(cls, msg):
        cls.logger.error(msg)

79 80 81 82 83 84
class Status:
    STATUS_STARTING = 1
    STATUS_RUNNING  = 2
    STATUS_STOPPING = 3
    STATUS_STOPPED  = 4

85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
    def __init__(self, status):
        self.set(status)

    def __repr__(self):
        return "[Status: v={}]".format(self._status)

    def set(self, status):
        self._status = status

    def get(self):
        return self._status

    def isStarting(self):
        return self._status == Status.STATUS_STARTING

    def isRunning(self):
        # return self._thread and self._thread.is_alive()
        return self._status == Status.STATUS_RUNNING

    def isStopping(self):
        return self._status == Status.STATUS_STOPPING

    def isStopped(self):
        return self._status == Status.STATUS_STOPPED

    def isStable(self):
        return self.isRunning() or self.isStopped()

113 114 115 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
# Deterministic random number generator
class Dice():
    seeded = False  # static, uninitialized

    @classmethod
    def seed(cls, s):  # static
        if (cls.seeded):
            raise RuntimeError(
                "Cannot seed the random generator more than once")
        cls.verifyRNG()
        random.seed(s)
        cls.seeded = True  # TODO: protect against multi-threading

    @classmethod
    def verifyRNG(cls):  # Verify that the RNG is determinstic
        random.seed(0)
        x1 = random.randrange(0, 1000)
        x2 = random.randrange(0, 1000)
        x3 = random.randrange(0, 1000)
        if (x1 != 864 or x2 != 394 or x3 != 776):
            raise RuntimeError("System RNG is not deterministic")

    @classmethod
    def throw(cls, stop):  # get 0 to stop-1
        return cls.throwRange(0, stop)

    @classmethod
    def throwRange(cls, start, stop):  # up to stop-1
        if (not cls.seeded):
            raise RuntimeError("Cannot throw dice before seeding it")
        return random.randrange(start, stop)

    @classmethod
    def choice(cls, cList):
        return random.choice(cList)

class Helper:
    @classmethod
    def convertErrno(cls, errno):
        return errno if (errno > 0) else 0x80000000 + errno

154 155 156 157 158 159 160
    @classmethod
    def getFriendlyPath(cls, path): # returns .../xxx/yyy
        ht1 = os.path.split(path)
        ht2 = os.path.split(ht1[0])
        return ".../" + ht2[1] + '/' + ht1[1]


161 162 163 164
class Progress:
    STEP_BOUNDARY = 0
    BEGIN_THREAD_STEP = 1
    END_THREAD_STEP   = 2
165
    SERVICE_HEART_BEAT= 3
166 167 168
    SERVICE_RECONNECT_START     = 4
    SERVICE_RECONNECT_SUCCESS   = 5
    SERVICE_RECONNECT_FAILURE   = 6
S
Steven Li 已提交
169 170
    SERVICE_START_NAP           = 7
    CREATE_TABLE_ATTEMPT        = 8
171

172 173 174
    tokens = {
        STEP_BOUNDARY:      '.',
        BEGIN_THREAD_STEP:  '[',
175
        END_THREAD_STEP:    '] ',
176 177 178 179
        SERVICE_HEART_BEAT: '.Y.',
        SERVICE_RECONNECT_START:    '<r.',
        SERVICE_RECONNECT_SUCCESS:  '.r>',
        SERVICE_RECONNECT_FAILURE:  '.xr>',
S
Steven Li 已提交
180
        SERVICE_START_NAP:           '_zz',
181
        CREATE_TABLE_ATTEMPT: '_c',
182 183 184 185 186
    }

    @classmethod
    def emit(cls, token):
        print(cls.tokens[token], end="", flush=True)