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

B
barrierye 已提交
29
from .proto import pipeline_service_pb2
B
barrierye 已提交
30
from .channel import (ThreadChannel, ProcessChannel, ChannelDataEcode,
B
bug fix  
barriery 已提交
31 32
                      ChannelData, ChannelDataType, ChannelStopError,
                      ChannelTimeoutError)
B
barrierye 已提交
33
from .util import NameGenerator
B
barriery 已提交
34
from .profiler import UnsafeTimeProfiler as TimeProfiler
35

36
_LOGGER = logging.getLogger(__name__)
B
barrierye 已提交
37 38
_op_name_gen = NameGenerator("Op")

D
dongdaxiang 已提交
39 40 41

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

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

65 66 67 68
        if timeout > 0:
            self._timeout = timeout / 1000.0
        else:
            self._timeout = -1
69 70 71
        self._retry = max(1, retry)
        self._input = None
        self._outputs = []
B
barrierye 已提交
72

B
barriery 已提交
73
        self._batch_size = batch_size
B
bug fix  
barriery 已提交
74
        self._auto_batching_timeout = auto_batching_timeout
B
barriery 已提交
75 76
        if self._auto_batching_timeout is not None:
            if self._auto_batching_timeout <= 0 or self._batch_size == 1:
77
                _LOGGER.warning(
B
barriery 已提交
78 79 80
                    self._log(
                        "Because auto_batching_timeout <= 0 or batch_size == 1,"
                        " set auto_batching_timeout to None."))
B
barriery 已提交
81
                self._auto_batching_timeout = None
82 83
            else:
                self._auto_batching_timeout = self._auto_batching_timeout / 1000.0
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
        if not isinstance(self, RequestOp) and not isinstance(self, ResponseOp):
            _LOGGER.info(
                self._log("\n\tinput_ops: {},"
                          "\n\tserver_endpoints: {}"
                          "\n\tfetch_list: {}"
                          "\n\tclient_config: {}"
                          "\n\tconcurrency: {},"
                          "\n\ttimeout(s): {},"
                          "\n\tretry: {},"
                          "\n\tbatch_size: {},"
                          "\n\tauto_batching_timeout(s): {}".format(
                              ", ".join([op.name for op in input_ops
                                         ]), self._server_endpoints,
                              self._fetch_names, self._client_config,
                              self.concurrency, self._timeout, self._retry,
                              self._batch_size, self._auto_batching_timeout)))
B
barriery 已提交
100

B
barrierye 已提交
101
        self._server_use_profile = False
B
barriery 已提交
102
        self._tracer = None
103

104
        # only for thread op
B
barrierye 已提交
105
        self._for_init_op_lock = threading.Lock()
B
barrierye 已提交
106
        self._for_close_op_lock = threading.Lock()
B
barrierye 已提交
107
        self._succ_init_op = False
B
barrierye 已提交
108
        self._succ_close_op = False
B
barrierye 已提交
109

B
barriery 已提交
110
    def use_default_auto_batching_config(self):
B
bug fix  
barriery 已提交
111
        if self._batch_size != 1:
112 113
            _LOGGER.warning("Op({}) reset batch_size=1 (original: {})"
                            .format(self.name, self._batch_size))
B
bug fix  
barriery 已提交
114 115
            self._batch_size = 1
        if self._auto_batching_timeout != None:
116
            _LOGGER.warning(
B
barriery 已提交
117 118
                "Op({}) reset auto_batching_timeout=None (original: {})"
                .format(self.name, self._auto_batching_timeout))
B
bug fix  
barriery 已提交
119
            self._auto_batching_timeout = None
B
barriery 已提交
120

B
barrierye 已提交
121
    def use_profiler(self, use_profile):
B
barrierye 已提交
122
        self._server_use_profile = use_profile
123

B
barriery 已提交
124 125 126
    def set_tracer(self, tracer):
        self._tracer = tracer

B
barrierye 已提交
127 128
    def init_client(self, client_type, client_config, server_endpoints,
                    fetch_names):
129
        if self.with_serving == False:
B
barriery 已提交
130
            _LOGGER.info("Op({}) has no client (and it also do not "
131
                         "run the process function)".format(self.name))
B
barrierye 已提交
132
            return None
133
        if client_type == 'brpc':
B
barrierye 已提交
134 135
            client = Client()
            client.load_client_config(client_config)
136
        elif client_type == 'grpc':
