operator.py 22.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
D
dongdaxiang 已提交
15

16 17 18 19 20 21
import threading
import multiprocessing
from paddle_serving_client import MultiLangClient, Client
from concurrent import futures
import logging
import func_timeout
22
import os
B
barrierye 已提交
23
import sys
B
barrierye 已提交
24
from numpy import *
25

B
barrierye 已提交
26
from .proto import pipeline_service_pb2
B
barrierye 已提交
27 28
from .channel import (ThreadChannel, ProcessChannel, ChannelDataEcode,
                      ChannelData, ChannelDataType, ChannelStopError)
B
barrierye 已提交
29
from .util import NameGenerator
B
barrierye 已提交
30
from .profiler import TimeProfiler
31

W
wangjiawei04 已提交
32
_LOGGER = logging.getLogger()
B
barrierye 已提交
33 34
_op_name_gen = NameGenerator("Op")

D
dongdaxiang 已提交
35 36 37

class Op(object):
    def __init__(self,
B
barrierye 已提交
38
                 name=None,
D
dongdaxiang 已提交
39 40
                 input_ops=[],
                 server_endpoints=[],
B
barrierye 已提交
41 42
                 fetch_list=[],
                 client_config=None,
D
dongdaxiang 已提交
43 44 45
                 concurrency=1,
                 timeout=-1,
                 retry=1):
B
barrierye 已提交
46
        if name is None:
B
barrierye 已提交
47
            name = _op_name_gen.next()
48
        self.name = name  # to identify the type of OP, it must be globally unique
B
barrierye 已提交
49
        self.concurrency = concurrency  # amount of concurrency
B
barrierye 已提交
50
        self.set_input_ops(input_ops)
B
barrierye 已提交
51 52

        self._server_endpoints = server_endpoints
53
        self.with_serving = False
B
barrierye 已提交
54
        if len(self._server_endpoints) != 0:
55
            self.with_serving = True
B
barrierye 已提交
56 57 58
        self._client_config = client_config
        self._fetch_names = fetch_list

59 60 61 62
        self._timeout = timeout
        self._retry = max(1, retry)
        self._input = None
        self._outputs = []
B
barrierye 已提交
63

B
barrierye 已提交
64
        self._server_use_profile = False
65

B
barrierye 已提交
66 67
        # only for multithread
        self._for_init_op_lock = threading.Lock()
B
barrierye 已提交
68
        self._for_close_op_lock = threading.Lock()
B
barrierye 已提交
69
        self._succ_init_op = False
B
barrierye 已提交
70
        self._succ_close_op = False
B
barrierye 已提交
71

B
barrierye 已提交
72
    def use_profiler(self, use_profile):
B
barrierye 已提交
73
        self._server_use_profile = use_profile
74 75 76 77 78 79

    def _profiler_record(self, string):
        if self._profiler is None:
            return
        self._profiler.record(string)

B
barrierye 已提交
80 81
    def init_client(self, client_type, client_config, server_endpoints,
                    fetch_names):
82
        if self.with_serving == False:
B
barrierye 已提交
83
            _LOGGER.debug("{} no client".format(self.name))
B
barrierye 已提交
84
            return None
B
barrierye 已提交
85 86
        _LOGGER.debug("{} client_config: {}".format(self.name, client_config))
        _LOGGER.debug("{} fetch_names: {}".format(self.name, fetch_names))
87
        if client_type == 'brpc':
B
barrierye 已提交
88 89
            client = Client()
            client.load_client_config(client_config)
90
        elif client_type == 'grpc':
B
barrierye 已提交
91
            client = MultiLangClient()
92 93
        else:
            raise ValueError("unknow client type: {}".format(client_type))
B
barrierye 已提交
94
        client.connect(server_endpoints)
95
        self._fetch_names = fetch_names
B
barrierye 已提交
96
        return client
97 98 99 100 101 102 103 104 105 106 107 108 109 110

    def get_input_ops(self):
        return self._input_ops

    def set_input_ops(self, ops):
        if not isinstance(ops, list):
            ops = [] if ops is None else [ops]
        self._input_ops = []
        for op in ops:
            if not isinstance(op, Op):
                raise TypeError(
                    self._log('input op must be Op type, not {}'.format(
                        type(op))))
            self._input_ops.append(op)
D
dongdaxiang 已提交
111

