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

B
barriery 已提交
27
from .proto import pipeline_service_pb2_grpc, pipeline_service_pb2
B
barriery 已提交
28 29 30
from . import operator
from . import dag
from . import util
B
barriery 已提交
31
from . import channel
32

33
_LOGGER = logging.getLogger(__name__)
34 35


B
barriery 已提交
36
class PipelineServicer(pipeline_service_pb2_grpc.PipelineServiceServicer):
37 38 39 40
    """
    Pipeline Servicer entrance.
    """

B
barriery 已提交
41
    def __init__(self, name, response_op, dag_conf, worker_idx=-1):
B
barriery 已提交
42
        super(PipelineServicer, self).__init__()
B
barriery 已提交
43 44
        self._name = name

B
barrierye 已提交
45
        # init dag executor
B
barriery 已提交
46
        self._dag_executor = dag.DAGExecutor(response_op, dag_conf, worker_idx)
B
barrierye 已提交
47
        self._dag_executor.start()
B
barriery 已提交
48
        _LOGGER.info("[PipelineServicer] succ init")
49 50

    def inference(self, request, context):
51 52 53
        _LOGGER.info(
            "(log_id={}) inference request name:{} self.name:{} time:{}".format(
                request.logid, request.name, self._name, time.time()))
B
barriery 已提交
54
        if request.name != "" and request.name != self._name:
55 56 57
            _LOGGER.error("(log_id={}) name dismatch error. request.name:{},"
                          "server.name={}".format(request.logid, request.name,
                                                  self._name))
B
barriery 已提交
58
            resp = pipeline_service_pb2.Response()
T
TeslaZhao 已提交
59 60
            resp.err_no = channel.ChannelDataErrcode.NO_SERVICE.value
            resp.err_msg = "Failed to inference: Service name error."
B
barriery 已提交
61
            return resp
62
        resp = self._dag_executor.call(request)
63 64
        return resp

B
barrierye 已提交
65

B
barrierye 已提交
66 67
@contextlib.contextmanager
def _reserve_port(port):
68 69 70
    """
    Find and reserve a port for all subprocesses to use.
    """
B
barrierye 已提交
71 72 73 74 75 76 77 78 79 80 81
    sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
    if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 0:
        raise RuntimeError("Failed to set SO_REUSEPORT.")
    sock.bind(('', port))
    try:
        yield sock.getsockname()[1]
    finally:
        sock.close()


82
class PipelineServer(object):
83 84 85 86
    """
    Pipeline Server : grpc gateway + grpc server.
    """

B
barriery 已提交
87 88
    def __init__(self, name=None):
        self._name = name  # for grpc-gateway path
B
barriery 已提交
89
        self._rpc_port = None
90
        self._worker_num = None
B
barrierye 已提交
91
        self._response_op = None
B
barriery 已提交
92 93
        self._proxy_server = None

B
barriery 已提交
94
    def _grpc_gateway(self, grpc_port, http_port):
95 96 97 98 99 100 101 102 103 104
        """
        Running a gateway server, linking libproxy_server.so

        Args:
            grpc_port: GRPC port
            http_port: HTTP port

        Returns:
            None
        """
B
barriery 已提交
105 106 107 108 109 110
        import os
        from ctypes import cdll
        from . import gateway
        lib_path = os.path.join(
            os.path.dirname(gateway.__file__), "libproxy_server.so")
        proxy_server = cdll.LoadLibrary(lib_path)
B
barriery 已提交
111
        proxy_server.run_proxy_server(grpc_port, http_port)
B
barriery 已提交
112

B
barriery 已提交
113
    def _run_grpc_gateway(self, grpc_port, http_port):
114 115 116 117 118 119 120 121 122 123 124
        """
        Starting the GRPC gateway in a new process. Exposing one 
        available HTTP port outside, and reflecting the data to RPC port.

        Args:
            grpc_port: GRPC port
            http_port: HTTP port

        Returns:
            None
        """
B
barriery 已提交
125
        if http_port <= 0:
B
barriery 已提交
126 127
            _LOGGER.info("Ignore grpc_gateway configuration.")
            return
B
barriery 已提交
128
        if not util.AvailablePortGenerator.port_is_available(http_port):
B
barriery 已提交
129
            raise SystemExit("Failed to run grpc-gateway: prot {} "
B
barriery 已提交
130
                             "is already used".format(http_port))
