channel.py 33.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# pylint: disable=doc-string-missing
B
barriery 已提交
15
from time import time as _time
D
dongdaxiang 已提交
16 17 18 19 20 21 22 23 24 25
import threading
import multiprocessing
import multiprocessing.queues
import sys
if sys.version_info.major == 2:
    import Queue
elif sys.version_info.major == 3:
    import queue as Queue
else:
    raise Exception("Error Python version")
26 27 28
import numpy as np
import logging
import enum
29
import os
30
import copy
D
dongdaxiang 已提交
31

32
_LOGGER = logging.getLogger(__name__)
B
barrierye 已提交
33

D
dongdaxiang 已提交
34

T
TeslaZhao 已提交
35 36 37 38
class ChannelDataErrcode(enum.Enum):
    """
    ChannelData error code
    """
D
dongdaxiang 已提交
39 40 41 42 43
    OK = 0
    TIMEOUT = 1
    NOT_IMPLEMENTED = 2
    TYPE_ERROR = 3
    RPC_PACKAGE_ERROR = 4
B
barrierye 已提交
44
    CLIENT_ERROR = 5
B
barrierye 已提交
45
    CLOSED_ERROR = 6
B
barriery 已提交
46 47
    NO_SERVICE = 7
    UNKNOW = 8
T
TeslaZhao 已提交
48 49 50 51 52 53 54 55 56
    PRODUCT_ERROR = 9


class ProductErrCode(enum.Enum):
    """
    ProductErrCode is a base class for recording business error code. 
    product developers inherit this class and extend more error codes. 
    """
    pass
D
dongdaxiang 已提交
57 58 59


class ChannelDataType(enum.Enum):
60 61 62
    """
    Channel data type
    """
D
dongdaxiang 已提交
63 64 65 66 67
    DICT = 0
    CHANNEL_NPDATA = 1
    ERROR = 2


68 69 70 71
class ChannelData(object):
    def __init__(self,
                 datatype=None,
                 npdata=None,
B
barrierye 已提交
72
                 dictdata=None,
73
                 data_id=None,
T
TeslaZhao 已提交
74 75
                 log_id=None,
                 error_code=None,
B
barrierye 已提交
76
                 error_info=None,
T
TeslaZhao 已提交
77 78
                 prod_error_code=None,
                 prod_error_info=None,
B
barrierye 已提交
79
                 client_need_profile=False):
80 81 82
        '''
        There are several ways to use it:
        
T
TeslaZhao 已提交
83 84 85
        1. ChannelData(ChannelDataType.CHANNEL_NPDATA.value, npdata, data_id, log_id)
        2. ChannelData(ChannelDataType.DICT.value, dictdata, data_id, log_id)
        3. ChannelData(error_code, error_info, prod_error_code, prod_error_info, data_id, log_id)
86 87 88 89

        Protobufs are not pickle-able:
        https://stackoverflow.com/questions/55344376/how-to-import-protobuf-module
        '''
T
TeslaZhao 已提交
90
        if error_code is not None or prod_error_code is not None:
91
            if data_id is None or error_info is None:
B
barriery 已提交
92 93
                _LOGGER.critical("Failed to generate ChannelData: data_id"
                                 " and error_info cannot be None")
94
                os._exit(-1)
95 96
            datatype = ChannelDataType.ERROR.value
        else:
B
barrierye 已提交
97
            if datatype == ChannelDataType.CHANNEL_NPDATA.value:
T
TeslaZhao 已提交
98 99
                error_code, error_info = ChannelData.check_npdata(npdata)
                if error_code != ChannelDataErrcode.OK.value:
B
barrierye 已提交
100
                    datatype = ChannelDataType.ERROR.value
T
TeslaZhao 已提交
101 102
                    _LOGGER.error("(data_id={} log_id={}) {}".format(
                        data_id, log_id, error_info))
B
barrierye 已提交
103
            elif datatype == ChannelDataType.DICT.value:
T
TeslaZhao 已提交
104 105
                error_code, error_info = ChannelData.check_dictdata(dictdata)
                if error_code != ChannelDataErrcode.OK.value:
B
barrierye 已提交
106
                    datatype = ChannelDataType.ERROR.value
T
TeslaZhao 已提交
107 108
                    _LOGGER.error("(data_id={} log_id={}) {}".format(
                        data_id, log_id, error_info))
109
            else:
T
TeslaZhao 已提交
110 111
                _LOGGER.critical("(data_id={} log_id={}) datatype not match".
                                 format(data_id, log_id))
112
                os._exit(-1)
113
        self.datatype = datatype
B
barrierye 已提交
114 115
        self.npdata = npdata
        self.dictdata = dictdata
116
        self.id = data_id
T
TeslaZhao 已提交
117 118
        self.log_id = log_id
        self.error_code = error_code
119
        self.error_info = error_info
T
TeslaZhao 已提交
120 121
        self.prod_error_code = prod_error_code
        self.prod_error_info = prod_error_info
