operator.py 25.0 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
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
import numpy as np
B
barrierye 已提交
25
from numpy import *
26

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

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

D
dongdaxiang 已提交
36 37 38

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

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

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

B
barriery 已提交
67 68 69 70 71
        self._batch_size = batch_size
        self._auto_batchint_timeout = auto_batchint_timeout
        if self._auto_batchint_timeout is not None and self._auto_batchint_timeout <= 0:
            self._auto_batchint_timeout = None

B
barrierye 已提交
72
        self._server_use_profile = False
73

B
barrierye 已提交
74 75
        # only for multithread
        self._for_init_op_lock = threading.Lock()
B
barrierye 已提交
76
        self._for_close_op_lock = threading.Lock()
B
barrierye 已提交
77
        self._succ_init_op = False
B
barrierye 已提交
78
        self._succ_close_op = False
B
barrierye 已提交
79

B
barrierye 已提交
80
    def use_profiler(self, use_profile):
B
barrierye 已提交
81
        self._server_use_profile = use_profile
82 83 84 85 86 87

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

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

    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 已提交
119

120 121 122 123 124 125 126
    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 已提交
127

128
    def clean_input_channel(self):
B
barrierye 已提交
129 130 131 132
        self._input = None

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

134 135 136 137 138 139 140
    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 已提交
141

142
    def clean_output_channels(self):
B
barrierye 已提交
143 144 145 146 147
        self._outputs = []

    def _get_output_channels(self):
        return self._outputs

W
wangjiawei04 已提交
148
    def preprocess(self, input_dicts):
B
barrierye 已提交
149
        # multiple previous Op
B
barrierye 已提交
150
        if len(input_dicts) != 1:
151
            raise NotImplementedError(
B
barrierye 已提交
152
                'this Op has multiple previous inputs. Please override this func.'
153
            )
D
dongdaxiang 已提交
154

B
barrierye 已提交
155 156
        (_, input_dict), = input_dicts.items()
        return input_dict
B
barrierye 已提交
157

B
barrierye 已提交
158
    def process(self, feed_dict):
B
barrierye 已提交
159 160 161 162
        err, err_info = ChannelData.check_npdata(feed_dict)
        if err != 0:
            raise NotImplementedError(
                "{} Please override preprocess func.".format(err_info))
B
barrierye 已提交
163
        call_result = self.client.predict(
B
barrierye 已提交
164 165
            feed=feed_dict, fetch=self._fetch_names)
        _LOGGER.debug(self._log("get call_result"))
166 167
        return call_result

W
wangjiawei04 已提交
168
    def postprocess(self, input_dict, fetch_dict):
B
barrierye 已提交
169
        return fetch_dict
D
dongdaxiang 已提交
170

B
barrierye 已提交
171
    def _parse_channeldata(self, channeldata_dict):
172
        data_id, error_channeldata = None, None
B
barrierye 已提交
173
        client_need_profile, profile_set = False, set()
B
barrierye 已提交
174 175 176 177
        parsed_data = {}

        key = list(channeldata_dict.keys())[0]
        data_id = channeldata_dict[key].id
B
barrierye 已提交
178
        client_need_profile = channeldata_dict[key].client_need_profile
B
barrierye 已提交
179 180 181 182 183 184

        for name, data in channeldata_dict.items():
            if data.ecode != ChannelDataEcode.OK.value:
                error_channeldata = data
                break
            parsed_data[name] = data.parse()
B
barrierye 已提交
185
            if client_need_profile:
B
barrierye 已提交
186
                profile_set |= data.profile_data_set
B
barrierye 已提交
187
        return (data_id, error_channeldata, parsed_data, client_need_profile,
B
barrierye 已提交
188
                profile_set)
B
barrierye 已提交
189 190 191 192 193 194

    def _push_to_output_channels(self,
                                 data,
                                 channels,
                                 name=None,
                                 client_need_profile=False,
B
barrierye 已提交
195
                                 profile_set=None):
196 197
        if name is None:
            name = self.name
B
barrierye 已提交
198
        self._add_profile_into_channeldata(data, client_need_profile,
B
barrierye 已提交
199
                                           profile_set)
200 201 202
        for channel in channels:
            channel.push(data, name)

B
barrierye 已提交
203
    def _add_profile_into_channeldata(self, data, client_need_profile,
B
barrierye 已提交
204
                                      profile_set):