B
barriery 已提交
131 132 133
        if self._proxy_server is not None:
            raise RuntimeError("Proxy server has been started.")
        self._proxy_server = multiprocessing.Process(
B
barriery 已提交
134 135 136
            target=self._grpc_gateway, args=(
                grpc_port,
                http_port, ))
B
barriery 已提交
137 138
        self._proxy_server.daemon = True
        self._proxy_server.start()
139

B
barrierye 已提交
140
    def set_response_op(self, response_op):
141 142 143 144 145 146 147 148 149
        """
        Set the response OP.

        Args:
            response_op: ResponseOp or its subclass object

        Returns:
            None
        """
B
barriery 已提交
150
        if not isinstance(response_op, operator.ResponseOp):
B
barriery 已提交
151 152
            raise Exception("Failed to set response_op: response_op "
                            "must be ResponseOp type.")
B
barrierye 已提交
153
        if len(response_op.get_input_ops()) != 1:
B
barriery 已提交
154 155
            raise Exception("Failed to set response_op: response_op "
                            "can only have one previous op.")
B
barrierye 已提交
156
        self._response_op = response_op
B
barriery 已提交
157
        self._used_op, _ = dag.DAG.get_use_ops(self._response_op)
B
barrierye 已提交
158

B
barriery 已提交
159
    def prepare_server(self, yml_file=None, yml_dict=None):
160 161 162 163 164 165 166 167 168 169 170
        """
        Reading configures from the yml file(config.yaml), and launching
        local services.

        Args:
            yml_file: Reading configures from yaml files
            yml_dict: Reading configures from yaml dict.
   
        Returns:
            None 
        """
B
barriery 已提交
171 172
        conf = ServerYamlConfChecker.load_server_yaml_conf(
            yml_file=yml_file, yml_dict=yml_dict)
B
barriery 已提交
173

B
barriery 已提交
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
        self._rpc_port = conf.get("rpc_port")
        self._http_port = conf.get("http_port")
        if self._rpc_port is None:
            if self._http_port is None:
                raise SystemExit("Failed to prepare_server: rpc_port or "
                                 "http_port can not be None.")
            else:
                # http mode: generate rpc_port
                if not util.AvailablePortGenerator.port_is_available(
                        self._http_port):
                    raise SystemExit("Failed to prepare_server: http_port({}) "
                                     "is already used".format(self._http_port))
                self._rpc_port = util.GetAvailablePortGenerator().next()
        else:
            if not util.AvailablePortGenerator.port_is_available(
                    self._rpc_port):
                raise SystemExit("Failed to prepare_server: prot {} "
                                 "is already used".format(self._rpc_port))
            if self._http_port is None:
                # rpc mode
                pass
            else:
                # http mode
                if not util.AvailablePortGenerator.port_is_available(
                        self._http_port):
                    raise SystemExit("Failed to prepare_server: http_port({}) "
                                     "is already used".format(self._http_port))

202 203
        self._worker_num = conf["worker_num"]
        self._build_dag_each_worker = conf["build_dag_each_worker"]
B
barriery 已提交
204
        self._init_ops(conf["op"])
B
barriery 已提交
205

B
barrierye 已提交
206
        _LOGGER.info("============= PIPELINE SERVER =============")
207 208 209
        _LOGGER.info("\n{}".format(
            json.dumps(
                conf, indent=4, separators=(',', ':'))))
210
        if self._build_dag_each_worker is True:
B
bug fix  
barrierye 已提交
211 212 213
            _LOGGER.warning(
                "(Make sure that install grpcio whl with --no-binary flag: "
                "pip install grpcio --no-binary grpcio)")
B
barrierye 已提交
214
        _LOGGER.info("-------------------------------------------")
215

B
barriery 已提交
216
        self._conf = conf
B
barriery 已提交
217
        self._start_local_rpc_service()
B
barrierye 已提交
218

B
barriery 已提交
219
    def _init_ops(self, op_conf):
220 221 222 223 224 225 226 227 228
        """
        Initializing all OPs from dicetory.

        Args:
            op_conf: the op configures in yaml dict.

        Returns:
            None.
        """
