channel.py 29.1 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 29
import numpy as np
import logging
import enum
import copy
D
dongdaxiang 已提交
30

W
wangjiawei04 已提交
31
_LOGGER = logging.getLogger()
B
barrierye 已提交
32

D
dongdaxiang 已提交
33 34 35 36 37 38 39

class ChannelDataEcode(enum.Enum):
    OK = 0
    TIMEOUT = 1
    NOT_IMPLEMENTED = 2
    TYPE_ERROR = 3
    RPC_PACKAGE_ERROR = 4
B
barrierye 已提交
40
    CLIENT_ERROR = 5
B
barrierye 已提交
41 42
    CLOSED_ERROR = 6
    UNKNOW = 7
D
dongdaxiang 已提交
43 44 45 46 47 48 49 50


class ChannelDataType(enum.Enum):
    DICT = 0
    CHANNEL_NPDATA = 1
    ERROR = 2


51 52 53 54
class ChannelData(object):
    def __init__(self,
                 datatype=None,
                 npdata=None,
B
barrierye 已提交
55
                 dictdata=None,
56 57
                 data_id=None,
                 ecode=None,
B
barrierye 已提交
58 59
                 error_info=None,
                 client_need_profile=False):
60 61 62
        '''
        There are several ways to use it:
        
B
barrierye 已提交
63 64 65
        1. ChannelData(ChannelDataType.CHANNEL_NPDATA.value, npdata, data_id)
        2. ChannelData(ChannelDataType.DICT.value, dictdata, data_id)
        3. ChannelData(ecode, error_info, data_id)
66 67 68 69 70 71 72 73 74

        Protobufs are not pickle-able:
        https://stackoverflow.com/questions/55344376/how-to-import-protobuf-module
        '''
        if ecode is not None:
            if data_id is None or error_info is None:
                raise ValueError("data_id and error_info cannot be None")
            datatype = ChannelDataType.ERROR.value
        else:
B
barrierye 已提交
75 76
            if datatype == ChannelDataType.CHANNEL_NPDATA.value:
                ecode, error_info = ChannelData.check_npdata(npdata)
77
                if ecode != ChannelDataEcode.OK.value:
B
barrierye 已提交
78
                    datatype = ChannelDataType.ERROR.value
B
barrierye 已提交
79
                    _LOGGER.error(error_info)
B
barrierye 已提交
80 81 82 83
            elif datatype == ChannelDataType.DICT.value:
                ecode, error_info = ChannelData.check_dictdata(dictdata)
                if ecode != ChannelDataEcode.OK.value:
                    datatype = ChannelDataType.ERROR.value
B
barrierye 已提交
84
                    _LOGGER.error(error_info)
85 86 87
            else:
                raise ValueError("datatype not match")
        self.datatype = datatype
B
barrierye 已提交
88 89
        self.npdata = npdata
        self.dictdata = dictdata
90 91 92
        self.id = data_id
        self.ecode = ecode
        self.error_info = error_info
B
barrierye 已提交
93
        self.client_need_profile = client_need_profile
B
barrierye 已提交
94
        self.profile_data_set = set()
B
barrierye 已提交
95

B
barrierye 已提交
96
    def add_profile(self, profile_set):
B
barrierye 已提交
97 98
        if self.client_need_profile is False:
            self.client_need_profile = True
B
barrierye 已提交
99
        self.profile_data_set |= profile_set
100

B
barrierye 已提交
101 102 103 104
    @staticmethod
    def check_dictdata(dictdata):
        ecode = ChannelDataEcode.OK.value
        error_info = None
B
barrierye 已提交
105 106 107 108 109 110 111 112 113 114
        if isinstance(dictdata, list):
            # batch data
            for sample in dictdata:
                if not isinstance(sample, dict):
                    ecode = ChannelDataEcode.TYPE_ERROR.value
                    error_info = "the value of data must " \
                            "be dict, but get {}.".format(type(sample))
                    break
        elif not isinstance(dictdata, dict):
            # batch size = 1
B
barrierye 已提交
115
            ecode = ChannelDataEcode.TYPE_ERROR.value
B
barrierye 已提交
116 117
            error_info = "the value of data must " \
                        "be dict, but get {}.".format(type(dictdata))