B
barrierye 已提交
137
            client = MultiLangClient()
138
        else:
B
barriery 已提交
139 140
            raise ValueError("Failed to init client: unknow client "
                             "type {}".format(client_type))
B
barrierye 已提交
141
        client.connect(server_endpoints)
142
        self._fetch_names = fetch_names
B
barrierye 已提交
143
        return client
144 145 146 147 148 149 150 151 152 153

    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):
154
                _LOGGER.critical(
B
barriery 已提交
155 156
                    self._log("Failed to set input_ops: input op "
                              "must be Op type, not {}".format(type(op))))
157
                os._exit(-1)
158
            self._input_ops.append(op)
D
dongdaxiang 已提交
159

160 161
    def add_input_channel(self, channel):
        if not isinstance(channel, (ThreadChannel, ProcessChannel)):
162
            _LOGGER.critical(
B
barriery 已提交
163 164 165
                self._log("Failed to set input_channel: input "
                          "channel must be Channel type, not {}".format(
                              type(channel))))
166
            os._exit(-1)
167 168
        channel.add_consumer(self.name)
        self._input = channel
D
dongdaxiang 已提交
169

170
    def clean_input_channel(self):
B
barrierye 已提交
171 172 173 174
        self._input = None

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

176 177
    def add_output_channel(self, channel):
        if not isinstance(channel, (ThreadChannel, ProcessChannel)):
178
            _LOGGER.critical(
B
barriery 已提交
179 180
                self._log("Failed to add output_channel: output channel "
                          "must be Channel type, not {}".format(type(channel))))
181
            os._exit(-1)
182 183
        channel.add_producer(self.name)
        self._outputs.append(channel)
D
dongdaxiang 已提交
184

185
    def clean_output_channels(self):
B
barrierye 已提交
186 187 188 189 190
        self._outputs = []

    def _get_output_channels(self):
        return self._outputs

W
wangjiawei04 已提交
191
    def preprocess(self, input_dicts):
B
barrierye 已提交
192
        # multiple previous Op
B
barrierye 已提交
193
        if len(input_dicts) != 1:
194 195
            _LOGGER.critical(
                self._log(
B
barriery 已提交
196 197
                    "Failed to run preprocess: this Op has multiple previous "
                    "inputs. Please override this func."))
198
            os._exit(-1)
D
dongdaxiang 已提交
199

B
barrierye 已提交
200 201
        (_, input_dict), = input_dicts.items()
        return input_dict
B
barrierye 已提交
202

B
barriery 已提交
203
    def process(self, feed_batch, typical_logid):
B
bug fix  
barriery 已提交
204
        err, err_info = ChannelData.check_batch_npdata(feed_batch)
B
barrierye 已提交
205
        if err != 0:
206
            _LOGGER.critical(
B
barriery 已提交
207 208
                self._log("Failed to run process: {}. Please override "
                          "preprocess func.".format(err_info)))
209
            os._exit(-1)
B
barrierye 已提交
210
        call_result = self.client.predict(
B
barriery 已提交
211
            feed=feed_batch, fetch=self._fetch_names, log_id=typical_logid)
B
barriery 已提交
212 213 214 215
        if isinstance(self.client, MultiLangClient):
            if call_result is None or call_result["serving_status_code"] != 0:
                return None
            call_result.pop("serving_status_code")
216 217
        return call_result

W
wangjiawei04 已提交
218
    def postprocess(self, input_dict, fetch_dict):
B
barrierye 已提交
219
        return fetch_dict
D
dongdaxiang 已提交
220

B
barrierye 已提交
221
    def _parse_channeldata(self, channeldata_dict):
222
        data_id, error_channeldata = None, None
B
barrierye 已提交
223
        client_need_profile, profile_set = False, set()
B
barrierye 已提交
224 225 226 227
        parsed_data = {}

        key = list(channeldata_dict.keys())[0]
        data_id = channeldata_dict[key].id
B
barrierye 已提交
228
        client_need_profile = channeldata_dict[key].client_need_profile
B
barrierye 已提交
229 230 231 232 233 234

        for name, data in channeldata_dict.items():
            if data.ecode != ChannelDataEcode.OK.value:
                error_channeldata = data
                break
            parsed_data[name] = data.parse()
B
barrierye 已提交
235
            if client_need_profile:
B
barrierye 已提交
236
                profile_set |= data.profile_data_set
