pipeline_server.py 17.6 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
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
import threading
import multiprocessing
import multiprocessing.queues
import sys
if sys.version_info.major == 2:
    import Queue
elif sys.version_info.major == 3:
    import queue as Queue
else:
    raise Exception("Error Python version")
import os
from paddle_serving_client import MultiLangClient, Client
from concurrent import futures
import numpy as np
import grpc
import logging
import random
import time
import func_timeout
import enum
import collections
import copy
B
barrierye 已提交
37 38 39
import socket
from contextlib import closing
import yaml
40

B
barrierye 已提交
41 42
from .proto import pipeline_service_pb2
from .proto import pipeline_service_pb2_grpc
B
barrierye 已提交
43
from .operator import Op, RequestOp, ResponseOp, VirtualOp
44 45
from .channel import ThreadChannel, ProcessChannel, ChannelData, ChannelDataEcode, ChannelDataType
from .profiler import TimeProfiler
B
barrierye 已提交
46
from .util import NameGenerator
47

W
wangjiawei04 已提交
48
_LOGGER = logging.getLogger()
49 50 51
_profiler = TimeProfiler()


B
barrierye 已提交
52
class PipelineService(pipeline_service_pb2_grpc.PipelineServiceServicer):
B
barrierye 已提交
53 54
    def __init__(self, in_channel, out_channel, unpack_func, pack_func,
                 retry=2):
B
barrierye 已提交
55
        super(PipelineService, self).__init__()
56 57 58
        self.name = "#G"
        self.set_in_channel(in_channel)
        self.set_out_channel(out_channel)
B
barrierye 已提交
59 60
        _LOGGER.debug(self._log(in_channel.debug()))
        _LOGGER.debug(self._log(out_channel.debug()))
61 62 63 64 65 66 67
        #TODO: 
        #  multi-lock for different clients
        #  diffenert lock for server and client
        self._id_lock = threading.Lock()
        self._cv = threading.Condition()
        self._globel_resp_dict = {}
        self._id_counter = 0
68
        self._reset_max_id = 1000000000000000000
69
        self._retry = retry
B
barrierye 已提交
70
        self._is_run = True
B
barrierye 已提交
71 72
        self._pack_func = pack_func
        self._unpack_func = unpack_func
73
        self._recive_func = threading.Thread(
B
barrierye 已提交
74
            target=PipelineService._recive_out_channel_func, args=(self, ))
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
        self._recive_func.start()

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

    def set_in_channel(self, in_channel):
        if not isinstance(in_channel, (ThreadChannel, ProcessChannel)):
            raise TypeError(
                self._log('in_channel must be Channel type, but get {}'.format(
                    type(in_channel))))
        in_channel.add_producer(self.name)
        self._in_channel = in_channel

    def set_out_channel(self, out_channel):
        if not isinstance(out_channel, (ThreadChannel, ProcessChannel)):
            raise TypeError(
                self._log('out_channel must be Channel type, but get {}'.format(
                    type(out_channel))))
        out_channel.add_consumer(self.name)
        self._out_channel = out_channel

B
barrierye 已提交
96 97 98
    def stop(self):
        self._is_run = False

99
    def _recive_out_channel_func(self):
B
barrierye 已提交
100
        while self._is_run:
B
barrierye 已提交
101 102 103 104
            channeldata_dict = self._out_channel.front(self.name)
            if len(channeldata_dict) != 1:
                raise Exception("out_channel cannot have multiple input ops")
            (_, channeldata), = channeldata_dict.items()
105 106 107 108 109 110 111 112 113 114 115
            if not isinstance(channeldata, ChannelData):
                raise TypeError(
                    self._log('data must be ChannelData type, but get {}'.
                              format(type(channeldata))))
            with self._cv:
                data_id = channeldata.id
                self._globel_resp_dict[data_id] = channeldata
                self._cv.notify_all()

    def _get_next_id(self):
        with self._id_lock:
116 117
            if self._id_counter >= self._reset_max_id:
                self._id_counter -= self._reset_max_id
118 119 120 121 122 123 124 125 126 127 128 129 130
            self._id_counter += 1
            return self._id_counter - 1

    def _get_data_in_globel_resp_dict(self, data_id):
        resp = None
        with self._cv:
            while data_id not in self._globel_resp_dict:
                self._cv.wait()
            resp = self._globel_resp_dict.pop(data_id)
            self._cv.notify_all()
        return resp

    def _pack_data_for_infer(self, request):
B
barrierye 已提交
131
        _LOGGER.debug(self._log('start inferce'))
132
        data_id = self._get_next_id()
B
barrierye 已提交
133
        dictdata = None
134
        try:
B
barrierye 已提交
135
            dictdata = self._unpack_func(request)