B
barrierye 已提交
118
        return ecode, error_info
B
barrierye 已提交
119

B
bug fix  
barriery 已提交
120 121 122 123 124 125 126 127 128 129
    @staticmethod
    def check_batch_npdata(batch):
        ecode = ChannelDataEcode.OK.value
        error_info = None
        for npdata in batch:
            ecode, error_info = ChannelData.check_npdata(npdata)
            if ecode != ChannelDataEcode.OK.value:
                break
        return ecode, error_info

B
barrierye 已提交
130 131
    @staticmethod
    def check_npdata(npdata):
132 133
        ecode = ChannelDataEcode.OK.value
        error_info = None
W
wangjiawei04 已提交
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
        if isinstance(npdata, list):
            # batch data
            for sample in npdata:
                if not isinstance(sample, dict):
                    ecode = ChannelDataEcode.TYPE_ERROR.value
                    error_info = "the value of data must " \
                            "be dict, but get {}.".format(type(sample))
                    break
                for _, value in sample.items():
                    if not isinstance(value, np.ndarray):
                        ecode = ChannelDataEcode.TYPE_ERROR.value
                        error_info = "the value of data must " \
                                "be np.ndarray, but get {}.".format(type(value))
                        return ecode, error_info
        elif isinstance(npdata, dict):
            # batch_size = 1
            for _, value in npdata.items():
                if not isinstance(value, np.ndarray):
                    ecode = ChannelDataEcode.TYPE_ERROR.value
                    error_info = "the value of data must " \
                            "be np.ndarray, but get {}.".format(type(value))
                    break
        else:
            ecode = ChannelDataEcode.TYPE_ERROR.value
            error_info = "the value of data must " \
                    "be dict, but get {}.".format(type(npdata))
160 161 162 163
        return ecode, error_info

    def parse(self):
        feed = None
B
barrierye 已提交
164 165
        if self.datatype == ChannelDataType.CHANNEL_NPDATA.value:
            # return narray
166
            feed = self.npdata
B
barrierye 已提交
167 168 169
        elif self.datatype == ChannelDataType.DICT.value:
            # return dict
            feed = self.dictdata
170 171 172 173 174 175 176 177 178
        else:
            raise TypeError("Error type({}) in datatype.".format(self.datatype))
        return feed

    def __str__(self):
        return "type[{}], ecode[{}], id[{}]".format(
            ChannelDataType(self.datatype).name, self.ecode, self.id)


B
barrierye 已提交
179
class ProcessChannel(object):
180 181 182 183 184 185 186 187 188
    """ 
    (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 已提交
189
    3. Function front support timeout param to make auto-batching.
190 191 192 193 194

    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 已提交
195 196 197 198 199 200 201 202 203 204 205

    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.
206 207
    """

B
barriery 已提交
208
    def __init__(self, manager, name=None, maxsize=0):
B
barrierye 已提交
209 210 211 212 213 214 215
        # 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
        self._que = manager.Queue(maxsize=maxsize)
216 217
        self._maxsize = maxsize
        self.name = name
218
        self._stop = manager.Value('i', 0)
219 220 221 222

        self._cv = multiprocessing.Condition()

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

226
        self._reset_max_cursor = 1000000000000000000
B
barrierye 已提交
227 228 229 230
        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()
231 232 233 234 235

    def get_producers(self):
        return self._producers

    def get_consumers(self):
B
barrierye 已提交
236
        return self._consumer_cursors.keys()
237 238 239 240 241 242 243 244 245 246 247 248 249

    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:
            raise ValueError(
                self._log("producer({}) is already in channel".format(op_name)))
        self._producers.append(op_name)

    def add_consumer(self, op_name):
        """ not thread safe, and can only be called during initialization. """
B
barrierye 已提交
250
        if op_name in self._consumer_cursors:
251 252
            raise ValueError(
                self._log("consumer({}) is already in channel".format(op_name)))
B
barrierye 已提交
253
        self._consumer_cursors[op_name] = 0
254

B
barrierye 已提交
255 256 257
        if self._cursor_count.get(0) is None:
            self._cursor_count[0] = 0
        self._cursor_count[0] += 1