112 113 114 115 116 117 118
    def add_input_channel(self, channel):
        if not isinstance(channel, (ThreadChannel, ProcessChannel)):
            raise TypeError(
                self._log('input channel must be Channel type, not {}'.format(
                    type(channel))))
        channel.add_consumer(self.name)
        self._input = channel
D
dongdaxiang 已提交
119

120
    def clean_input_channel(self):
B
barrierye 已提交
121 122 123 124
        self._input = None

    def _get_input_channel(self):
        return self._input
D
dongdaxiang 已提交
125

126 127 128 129 130 131 132
    def add_output_channel(self, channel):
        if not isinstance(channel, (ThreadChannel, ProcessChannel)):
            raise TypeError(
                self._log('output channel must be Channel type, not {}'.format(
                    type(channel))))
        channel.add_producer(self.name)
        self._outputs.append(channel)
D
dongdaxiang 已提交
133

134
    def clean_output_channels(self):
B
barrierye 已提交
135 136 137 138 139
        self._outputs = []

    def _get_output_channels(self):
        return self._outputs

W
wangjiawei04 已提交
140
    def preprocess(self, input_dicts):
B
barrierye 已提交
141
        # multiple previous Op
B
barrierye 已提交
142
        if len(input_dicts) != 1:
143
            raise NotImplementedError(
B
barrierye 已提交
144
                'this Op has multiple previous inputs. Please override this func.'
145
            )
D
dongdaxiang 已提交
146

B
barrierye 已提交
147 148
        (_, input_dict), = input_dicts.items()
        return input_dict
B
barrierye 已提交
149

B
barrierye 已提交
150
    def process(self, feed_dict):
B
barrierye 已提交
151 152 153 154
        err, err_info = ChannelData.check_npdata(feed_dict)
        if err != 0:
            raise NotImplementedError(
                "{} Please override preprocess func.".format(err_info))
B
barrierye 已提交
155
        call_result = self.client.predict(
B
barrierye 已提交
156 157
            feed=feed_dict, fetch=self._fetch_names)
        _LOGGER.debug(self._log("get call_result"))
158 159
        return call_result

W
wangjiawei04 已提交
160
    def postprocess(self, input_dict, fetch_dict):
B
barrierye 已提交
161
        return fetch_dict
D
dongdaxiang 已提交
162

B
barrierye 已提交
163
    def _parse_channeldata(self, channeldata_dict):
164
        data_id, error_channeldata = None, None
B
barrierye 已提交
165
        client_need_profile, profile_set = False, set()
B
barrierye 已提交
166 167 168 169
        parsed_data = {}

        key = list(channeldata_dict.keys())[0]
        data_id = channeldata_dict[key].id
B
barrierye 已提交
170
        client_need_profile = channeldata_dict[key].client_need_profile
B
barrierye 已提交
171 172 173 174 175 176

        for name, data in channeldata_dict.items():
            if data.ecode != ChannelDataEcode.OK.value:
                error_channeldata = data
                break
            parsed_data[name] = data.parse()
B
barrierye 已提交
177
            if client_need_profile:
B
barrierye 已提交
178
                profile_set |= data.profile_data_set
B
barrierye 已提交
179
        return (data_id, error_channeldata, parsed_data, client_need_profile,
B
barrierye 已提交
180
                profile_set)
B
barrierye 已提交
181 182 183 184 185 186

    def _push_to_output_channels(self,
                                 data,
                                 channels,
                                 name=None,
                                 client_need_profile=False,
B
barrierye 已提交
187
                                 profile_set=None):
188 189
        if name is None:
            name = self.name
B
barrierye 已提交
190
        self._add_profile_into_channeldata(data, client_need_profile,
B
barrierye 已提交
191
                                           profile_set)
192 193 194
        for channel in channels:
            channel.push(data, name)

B
barrierye 已提交
195
    def _add_profile_into_channeldata(self, data, client_need_profile,
B
barrierye 已提交
196
                                      profile_set):
B
barrierye 已提交
197 198 199 200
        profile_str = self._profiler.gen_profile_str()
        if self._server_use_profile:
            sys.stderr.write(profile_str)

B
barrierye 已提交
201 202 203
        if client_need_profile and profile_set is not None:
            profile_set.add(profile_str)
            data.add_profile(profile_set)
B
barrierye 已提交
204

B
barrierye 已提交
205
    def start_with_process(self, client_type):
206
        proces = []