B
barriery 已提交
229 230 231 232 233
        default_conf = {
            "concurrency": 1,
            "timeout": -1,
            "retry": 1,
            "batch_size": 1,
B
barriery 已提交
234
            "auto_batching_timeout": -1,
B
barriery 已提交
235
            "local_service_conf": {
B
barriery 已提交
236
                "workdir": "",
B
barriery 已提交
237
                "thread_num": 2,
238
                "device_type": -1,
B
barriery 已提交
239 240 241
                "devices": "",
                "mem_optim": True,
                "ir_optim": False,
Z
zhangjun 已提交
242 243
                "precision": "fp32",
                "use_calib": False,
T
TeslaZhao 已提交
244 245
                "use_mkldnn": False,
                "mkldnn_cache_capacity": 0,
B
barriery 已提交
246 247 248
            },
        }
        for op in self._used_op:
B
barriery 已提交
249 250
            if not isinstance(op, operator.RequestOp) and not isinstance(
                    op, operator.ResponseOp):
B
barriery 已提交
251
                conf = op_conf.get(op.name, default_conf)
B
barriery 已提交
252
                op.init_from_dict(conf)
B
barriery 已提交
253 254

    def _start_local_rpc_service(self):
255
        # only brpc now
B
barriery 已提交
256
        if self._conf["dag"]["client_type"] != "brpc":
B
barrierye 已提交
257
            _LOGGER.warning("Local service version must be brpc type now.")
B
barriery 已提交
258 259
        for op in self._used_op:
            if not isinstance(op, operator.RequestOp):
B
barriery 已提交
260
                op.launch_local_rpc_service()
261

262
    def run_server(self):
263 264 265 266 267 268 269 270 271 272 273
        """
        If _build_dag_each_worker is True, Starting _worker_num processes and 
        running one GRPC server in each process. Otherwise, Staring one GRPC
        server.

        Args:
            None

        Returns:
            None
        """
274
        if self._build_dag_each_worker:
B
barriery 已提交
275
            with _reserve_port(self._rpc_port) as port:
B
barrierye 已提交
276 277 278 279 280
                bind_address = 'localhost:{}'.format(port)
                workers = []
                for i in range(self._worker_num):
                    worker = multiprocessing.Process(
                        target=self._run_server_func,
281
                        args=(bind_address, self._response_op, self._conf, i))
B
barrierye 已提交
282 283
                    worker.start()
                    workers.append(worker)
B
barriery 已提交
284
                self._run_grpc_gateway(
B
barriery 已提交
285 286
                    grpc_port=self._rpc_port,
                    http_port=self._http_port)  # start grpc_gateway
B
barrierye 已提交
287 288 289 290
                for worker in workers:
                    worker.join()
        else:
            server = grpc.server(
B
bug fix  
barrierye 已提交
291 292
                futures.ThreadPoolExecutor(max_workers=self._worker_num),
                options=[('grpc.max_send_message_length', 256 * 1024 * 1024),
B
barriery 已提交
293 294
                         ('grpc.max_receive_message_length', 256 * 1024 * 1024)
                         ])
B
barriery 已提交
295
            pipeline_service_pb2_grpc.add_PipelineServiceServicer_to_server(
B
barriery 已提交
296 297
                PipelineServicer(self._name, self._response_op, self._conf),
                server)
B
barriery 已提交
298
            server.add_insecure_port('[::]:{}'.format(self._rpc_port))
B
barrierye 已提交
299
            server.start()
B
barriery 已提交
300
            self._run_grpc_gateway(
B
barriery 已提交
301 302
                grpc_port=self._rpc_port,
                http_port=self._http_port)  # start grpc_gateway
B
barrierye 已提交
303 304
            server.wait_for_termination()

305
    def _run_server_func(self, bind_address, response_op, dag_conf, worker_idx):
306 307 308 309 310 311 312 313 314
        """
        Running one GRPC server with PipelineServicer.

        Args:
            bind_address: binding IP/Port
            response_op: ResponseOp or its subclass object
            dag_conf: DAG config
            worker_idx: Process index.
        """
B
bug fix  
barrierye 已提交
315
        options = [('grpc.so_reuseport', 1),
B
barriery 已提交
316 317
                   ('grpc.max_send_message_length', 256 * 1024 * 1024),
                   ('grpc.max_send_message_length', 256 * 1024 * 1024)]
318
        server = grpc.server(
B
barrierye 已提交
319
            futures.ThreadPoolExecutor(
B
barrierye 已提交
320
                max_workers=1, ), options=options)