258 259

    def push(self, channeldata, op_name=None):
B
barrierye 已提交
260
        _LOGGER.debug(
B
barriery 已提交
261 262
            self._log("{} try to push data[{}]".format(op_name,
                                                       channeldata.id)))
263 264 265 266 267 268 269
        if len(self._producers) == 0:
            raise Exception(
                self._log(
                    "expected number of producers to be greater than 0, but the it is 0."
                ))
        elif len(self._producers) == 1:
            with self._cv:
270
                while self._stop.value == 0:
271
                    try:
B
barrierye 已提交
272
                        self._que.put({op_name: channeldata}, timeout=0)
273 274 275
                        break
                    except Queue.Full:
                        self._cv.wait()
276
                if self._stop.value == 1:
B
barrierye 已提交
277
                    raise ChannelStopError()
278
                self._cv.notify_all()
B
barriery 已提交
279 280 281
            _LOGGER.debug(
                self._log("{} succ push data[{}] into internal queue.".format(
                    op_name, channeldata.id)))
282 283 284 285 286 287 288 289 290 291
            return True
        elif op_name is None:
            raise Exception(
                self._log(
                    "There are multiple producers, so op_name cannot be None."))

        producer_num = len(self._producers)
        data_id = channeldata.id
        put_data = None
        with self._cv:
B
barrierye 已提交
292 293
            if data_id not in self._input_buf:
                self._input_buf[data_id] = {
294 295 296
                    name: None
                    for name in self._producers
                }
B
barrierye 已提交
297
                self._pushed_producer_count[data_id] = 0
298
            # see: https://docs.python.org/3.6/library/multiprocessing.html?highlight=multiprocess#proxy-objects
B
barrierye 已提交
299 300 301 302 303
            # 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 已提交
304
            if self._pushed_producer_count[data_id] + 1 == producer_num:
B
barrierye 已提交
305 306
                put_data = self._input_buf[data_id]
                self._input_buf.pop(data_id)
B
barrierye 已提交
307
                self._pushed_producer_count.pop(data_id)
308
            else:
B
barrierye 已提交
309
                self._pushed_producer_count[data_id] += 1
310 311

            if put_data is None:
B
barrierye 已提交
312
                _LOGGER.debug(
B
barriery 已提交
313 314
                    self._log("{} succ push data[{}] into input_buffer.".format(
                        op_name, data_id)))
315
            else:
316
                while self._stop.value == 0:
317
                    try:
B
barrierye 已提交
318
                        self._que.put(put_data, timeout=0)
319 320 321
                        break
                    except Queue.Empty:
                        self._cv.wait()
322
                if self._stop.value == 1:
B
barrierye 已提交
323
                    raise ChannelStopError()
324

B
barrierye 已提交
325
                _LOGGER.debug(
B
barriery 已提交
326 327
                    self._log("{} succ push data[{}] into internal queue.".
                              format(op_name, data_id)))
328 329 330
            self._cv.notify_all()
        return True

B
barriery 已提交
331
    def front(self, op_name=None, timeout=None):
B
barriery 已提交
332
        _LOGGER.debug(
B
barriery 已提交
333 334
            self._log("{} try to get data[?]; timeout(s)={}".format(op_name,
                                                                    timeout)))
B
barriery 已提交
335
        endtime = None
B
bug fix  
barriery 已提交
336 337 338 339 340
        if timeout is not None:
            if timeout <= 0:
                timeout = None
            else:
                endtime = _time() + timeout
B
barriery 已提交
341

B
barrierye 已提交
342
        if len(self._consumer_cursors) == 0:
343 344 345 346
            raise Exception(
                self._log(
                    "expected number of consumers to be greater than 0, but the it is 0."
                ))
B
barrierye 已提交
347
        elif len(self._consumer_cursors) == 1:
348 349
            resp = None
            with self._cv:
350
                while self._stop.value == 0 and resp is None:
351
                    try:
B
barrierye 已提交
352
                        resp = self._que.get(timeout=0)
353 354
                        break
                    except Queue.Empty:
B
barriery 已提交
355 356 357
                        if timeout is not None:
                            remaining = endtime - _time()
                            if remaining <= 0.0:
B
barriery 已提交
358 359 360
                                _LOGGER.debug(
                                    self._log("{} get data[?] timeout".format(
                                        op_name)))
B
barriery 已提交
361 362 363 364
                                raise ChannelTimeoutError()
                            self._cv.wait(remaining)
                        else:
                            self._cv.wait()
365
                if self._stop.value == 1:
B
barrierye 已提交
366
                    raise ChannelStopError()
B
barriery 已提交
367 368 369
            _LOGGER.debug(
                self._log("{} succ get data[{}]".format(op_name,
                                                        resp.values()[0].id)))
370 371 372 373 374 375
            return resp
        elif op_name is None:
            raise Exception(
                self._log(
                    "There are multiple consumers, so op_name cannot be None."))

B
barrierye 已提交
376 377 378 379 380 381 382 383 384 385
        # 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)
386
        with self._cv:
B
barrierye 已提交
387 388
            # 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.
389
            while self._stop.value == 0 and self._consumer_cursors[
B
barrierye 已提交
390
                    op_name] - self._base_cursor.value >= len(self._output_buf):
391
                try:
B
barrierye 已提交
392
                    channeldata = self._que.get(timeout=0)
B
barrierye 已提交
393
                    self._output_buf.append(channeldata)
B
barriery 已提交
394 395 396
                    _LOGGER.debug(
                        self._log("pop ready item[{}] into output_buffer".
                                  format(channeldata.values()[0].id)))
397 398
                    break
                except Queue.Empty:
B
barriery 已提交
399 400 401
                    if timeout is not None:
                        remaining = endtime - _time()
                        if remaining <= 0.0:
B
barriery 已提交
402 403 404
                            _LOGGER.debug(
                                self._log("{} get data[?] timeout".format(
                                    op_name)))
B
barriery 已提交
405 406 407 408
                            raise ChannelTimeoutError()
                        self._cv.wait(remaining)
                    else:
                        self._cv.wait()
409
            if self._stop.value == 1:
B
barrierye 已提交
410
                raise ChannelStopError()
411

B
barrierye 已提交
412 413 414 415
            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]
416

B
barrierye 已提交
417 418 419 420 421 422 423 424
            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
425 426
                # to avoid cursor overflow
                if self._base_cursor.value >= self._reset_max_cursor:
B
barriery 已提交
427
                    _LOGGER.info(self._log("reset cursor in Channel"))
428 429 430 431 432 433 434 435 436 437
                    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 已提交
438 439 440 441 442 443

            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
444

445 446
            self._cv.notify_all()

B
barriery 已提交
447 448 449 450
        _LOGGER.debug(
            self._log("{} succ get data[{}] from output_buffer".format(
                op_name, resp.values()[0].id)))
        return resp
451 452

    def stop(self):
B
barrierye 已提交
453
        _LOGGER.debug(self._log("stop."))
454
        self._stop.value = 1
B
barrierye 已提交
455 456
        with self._cv:
            self._cv.notify_all()
457 458 459 460 461 462 463 464 465 466 467 468


class ThreadChannel(Queue.Queue):
    """ 
    (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 已提交
469
    3. Function front support timeout param to make auto-batching.
470 471 472 473 474

    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 已提交
475 476 477 478 479 480 481 482 483 484 485

    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.
486 487
    """

B
barriery 已提交
488
    def __init__(self, name=None, maxsize=-1):
489 490 491 492 493 494 495 496
        Queue.Queue.__init__(self, maxsize=maxsize)
        self._maxsize = maxsize
        self.name = name
        self._stop = False

        self._cv = threading.Condition()

        self._producers = []
B
barrierye 已提交
497
        self._pushed_producer_count = {}  # {data_id: count}
B
barrierye 已提交
498
        self._input_buf = {}  # {data_id: {op_name: data}}
499

500
        self._reset_max_cursor = 1000000000000000000
B
barrierye 已提交
501 502 503 504
        self._consumer_cursors = {}  # {op_name: idx}
        self._cursor_count = {}  # {cursor: count}
        self._base_cursor = 0
        self._output_buf = []
505 506 507 508 509

    def get_producers(self):
        return self._producers

    def get_consumers(self):