136 137 138
        except Exception as e:
            return ChannelData(
                ecode=ChannelDataEcode.RPC_PACKAGE_ERROR.value,
B
barrierye 已提交
139
                error_info="rpc package error: {}".format(e),
140 141 142
                data_id=data_id), data_id
        else:
            return ChannelData(
B
barrierye 已提交
143 144
                datatype=ChannelDataType.DICT.value,
                dictdata=dictdata,
145 146 147
                data_id=data_id), data_id

    def _pack_data_for_resp(self, channeldata):
B
barrierye 已提交
148 149
        _LOGGER.debug(self._log('get channeldata'))
        return self._pack_func(channeldata)
150 151 152 153 154 155 156 157

    def inference(self, request, context):
        _profiler.record("{}-prepack_0".format(self.name))
        data, data_id = self._pack_data_for_infer(request)
        _profiler.record("{}-prepack_1".format(self.name))

        resp_channeldata = None
        for i in range(self._retry):
B
barrierye 已提交
158
            _LOGGER.debug(self._log('push data'))
159 160 161 162
            _profiler.record("{}-push_0".format(self.name))
            self._in_channel.push(data, self.name)
            _profiler.record("{}-push_1".format(self.name))

B
barrierye 已提交
163
            _LOGGER.debug(self._log('wait for infer'))
164 165 166 167 168 169 170
            _profiler.record("{}-fetch_0".format(self.name))
            resp_channeldata = self._get_data_in_globel_resp_dict(data_id)
            _profiler.record("{}-fetch_1".format(self.name))

            if resp_channeldata.ecode == ChannelDataEcode.OK.value:
                break
            if i + 1 < self._retry:
B
barrierye 已提交
171
                _LOGGER.warn("retry({}): {}".format(
172 173 174 175 176 177 178 179 180 181
                    i + 1, resp_channeldata.error_info))

        _profiler.record("{}-postpack_0".format(self.name))
        resp = self._pack_data_for_resp(resp_channeldata)
        _profiler.record("{}-postpack_1".format(self.name))
        _profiler.print_profile()
        return resp


class PipelineServer(object):
B
barrierye 已提交
182
    def __init__(self):
183 184 185 186 187 188
        self._channels = []
        self._actual_ops = []
        self._port = None
        self._worker_num = None
        self._in_channel = None
        self._out_channel = None
B
barrierye 已提交
189
        self._response_op = None
B
barrierye 已提交
190 191
        self._pack_func = None
        self._unpack_func = None
192 193 194 195 196

    def add_channel(self, channel):
        self._channels.append(channel)

    def gen_desc(self):
B
barrierye 已提交
197
        _LOGGER.info('here will generate desc for PAAS')
198 199
        pass

B
barrierye 已提交
200 201 202
    def set_response_op(self, response_op):
        if not isinstance(response_op, Op):
            raise Exception("response_op must be Op type.")
B
barrierye 已提交
203 204
        if len(response_op.get_input_ops()) != 1:
            raise Exception("response_op can only have one previous op.")
B
barrierye 已提交
205 206 207 208 209 210 211
        self._response_op = response_op

    def _topo_sort(self, response_op):
        if response_op is None:
            raise Exception("response_op has not been set.")

        def get_use_ops(root):
B
barrierye 已提交
212
            # root: response_op
B
barrierye 已提交
213 214 215 216 217
            unique_names = set()
            use_ops = set()
            succ_ops_of_use_op = {}  # {op_name: succ_ops}
            que = Queue.Queue()
            que.put(root)
B
barrierye 已提交
218 219
            #use_ops.add(root)
            #unique_names.add(root.name)
B
barrierye 已提交
220 221 222 223 224
            while que.qsize() != 0:
                op = que.get()
                for pred_op in op.get_input_ops():
                    if pred_op.name not in succ_ops_of_use_op:
                        succ_ops_of_use_op[pred_op.name] = []
B
barrierye 已提交
225 226
                    if op != root:
                        succ_ops_of_use_op[pred_op.name].append(op)
B
barrierye 已提交
227 228 229 230 231 232 233 234 235 236 237
                    if pred_op not in use_ops:
                        que.put(pred_op)
                        use_ops.add(pred_op)
                        # check the name of op is globally unique
                        if pred_op.name in unique_names:
                            raise Exception("the name of Op must be unique: {}".
                                            format(pred_op.name))
                        unique_names.add(pred_op.name)
            return use_ops, succ_ops_of_use_op

        use_ops, out_degree_ops = get_use_ops(response_op)
B
barrierye 已提交
238 239
        _LOGGER.info("================= use op ==================")
        for op in use_ops:
B
barrierye 已提交
240
            _LOGGER.info(op.name)