B
barrierye 已提交
237
        return (data_id, error_channeldata, parsed_data, client_need_profile,
B
barrierye 已提交
238
                profile_set)
B
barrierye 已提交
239 240 241 242 243

    def _push_to_output_channels(self,
                                 data,
                                 channels,
                                 name=None,
B
barriery 已提交
244
                                 profile_str=None,
B
barrierye 已提交
245
                                 client_need_profile=False,
B
barrierye 已提交
246
                                 profile_set=None):
247 248
        if name is None:
            name = self.name
B
barrierye 已提交
249

B
barriery 已提交
250
        # add profile into channeldata
B
barrierye 已提交
251
        if client_need_profile and profile_set is not None:
B
barriery 已提交
252 253
            if profile_str is not None:
                profile_set.add(profile_str)
B
barrierye 已提交
254
            data.add_profile(profile_set)
B
barrierye 已提交
255

B
barriery 已提交
256 257 258
        for channel in channels:
            channel.push(data, name)

B
barrierye 已提交
259
    def start_with_process(self, client_type):
B
barriery 已提交
260 261 262
        trace_buffer = None
        if self._tracer is not None:
            trace_buffer = self._tracer.data_buffer()
263
        proces = []
B
barrierye 已提交
264
        for concurrency_idx in range(self.concurrency):
265 266
            p = multiprocessing.Process(
                target=self._run,
B
barrierye 已提交
267
                args=(concurrency_idx, self._get_input_channel(),
B
barriery 已提交
268
                      self._get_output_channels(), client_type, False,
B
barriery 已提交
269
                      trace_buffer))
B
barriery 已提交
270
            p.daemon = True
271 272 273 274
            p.start()
            proces.append(p)
        return proces

B
barrierye 已提交
275
    def start_with_thread(self, client_type):
B
barriery 已提交
276 277 278
        trace_buffer = None
        if self._tracer is not None:
            trace_buffer = self._tracer.data_buffer()
279
        threads = []
B
barrierye 已提交
280
        for concurrency_idx in range(self.concurrency):
281 282
            t = threading.Thread(
                target=self._run,
B
barrierye 已提交
283
                args=(concurrency_idx, self._get_input_channel(),
B
barriery 已提交
284
                      self._get_output_channels(), client_type, True,
B
barriery 已提交
285
                      trace_buffer))
B
barriery 已提交
286 287 288
            # When a process exits, it attempts to terminate
            # all of its daemonic child processes.
            t.daemon = True
289 290 291 292
            t.start()
            threads.append(t)
        return threads

B
barrierye 已提交
293
    def init_op(self):
B
barrierye 已提交
294 295
        pass

B
barriery 已提交
296 297
    def _run_preprocess(self, parsed_data_dict, op_info_prefix):
        _LOGGER.debug("{} Running preprocess".format(op_info_prefix))
298 299
        preped_data_dict = collections.OrderedDict()
        err_channeldata_dict = collections.OrderedDict()
300 301 302 303 304 305
        for data_id, parsed_data in parsed_data_dict.items():
            preped_data, error_channeldata = None, None
            try:
                preped_data = self.preprocess(parsed_data)
            except TypeError as e:
                # Error type in channeldata.datatype
B
barriery 已提交
306 307 308
                error_info = "(logid={}) {} Failed to preprocess: {}".format(
                    data_id, op_info_prefix, e)
                _LOGGER.error(error_info, exc_info=True)
309 310 311 312 313
                error_channeldata = ChannelData(
                    ecode=ChannelDataEcode.TYPE_ERROR.value,
                    error_info=error_info,
                    data_id=data_id)
            except Exception as e:
B
barriery 已提交
314 315 316
                error_info = "(logid={}) {} Failed to preprocess: {}".format(
                    data_id, op_info_prefix, e)
                _LOGGER.error(error_info, exc_info=True)
317 318 319 320 321 322 323 324
                error_channeldata = ChannelData(
                    ecode=ChannelDataEcode.UNKNOW.value,
                    error_info=error_info,
                    data_id=data_id)
            if error_channeldata is not None:
                err_channeldata_dict[data_id] = error_channeldata
            else:
                preped_data_dict[data_id] = preped_data
B
barriery 已提交
325
        _LOGGER.debug("{} Succ preprocess".format(op_info_prefix))
326 327
        return preped_data_dict, err_channeldata_dict