B
barrierye 已提交
122
        self.client_need_profile = client_need_profile
B
barrierye 已提交
123
        self.profile_data_set = set()
B
barrierye 已提交
124

B
barrierye 已提交
125
    def add_profile(self, profile_set):
B
barrierye 已提交
126 127
        if self.client_need_profile is False:
            self.client_need_profile = True
B
barrierye 已提交
128
        self.profile_data_set |= profile_set
129

B
barrierye 已提交
130 131
    @staticmethod
    def check_dictdata(dictdata):
T
TeslaZhao 已提交
132
        error_code = ChannelDataErrcode.OK.value
B
barrierye 已提交
133
        error_info = None
B
barrierye 已提交
134 135 136 137
        if isinstance(dictdata, list):
            # batch data
            for sample in dictdata:
                if not isinstance(sample, dict):
T
TeslaZhao 已提交
138
                    error_code = ChannelDataErrcode.TYPE_ERROR.value
B
barriery 已提交
139 140
                    error_info = "Failed to check data: the type of " \
                            "data must be dict, but get {}.".format(type(sample))
B
barrierye 已提交
141 142 143
                    break
        elif not isinstance(dictdata, dict):
            # batch size = 1
T
TeslaZhao 已提交
144
            error_code = ChannelDataErrcode.TYPE_ERROR.value
B
barriery 已提交
145 146
            error_info = "Failed to check data: the type of data must " \
                    "be dict, but get {}.".format(type(dictdata))
T
TeslaZhao 已提交
147
        return error_code, error_info
B
barrierye 已提交
148

B
bug fix  
barriery 已提交
149 150
    @staticmethod
    def check_batch_npdata(batch):
T
TeslaZhao 已提交
151
        error_code = ChannelDataErrcode.OK.value
B
bug fix  
barriery 已提交
152 153
        error_info = None
        for npdata in batch:
T
TeslaZhao 已提交
154 155
            error_code, error_info = ChannelData.check_npdata(npdata)
            if error_code != ChannelDataErrcode.OK.value:
B
bug fix  
barriery 已提交
156
                break
T
TeslaZhao 已提交
157
        return error_code, error_info
B
bug fix  
barriery 已提交
158

B
barrierye 已提交
159 160
    @staticmethod
    def check_npdata(npdata):
T
TeslaZhao 已提交
161
        error_code = ChannelDataErrcode.OK.value
162
        error_info = None
W
wangjiawei04 已提交
163 164 165 166
        if isinstance(npdata, list):
            # batch data
            for sample in npdata:
                if not isinstance(sample, dict):
T
TeslaZhao 已提交
167
                    error_code = ChannelDataErrcode.TYPE_ERROR.value
B
barriery 已提交
168 169 170
                    error_info = "Failed to check data: the " \
                            "value of data must be dict, but get {}.".format(
                                    type(sample))
W
wangjiawei04 已提交
171 172 173
                    break
                for _, value in sample.items():
                    if not isinstance(value, np.ndarray):
T
TeslaZhao 已提交
174
                        error_code = ChannelDataErrcode.TYPE_ERROR.value
B
barriery 已提交
175 176 177
                        error_info = "Failed to check data: the" \
                                " value of data must be np.ndarray, but get {}.".format(
                                        type(value))
T
TeslaZhao 已提交
178
                        return error_code, error_info
W
wangjiawei04 已提交
179 180 181 182
        elif isinstance(npdata, dict):
            # batch_size = 1
            for _, value in npdata.items():
                if not isinstance(value, np.ndarray):
T
TeslaZhao 已提交
183
                    error_code = ChannelDataErrcode.TYPE_ERROR.value
B
barriery 已提交
184 185 186
                    error_info = "Failed to check data: the value " \
                            "of data must be np.ndarray, but get {}.".format(
                                    type(value))
W
wangjiawei04 已提交
187 188
                    break
        else:
T
TeslaZhao 已提交
189
            error_code = ChannelDataErrcode.TYPE_ERROR.value
B
barriery 已提交
190 191
            error_info = "Failed to check data: the value of data " \
                    "must be dict, but get {}.".format(type(npdata))
T
TeslaZhao 已提交
192
        return error_code, error_info
193 194 195

    def parse(self):
        feed = None
B
barrierye 已提交
196 197
        if self.datatype == ChannelDataType.CHANNEL_NPDATA.value:
            # return narray
198
            feed = self.npdata
B
barrierye 已提交
199 200 201
        elif self.datatype == ChannelDataType.DICT.value:
            # return dict
            feed = self.dictdata
202
        else:
B
barriery 已提交
203 204
            _LOGGER.critical("Failed to parse channeldata: error " \
                    "type({}) in datatype.".format(self.datatype))
205
            os._exit(-1)
206 207
        return feed

208 209 210 211 212 213 214 215
    def __cmp__(self, other):
        if self.id < other.id:
            return -1
        elif self.id == other.id:
            return 0
        else:
            return 1