B
barrierye 已提交
241
        _LOGGER.info("===========================================")
242 243 244 245
        if len(use_ops) <= 1:
            raise Exception(
                "Besides RequestOp and ResponseOp, there should be at least one Op in DAG."
            )
B
barrierye 已提交
246 247 248 249 250 251

        name2op = {op.name: op for op in use_ops}
        out_degree_num = {
            name: len(ops)
            for name, ops in out_degree_ops.items()
        }
252 253
        que_idx = 0  # scroll queue 
        ques = [Queue.Queue() for _ in range(2)]
B
barrierye 已提交
254 255
        zero_indegree_num = 0
        for op in use_ops:
256
            if len(op.get_input_ops()) == 0:
B
barrierye 已提交
257 258
                zero_indegree_num += 1
        if zero_indegree_num != 1:
259
            raise Exception("DAG contains multiple input Ops")
B
barrierye 已提交
260 261
        last_op = response_op.get_input_ops()[0]
        ques[que_idx].put(last_op)
262 263 264 265 266 267 268 269 270 271 272 273

        # topo sort to get dag_views
        dag_views = []
        sorted_op_num = 0
        while True:
            que = ques[que_idx]
            next_que = ques[(que_idx + 1) % 2]
            dag_view = []
            while que.qsize() != 0:
                op = que.get()
                dag_view.append(op)
                sorted_op_num += 1
B
barrierye 已提交
274 275 276 277
                for pred_op in op.get_input_ops():
                    out_degree_num[pred_op.name] -= 1
                    if out_degree_num[pred_op.name] == 0:
                        next_que.put(pred_op)
278 279 280 281
            dag_views.append(dag_view)
            if next_que.qsize() == 0:
                break
            que_idx = (que_idx + 1) % 2
B
barrierye 已提交
282
        if sorted_op_num < len(use_ops):
283 284 285 286 287 288
            raise Exception("not legal DAG")

        # create channels and virtual ops
        def gen_channel(name_gen):
            channel = None
            if self._use_multithread:
B
barrierye 已提交
289
                channel = ThreadChannel(name=name_gen.next())
290
            else:
B
barrierye 已提交
291
                channel = ProcessChannel(self._manager, name=name_gen.next())
292 293 294
            return channel

        def gen_virtual_op(name_gen):
B
barrierye 已提交
295
            return VirtualOp(name=name_gen.next())
296

B
barrierye 已提交
297 298
        virtual_op_name_gen = NameGenerator("vir")
        channel_name_gen = NameGenerator("chl")
299 300 301 302
        virtual_ops = []
        channels = []
        input_channel = None
        actual_view = None
B
barrierye 已提交
303
        dag_views = list(reversed(dag_views))
304 305 306 307 308 309 310 311 312 313
        for v_idx, view in enumerate(dag_views):
            if v_idx + 1 >= len(dag_views):
                break
            next_view = dag_views[v_idx + 1]
            if actual_view is None:
                actual_view = view
            actual_next_view = []
            pred_op_of_next_view_op = {}
            for op in actual_view:
                # find actual succ op in next view and create virtual op
B
barrierye 已提交
314
                for succ_op in out_degree_ops[op.name]:
315 316 317 318 319 320 321 322 323 324
                    if succ_op in next_view:
                        if succ_op not in actual_next_view:
                            actual_next_view.append(succ_op)
                        if succ_op.name not in pred_op_of_next_view_op:
                            pred_op_of_next_view_op[succ_op.name] = []
                        pred_op_of_next_view_op[succ_op.name].append(op)
                    else:
                        # create virtual op
                        virtual_op = gen_virtual_op(virtual_op_name_gen)
                        virtual_ops.append(virtual_op)
B
barrierye 已提交
325
                        out_degree_ops[virtual_op.name] = [succ_op]
326 327 328 329 330 331 332 333 334 335 336
                        actual_next_view.append(virtual_op)
                        pred_op_of_next_view_op[virtual_op.name] = [op]
                        virtual_op.add_virtual_pred_op(op)
            actual_view = actual_next_view
            # create channel
            processed_op = set()
            for o_idx, op in enumerate(actual_next_view):
                if op.name in processed_op:
                    continue
                channel = gen_channel(channel_name_gen)
                channels.append(channel)
B
barrierye 已提交
337
                _LOGGER.debug("{} => {}".format(channel.name, op.name))
338 339 340 341 342 343 344
                op.add_input_channel(channel)
                pred_ops = pred_op_of_next_view_op[op.name]
                if v_idx == 0:
                    input_channel = channel
                else:
                    # if pred_op is virtual op, it will use ancestors as producers to channel
                    for pred_op in pred_ops:
B
barrierye 已提交
345
                        _LOGGER.debug("{} => {}".format(pred_op.name,
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
                                                        channel.name))
                        pred_op.add_output_channel(channel)
                processed_op.add(op.name)
                # find same input op to combine channel
                for other_op in actual_next_view[o_idx + 1:]:
                    if other_op.name in processed_op:
                        continue
                    other_pred_ops = pred_op_of_next_view_op[other_op.name]
                    if len(other_pred_ops) != len(pred_ops):
                        continue
                    same_flag = True
                    for pred_op in pred_ops:
                        if pred_op not in other_pred_ops:
                            same_flag = False
                            break
                    if same_flag:
B
barrierye 已提交
362
                        _LOGGER.debug("{} => {}".format(channel.name,
363 364 365 366 367
                                                        other_op.name))
                        other_op.add_input_channel(channel)
                        processed_op.add(other_op.name)
        output_channel = gen_channel(channel_name_gen)
        channels.append(output_channel)
B
barrierye 已提交
368
        last_op.add_output_channel(output_channel)
369

B
barrierye 已提交
370 371
        pack_func, unpack_func = None, None
        pack_func = self._response_op.pack_response_package
372
        self._actual_ops = virtual_ops
B
barrierye 已提交
373
        for op in use_ops:
374
            if len(op.get_input_ops()) == 0:
B
barrierye 已提交
375
                unpack_func = op.unpack_request_package
376 377 378 379
                continue
            self._actual_ops.append(op)
        self._channels = channels
        for c in channels:
B
barrierye 已提交
380 381
            _LOGGER.debug(c.debug())
        return input_channel, output_channel, pack_func, unpack_func
382

B
barrierye 已提交
383 384 385 386 387 388 389 390
    def _port_is_available(self, port):
        with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
            sock.settimeout(2)
            result = sock.connect_ex(('0.0.0.0', port))
        return result != 0

    def prepare_server(self, yml_file):
        with open(yml_file) as f:
B
barrierye 已提交
391
            yml_config = yaml.load(f.read())
B
barrierye 已提交
392 393 394 395 396 397 398 399 400
        self._port = yml_config.get('port', 8080)
        if not self._port_is_available(self._port):
            raise SystemExit("Prot {} is already used".format(self._port))
        self._worker_num = yml_config.get('worker_num', 2)

        self._retry = yml_config.get('retry', 1)
        self._client_type = yml_config.get('client_type', 'brpc')
        self._use_multithread = yml_config.get('use_multithread', True)
        profile = yml_config.get('profile', False)
401

B
barrierye 已提交
402 403 404 405 406 407 408
        if not self._use_multithread:
            self._manager = multiprocessing.Manager()
            if profile:
                raise Exception(
                    "profile cannot be used in multiprocess version temporarily")
        _profiler.enable(profile)

B
barrierye 已提交
409 410
        input_channel, output_channel, self._pack_func, self._unpack_func = self._topo_sort(
            self._response_op)
411 412 413 414 415 416 417 418 419 420 421 422 423
        self._in_channel = input_channel
        self._out_channel = output_channel
        for op in self._actual_ops:
            if op.with_serving:
                self.prepare_serving(op)
        self.gen_desc()

    def _run_ops(self):
        threads_or_proces = []
        for op in self._actual_ops:
            op.init_profiler(_profiler)
            if self._use_multithread:
                threads_or_proces.extend(
B
barrierye 已提交
424
                    op.start_with_thread(self._client_type))
425 426
            else:
                threads_or_proces.extend(
B
barrierye 已提交
427
                    op.start_with_process(self._client_type))
428 429
        return threads_or_proces

B
barrierye 已提交
430 431
    def _stop_all(self, service):
        service.stop()
432 433
        for op in self._actual_ops:
            op.stop()
B
barrierye 已提交
434 435
        for chl in self._channels:
            chl.stop()
436 437 438

    def run_server(self):
        op_threads_or_proces = self._run_ops()
B
barrierye 已提交
439 440 441
        service = PipelineService(self._in_channel, self._out_channel,
                                  self._unpack_func, self._pack_func,
                                  self._retry)
442 443
        server = grpc.server(
            futures.ThreadPoolExecutor(max_workers=self._worker_num))
B
barrierye 已提交
444 445
        pipeline_service_pb2_grpc.add_PipelineServiceServicer_to_server(service,
                                                                        server)
446 447 448
        server.add_insecure_port('[::]:{}'.format(self._port))
        server.start()
        server.wait_for_termination()
B
barrierye 已提交
449
        self._stop_all()  # TODO
450 451 452 453 454
        for x in op_threads_or_proces:
            x.join()

    def prepare_serving(self, op):
        # run a server (not in PyServing)
B
barrierye 已提交
455
        _LOGGER.info("run a server (not in PyServing)")