B
barrierye 已提交
510
        return self._consumer_cursors.keys()
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527

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

    def debug(self):
        return self._log("p: {}, c: {}".format(self.get_producers(),
                                               self.get_consumers()))

    def add_producer(self, op_name):
        """ not thread safe, and can only be called during initialization. """
        if op_name in self._producers:
            raise ValueError(
                self._log("producer({}) is already in channel".format(op_name)))
        self._producers.append(op_name)

    def add_consumer(self, op_name):
        """ not thread safe, and can only be called during initialization. """
B
barrierye 已提交
528
        if op_name in self._consumer_cursors:
529 530
            raise ValueError(
                self._log("consumer({}) is already in channel".format(op_name)))
B
barrierye 已提交
531
        self._consumer_cursors[op_name] = 0
532

B
barrierye 已提交
533 534 535
        if self._cursor_count.get(0) is None:
            self._cursor_count[0] = 0
        self._cursor_count[0] += 1
536 537

    def push(self, channeldata, op_name=None):
B
barrierye 已提交
538
        _LOGGER.debug(
B
barriery 已提交
539 540
            self._log("{} try to push data[{}]".format(op_name,
                                                       channeldata.id)))
541 542 543 544 545 546 547 548 549
        if len(self._producers) == 0:
            raise Exception(
                self._log(
                    "expected number of producers to be greater than 0, but the it is 0."
                ))
        elif len(self._producers) == 1:
            with self._cv:
                while self._stop is False:
                    try:
B
barrierye 已提交
550
                        self.put({op_name: channeldata}, timeout=0)
551 552 553
                        break
                    except Queue.Full:
                        self._cv.wait()
B
barrierye 已提交
554 555
                if self._stop:
                    raise ChannelStopError()
556
                self._cv.notify_all()
B
barriery 已提交
557
            _LOGGER.debug(
B
barriery 已提交
558 559
                self._log("{} succ push data[{}] into internal queue.".format(
                    op_name, channeldata.id)))
560 561 562 563 564 565 566 567 568 569
            return True
        elif op_name is None:
            raise Exception(
                self._log(
                    "There are multiple producers, so op_name cannot be None."))

        producer_num = len(self._producers)
        data_id = channeldata.id
        put_data = None
        with self._cv:
B
barrierye 已提交
570 571
            if data_id not in self._input_buf:
                self._input_buf[data_id] = {
572 573 574
                    name: None
                    for name in self._producers
                }
B
barrierye 已提交
575
                self._pushed_producer_count[data_id] = 0
B
barrierye 已提交
576
            self._input_buf[data_id][op_name] = channeldata
B
barrierye 已提交
577
            if self._pushed_producer_count[data_id] + 1 == producer_num:
B
barrierye 已提交
578 579
                put_data = self._input_buf[data_id]
                self._input_buf.pop(data_id)
B
barrierye 已提交
580
                self._pushed_producer_count.pop(data_id)
581
            else:
B
barrierye 已提交
582
                self._pushed_producer_count[data_id] += 1
583 584

            if put_data is None:
B
barrierye 已提交
585
                _LOGGER.debug(
B
barriery 已提交
586 587
                    self._log("{} succ push data[{}] into input_buffer.".format(
                        op_name, data_id)))
588 589 590 591 592 593 594
            else:
                while self._stop is False:
                    try:
                        self.put(put_data, timeout=0)
                        break
                    except Queue.Empty:
                        self._cv.wait()
B
barrierye 已提交
595 596
                if self._stop:
                    raise ChannelStopError()
597

B
barrierye 已提交
598
                _LOGGER.debug(
B
barriery 已提交
599 600
                    self._log("{} succ push data[{}] into internal queue.".
                              format(op_name, data_id)))
601 602 603
            self._cv.notify_all()
        return True

B
barriery 已提交
604
    def front(self, op_name=None, timeout=None):
B
barriery 已提交
605
        _LOGGER.debug(
B
barriery 已提交
606 607
            self._log("{} try to get data[?]; timeout(s)={}".format(op_name,
                                                                    timeout)))
B
barriery 已提交
608
        endtime = None
B
bug fix  
barriery 已提交
609 610 611 612 613
        if timeout is not None:
            if timeout <= 0:
                timeout = None
            else:
                endtime = _time() + timeout