B
barrierye 已提交
207
        for concurrency_idx in range(self.concurrency):
208 209
            p = multiprocessing.Process(
                target=self._run,
B
barrierye 已提交
210
                args=(concurrency_idx, self._get_input_channel(),
211
                      self._get_output_channels(), client_type, False))
212 213 214 215
            p.start()
            proces.append(p)
        return proces

B
barrierye 已提交
216
    def start_with_thread(self, client_type):
217
        threads = []
B
barrierye 已提交
218
        for concurrency_idx in range(self.concurrency):
219 220
            t = threading.Thread(
                target=self._run,
B
barrierye 已提交
221
                args=(concurrency_idx, self._get_input_channel(),
222
                      self._get_output_channels(), client_type, True))
223 224 225 226
            t.start()
            threads.append(t)
        return threads

B
barrierye 已提交
227
    def init_op(self):
B
barrierye 已提交
228 229
        pass

W
wangjiawei04 已提交
230
    def _run_preprocess(self, parsed_data, data_id, log_func):
231 232
        preped_data, error_channeldata = None, None
        try:
W
wangjiawei04 已提交
233
            preped_data = self.preprocess(parsed_data)
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
        except NotImplementedError as e:
            # preprocess function not implemented
            error_info = log_func(e)
            _LOGGER.error(error_info)
            error_channeldata = ChannelData(
                ecode=ChannelDataEcode.NOT_IMPLEMENTED.value,
                error_info=error_info,
                data_id=data_id)
        except TypeError as e:
            # Error type in channeldata.datatype
            error_info = log_func(e)
            _LOGGER.error(error_info)
            error_channeldata = ChannelData(
                ecode=ChannelDataEcode.TYPE_ERROR.value,
                error_info=error_info,
                data_id=data_id)
        except Exception as e:
            error_info = log_func(e)
            _LOGGER.error(error_info)
            error_channeldata = ChannelData(
                ecode=ChannelDataEcode.UNKNOW.value,
                error_info=error_info,
                data_id=data_id)
        return preped_data, error_channeldata

B
barrierye 已提交
259
    def _run_process(self, preped_data, data_id, log_func):
260 261 262 263 264
        midped_data, error_channeldata = None, None
        if self.with_serving:
            ecode = ChannelDataEcode.OK.value
            if self._timeout <= 0:
                try:
B
barrierye 已提交
265
                    midped_data = self.process(preped_data)
266 267 268 269 270 271 272 273
                except Exception as e:
                    ecode = ChannelDataEcode.UNKNOW.value
                    error_info = log_func(e)
                    _LOGGER.error(error_info)
            else:
                for i in range(self._retry):
                    try:
                        midped_data = func_timeout.func_timeout(
B
barrierye 已提交
274
                            self._timeout, self.process, args=(preped_data, ))
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
                    except func_timeout.FunctionTimedOut as e:
                        if i + 1 >= self._retry:
                            ecode = ChannelDataEcode.TIMEOUT.value
                            error_info = log_func(e)
                            _LOGGER.error(error_info)
                        else:
                            _LOGGER.warn(
                                log_func("timeout, retry({})".format(i + 1)))
                    except Exception as e:
                        ecode = ChannelDataEcode.UNKNOW.value
                        error_info = log_func(e)
                        _LOGGER.error(error_info)
                        break
                    else:
                        break
            if ecode != ChannelDataEcode.OK.value:
                error_channeldata = ChannelData(
                    ecode=ecode, error_info=error_info, data_id=data_id)
            elif midped_data is None:
                # op client return None
                error_channeldata = ChannelData(
                    ecode=ChannelDataEcode.CLIENT_ERROR.value,
                    error_info=log_func(
                        "predict failed. pls check the server side."),
                    data_id=data_id)
        else:
            midped_data = preped_data
        return midped_data, error_channeldata

W
wangjiawei04 已提交
304
    def _run_postprocess(self, input_dict, midped_data, data_id, log_func):
305 306
        output_data, error_channeldata = None, None
        try:
W
wangjiawei04 已提交
307
            postped_data = self.postprocess(input_dict, midped_data)
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
        except Exception as e:
            error_info = log_func(e)
            _LOGGER.error(error_info)
            error_channeldata = ChannelData(
                ecode=ChannelDataEcode.UNKNOW.value,
                error_info=error_info,
                data_id=data_id)
            return output_data, error_channeldata

        if not isinstance(postped_data, dict):
            error_info = log_func("output of postprocess funticon must be " \
                    "dict type, but get {}".format(type(postped_data)))
            _LOGGER.error(error_info)
            error_channeldata = ChannelData(
                ecode=ChannelDataEcode.UNKNOW.value,
                error_info=error_info,
                data_id=data_id)
            return output_data, error_channeldata

        err, _ = ChannelData.check_npdata(postped_data)
        if err == 0:
            output_data = ChannelData(
                ChannelDataType.CHANNEL_NPDATA.value,
                npdata=postped_data,
                data_id=data_id)
        else:
            output_data = ChannelData(
                ChannelDataType.DICT.value,
                dictdata=postped_data,
                data_id=data_id)
        return output_data, error_channeldata

340
    def _run(self, concurrency_idx, input_channel, output_channels, client_type,
341
             is_thread_op):
B
barrierye 已提交
342 343 344 345 346 347
        def get_log_func(op_info_prefix):
            def log_func(info_str):
                return "{} {}".format(op_info_prefix, info_str)

            return log_func

348
        op_info_prefix = "[{}|{}]".format(self.name, concurrency_idx)
B
barrierye 已提交
349
        log = get_log_func(op_info_prefix)
B
barrierye 已提交
350
        tid = threading.current_thread().ident
B
barrierye 已提交
351

B
barrierye 已提交
352
        # init op
353
        self.concurrency_idx = concurrency_idx
B
barrierye 已提交
354
        try:
355
            if is_thread_op:
B
barrierye 已提交
356 357
                with self._for_init_op_lock:
                    if not self._succ_init_op:
B
barrierye 已提交
358 359
                        # init profiler
                        self._profiler = TimeProfiler()
B
barrierye 已提交
360
                        self._profiler.enable(True)
B
barrierye 已提交
361
                        # init client
B
barrierye 已提交
362
                        self.client = self.init_client(
B
barrierye 已提交
363 364 365
                            client_type, self._client_config,
                            self._server_endpoints, self._fetch_names)
                        # user defined
366
                        self.init_op()
B
barrierye 已提交
367
                        self._succ_init_op = True
B
barrierye 已提交
368
                        self._succ_close_op = False
B
barrierye 已提交
369
            else:
B
barrierye 已提交
370 371
                # init profiler
                self._profiler = TimeProfiler()
B
barrierye 已提交
372
                self._profiler.enable(True)
B
barrierye 已提交
373
                # init client
B
barrierye 已提交
374 375 376
                self.client = self.init_client(client_type, self._client_config,
                                               self._server_endpoints,
                                               self._fetch_names)
B
barrierye 已提交
377
                # user defined
378
                self.init_op()
B
barrierye 已提交
379 380 381
        except Exception as e:
            _LOGGER.error(log(e))
            os._exit(-1)
382

B
barrierye 已提交
383
        while True:
B
barrierye 已提交
384
            #self._profiler_record("get#{}_0".format(op_info_prefix))
B
barrierye 已提交
385 386 387
            try:
                channeldata_dict = input_channel.front(self.name)
            except ChannelStopError:
B
barrierye 已提交
388
                _LOGGER.debug(log("stop."))
389 390 391 392 393 394 395
                if is_thread_op:
                    with self._for_close_op_lock:
                        if not self._succ_close_op:
                            self._profiler = None
                            self.client = None
                            self._succ_init_op = False
                            self._succ_close_op = True
B
barrierye 已提交
396
                break
B
barrierye 已提交
397
            #self._profiler_record("get#{}_1".format(op_info_prefix))
B
barrierye 已提交
398
            _LOGGER.debug(log("input_data: {}".format(channeldata_dict)))
399

B
barrierye 已提交
400
            (data_id, error_channeldata, parsed_data, client_need_profile,
B
barrierye 已提交
401
             profile_set) = self._parse_channeldata(channeldata_dict)
402 403
            # error data in predecessor Op
            if error_channeldata is not None:
B
barrierye 已提交
404
                try:
B
barrierye 已提交
405
                    # error_channeldata with profile info
B
barrierye 已提交
406 407 408
                    self._push_to_output_channels(error_channeldata,
                                                  output_channels)
                except ChannelStopError:
B
barrierye 已提交
409 410
                    _LOGGER.debug(log("stop."))
                    break
411 412 413
                continue

            # preprecess