B
barriery 已提交
321
        pipeline_service_pb2_grpc.add_PipelineServiceServicer_to_server(
B
barriery 已提交
322 323
            PipelineServicer(self._name, response_op, dag_conf, worker_idx),
            server)
B
barrierye 已提交
324
        server.add_insecure_port(bind_address)
325 326
        server.start()
        server.wait_for_termination()
327 328 329


class ServerYamlConfChecker(object):
330 331 332 333
    """
    Checking validities of server yaml files.
    """

334 335 336 337
    def __init__(self):
        pass

    @staticmethod
B
barriery 已提交
338 339 340 341 342
    def load_server_yaml_conf(yml_file=None, yml_dict=None):
        if yml_file is not None and yml_dict is not None:
            raise SystemExit("Failed to prepare_server: only one of yml_file"
                             " or yml_dict can be selected as the parameter.")
        if yml_file is not None:
343
            with io.open(yml_file, encoding='utf-8') as f:
344
                conf = yaml.load(f.read(), yaml.FullLoader)
B
barriery 已提交
345 346 347 348 349
        elif yml_dict is not None:
            conf = yml_dict
        else:
            raise SystemExit("Failed to prepare_server: yml_file or yml_dict"
                             " can not be None.")
350 351
        ServerYamlConfChecker.check_server_conf(conf)
        ServerYamlConfChecker.check_dag_conf(conf["dag"])
B
barriery 已提交
352
        ServerYamlConfChecker.check_tracer_conf(conf["dag"]["tracer"])
B
barriery 已提交
353 354 355 356
        for op_name in conf["op"]:
            ServerYamlConfChecker.check_op_conf(conf["op"][op_name])
            ServerYamlConfChecker.check_local_service_conf(conf["op"][op_name][
                "local_service_conf"])
357 358
        return conf

B
barriery 已提交
359 360 361 362 363 364
    @staticmethod
    def check_conf(conf, default_conf, conf_type, conf_qualification):
        ServerYamlConfChecker.fill_with_default_conf(conf, default_conf)
        ServerYamlConfChecker.check_conf_type(conf, conf_type)
        ServerYamlConfChecker.check_conf_qualification(conf, conf_qualification)

365 366 367
    @staticmethod
    def check_server_conf(conf):
        default_conf = {
B
barriery 已提交
368
            # "rpc_port": 9292,
369 370
            "worker_num": 1,
            "build_dag_each_worker": False,
B
barriery 已提交
371
            #"http_port": 0,
372
            "dag": {},
B
barriery 已提交
373
            "op": {},
374 375 376
        }

        conf_type = {
B
barriery 已提交
377 378
            "rpc_port": int,
            "http_port": int,
379 380
            "worker_num": int,
            "build_dag_each_worker": bool,
B
barriery 已提交
381
            "grpc_gateway_port": int,
382 383 384
        }

        conf_qualification = {
B
barriery 已提交
385 386
            "rpc_port": [(">=", 1024), ("<=", 65535)],
            "http_port": [(">=", 1024), ("<=", 65535)],
387 388 389
            "worker_num": (">=", 1),
        }

B
barriery 已提交
390 391 392
        ServerYamlConfChecker.check_conf(conf, default_conf, conf_type,
                                         conf_qualification)

B
barriery 已提交
393 394 395
    @staticmethod
    def check_local_service_conf(conf):
        default_conf = {
B
barriery 已提交
396
            "workdir": "",
B
barriery 已提交
397
            "thread_num": 2,
398
            "device_type": -1,
B
barriery 已提交
399 400 401
            "devices": "",
            "mem_optim": True,
            "ir_optim": False,
Z
zhangjun 已提交
402 403
            "precision": "fp32",
            "use_calib": False,
T
TeslaZhao 已提交
404 405
            "use_mkldnn": False,
            "mkldnn_cache_capacity": 0,
B
barriery 已提交
406 407 408 409 410
        }
        conf_type = {
            "model_config": str,
            "workdir": str,
            "thread_num": int,
411
            "device_type": int,
B
barriery 已提交
412 413 414
            "devices": str,
            "mem_optim": bool,
            "ir_optim": bool,
Z
zhangjun 已提交
415 416
            "precision": str,
            "use_calib": bool,
T
TeslaZhao 已提交
417 418 419 420
            "use_mkldnn": bool,
            "mkldnn_cache_capacity": int,
            "mkldnn_op_list": list,
            "mkldnn_bf16_op_list": list,
B
barriery 已提交
421 422 423 424 425 426 427 428 429 430 431 432
        }
        conf_qualification = {"thread_num": (">=", 1), }
        ServerYamlConfChecker.check_conf(conf, default_conf, conf_type,
                                         conf_qualification)

    @staticmethod
    def check_op_conf(conf):
        default_conf = {
            "concurrency": 1,
            "timeout": -1,
            "retry": 1,
            "batch_size": 1,
B
barriery 已提交
433
            "auto_batching_timeout": -1,
B
barriery 已提交
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
            "local_service_conf": {},
        }
        conf_type = {
            "server_endpoints": list,
            "fetch_list": list,
            "client_config": str,
            "concurrency": int,
            "timeout": int,
            "retry": int,
            "batch_size": int,
            "auto_batching_timeout": int,
        }
        conf_qualification = {
            "concurrency": (">=", 1),
            "retry": (">=", 1),
            "batch_size": (">=", 1),
        }