B
barriery 已提交
328 329
    def _run_process(self, preped_data_dict, op_info_prefix):
        _LOGGER.debug("{} Running process".format(op_info_prefix))
330 331
        midped_data_dict = collections.OrderedDict()
        err_channeldata_dict = collections.OrderedDict()
332
        if self.with_serving:
333
            data_ids = preped_data_dict.keys()
B
barriery 已提交
334 335 336 337
            typical_logid = data_ids[0]
            if len(data_ids) != 1:
                for data_id in data_ids:
                    _LOGGER.info(
338 339 340 341
                        "(logid={}) {} During access to PaddleServingService,"
                        " we selected logid={} (from batch: {}) as a "
                        "representative for logging.".format(
                            data_id, op_info_prefix, typical_logid, data_ids))
B
bug fix  
barriery 已提交
342 343
            feed_batch = [preped_data_dict[data_id] for data_id in data_ids]
            midped_batch = None
344 345 346
            ecode = ChannelDataEcode.OK.value
            if self._timeout <= 0:
                try:
B
barriery 已提交
347
                    midped_batch = self.process(feed_batch, typical_logid)
348 349
                except Exception as e:
                    ecode = ChannelDataEcode.UNKNOW.value
B
barriery 已提交
350 351
                    error_info = "(logid={}) {} Failed to process(batch: {}): {}".format(
                        typical_logid, op_info_prefix, data_ids, e)
B
barriery 已提交
352
                    _LOGGER.error(error_info, exc_info=True)
353 354 355
            else:
                for i in range(self._retry):
                    try:
356
                        midped_batch = func_timeout.func_timeout(
B
barriery 已提交
357 358 359
                            self._timeout,
                            self.process,
                            args=(feed_batch, typical_logid))
360 361 362
                    except func_timeout.FunctionTimedOut as e:
                        if i + 1 >= self._retry:
                            ecode = ChannelDataEcode.TIMEOUT.value
B
barriery 已提交
363
                            error_info = "(logid={}) {} Failed to process(batch: {}): " \
B
barriery 已提交
364
                                    "exceeded retry count.".format(
B
barriery 已提交
365
                                            typical_logid, op_info_prefix, data_ids)
366 367
                            _LOGGER.error(error_info)
                        else:
368
                            _LOGGER.warning(
B
barriery 已提交
369 370 371 372
                                "(logid={}) {} Failed to process(batch: {}): timeout,"
                                " and retrying({}/{})...".format(
                                    typical_logid, op_info_prefix, data_ids, i +
                                    1, self._retry))
373 374
                    except Exception as e:
                        ecode = ChannelDataEcode.UNKNOW.value
B
barriery 已提交
375 376
                        error_info = "(logid={}) {} Failed to process(batch: {}): {}".format(
                            typical_logid, op_info_prefix, data_ids, e)
B
barriery 已提交
377
                        _LOGGER.error(error_info, exc_info=True)
378 379 380 381
                        break
                    else:
                        break
            if ecode != ChannelDataEcode.OK.value:
382 383
                for data_id in data_ids:
                    err_channeldata_dict[data_id] = ChannelData(
B
barriery 已提交
384
                        ecode=ecode, error_info=error_info, data_id=data_id)
385
            elif midped_batch is None:
386
                # op client return None
B
barriery 已提交
387 388 389 390
                error_info = "(logid={}) {} Failed to predict, please check if " \
                        "PaddleServingService is working properly.".format(
                                typical_logid, op_info_prefix)
                _LOGGER.error(error_info)
391 392
                for data_id in data_ids:
                    err_channeldata_dict[data_id] = ChannelData(
B
barriery 已提交
393 394 395
                        ecode=ChannelDataEcode.CLIENT_ERROR.value,
                        error_info=error_info,
                        data_id=data_id)
396 397 398 399
            else:
                # transform np format to dict format
                for idx, data_id in enumerate(data_ids):
                    midped_data_dict[data_id] = {
B
barriery 已提交
400 401
                        k: v[idx]
                        for k, v in midped_batch.items()
402
                    }
403
        else:
404
            midped_data_dict = preped_data_dict
B
barriery 已提交
405
        _LOGGER.debug("{} Succ process".format(op_info_prefix))
406 407
        return midped_data_dict, err_channeldata_dict

B
barriery 已提交
408 409 410
    def _run_postprocess(self, parsed_data_dict, midped_data_dict,
                         op_info_prefix):
        _LOGGER.debug("{} Running postprocess".format(op_info_prefix))
