channel.py 33.8 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()
T
TeslaZhao 已提交
432 433 434 435 436 437

            if resp is not None:
                list_values = list(resp.values())
                _LOGGER.debug(
                    self._log("(data_id={} log_id={}) Op({}) Got data".format(
                        list_values[0].id, list_values[0].log_id, op_name)))
438 439
            return resp
        elif op_name is None:
440
            _LOGGER.critical(
441
                self._log(
B
barriery 已提交
442 443
                    "Op({}) Failed to get data: there are multiple consumers, "
                    "so op_name cannot be None.".format(op_name)))
444
            os._exit(-1)
445

B
barrierye 已提交
446 447 448 449 450 451 452 453 454 455
        # 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)
456
        with self._cv:
B
barrierye 已提交
457 458
            # 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.
459
            while self._stop.value == 0 and self._consumer_cursors[
B
barrierye 已提交
460
                    op_name] - self._base_cursor.value >= len(self._output_buf):
461
                try:
B
barrierye 已提交
462
                    channeldata = self._que.get(timeout=0)
B
barrierye 已提交
463
                    self._output_buf.append(channeldata)
T
TeslaZhao 已提交
464
                    list_values = list(channeldata.values())
B
barriery 已提交
465
                    _LOGGER.debug(
B
barriery 已提交
466
                        self._log(
T
TeslaZhao 已提交
467
                            "(data_id={} log_id={}) Op({}) Pop ready item into output_buffer".
T
TeslaZhao 已提交
468 469
                            format(list_values[0].id, list_values[0].log_id,
                                   op_name)))
470 471
                    break
                except Queue.Empty:
B
barriery 已提交
472 473 474
                    if timeout is not None:
                        remaining = endtime - _time()
                        if remaining <= 0.0:
B
barriery 已提交
475
                            _LOGGER.debug(
B
barriery 已提交
476 477
                                self._log("Op({}) Failed to get data: timeout".
                                          format(op_name)))
B
barriery 已提交
478 479 480 481
                            raise ChannelTimeoutError()
                        self._cv.wait(remaining)
                    else:
                        self._cv.wait()
482
            if self._stop.value == 1:
B
barrierye 已提交
483
                raise ChannelStopError()
484

B
barrierye 已提交
485 486 487 488
            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]
489

B
barrierye 已提交
490 491 492 493 494 495 496 497
            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
498 499
                # to avoid cursor overflow
                if self._base_cursor.value >= self._reset_max_cursor:
B
barriery 已提交
500
                    _LOGGER.info(self._log("Reset cursor in Channel"))
501 502 503 504 505 506 507 508 509 510
                    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 已提交
511 512 513 514 515 516

            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
517

518 519
            self._cv.notify_all()

T
TeslaZhao 已提交
520 521 522 523 524 525
        if resp is not None:
            list_values = list(resp.values())
            _LOGGER.debug(
                self._log(
                    "(data_id={} log_id={}) Op({}) Got data from output_buffer".
                    format(list_values[0].id, list_values[0].log_id, op_name)))
B
barriery 已提交
526
        return resp
527 528

    def stop(self):
529
        _LOGGER.info(self._log("stop."))
530
        self._stop.value = 1
B
barrierye 已提交
531 532
        with self._cv:
            self._cv.notify_all()
533 534


535
class ThreadChannel(Queue.PriorityQueue):
536 537 538 539 540 541 542 543 544
    """ 
    (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 已提交
545
    3. Function front support timeout param to make auto-batching.
546 547 548 549 550

    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 已提交
551 552 553 554 555 556 557 558 559 560 561

    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.
562 563
    """

B
barriery 已提交
564
    def __init__(self, name=None, maxsize=-1):
565 566 567 568 569 570 571 572
        Queue.Queue.__init__(self, maxsize=maxsize)
        self._maxsize = maxsize
        self.name = name
        self._stop = False

        self._cv = threading.Condition()

        self._producers = []
B
barrierye 已提交
573
        self._pushed_producer_count = {}  # {data_id: count}
B
barrierye 已提交
574
        self._input_buf = {}  # {data_id: {op_name: data}}
575

576
        self._reset_max_cursor = 1000000000000000000
B
barrierye 已提交
577 578 579 580
        self._consumer_cursors = {}  # {op_name: idx}
        self._cursor_count = {}  # {cursor: count}
        self._base_cursor = 0
        self._output_buf = []
581

B
barriery 已提交
582 583 584
    def get_maxsize(self):
        return self._maxsize

B
barriery 已提交
585 586 587
    def size(self):
        return self.qsize()

588 589 590 591
    def get_producers(self):
        return self._producers

    def get_consumers(self):
B
barrierye 已提交
592
        return self._consumer_cursors.keys()
593 594 595 596 597 598 599

    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:
600
            _LOGGER.critical(
B
barriery 已提交
601 602
                self._log("Failed to add producer: producer({}) is "
                          "already in channel".format(op_name)))
603
            os._exit(-1)
604
        self._producers.append(op_name)
B
barriery 已提交
605
        _LOGGER.debug(self._log("Succ add a producer: {}".format(op_name)))
606 607 608

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

B
barrierye 已提交
616 617 618
        if self._cursor_count.get(0) is None:
            self._cursor_count[0] = 0
        self._cursor_count[0] += 1