B
barriery 已提交
451 452
        ServerYamlConfChecker.check_conf(conf, default_conf, conf_type,
                                         conf_qualification)
B
barriery 已提交
453

B
barriery 已提交
454 455
    @staticmethod
    def check_tracer_conf(conf):
B
bug fix  
barrierye 已提交
456
        default_conf = {"interval_s": -1, }
B
barriery 已提交
457 458 459 460 461 462 463

        conf_type = {"interval_s": int, }

        conf_qualification = {}

        ServerYamlConfChecker.check_conf(conf, default_conf, conf_type,
                                         conf_qualification)
464 465 466 467 468 469 470 471

    @staticmethod
    def check_dag_conf(conf):
        default_conf = {
            "retry": 1,
            "client_type": "brpc",
            "use_profile": False,
            "channel_size": 0,
B
barriery 已提交
472 473
            "is_thread_op": True,
            "tracer": {},
474
            "channel_recv_frist_arrive": False,
475 476 477 478 479 480 481 482
        }

        conf_type = {
            "retry": int,
            "client_type": str,
            "use_profile": bool,
            "channel_size": int,
            "is_thread_op": bool,
483
            "channel_recv_frist_arrive": bool,
484 485 486 487 488 489 490 491
        }

        conf_qualification = {
            "retry": (">=", 1),
            "client_type": ("in", ["brpc", "grpc"]),
            "channel_size": (">=", 0),
        }

B
barriery 已提交
492 493
        ServerYamlConfChecker.check_conf(conf, default_conf, conf_type,
                                         conf_qualification)
494 495 496 497 498 499 500 501 502 503 504 505

    @staticmethod
    def fill_with_default_conf(conf, default_conf):
        for key, val in default_conf.items():
            if conf.get(key) is None:
                _LOGGER.warning("[CONF] {} not set, use default: {}"
                                .format(key, val))
                conf[key] = val

    @staticmethod
    def check_conf_type(conf, conf_type):
        for key, val in conf_type.items():
B
barriery 已提交
506 507
            if key not in conf:
                continue
508 509 510 511 512 513 514
            if not isinstance(conf[key], val):
                raise SystemExit("[CONF] {} must be {} type, but get {}."
                                 .format(key, val, type(conf[key])))

    @staticmethod
    def check_conf_qualification(conf, conf_qualification):
        for key, qualification in conf_qualification.items():
B
barriery 已提交
515 516
            if key not in conf:
                continue
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
            if not isinstance(qualification, list):
                qualification = [qualification]
            if not ServerYamlConfChecker.qualification_check(conf[key],
                                                             qualification):
                raise SystemExit("[CONF] {} must be {}, but get {}."
                                 .format(key, ", ".join([
                                     "{} {}"
                                     .format(q[0], q[1]) for q in qualification
                                 ]), conf[key]))

    @staticmethod
    def qualification_check(value, qualifications):
        if not isinstance(qualifications, list):
            qualifications = [qualifications]
        ok = True
        for q in qualifications:
            operator, limit = q
            if operator == "<":
                ok = value < limit
            elif operator == "==":
                ok = value == limit
            elif operator == ">":
                ok = value > limit
            elif operator == "<=":
                ok = value <= limit
            elif operator == ">=":
                ok = value >= limit
            elif operator == "in":
                ok = value in limit
            else:
                raise SystemExit("unknow operator: {}".format(operator))
            if ok == False:
                break
        return ok