411 412
        postped_data_dict = collections.OrderedDict()
        err_channeldata_dict = collections.OrderedDict()
B
bug fix  
barriery 已提交
413
        for data_id, midped_data in midped_data_dict.items():
414 415
            postped_data, err_channeldata = None, None
            try:
B
barriery 已提交
416 417
                postped_data = self.postprocess(parsed_data_dict[data_id],
                                                midped_data)
418
            except Exception as e:
B
barriery 已提交
419 420 421
                error_info = "(logid={}) {} Failed to postprocess: {}".format(
                    data_id, op_info_prefix, e)
                _LOGGER.error(error_info, exc_info=True)
422 423 424 425 426 427 428 429 430
                err_channeldata = ChannelData(
                    ecode=ChannelDataEcode.UNKNOW.value,
                    error_info=error_info,
                    data_id=data_id)
            if err_channeldata is not None:
                err_channeldata_dict[data_id] = err_channeldata
                continue
            else:
                if not isinstance(postped_data, dict):
B
barriery 已提交
431 432 433 434 435
                    error_info = "(logid={}) {} Failed to postprocess: " \
                            "output of postprocess funticon must be " \
                            "dict type, but get {}".format(
                                data_id, op_info_prefix,
                                type(postped_data))
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
                    _LOGGER.error(error_info)
                    err_channeldata = ChannelData(
                        ecode=ChannelDataEcode.UNKNOW.value,
                        error_info=error_info,
                        data_id=data_id)
                    err_channeldata_dict[data_id] = err_channeldata
                    continue

                output_data = None
                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)
                postped_data_dict[data_id] = output_data
B
barriery 已提交
457
        _LOGGER.debug("{} Succ postprocess".format(op_info_prefix))
458
        return postped_data_dict, err_channeldata_dict
B
barriery 已提交
459 460

    def _auto_batching_generator(self, input_channel, op_name, batch_size,
B
barriery 已提交
461
                                 timeout, op_info_prefix):
B
barriery 已提交
462 463 464 465 466 467 468 469 470 471 472 473
        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:
B
barriery 已提交
474 475
                                _LOGGER.debug("{} Failed to generate batch: "
                                              "timeout".format(op_info_prefix))
B
barriery 已提交
476
                                break
B
barriery 已提交
477 478
                            channeldata_dict = input_channel.front(op_name,
                                                                   timeout)
B
barriery 已提交
479 480 481 482
                        else:
                            channeldata_dict = input_channel.front(op_name)
                        batch.append(channeldata_dict)
                    except ChannelTimeoutError:
B
barriery 已提交
483 484
                        _LOGGER.debug("{} Failed to generate batch: "
                                      "timeout".format(op_info_prefix))
B
barriery 已提交
485
                        break
B
barriery 已提交
486 487
            _LOGGER.debug("{} Got actual batch_size: {}".format(op_info_prefix,
                                                                len(batch)))
B
barriery 已提交
488
            yield batch
489

490
    def _parse_channeldata_batch(self, batch, output_channels):
491
        parsed_data_dict = collections.OrderedDict()
492 493
        need_profile_dict = {}
        profile_dict = {}
B
bug fix  
barriery 已提交
494
        for channeldata_dict in batch:
495 496 497 498 499 500 501 502 503 504
            (data_id, error_channeldata, parsed_data,
                    client_need_profile, profile_set) = \
                            self._parse_channeldata(channeldata_dict)
            if error_channeldata is None:
                parsed_data_dict[data_id] = parsed_data
                need_profile_dict[data_id] = client_need_profile
                profile_dict[data_id] = profile_set
            else:
                # error data in predecessor Op
                # (error_channeldata with profile info)
B
barriery 已提交
505 506
                self._push_to_output_channels(error_channeldata,
                                              output_channels)
507 508

        return parsed_data_dict, need_profile_dict, profile_dict
B
barriery 已提交
509 510

    def _run(self, concurrency_idx, input_channel, output_channels, client_type,
B
barriery 已提交
511
             is_thread_op, trace_buffer):
512
        op_info_prefix = "[{}|{}]".format(self.name, concurrency_idx)
B
barrierye 已提交
513
        tid = threading.current_thread().ident
B
barrierye 已提交
514

B
barrierye 已提交
515
        # init op
B
barriery 已提交
516
        profiler = None
B
barrierye 已提交
517
        try:
B
barriery 已提交
518 519
            profiler = self._initialize(is_thread_op, client_type,
                                        concurrency_idx)
B
barrierye 已提交
520
        except Exception as e:
B
barriery 已提交
521 522 523
            _LOGGER.critical(
                "{} Failed to init op: {}".format(op_info_prefix, e),
                exc_info=True)
B
barrierye 已提交
524
            os._exit(-1)
B
barriery 已提交
525
        _LOGGER.info("{} Succ init".format(op_info_prefix))
526

B
barriery 已提交
527
        batch_generator = self._auto_batching_generator(
B
barriery 已提交
528 529 530 531
            input_channel=input_channel,
            op_name=self.name,
            batch_size=self._batch_size,
            timeout=self._auto_batching_timeout,
B
barriery 已提交
532
            op_info_prefix=op_info_prefix)
B
barriery 已提交
533

B
barriery 已提交
534
        start, end = None, None
B
barrierye 已提交
535
        while True:
B
barriery 已提交
536
            start = int(round(_time() * 1000000))
B
barrierye 已提交
537
            try:
B
barriery 已提交
538
                channeldata_dict_batch = next(batch_generator)
B
barrierye 已提交
539
            except ChannelStopError:
B
barriery 已提交
540
                _LOGGER.debug("{} Stop.".format(op_info_prefix))
B
barriery 已提交
541
                self._finalize(is_thread_op)
B
barrierye 已提交
542
                break
B
barriery 已提交
543
            end = int(round(_time() * 1000000))
B
barriery 已提交
544 545
            if trace_buffer is not None:
                trace_buffer.put((self.name, "in", True, end - start))
546

B
barriery 已提交
547 548
            # parse channeldata batch
            try:
549 550 551
                parsed_data_dict, need_profile_dict, profile_dict \
                        = self._parse_channeldata_batch(
                                channeldata_dict_batch, output_channels)
B
barriery 已提交
552
            except ChannelStopError:
B
barriery 已提交
553
                _LOGGER.debug("{} Stop.".format(op_info_prefix))
554
                self._finalize(is_thread_op)
B
barriery 已提交
555
                break
556 557 558
            if len(parsed_data_dict) == 0:
                # data in the whole batch is all error data
                continue
559 560

            # preprecess
B
barriery 已提交
561
            start = profiler.record("prep#{}_0".format(op_info_prefix))
562
            preped_data_dict, err_channeldata_dict \
B
barriery 已提交
563
                    = self._run_preprocess(parsed_data_dict, op_info_prefix)
B
barriery 已提交
564
            end = profiler.record("prep#{}_1".format(op_info_prefix))
B
barriery 已提交
565 566
            if trace_buffer is not None:
                trace_buffer.put((self.name, "prep", True, end - start))
567 568
            try:
                for data_id, err_channeldata in err_channeldata_dict.items():
B
barrierye 已提交
569
                    self._push_to_output_channels(
B
barriery 已提交
570 571
                        data=err_channeldata,
                        channels=output_channels,
572 573 574
                        client_need_profile=need_profile_dict[data_id],
                        profile_set=profile_dict[data_id])
            except ChannelStopError:
B
barriery 已提交
575
                _LOGGER.debug("{} Stop.".format(op_info_prefix))
576 577 578
                self._finalize(is_thread_op)
                break
            if len(parsed_data_dict) == 0:
579 580
                continue

B
barrierye 已提交
581
            # process
B
barriery 已提交
582
            start = profiler.record("midp#{}_0".format(op_info_prefix))
583
            midped_data_dict, err_channeldata_dict \
B
barriery 已提交
584
                    = self._run_process(preped_data_dict, op_info_prefix)
B
barriery 已提交
585
            end = profiler.record("midp#{}_1".format(op_info_prefix))
B
barriery 已提交
586 587
            if trace_buffer is not None:
                trace_buffer.put((self.name, "midp", True, end - start))
588 589
            try:
                for data_id, err_channeldata in err_channeldata_dict.items():
B
barrierye 已提交
590
                    self._push_to_output_channels(
B
barriery 已提交
591 592
                        data=err_channeldata,
                        channels=output_channels,
B
barriery 已提交
593 594
                        client_need_profile=need_profile_dict[data_id],
                        profile_set=profile_dict[data_id])
595
            except ChannelStopError:
B
barriery 已提交
596
                _LOGGER.debug("{} Stop.".format(op_info_prefix))