B
barrierye 已提交
205 206 207 208
        profile_str = self._profiler.gen_profile_str()
        if self._server_use_profile:
            sys.stderr.write(profile_str)

B
barrierye 已提交
209 210 211
        if client_need_profile and profile_set is not None:
            profile_set.add(profile_str)
            data.add_profile(profile_set)
B
barrierye 已提交
212

B
barrierye 已提交
213
    def start_with_process(self, client_type):
214
        proces = []
B
barrierye 已提交
215
        for concurrency_idx in range(self.concurrency):
216 217
            p = multiprocessing.Process(
                target=self._run,
B
barrierye 已提交
218
                args=(concurrency_idx, self._get_input_channel(),
219
                      self._get_output_channels(), client_type, False))
220 221 222 223
            p.start()
            proces.append(p)
        return proces

B
barrierye 已提交
224
    def start_with_thread(self, client_type):
225
        threads = []
B
barrierye 已提交
226
        for concurrency_idx in range(self.concurrency):
227 228
            t = threading.Thread(
                target=self._run,
B
barrierye 已提交
229
                args=(concurrency_idx, self._get_input_channel(),
230
                      self._get_output_channels(), client_type, True))
231 232 233 234
            t.start()
            threads.append(t)
        return threads

B
barrierye 已提交
235
    def init_op(self):
B
barrierye 已提交
236 237
        pass

W
wangjiawei04 已提交
238
    def _run_preprocess(self, parsed_data, data_id, log_func):
239 240
        preped_data, error_channeldata = None, None
        try:
W
wangjiawei04 已提交
241
            preped_data = self.preprocess(parsed_data)
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
        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 已提交
267
    def _run_process(self, preped_data, data_id, log_func):
268 269 270 271 272
        midped_data, error_channeldata = None, None
        if self.with_serving:
            ecode = ChannelDataEcode.OK.value
            if self._timeout <= 0:
                try:
B
barrierye 已提交
273
                    midped_data = self.process(preped_data)
274 275 276 277 278 279 280 281
                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 已提交
282
                            self._timeout, self.process, args=(preped_data, ))
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
                    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 已提交
312
    def _run_postprocess(self, input_dict, midped_data, data_id, log_func):
313 314
        output_data, error_channeldata = None, None
        try:
W
wangjiawei04 已提交
315
            postped_data = self.postprocess(input_dict, midped_data)
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
        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
B
barriery 已提交
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
    
    def _auto_batching_generator(self, input_channel, op_name, batch_size, timeout):
        while True:
            batch = []
            while len(batch) == 0:
                endtime = None
                if timeout is not None:
                    endtime = _time() + timeout
                for idx in range(batch_size):
                    try:
                        channeldata_dict = None
                        if timeout is not None:
                            remaining = endtime - _time()
                            if remaining <= 0.0:
                                _LOGGER.info(log("auto-batching timeout"))
                                break
                            channeldata_dict = input_channel.front(op_name, timeout)
                        else:
                            channeldata_dict = input_channel.front(op_name)
                        batch.append(channeldata_dict)
                    except ChannelTimeoutError:
                        _LOGGER.info(log("auto-batching timeout"))
                        break
            yield batch
371

B
barriery 已提交
372
   def _run(self, concurrency_idx, input_channel, output_channels, client_type,
373
             is_thread_op):
B
barrierye 已提交
374 375 376 377 378 379
        def get_log_func(op_info_prefix):
            def log_func(info_str):
                return "{} {}".format(op_info_prefix, info_str)

            return log_func

380
        op_info_prefix = "[{}|{}]".format(self.name, concurrency_idx)
B
barrierye 已提交
381
        log = get_log_func(op_info_prefix)
B
barrierye 已提交
382
        tid = threading.current_thread().ident
B
barrierye 已提交
383

B
barrierye 已提交
384
        # init op
B
barrierye 已提交
385
        try:
B
barriery 已提交
386
            self._initialize(is_thread_op)
B
barrierye 已提交
387 388 389
        except Exception as e:
            _LOGGER.error(log(e))
            os._exit(-1)
390

B
barriery 已提交
391 392 393 394 395 396
        batch_generator = self._auto_batching_generator(
                input_channel=input_channel, 
                op_name=self.name,
                batch_size=self._batch_size,
                timeout=self._auto_batching_timeout)
        
B
barrierye 已提交
397
        while True:
B
barriery 已提交
398
            channeldata_dict_batch = None