216
    def __str__(self):
217
        return "type[{}], error_code[{}], data_id[{}], log_id[{}], dict_data[{}]".format(
T
TeslaZhao 已提交
218
            ChannelDataType(self.datatype).name, self.error_code, self.id,
219
            self.log_id, str(self.dictdata))
220 221


B
barrierye 已提交
222
class ProcessChannel(object):
223 224 225 226 227 228 229 230 231
    """ 
    (Process version) The channel used for communication between Ops.

    1. Support multiple different Op feed data (multiple producer)
        Different types of data will be packaged through the data ID
    2. Support multiple different Op fetch data (multiple consumer)
        Only when all types of Ops get the data of the same ID,
        the data will be poped; The Op of the same type will not
        get the data of the same ID.
B
barriery 已提交
232
    3. Function front support timeout param to make auto-batching.
233 234 235 236 237

    Note:
    1. The ID of the data in the channel must be different.
    2. The function add_producer() and add_consumer() are not thread safe,
       and can only be called during initialization.
B
barrierye 已提交
238 239 240 241 242 243 244 245 246 247 248

    There are two buffers and one queue in Channel:

        op_A \                                           / op_D
        op_B - a. input_buf -> b. queue -> c. output_buf - op_E
        op_C /                                           \ op_F
    
    a. In input_buf, the input of multiple predecessor Ops is packed by data ID.
    b. The packed data will be stored in queue.
    c. In order to support multiple successor Ops to retrieve data, output_buf
        maintains the data obtained from queue.
249 250
    """

B
barriery 已提交
251
    def __init__(self, manager, name=None, maxsize=0):
B
barrierye 已提交
252 253 254 255 256 257
        # For queue multiprocess: after putting an object on 
        # an empty queue there may be an infinitessimal delay
        # before the queue's :meth:`~Queue.empty`
        # see more:
        # - https://bugs.python.org/issue18277
        # - https://hg.python.org/cpython/rev/860fc6a2bd21
258
        self._que = manager.PriorityQueue(maxsize=maxsize)
259 260
        self._maxsize = maxsize
        self.name = name
261
        self._stop = manager.Value('i', 0)
262 263 264 265

        self._cv = multiprocessing.Condition()

        self._producers = []
B
barrierye 已提交
266
        self._pushed_producer_count = manager.dict()  # {data_id: count}
B
barrierye 已提交
267
        self._input_buf = manager.dict()  # {data_id: {op_name: data}}
268

269
        self._reset_max_cursor = 1000000000000000000
B
barrierye 已提交
270 271 272 273
        self._consumer_cursors = manager.dict()  # {op_name: cursor}
        self._cursor_count = manager.dict()  # {cursor: count}
        self._base_cursor = manager.Value('i', 0)
        self._output_buf = manager.list()
274

B
barriery 已提交
275 276 277
    def get_maxsize(self):
        return self._maxsize

B
barriery 已提交
278 279 280
    def size(self):
        return self._que.qsize()

281 282 283 284
    def get_producers(self):
        return self._producers

    def get_consumers(self):
B
barrierye 已提交
285
        return self._consumer_cursors.keys()
286 287 288 289 290 291 292

    def _log(self, info_str):
        return "[{}] {}".format(self.name, info_str)

    def add_producer(self, op_name):
        """ not thread safe, and can only be called during initialization. """
        if op_name in self._producers:
293
            _LOGGER.critical(
B
barriery 已提交
294 295
                self._log("Failed to add producer: producer({})" \
                        " is already in channel".format(op_name)))
296
            os._exit(-1)
297
        self._producers.append(op_name)
B
barriery 已提交
298
        _LOGGER.debug(self._log("Succ add a producer: {}".format(op_name)))
299 300 301

    def add_consumer(self, op_name):
        """ not thread safe, and can only be called during initialization. """
B
barrierye 已提交
302
        if op_name in self._consumer_cursors:
303
            _LOGGER.critical(
B
barriery 已提交
304 305
                    self._log("Failed to add consumer: consumer({})" \
                            " is already in channel".format(op_name)))
306
            os._exit(-1)
B
barrierye 已提交
307
        self._consumer_cursors[op_name] = 0
308

B
barrierye 已提交
309 310 311
        if self._cursor_count.get(0) is None:
            self._cursor_count[0] = 0
        self._cursor_count[0] += 1
B
barriery 已提交
312
        _LOGGER.debug(self._log("Succ add a consumer: {}".format(op_name)))
313 314

    def push(self, channeldata, op_name=None):
B
barrierye 已提交
315
        _LOGGER.debug(
316 317
            self._log("(data_id={} log_id={}) Op({}) Enter channel::push".
                      format(channeldata.id, channeldata.log_id, op_name)))
318
        if len(self._producers) == 0:
319
            _LOGGER.critical(
320
                self._log(
T
TeslaZhao 已提交
321
                    "(data_id={} log_id={}) Op({}) Failed to push data: expected number"
B
barriery 已提交
322
                    " of producers to be greater than 0, but the it is 0.".
T
TeslaZhao 已提交
323
                    format(channeldata.id, channeldata.log_id, op_name)))
324
            os._exit(-1)
325 326
        elif len(self._producers) == 1:
            with self._cv:
327
                while self._stop.value == 0:
328
                    try:
B
barrierye 已提交
329
                        self._que.put({op_name: channeldata}, timeout=0)
330 331 332
                        break
                    except Queue.Full:
                        self._cv.wait()
333
                if self._stop.value == 1:
B
barrierye 已提交
334
                    raise ChannelStopError()
335
                self._cv.notify_all()
B
barriery 已提交
336
            _LOGGER.debug(
T
TeslaZhao 已提交
337 338 339
                self._log(
                    "(data_id={} log_id={}) Op({}) Pushed data into internal queue.".
                    format(channeldata.id, channeldata.log_id, op_name)))
340 341
            return True
        elif op_name is None:
342
            _LOGGER.critical(
343
                self._log(
T
TeslaZhao 已提交
344
                    "(data_id={} log_id={}) Op({}) Failed to push data: there are multiple "
B
barriery 已提交
345
                    "producers, so op_name cannot be None.".format(
T
TeslaZhao 已提交
346
                        channeldata.id, channeldata.log_id, op_name)))
347
            os._exit(-1)
348 349 350

        producer_num = len(self._producers)
        data_id = channeldata.id
T
TeslaZhao 已提交
351
        log_id = channeldata.log_id
352 353
        put_data = None
        with self._cv:
B
barrierye 已提交
354 355
            if data_id not in self._input_buf:
                self._input_buf[data_id] = {
356 357 358
                    name: None
                    for name in self._producers
                }
B
barrierye 已提交
359
                self._pushed_producer_count[data_id] = 0
360
            # see: https://docs.python.org/3.6/library/multiprocessing.html?highlight=multiprocess#proxy-objects
B
barrierye 已提交
361 362 363 364 365
            # self._input_buf[data_id][op_name] = channeldata
            tmp_input_buf = self._input_buf[data_id]
            tmp_input_buf[op_name] = channeldata
            self._input_buf[data_id] = tmp_input_buf

B
barrierye 已提交
366
            if self._pushed_producer_count[data_id] + 1 == producer_num:
B
barrierye 已提交
367 368
                put_data = self._input_buf[data_id]
                self._input_buf.pop(data_id)
B
barrierye 已提交
369
                self._pushed_producer_count.pop(data_id)
370
            else:
B
barrierye 已提交
371
                self._pushed_producer_count[data_id] += 1
372 373

            if put_data is None:
B
barrierye 已提交
374
                _LOGGER.debug(
B
barriery 已提交
375
                    self._log(
T
TeslaZhao 已提交
376 377
                        "(data_id={} log_id={}) Op({}) Pushed data into input_buffer.".
                        format(data_id, log_id, op_name)))
378
            else:
379
                while self._stop.value == 0:
380
                    try:
B
barrierye 已提交
381
                        self._que.put(put_data, timeout=0)
382 383 384
                        break
                    except Queue.Empty:
                        self._cv.wait()
385
                if self._stop.value == 1:
B
barrierye 已提交
386
                    raise ChannelStopError()
387

B
barrierye 已提交
388
                _LOGGER.debug(
B
barriery 已提交
389
                    self._log(
T
TeslaZhao 已提交
390 391
                        "(data_id={} log_id={}) Op({}) Pushed data into internal_queue.".
                        format(data_id, log_id, op_name)))
392 393 394
            self._cv.notify_all()
        return True

B
barriery 已提交
395
    def front(self, op_name=None, timeout=None):
B
barriery 已提交
396
        _LOGGER.debug(
B
barriery 已提交
397 398
            self._log("Op({}) Getting data[?]; timeout(s)={}".format(op_name,
                                                                     timeout)))
B
barriery 已提交
399
        endtime = None
B
bug fix  
barriery 已提交
400 401 402 403 404
        if timeout is not None:
            if timeout <= 0:
                timeout = None
            else:
                endtime = _time() + timeout
B
barriery 已提交
405

B
barrierye 已提交
406
        if len(self._consumer_cursors) == 0:
407
            _LOGGER.critical(
408
                self._log(
B
barriery 已提交
409 410
                    "Op({}) Failed to get data: expected number of consumers to be " \
                            "greater than 0, but the it is 0.".format(op_name)))
411
            os._exit(-1)
B
barrierye 已提交
412
        elif len(self._consumer_cursors) == 1:
413 414
            resp = None
            with self._cv:
415
                while self._stop.value == 0 and resp is None:
416
                    try:
B
barrierye 已提交
417
                        resp = self._que.get(timeout=0)
418 419
                        break
                    except Queue.Empty:
B
barriery 已提交
420 421 422
                        if timeout is not None:
                            remaining = endtime - _time()
                            if remaining <= 0.0:
B
barriery 已提交
423
                                _LOGGER.debug(
B
barriery 已提交
424 425
                                    self._log("Op({}) Failed to get data: "
                                              "timeout".format(op_name)))
B
barriery 已提交
426 427 428 429
                                raise ChannelTimeoutError()
                            self._cv.wait(remaining)
                        else:
                            self._cv.wait()
430
                if self._stop.value == 1:
B
barrierye 已提交
431
                    raise ChannelStopError()
B
barriery 已提交
432
            _LOGGER.debug(
T
TeslaZhao 已提交
433 434
                self._log("(data_id={} log_id={}) Op({}) Got data".format(
                    resp.values()[0].id, resp.values()[0].log_id, op_name)))
435 436
            return resp
        elif op_name is None:
437
            _LOGGER.critical(
438
                self._log(
B
barriery 已提交
439 440
                    "Op({}) Failed to get data: there are multiple consumers, "
                    "so op_name cannot be None.".format(op_name)))
441
            os._exit(-1)
442

B
barrierye 已提交
443 444 445 446 447 448 449 450 451 452
        # In output_buf, different Ops (according to op_name) have different
        # cursors. In addition, there is a base_cursor. Their difference is
        # the data_idx to be taken by the corresponding Op at the current
        # time:    data_idx = consumer_cursor - base_cursor
        # 
        #            base_cursor    consumer_B_cursor (data_idx: 3)
        #                 |                       |
        # output_buf: | data0 | data1 | data2 | data3 |
        #                 |
        #   consumer_A_cursor (data_idx: 0)
453
        with self._cv:
B
barrierye 已提交
454 455
            # When the data required by the current Op is not in output_buf,
            # it is necessary to obtain a data from queue and add it to output_buf.
456
            while self._stop.value == 0 and self._consumer_cursors[
B
barrierye 已提交
457
                    op_name] - self._base_cursor.value >= len(self._output_buf):
458
                try:
B
barrierye 已提交
459
                    channeldata = self._que.get(timeout=0)
B
barrierye 已提交
460
                    self._output_buf.append(channeldata)
B
barriery 已提交
461
                    _LOGGER.debug(
B
barriery 已提交
462
                        self._log(
T
TeslaZhao 已提交
463 464 465
                            "(data_id={} log_id={}) Op({}) Pop ready item into output_buffer".
                            format(channeldata.values()[0].id,
                                   channeldata.values()[0].log_id, op_name)))
466 467
                    break
                except Queue.Empty:
B
barriery 已提交
468 469 470
                    if timeout is not None:
                        remaining = endtime - _time()
                        if remaining <= 0.0:
B
barriery 已提交
471
                            _LOGGER.debug(
B
barriery 已提交
472 473
                                self._log("Op({}) Failed to get data: timeout".
                                          format(op_name)))
B
barriery 已提交
474 475 476 477
                            raise ChannelTimeoutError()
                        self._cv.wait(remaining)
                    else:
                        self._cv.wait()
478
            if self._stop.value == 1:
B
barrierye 已提交
479
                raise ChannelStopError()
480

B
barrierye 已提交
481 482 483 484
            consumer_cursor = self._consumer_cursors[op_name]
            base_cursor = self._base_cursor.value
            data_idx = consumer_cursor - base_cursor
            resp = self._output_buf[data_idx]
485

B
barrierye 已提交
486 487 488 489 490 491 492 493
            self._cursor_count[consumer_cursor] -= 1
            if consumer_cursor == base_cursor and self._cursor_count[
                    consumer_cursor] == 0:
                # When all the different Ops get the data that data_idx points
                # to, pop the data from output_buf.
                self._cursor_count.pop(consumer_cursor)
                self._output_buf.pop(0)
                self._base_cursor.value += 1
494 495
                # to avoid cursor overflow
                if self._base_cursor.value >= self._reset_max_cursor:
B
barriery 已提交
496
                    _LOGGER.info(self._log("Reset cursor in Channel"))
497 498 499 500 501 502 503 504 505 506
                    self._base_cursor.value -= self._reset_max_cursor
                    for name in self._consumer_cursors.keys():
                        self._consumer_cursors[name] -= self._reset_max_cursor
                    cursor_count_tmp = {
                        cursor - self._reset_max_cursor: count
                        for cursor, count in self._cursor_count.copy().items()
                    }
                    self._cursor_count.clear()
                    for cursor, count in cursor_count_tmp.items():
                        self._cursor_count[cursor] = count
B
barrierye 已提交
507 508 509 510 511 512

            self._consumer_cursors[op_name] += 1
            new_consumer_cursor = self._consumer_cursors[op_name]
            if self._cursor_count.get(new_consumer_cursor) is None:
                self._cursor_count[new_consumer_cursor] = 0
            self._cursor_count[new_consumer_cursor] += 1
513

514 515
            self._cv.notify_all()