597 598 599
                self._finalize(is_thread_op)
                break
            if len(midped_data_dict) == 0:
600
                continue
601 602

            # postprocess
B
barriery 已提交
603
            start = profiler.record("postp#{}_0".format(op_info_prefix))
604 605
            postped_data_dict, err_channeldata_dict \
                    = self._run_postprocess(
B
barriery 已提交
606
                            parsed_data_dict, midped_data_dict, op_info_prefix)
B
barriery 已提交
607
            end = profiler.record("postp#{}_1".format(op_info_prefix))
B
barriery 已提交
608 609
            if trace_buffer is not None:
                trace_buffer.put((self.name, "postp", True, end - start))
610 611
            try:
                for data_id, err_channeldata in err_channeldata_dict.items():
B
barrierye 已提交
612
                    self._push_to_output_channels(
B
barriery 已提交
613 614
                        data=error_channeldata,
                        channels=output_channels,
B
barriery 已提交
615 616
                        client_need_profile=need_profile_dict[data_id],
                        profile_set=profile_dict[data_id])
617
            except ChannelStopError:
B
barriery 已提交
618
                _LOGGER.debug("{} Stop.".format(op_info_prefix))
619 620 621
                self._finalize(is_thread_op)
                break
            if len(postped_data_dict) == 0:
622
                continue
623 624

            # push data to channel (if run succ)
B
barriery 已提交
625
            start = int(round(_time() * 1000000))
B
barrierye 已提交
626
            try:
B
barriery 已提交
627
                profile_str = profiler.gen_profile_str()
628
                for data_id, postped_data in postped_data_dict.items():
B
barriery 已提交
629 630
                    if self._server_use_profile:
                        sys.stderr.write(profile_str)
631
                    self._push_to_output_channels(
B
barriery 已提交
632 633 634
                        data=postped_data,
                        channels=output_channels,
                        profile_str=profile_str,
B
barriery 已提交
635 636
                        client_need_profile=need_profile_dict[data_id],
                        profile_set=profile_dict[data_id])
B
barrierye 已提交
637
            except ChannelStopError:
B
barriery 已提交
638
                _LOGGER.debug("{} Stop.".format(op_info_prefix))
639
                self._finalize(is_thread_op)
B
barrierye 已提交
640
                break
B
barriery 已提交
641
            end = int(round(_time() * 1000000))
B
barriery 已提交
642 643
            if trace_buffer is not None:
                trace_buffer.put((self.name, "out", True, end - start))
B
barriery 已提交
644

B
bug fix  
barriery 已提交
645
    def _initialize(self, is_thread_op, client_type, concurrency_idx):
B
barriery 已提交
646 647 648 649 650 651 652
        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 client
                    self.client = self.init_client(
B
barriery 已提交
653 654
                        client_type, self._client_config,
                        self._server_endpoints, self._fetch_names)
B
barriery 已提交
655 656 657 658
                    # user defined
                    self.init_op()
                    self._succ_init_op = True
                    self._succ_close_op = False
B
bug fix  
barriery 已提交
659 660 661
        else:
            self.concurrency_idx = concurrency_idx
            # init client
B
barriery 已提交
662 663 664
            self.client = self.init_client(client_type, self._client_config,
                                           self._server_endpoints,
                                           self._fetch_names)
B
bug fix  
barriery 已提交
665 666
            # user defined
            self.init_op()
B
barriery 已提交
667

B
barriery 已提交
668 669 670 671 672
        # use a separate TimeProfiler per thread or process
        profiler = TimeProfiler()
        profiler.enable(True)
        return profiler

B
barriery 已提交
673 674 675 676 677 678 679 680
    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
681 682 683 684 685

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


B
barrierye 已提交
686 687 688
class RequestOp(Op):
    """ RequestOp do not run preprocess, process, postprocess. """

B
barrierye 已提交
689
    def __init__(self):
B
barriery 已提交
690 691
        # PipelineService.name = "@DAGExecutor"
        super(RequestOp, self).__init__(name="@DAGExecutor", input_ops=[])
B
barrierye 已提交
692
        # init op
693
        try:
694
            self.init_op()
695
        except Exception as e:
B
barriery 已提交
696
            _LOGGER.critical("Op(Request) Failed to init: {}".format(e))
697
            os._exit(-1)
B
barrierye 已提交
698 699 700 701

    def unpack_request_package(self, request):
        dictdata = {}
        for idx, key in enumerate(request.key):