B
barrierye 已提交
414
            self._profiler_record("prep#{}_0".format(op_info_prefix))
W
wangjiawei04 已提交
415 416
            preped_data, error_channeldata = self._run_preprocess(parsed_data,
                                                                  data_id, log)
B
barrierye 已提交
417
            self._profiler_record("prep#{}_1".format(op_info_prefix))
418
            if error_channeldata is not None:
B
barrierye 已提交
419
                try:
B
barrierye 已提交
420 421 422 423
                    self._push_to_output_channels(
                        error_channeldata,
                        output_channels,
                        client_need_profile=client_need_profile,
B
barrierye 已提交
424
                        profile_set=profile_set)
B
barrierye 已提交
425
                except ChannelStopError:
B
barrierye 已提交
426 427
                    _LOGGER.debug(log("stop."))
                    break
428 429
                continue

B
barrierye 已提交
430
            # process
B
barrierye 已提交
431
            self._profiler_record("midp#{}_0".format(op_info_prefix))
B
barrierye 已提交
432 433
            midped_data, error_channeldata = self._run_process(preped_data,
                                                               data_id, log)
B
barrierye 已提交
434
            self._profiler_record("midp#{}_1".format(op_info_prefix))
435
            if error_channeldata is not None:
B
barrierye 已提交
436
                try:
B
barrierye 已提交
437 438 439 440
                    self._push_to_output_channels(
                        error_channeldata,
                        output_channels,
                        client_need_profile=client_need_profile,
B
barrierye 已提交
441
                        profile_set=profile_set)
B
barrierye 已提交
442
                except ChannelStopError:
B
barrierye 已提交
443 444
                    _LOGGER.debug(log("stop."))
                    break
445
                continue
446 447

            # postprocess
B
barrierye 已提交
448
            self._profiler_record("postp#{}_0".format(op_info_prefix))
W
wangjiawei04 已提交
449
            output_data, error_channeldata = self._run_postprocess(
W
wangjiawei04 已提交
450
                parsed_data, midped_data, data_id, log)
B
barrierye 已提交
451
            self._profiler_record("postp#{}_1".format(op_info_prefix))
452
            if error_channeldata is not None:
B
barrierye 已提交
453
                try:
B
barrierye 已提交
454 455 456 457
                    self._push_to_output_channels(
                        error_channeldata,
                        output_channels,
                        client_need_profile=client_need_profile,
B
barrierye 已提交
458
                        profile_set=profile_set)
B
barrierye 已提交
459
                except ChannelStopError:
B
barrierye 已提交
460 461
                    _LOGGER.debug(log("stop."))
                    break
462
                continue
463 464

            # push data to channel (if run succ)
B
barrierye 已提交
465
            #self._profiler_record("push#{}_0".format(op_info_prefix))
B
barrierye 已提交
466
            try:
B
barrierye 已提交
467 468 469 470
                self._push_to_output_channels(
                    output_data,
                    output_channels,
                    client_need_profile=client_need_profile,
B
barrierye 已提交
471
                    profile_set=profile_set)
B
barrierye 已提交
472
            except ChannelStopError:
B
barrierye 已提交
473
                _LOGGER.debug(log("stop."))
B
barrierye 已提交
474
                break
B
barrierye 已提交
475
            #self._profiler_record("push#{}_1".format(op_info_prefix))
476 477 478 479 480

    def _log(self, info):
        return "{} {}".format(self.name, info)


B
barrierye 已提交
481 482 483
class RequestOp(Op):
    """ RequestOp do not run preprocess, process, postprocess. """

B
barrierye 已提交
484
    def __init__(self, concurrency=1):
B
barrierye 已提交
485
        # PipelineService.name = "@G"
B
barrierye 已提交
486
        super(RequestOp, self).__init__(
B
barrierye 已提交
487
            name="@G", input_ops=[], concurrency=concurrency)
B
barrierye 已提交
488
        # init op
489
        try:
490
            self.init_op()
491
        except Exception as e:
B
bug fix  
barrierye 已提交
492
            _LOGGER.error(e)
493
            os._exit(-1)
B
barrierye 已提交
494 495 496 497

    def unpack_request_package(self, request):
        dictdata = {}
        for idx, key in enumerate(request.key):
B
barrierye 已提交
498 499 500 501 502 503
            data = request.value[idx]
            try:
                data = eval(data)
            except Exception as e:
                pass
            dictdata[key] = data