B
barriery 已提交
614

B
barrierye 已提交
615
        if len(self._consumer_cursors) == 0:
616 617 618 619
            raise Exception(
                self._log(
                    "expected number of consumers to be greater than 0, but the it is 0."
                ))
B
barrierye 已提交
620
        elif len(self._consumer_cursors) == 1:
621 622 623 624 625 626 627
            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 已提交
628 629 630
                        if timeout is not None:
                            remaining = endtime - _time()
                            if remaining <= 0.0:
B
barriery 已提交
631
                                _LOGGER.debug(
B
barriery 已提交
632 633
                                    self._log("{} get data[?] timeout".format(
                                        op_name)))
B
barriery 已提交
634 635 636 637
                                raise ChannelTimeoutError()
                            self._cv.wait(remaining)
                        else:
                            self._cv.wait()
B
barrierye 已提交
638 639
                if self._stop:
                    raise ChannelStopError()
B
barrierye 已提交
640
            _LOGGER.debug(
B
barriery 已提交
641 642
                self._log("{} succ get data[{}]".format(op_name,
                                                        resp.values()[0].id)))
643 644 645 646 647 648
            return resp
        elif op_name is None:
            raise Exception(
                self._log(
                    "There are multiple consumers, so op_name cannot be None."))

B
barrierye 已提交
649 650 651 652 653 654 655 656 657 658
        # 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)
659
        with self._cv:
B
barrierye 已提交
660 661 662 663
            # 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):
664 665
                try:
                    channeldata = self.get(timeout=0)
B
barrierye 已提交
666
                    self._output_buf.append(channeldata)
B
barriery 已提交
667
                    _LOGGER.debug(
B
barriery 已提交
668 669
                        self._log("pop ready item[{}] into output_buffer".
                                  format(channeldata.values()[0].id)))
670 671
                    break
                except Queue.Empty:
B
barriery 已提交
672 673 674
                    if timeout is not None:
                        remaining = endtime - _time()
                        if remaining <= 0.0:
B
barriery 已提交
675
                            _LOGGER.debug(
B
barriery 已提交
676 677
                                self._log("{} get data[?] timeout".format(
                                    op_name)))
B
barriery 已提交
678 679 680 681
                            raise ChannelTimeoutError()
                        self._cv.wait(remaining)
                    else:
                        self._cv.wait()
B
barrierye 已提交
682 683
            if self._stop:
                raise ChannelStopError()
684

B
barrierye 已提交
685 686 687
            consumer_cursor = self._consumer_cursors[op_name]
            base_cursor = self._base_cursor
            data_idx = consumer_cursor - base_cursor
B
barrierye 已提交
688 689

            resp = None
690

B
barrierye 已提交
691 692 693 694 695 696
            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 已提交
697
                resp = self._output_buf.pop(0)
B
barrierye 已提交
698
                self._base_cursor += 1
699 700
                # to avoid cursor overflow
                if self._base_cursor >= self._reset_max_cursor:
B
barriery 已提交
701
                    _LOGGER.info(self._log("reset cursor in Channel"))
702 703 704 705 706 707 708
                    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 已提交
709 710
            else:
                resp = copy.deepcopy(self._output_buf[data_idx])
B
barrierye 已提交
711 712 713 714 715 716

            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
717 718 719

            self._cv.notify_all()

B
barriery 已提交
720
        _LOGGER.debug(
B
barriery 已提交
721 722
            self._log("{} succ get data[{}] from output_buffer".format(
                op_name, resp.values()[0].id)))
B
barrierye 已提交
723
        return resp
724 725

    def stop(self):
B
barrierye 已提交
726
        _LOGGER.debug(self._log("stop."))
727
        self._stop = True
B
barrierye 已提交
728 729 730
        with self._cv:
            self._cv.notify_all()

B
barriery 已提交
731

B
barriery 已提交
732 733 734
class ChannelTimeoutError(RuntimeError):
    def __init__(self):
        pass
B
barrierye 已提交
735

B
barriery 已提交
736

B
barrierye 已提交
737 738 739
class ChannelStopError(RuntimeError):
    def __init__(self):
        pass