B
barriery 已提交
516
        _LOGGER.debug(
T
TeslaZhao 已提交
517 518 519
            self._log(
                "(data_id={} log_id={}) Op({}) Got data from output_buffer".
                format(resp.values()[0].id, resp.values()[0].log_id, op_name)))
B
barriery 已提交
520
        return resp
521 522

    def stop(self):
523
        _LOGGER.info(self._log("stop."))
524
        self._stop.value = 1
B
barrierye 已提交
525 526
        with self._cv:
            self._cv.notify_all()
527 528


529
class ThreadChannel(Queue.PriorityQueue):
530 531 532 533 534 535 536 537 538
    """ 
    (Thread version)The channel used for communication between Ops.

    1. Support multiple different Op feed data (multiple producer)
        Different types of data will be packaged through the data ID
    2. Support multiple different Op fetch data (multiple consumer)
        Only when all types of Ops get the data of the same ID,
        the data will be poped; The Op of the same type will not
        get the data of the same ID.
B
barriery 已提交
539
    3. Function front support timeout param to make auto-batching.
540 541 542 543 544

    Note:
    1. The ID of the data in the channel must be different.
    2. The function add_producer() and add_consumer() are not thread safe,
       and can only be called during initialization.
B
barrierye 已提交
545 546 547 548 549 550 551 552 553 554 555

    There are two buffers and one queue in Channel:

        op_A \                                           / op_D
        op_B - a. input_buf -> b. queue -> c. output_buf - op_E
        op_C /                                           \ op_F
    
    a. In input_buf, the input of multiple predecessor Ops is packed by data ID.
    b. The packed data will be stored in queue.
    c. In order to support multiple successor Ops to retrieve data, output_buf
        maintains the data obtained from queue.
556 557
    """

B
barriery 已提交
558
    def __init__(self, name=None, maxsize=-1):
559 560 561 562 563 564 565 566
        Queue.Queue.__init__(self, maxsize=maxsize)
        self._maxsize = maxsize
        self.name = name
        self._stop = False

        self._cv = threading.Condition()

        self._producers = []
B
barrierye 已提交
567
        self._pushed_producer_count = {}  # {data_id: count}
B
barrierye 已提交
568
        self._input_buf = {}  # {data_id: {op_name: data}}
569

570
        self._reset_max_cursor = 1000000000000000000
B
barrierye 已提交
571 572 573 574
        self._consumer_cursors = {}  # {op_name: idx}
        self._cursor_count = {}  # {cursor: count}
        self._base_cursor = 0
        self._output_buf = []
575

B
barriery 已提交
576 577 578
    def get_maxsize(self):
        return self._maxsize

B
barriery 已提交
579 580 581
    def size(self):
        return self.qsize()

582 583 584 585
    def get_producers(self):
        return self._producers

    def get_consumers(self):
B
barrierye 已提交
586
        return self._consumer_cursors.keys()
587 588 589 590 591 592 593

    def _log(self, info_str):
        return "[{}] {}".format(self.name, info_str)

    def add_producer(self, op_name):
        """ not thread safe, and can only be called during initialization. """
        if op_name in self._producers:
594
            _LOGGER.critical(
B
barriery 已提交
595 596
                self._log("Failed to add producer: producer({}) is "
                          "already in channel".format(op_name)))
597
            os._exit(-1)
598
        self._producers.append(op_name)
B
barriery 已提交
599
        _LOGGER.debug(self._log("Succ add a producer: {}".format(op_name)))
600 601 602

    def add_consumer(self, op_name):
        """ not thread safe, and can only be called during initialization. """
B
barrierye 已提交
603
        if op_name in self._consumer_cursors:
604
            _LOGGER.critical(
B
barriery 已提交
605 606
                self._log("Failed to add consumer: consumer({}) is "
                          "already in channel".format(op_name)))
607
            os._exit(-1)
B
barrierye 已提交
608
        self._consumer_cursors[op_name] = 0
609

B
barrierye 已提交
610 611 612
        if self._cursor_count.get(0) is None:
            self._cursor_count[0] = 0
        self._cursor_count[0] += 1
B
barriery 已提交
613
        _LOGGER.debug(self._log("Succ add a consumer: {}".format(op_name)))
614 615

    def push(self, channeldata, op_name=None):
B
barrierye 已提交
616
        _LOGGER.debug(
T
TeslaZhao 已提交
617 618
            self._log("(data_id={} log_id={}) Op({}) Pushing data".format(
                channeldata.id, channeldata.log_id, op_name)))
619
        if len(self._producers) == 0:
620
            _LOGGER.critical(
621
                self._log(
T
TeslaZhao 已提交
622
                    "(data_id={} log_id={}) Op({}) Failed to push data: expected number of "
B
barriery 已提交
623
                    "producers to be greater than 0, but the it is 0.".format(
T
TeslaZhao 已提交
624
                        channeldata.id, channeldata.log_id, op_name)))
625
            os._exit(-1)