B
barrierye 已提交
702 703 704 705 706 707
            data = request.value[idx]
            try:
                data = eval(data)
            except Exception as e:
                pass
            dictdata[key] = data
B
barrierye 已提交
708 709 710 711 712 713
        return dictdata


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

B
barrierye 已提交
714
    def __init__(self, input_ops):
B
barriery 已提交
715 716
        super(ResponseOp, self).__init__(
            name="@DAGExecutor", input_ops=input_ops)
B
barrierye 已提交
717
        # init op
718
        try:
719
            self.init_op()
720
        except Exception as e:
B
barriery 已提交
721 722
            _LOGGER.critical("Op(ResponseOp) Failed to init: {}".format(
                e, exc_info=True))
723
            os._exit(-1)
B
barrierye 已提交
724 725 726 727 728 729 730 731 732

    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 已提交
733
                np.set_printoptions(threshold=np.nan)
B
barrierye 已提交
734 735 736 737 738 739 740 741 742 743 744
                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)))
B
barriery 已提交
745 746 747
                        _LOGGER.error("(logid={}) Failed to pack RPC "
                                      "response package: {}".format(
                                          channeldata.id, resp.error_info))
B
barrierye 已提交
748 749 750 751 752 753
                        break
                    resp.value.append(var)
                    resp.key.append(name)
            else:
                resp.ecode = ChannelDataEcode.TYPE_ERROR.value
                resp.error_info = self._log(
B
barriery 已提交
754 755 756 757
                    "error type({}) in datatype.".format(channeldata.datatype))
                _LOGGER.error("(logid={}) Failed to pack RPC response"
                              " package: {}".format(channeldata.id,
                                                    resp.error_info))
B
barrierye 已提交
758 759 760
        else:
            resp.error_info = channeldata.error_info
        return resp
761 762 763 764 765 766 767


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

    def __init__(self, name, concurrency=1):
        super(VirtualOp, self).__init__(
B
barrierye 已提交
768
            name=name, input_ops=None, concurrency=concurrency)
769 770 771 772 773
        self._virtual_pred_ops = []

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

B
barrierye 已提交
774
    def _actual_pred_op_names(self, op):
B
barriery 已提交
775
        # can use disjoint-set, but it's not necessary
B
barrierye 已提交
776 777 778 779 780 781 782
        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

783 784
    def add_output_channel(self, channel):
        if not isinstance(channel, (ThreadChannel, ProcessChannel)):
785
            _LOGGER.critical(
B
barriery 已提交
786 787 788
                self._log("Failed to add output_channel: output_channel"
                          " must be Channel type, not {}".format(
                              type(channel))))
789
            os._exit(-1)
790
        for op in self._virtual_pred_ops:
B
barrierye 已提交
791 792
            for op_name in self._actual_pred_op_names(op):
                channel.add_producer(op_name)
793
        self._outputs.append(channel)
D
dongdaxiang 已提交
794

795
    def _run(self, concurrency_idx, input_channel, output_channels, client_type,
796
             is_thread_op):
797
        op_info_prefix = "[{}|{}]".format(self.name, concurrency_idx)
B
barrierye 已提交
798 799 800
        log = get_log_func(op_info_prefix)
        tid = threading.current_thread().ident

801 802 803 804 805 806 807
        batch_generator = self._auto_batching_generator(
            input_channel=input_channel,
            op_name=self.name,
            batch_size=1,
            timeout=None,
            log_func=log)

B
barrierye 已提交
808 809
        while True:
            try:
810
                channeldata_dict_batch = next(batch_generator)
B
barrierye 已提交
811
            except ChannelStopError:
B
barriery 已提交
812
                _LOGGER.debug("{} Stop.".format(op_info_prefix))
813
                self._finalize(is_thread_op)
B
barrierye 已提交
814
                break
D
dongdaxiang 已提交
815

B
barrierye 已提交
816
            try:
817 818 819 820
                for channeldata_dict in channeldata_dict_batch:
                    for name, data in channeldata_dict.items():
                        self._push_to_output_channels(
                            data, channels=output_channels, name=name)
B
barrierye 已提交
821
            except ChannelStopError:
B
barriery 已提交
822
                _LOGGER.debug("{} Stop.".format(op_info_prefix))
823
                self._finalize(is_thread_op)
B
barrierye 已提交
824
                break