B
barrierye 已提交
504 505 506 507 508 509 510 511
        return dictdata


class ResponseOp(Op):
    """ ResponseOp do not run preprocess, process, postprocess. """

    def __init__(self, input_ops, concurrency=1):
        super(ResponseOp, self).__init__(
B
barrierye 已提交
512
            name="@R", input_ops=input_ops, concurrency=concurrency)
B
barrierye 已提交
513
        # init op
514
        try:
515
            self.init_op()
516
        except Exception as e:
B
bug fix  
barrierye 已提交
517
            _LOGGER.error(e)
518
            os._exit(-1)
B
barrierye 已提交
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549

    def pack_response_package(self, channeldata):
        resp = pipeline_service_pb2.Response()
        resp.ecode = channeldata.ecode
        if resp.ecode == ChannelDataEcode.OK.value:
            if channeldata.datatype == ChannelDataType.CHANNEL_NPDATA.value:
                feed = channeldata.parse()
                # ndarray to string:
                # https://stackoverflow.com/questions/30167538/convert-a-numpy-ndarray-to-stringor-bytes-and-convert-it-back-to-numpy-ndarray
                for name, var in feed.items():
                    resp.value.append(var.__repr__())
                    resp.key.append(name)
            elif channeldata.datatype == ChannelDataType.DICT.value:
                feed = channeldata.parse()
                for name, var in feed.items():
                    if not isinstance(var, str):
                        resp.ecode = ChannelDataEcode.TYPE_ERROR.value
                        resp.error_info = self._log(
                            "fetch var type must be str({}).".format(
                                type(var)))
                        break
                    resp.value.append(var)
                    resp.key.append(name)
            else:
                resp.ecode = ChannelDataEcode.TYPE_ERROR.value
                resp.error_info = self._log(
                    "Error type({}) in datatype.".format(channeldata.datatype))
                _LOGGER.error(resp.error_info)
        else:
            resp.error_info = channeldata.error_info
        return resp
550 551 552 553 554 555 556


class VirtualOp(Op):
    ''' For connecting two channels. '''

    def __init__(self, name, concurrency=1):
        super(VirtualOp, self).__init__(
B
barrierye 已提交
557
            name=name, input_ops=None, concurrency=concurrency)
558 559 560 561 562
        self._virtual_pred_ops = []

    def add_virtual_pred_op(self, op):
        self._virtual_pred_ops.append(op)

B
barrierye 已提交
563 564 565 566 567 568 569 570
    def _actual_pred_op_names(self, op):
        if not isinstance(op, VirtualOp):
            return [op.name]
        names = []
        for x in op._virtual_pred_ops:
            names.extend(self._actual_pred_op_names(x))
        return names

571 572 573 574 575 576
    def add_output_channel(self, channel):
        if not isinstance(channel, (ThreadChannel, ProcessChannel)):
            raise TypeError(
                self._log('output channel must be Channel type, not {}'.format(
                    type(channel))))
        for op in self._virtual_pred_ops:
B
barrierye 已提交
577 578
            for op_name in self._actual_pred_op_names(op):
                channel.add_producer(op_name)
579
        self._outputs.append(channel)
D
dongdaxiang 已提交
580

581
    def _run(self, concurrency_idx, input_channel, output_channels, client_type,
582
             is_thread_op):
B
barrierye 已提交
583 584 585 586 587 588
        def get_log_func(op_info_prefix):
            def log_func(info_str):
                return "{} {}".format(op_info_prefix, info_str)

            return log_func

589
        op_info_prefix = "[{}|{}]".format(self.name, concurrency_idx)
B
barrierye 已提交
590 591 592
        log = get_log_func(op_info_prefix)
        tid = threading.current_thread().ident

B
barrierye 已提交
593 594 595 596
        while True:
            try:
                channeldata_dict = input_channel.front(self.name)
            except ChannelStopError:
B
barrierye 已提交
597
                _LOGGER.debug(log("stop."))
B
barrierye 已提交
598
                break
D
dongdaxiang 已提交
599

B
barrierye 已提交
600 601 602 603 604
            try:
                for name, data in channeldata_dict.items():
                    self._push_to_output_channels(
                        data, channels=output_channels, name=name)
            except ChannelStopError:
B
barrierye 已提交
605
                _LOGGER.debug(log("stop."))
B
barrierye 已提交
606
                break