626 627 628 629
        elif len(self._producers) == 1:
            with self._cv:
                while self._stop is False:
                    try:
B
barrierye 已提交
630
                        self.put({op_name: channeldata}, timeout=0)
631 632 633
                        break
                    except Queue.Full:
                        self._cv.wait()
B
barrierye 已提交
634 635
                if self._stop:
                    raise ChannelStopError()
636
                self._cv.notify_all()
B
barriery 已提交
637
            _LOGGER.debug(
T
TeslaZhao 已提交
638 639 640
                self._log(
                    "(data_id={} log_id={}) Op({}) Pushed data into internal_queue.".
                    format(channeldata.id, channeldata.log_id, op_name)))
641 642
            return True
        elif op_name is None:
643
            _LOGGER.critical(
644
                self._log(
T
TeslaZhao 已提交
645
                    "(data_id={} log_id={}) Op({}) Failed to push data: there are multiple"
B
barriery 已提交
646
                    " producers, so op_name cannot be None.".format(
T
TeslaZhao 已提交
647
                        channeldata.id, channeldata.log_id, op_name)))
648
            os._exit(-1)
649 650 651

        producer_num = len(self._producers)
        data_id = channeldata.id
T
TeslaZhao 已提交
652
        log_id = channeldata.log_id
653 654
        put_data = None
        with self._cv:
B
barrierye 已提交
655 656
            if data_id not in self._input_buf:
                self._input_buf[data_id] = {
657 658 659
                    name: None
                    for name in self._producers
                }
B
barrierye 已提交
660
                self._pushed_producer_count[data_id] = 0
B
barrierye 已提交
661
            self._input_buf[data_id][op_name] = channeldata
B
barrierye 已提交
662
            if self._pushed_producer_count[data_id] + 1 == producer_num:
B
barrierye 已提交
663 664
                put_data = self._input_buf[data_id]
                self._input_buf.pop(data_id)
B
barrierye 已提交
665
                self._pushed_producer_count.pop(data_id)
666
            else:
B
barrierye 已提交
667
                self._pushed_producer_count[data_id] += 1
668 669

            if put_data is None:
B
barrierye 已提交
670
                _LOGGER.debug(
B
barriery 已提交
671
                    self._log(
T
TeslaZhao 已提交
672 673
                        "(data_id={} log_id={}) Op({}) Pushed data into input_buffer.".
                        format(data_id, log_id, op_name)))
674 675 676 677 678 679 680
            else:
                while self._stop is False:
                    try:
                        self.put(put_data, timeout=0)
                        break
                    except Queue.Empty:
                        self._cv.wait()
B
barrierye 已提交
681 682
                if self._stop:
                    raise ChannelStopError()
683

B
barrierye 已提交
684
                _LOGGER.debug(
B
barriery 已提交
685
                    self._log(
T
TeslaZhao 已提交
686 687
                        "(data_id={} log_id={}) Op({}) Pushed data into internal_queue.".
                        format(data_id, log_id, op_name)))
688 689 690
            self._cv.notify_all()
        return True

B
barriery 已提交
691
    def front(self, op_name=None, timeout=None):
B
barriery 已提交
692
        _LOGGER.debug(
B
barriery 已提交
693 694
            self._log("Op({}) Getting data[?]; timeout(s)={}".format(op_name,
                                                                     timeout)))
B
barriery 已提交
695
        endtime = None
B
bug fix  
barriery 已提交
696 697 698 699 700
        if timeout is not None:
            if timeout <= 0:
                timeout = None
            else:
                endtime = _time() + timeout
B
barriery 已提交
701

B
barrierye 已提交
702
        if len(self._consumer_cursors) == 0:
703
            _LOGGER.critical(
704
                self._log(
B
barriery 已提交
705 706
                    "Op({}) Failed to get data: expected number of consumers to be "
                    "greater than 0, but the it is 0.".format(op_name)))
707
            os._exit(-1)
B
barrierye 已提交
708
        elif len(self._consumer_cursors) == 1:
709 710 711 712 713 714 715
            resp = None
            with self._cv:
                while self._stop is False and resp is None:
                    try:
                        resp = self.get(timeout=0)
                        break
                    except Queue.Empty:
B
barriery 已提交
716 717 718
                        if timeout is not None:
                            remaining = endtime - _time()
                            if remaining <= 0.0:
B
barriery 已提交
719
                                _LOGGER.debug(
B
barriery 已提交
720 721 722
                                    self._log(
                                        "Op({}) Failed to get data: timeout".
                                        format(op_name)))
B
barriery 已提交
723 724 725 726
                                raise ChannelTimeoutError()
                            self._cv.wait(remaining)
                        else:
                            self._cv.wait()
B
barrierye 已提交
727 728
                if self._stop:
                    raise ChannelStopError()
B
barrierye 已提交
729
            _LOGGER.debug(
T
TeslaZhao 已提交
730 731
                self._log("(data_id={} log_id={}) Op({}) Got data".format(
                    resp.values()[0].id, resp.values()[0].log_id, op_name)))