B
barriery 已提交
619
        _LOGGER.debug(self._log("Succ add a consumer: {}".format(op_name)))
620 621

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

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

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

B
barrierye 已提交
690
                _LOGGER.debug(
B
barriery 已提交
691
                    self._log(
T
TeslaZhao 已提交
692 693
                        "(data_id={} log_id={}) Op({}) Pushed data into internal_queue.".
                        format(data_id, log_id, op_name)))
694 695 696
            self._cv.notify_all()
        return True

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

B
barrierye 已提交
708
        if len(self._consumer_cursors) == 0:
709
            _LOGGER.critical(
710
                self._log(
B
barriery 已提交
711 712
                    "Op({}) Failed to get data: expected number of consumers to be "
                    "greater than 0, but the it is 0.".format(op_name)))
713
            os._exit(-1)
B
barrierye 已提交
714
        elif len(self._consumer_cursors) == 1:
715 716 717 718 719 720 721
            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 已提交
722 723 724
                        if timeout is not None:
                            remaining = endtime - _time()
                            if remaining <= 0.0:
B
barriery 已提交
725
                                _LOGGER.debug(
B
barriery 已提交
726 727 728
                                    self._log(
                                        "Op({}) Failed to get data: timeout".
                                        format(op_name)))
B
barriery 已提交
729 730 731 732
                                raise ChannelTimeoutError()
                            self._cv.wait(remaining)
                        else:
                            self._cv.wait()
B
barrierye 已提交
733 734
                if self._stop:
                    raise ChannelStopError()
T
TeslaZhao 已提交
735 736 737 738 739
            if resp is not None:
                list_values = list(resp.values())
                _LOGGER.debug(
                    self._log("(data_id={} log_id={}) Op({}) Got data".format(
                        list_values[0].id, list_values[0].log_id, op_name)))
740 741
            return resp
        elif op_name is None:
742
            _LOGGER.critical(
B
barriery 已提交
743 744 745
                self._log("Op({}) Failed to get data: there are multiple "
                          "consumers, so op_name cannot be None.".format(
                              op_name)))
746
            os._exit(-1)
747

B
barrierye 已提交
748 749 750 751 752 753 754 755 756 757
        # 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)
758
        with self._cv:
B
barrierye 已提交
759 760 761 762
            # 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):
763 764
                try:
                    channeldata = self.get(timeout=0)
B
barrierye 已提交
765
                    self._output_buf.append(channeldata)
T
TeslaZhao 已提交
766
                    list_values = list(channeldata.values())
B
barriery 已提交
767
                    _LOGGER.debug(
B
barriery 已提交
768
                        self._log(
T
TeslaZhao 已提交
769
                            "(data_id={} log_id={}) Op({}) Pop ready item into output_buffer".
T
TeslaZhao 已提交
770 771
                            format(list_values[0].id, list_values[0].log_id,
                                   op_name)))
772 773
                    break
                except Queue.Empty:
B
barriery 已提交
774 775 776
                    if timeout is not None:
                        remaining = endtime - _time()
                        if remaining <= 0.0:
B
barriery 已提交
777
                            _LOGGER.debug(
B
barriery 已提交
778 779
                                self._log("Op({}) Failed to get data: timeout".
                                          format(op_name)))
B
barriery 已提交
780 781 782 783
                            raise ChannelTimeoutError()
                        self._cv.wait(remaining)
                    else:
                        self._cv.wait()
B
barrierye 已提交
784 785
            if self._stop:
                raise ChannelStopError()
786

B
barrierye 已提交
787 788 789
            consumer_cursor = self._consumer_cursors[op_name]
            base_cursor = self._base_cursor
            data_idx = consumer_cursor - base_cursor
B
barrierye 已提交
790 791

            resp = None
792

B
barrierye 已提交
793 794 795 796 797 798
            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 已提交
799
                resp = self._output_buf.pop(0)
B
barrierye 已提交
800
                self._base_cursor += 1
801 802
                # to avoid cursor overflow
                if self._base_cursor >= self._reset_max_cursor:
B
barriery 已提交
803
                    _LOGGER.info(self._log("Reset cursor in Channel"))
804 805 806 807 808 809 810
                    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 已提交
811 812
            else:
                resp = copy.deepcopy(self._output_buf[data_idx])
B
barrierye 已提交
813 814 815 816 817 818

            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
819 820 821

            self._cv.notify_all()

T
TeslaZhao 已提交
822 823 824 825 826 827
        if resp is not None:
            list_values = list(resp.values())
            _LOGGER.debug(
                self._log(
                    "(data_id={} log_id={}) Op({}) Got data from output_buffer".
                    format(list_values[0].id, list_values[0].log_id, op_name)))
B
barrierye 已提交
828
        return resp
829 830

    def stop(self):
831
        _LOGGER.info(self._log("stop."))
832
        self._stop = True
B
barrierye 已提交
833 834 835
        with self._cv:
            self._cv.notify_all()

B
barriery 已提交
836

B
barriery 已提交
837 838 839
class ChannelTimeoutError(RuntimeError):
    def __init__(self):
        pass
B
barrierye 已提交
840

B
barriery 已提交
841

B
barrierye 已提交
842 843 844
class ChannelStopError(RuntimeError):
    def __init__(self):
        pass