B
barrierye 已提交
399
            try:
B
barriery 已提交
400
                channeldata_dict_batch = next(batch_generator)
B
barrierye 已提交
401
            except ChannelStopError:
B
barrierye 已提交
402
                _LOGGER.debug(log("stop."))
B
barriery 已提交
403
                self._finalize(is_thread_op)
B
barrierye 已提交
404
                break
405

B
barriery 已提交
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
            # parse channeldata batch
            try:
                # parse channeldata batch
            except ChannelStopError:
                _LOGGER.debug(log("stop."))
                break
            nor_dataid_list = []
            err_dataid_list = []
            nor_datas = {}
            err_datas = {}
            for channeldata_dict in channeldata_dict_batch:
                (data_id, error_channeldata, parsed_data,
                        client_need_profile, profile_set) = \
                                self._parse_channeldata(channeldata_dict)
                if error_channeldata is None:
                    nor_dataid_list.append(data_id)
                    nor_datas[data_id] = {
                        "pd": parsed_data,
                        "np": client_need_profile,
                        "ps": profile_set,
                    }
                else:
                    # error data in predecessor Op
                    try:
                        # error_channeldata with profile info
                        self._push_to_output_channels(error_channeldata,
                                                      output_channels)
                    except ChannelStopError:
                        _LOGGER.debug(log("stop."))
                        break
436 437

            # preprecess
B
barrierye 已提交
438
            self._profiler_record("prep#{}_0".format(op_info_prefix))
W
wangjiawei04 已提交
439 440
            preped_data, error_channeldata = self._run_preprocess(parsed_data,
                                                                  data_id, log)
B
barrierye 已提交
441
            self._profiler_record("prep#{}_1".format(op_info_prefix))
442
            if error_channeldata is not None:
B
barrierye 已提交
443
                try:
B
barrierye 已提交
444 445 446 447
                    self._push_to_output_channels(
                        error_channeldata,
                        output_channels,
                        client_need_profile=client_need_profile,
B
barrierye 已提交
448
                        profile_set=profile_set)
B
barrierye 已提交
449
                except ChannelStopError:
B
barrierye 已提交
450 451
                    _LOGGER.debug(log("stop."))
                    break
452 453
                continue

B
barrierye 已提交
454
            # process
B
barrierye 已提交
455
            self._profiler_record("midp#{}_0".format(op_info_prefix))
B
barrierye 已提交
456 457
            midped_data, error_channeldata = self._run_process(preped_data,
                                                               data_id, log)
B
barrierye 已提交
458
            self._profiler_record("midp#{}_1".format(op_info_prefix))
459
            if error_channeldata is not None:
B
barrierye 已提交
460
                try:
B
barrierye 已提交
461 462 463 464
                    self._push_to_output_channels(
                        error_channeldata,
                        output_channels,
                        client_need_profile=client_need_profile,
B
barrierye 已提交
465
                        profile_set=profile_set)
B
barrierye 已提交
466
                except ChannelStopError:
B
barrierye 已提交
467 468
                    _LOGGER.debug(log("stop."))
                    break
469
                continue
470 471

            # postprocess
B
barrierye 已提交
472
            self._profiler_record("postp#{}_0".format(op_info_prefix))
W
wangjiawei04 已提交
473
            output_data, error_channeldata = self._run_postprocess(
W
wangjiawei04 已提交
474
                parsed_data, midped_data, data_id, log)
B
barrierye 已提交
475
            self._profiler_record("postp#{}_1".format(op_info_prefix))
476
            if error_channeldata is not None:
B
barrierye 已提交
477
                try:
B
barrierye 已提交
478 479 480 481
                    self._push_to_output_channels(
                        error_channeldata,
                        output_channels,
                        client_need_profile=client_need_profile,
B
barrierye 已提交
482
                        profile_set=profile_set)
B
barrierye 已提交
483
                except ChannelStopError:
B
barrierye 已提交
484 485
                    _LOGGER.debug(log("stop."))
                    break
486
                continue
487 488

            # push data to channel (if run succ)
B
barrierye 已提交
489
            try:
B
barrierye 已提交
490 491 492 493
                self._push_to_output_channels(
                    output_data,
                    output_channels,
                    client_need_profile=client_need_profile,
B
barrierye 已提交
494
                    profile_set=profile_set)
B
barrierye 已提交
495
            except ChannelStopError:
B
barrierye 已提交
496
                _LOGGER.debug(log("stop."))