732 733
            return resp
        elif op_name is None:
734
            _LOGGER.critical(
B
barriery 已提交
735 736 737
                self._log("Op({}) Failed to get data: there are multiple "
                          "consumers, so op_name cannot be None.".format(
                              op_name)))
738
            os._exit(-1)
739

B
barrierye 已提交
740 741 742 743 744 745 746 747 748 749
        # In output_buf, different Ops (according to op_name) have different
        # cursors. In addition, there is a base_cursor. Their difference is
        # the data_idx to be taken by the corresponding Op at the current
        # time:    data_idx = consumer_cursor - base_cursor
        # 
        #            base_cursor    consumer_B_cursor (data_idx: 3)
        #                 |                       |
        # output_buf: | data0 | data1 | data2 | data3 |
        #                 |
        #   consumer_A_cursor (data_idx: 0)
750
        with self._cv:
B
barrierye 已提交
751 752 753 754
            # When the data required by the current Op is not in output_buf,
            # it is necessary to obtain a data from queue and add it to output_buf.
            while self._stop is False and self._consumer_cursors[
                    op_name] - self._base_cursor >= len(self._output_buf):
755 756
                try:
                    channeldata = self.get(timeout=0)
B
barrierye 已提交
757
                    self._output_buf.append(channeldata)
B
barriery 已提交
758
                    _LOGGER.debug(
B
barriery 已提交
759
                        self._log(
T
TeslaZhao 已提交
760 761 762
                            "(data_id={} log_id={}) Op({}) Pop ready item into output_buffer".
                            format(channeldata.values()[0].id,
                                   channeldata.values()[0].log_id, op_name)))
763 764
                    break
                except Queue.Empty:
B
barriery 已提交
765 766 767
                    if timeout is not None:
                        remaining = endtime - _time()
                        if remaining <= 0.0:
B
barriery 已提交
768
                            _LOGGER.debug(
B
barriery 已提交
769 770
                                self._log("Op({}) Failed to get data: timeout".
                                          format(op_name)))
B
barriery 已提交
771 772 773 774
                            raise ChannelTimeoutError()
                        self._cv.wait(remaining)
                    else:
                        self._cv.wait()
B
barrierye 已提交
775 776
            if self._stop:
                raise ChannelStopError()
777

B
barrierye 已提交
778 779 780
            consumer_cursor = self._consumer_cursors[op_name]
            base_cursor = self._base_cursor
            data_idx = consumer_cursor - base_cursor
B
barrierye 已提交
781 782

            resp = None
783

B
barrierye 已提交
784 785 786 787 788 789
            self._cursor_count[consumer_cursor] -= 1
            if consumer_cursor == base_cursor and self._cursor_count[
                    consumer_cursor] == 0:
                # When all the different Ops get the data that data_idx points
                # to, pop the data from output_buf.
                self._cursor_count.pop(consumer_cursor)
B
barrierye 已提交
790
                resp = self._output_buf.pop(0)
B
barrierye 已提交
791
                self._base_cursor += 1
792 793
                # to avoid cursor overflow
                if self._base_cursor >= self._reset_max_cursor:
B
barriery 已提交
794
                    _LOGGER.info(self._log("Reset cursor in Channel"))
795 796 797 798 799 800 801
                    self._base_cursor -= self._reset_max_cursor
                    for name in self._consumer_cursors:
                        self._consumer_cursors[name] -= self._reset_max_cursor
                    self._cursor_count = {
                        cursor - self._reset_max_cursor: count
                        for cursor, count in self._cursor_count.items()
                    }
B
barrierye 已提交
802 803
            else:
                resp = copy.deepcopy(self._output_buf[data_idx])
B
barrierye 已提交
804 805 806 807 808 809

            self._consumer_cursors[op_name] += 1
            new_consumer_cursor = self._consumer_cursors[op_name]
            if self._cursor_count.get(new_consumer_cursor) is None:
                self._cursor_count[new_consumer_cursor] = 0
            self._cursor_count[new_consumer_cursor] += 1
810 811 812

            self._cv.notify_all()

B
barriery 已提交
813
        _LOGGER.debug(
T
TeslaZhao 已提交
814 815 816
            self._log(
                "(data_id={} log_id={}) Op({}) Got data from output_buffer".
                format(resp.values()[0].id, resp.values()[0].log_id, op_name)))
B
barrierye 已提交
817
        return resp
818 819

    def stop(self):
820
        _LOGGER.info(self._log("stop."))
821
        self._stop = True
B
barrierye 已提交
822 823 824
        with self._cv:
            self._cv.notify_all()

B
barriery 已提交
825

B
barriery 已提交
826 827 828
class ChannelTimeoutError(RuntimeError):
    def __init__(self):
        pass
B
barrierye 已提交
829

B
barriery 已提交
830

B
barrierye 已提交
831 832 833
class ChannelStopError(RuntimeError):
    def __init__(self):
        pass