B
barrierye 已提交
497
                break
B
barriery 已提交
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536

    def _initialize(self, is_thread_op):
        if is_thread_op:
            with self._for_init_op_lock:
                if not self._succ_init_op:
                    # for the threaded version of Op, each thread cannot get its concurrency_idx
                    self.concurrency_idx = None
                    # init profiler
                    self._profiler = TimeProfiler()
                    self._profiler.enable(True)
                    # init client
                    self.client = self.init_client(
                            client_type, self._client_config,
                            self._server_endpoints, self._fetch_names)
                    # user defined
                    self.init_op()
                    self._succ_init_op = True
                    self._succ_close_op = False
            else:
                self.concurrency_idx = concurrency_idx
                # init profiler
                self._profiler = TimeProfiler()
                self._profiler.enable(True)
                # init client
                self.client = self.init_client(
                        client_type, self._client_config,
                        self._server_endpoints,
                        self._fetch_names)
                # user defined
                self.init_op()
 
    def _finalize(self, is_thread_op):
        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
537 538 539 540 541

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


B
barrierye 已提交
542 543 544
class RequestOp(Op):
    """ RequestOp do not run preprocess, process, postprocess. """

B
barrierye 已提交
545
    def __init__(self):
B
barrierye 已提交
546
        # PipelineService.name = "@G"
B
barrierye 已提交
547
        super(RequestOp, self).__init__(name="@G", input_ops=[])
B
barrierye 已提交
548
        # init op
549
        try:
550
            self.init_op()
551
        except Exception as e:
B
bug fix  
barrierye 已提交
552
            _LOGGER.error(e)
553
            os._exit(-1)
B
barrierye 已提交
554 555 556 557

    def unpack_request_package(self, request):
        dictdata = {}
        for idx, key in enumerate(request.key):
B
barrierye 已提交
558 559 560 561 562 563
            data = request.value[idx]
            try:
                data = eval(data)
            except Exception as e:
                pass
            dictdata[key] = data
B
barrierye 已提交
564 565 566 567 568 569
        return dictdata


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

B
barrierye 已提交
570 571
    def __init__(self, input_ops):
        super(ResponseOp, self).__init__(name="@R", input_ops=input_ops)
B
barrierye 已提交
572
        # init op
573
        try:
574
            self.init_op()
575
        except Exception as e:
B
bug fix  
barrierye 已提交
576
            _LOGGER.error(e)
577
            os._exit(-1)
B
barrierye 已提交
578 579 580 581 582 583 584 585 586

    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
B
barrierye 已提交
587
                np.set_printoptions(threshold=np.nan)
B
barrierye 已提交
588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
                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
610 611 612 613 614 615 616


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

    def __init__(self, name, concurrency=1):
        super(VirtualOp, self).__init__(
B
barrierye 已提交
617
            name=name, input_ops=None, concurrency=concurrency)
618 619 620 621 622
        self._virtual_pred_ops = []

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

B
barrierye 已提交
623 624 625 626 627 628 629 630
    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

631 632 633 634 635 636
    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 已提交
637 638
            for op_name in self._actual_pred_op_names(op):
                channel.add_producer(op_name)
639
        self._outputs.append(channel)
D
dongdaxiang 已提交
640

641
    def _run(self, concurrency_idx, input_channel, output_channels, client_type,
642
             is_thread_op):
B
barrierye 已提交
643 644 645 646 647 648
        def get_log_func(op_info_prefix):
            def log_func(info_str):
                return "{} {}".format(op_info_prefix, info_str)

            return log_func

649
        op_info_prefix = "[{}|{}]".format(self.name, concurrency_idx)
B
barrierye 已提交
650 651 652
        log = get_log_func(op_info_prefix)
        tid = threading.current_thread().ident

B
barrierye 已提交
653 654 655 656
        while True:
            try:
                channeldata_dict = input_channel.front(self.name)
            except ChannelStopError:
B
barrierye 已提交
657
                _LOGGER.debug(log("stop."))
B
barrierye 已提交
658
                break
D
dongdaxiang 已提交
659

B
barrierye 已提交
660 661 662 663 664
            try:
                for name, data in channeldata_dict.items():
                    self._push_to_output_channels(
                        data, channels=output_channels, name=name)
            except ChannelStopError:
B
barrierye 已提交
665
                _LOGGER.debug(log("stop."))
B
barrierye 已提交
666
                break