pipeline_server.py 9.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
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

B
barrierye 已提交
25
from .proto import pipeline_service_pb2_grpc
B
barrierye 已提交
26
from .operator import ResponseOp
27
from .dag import DAGExecutor
28

B
barriery 已提交
29
_LOGGER = logging.getLogger("pipeline.pipeline_server")
30 31


B
barriery 已提交
32
class PipelineServicer(pipeline_service_pb2_grpc.PipelineServiceServicer):
33
    def __init__(self, response_op, dag_conf):
B
barriery 已提交
34
        super(PipelineServicer, self).__init__()
B
barrierye 已提交
35
        # init dag executor
36
        self._dag_executor = DAGExecutor(response_op, dag_conf)
B
barrierye 已提交
37
        self._dag_executor.start()
B
barriery 已提交
38
        _LOGGER.info("[PipelineServicer] succ init")
39 40

    def inference(self, request, context):
41
        resp = self._dag_executor.call(request)
42 43
        return resp

B
barrierye 已提交
44

B
barrierye 已提交
45 46 47 48 49 50 51 52 53 54 55 56 57 58
@contextlib.contextmanager
def _reserve_port(port):
    """Find and reserve a port for all subprocesses to use."""
    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()


59
class PipelineServer(object):
B
barrierye 已提交
60
    def __init__(self):
61 62
        self._port = None
        self._worker_num = None
B
barrierye 已提交
63
        self._response_op = None
64

B
barrierye 已提交
65
    def set_response_op(self, response_op):
B
barrierye 已提交
66
        if not isinstance(response_op, ResponseOp):
B
barriery 已提交
67 68
            raise Exception("Failed to set response_op: response_op "
                            "must be ResponseOp type.")
B
barrierye 已提交
69
        if len(response_op.get_input_ops()) != 1:
B
barriery 已提交
70 71
            raise Exception("Failed to set response_op: response_op "
                            "can only have one previous op.")
B
barrierye 已提交
72 73 74 75 76 77 78 79 80
        self._response_op = response_op

    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):
81
        conf = ServerYamlConfChecker.load_server_yaml_conf(yml_file)
B
barriery 已提交
82

83
        self._port = conf["port"]
B
barrierye 已提交
84
        if not self._port_is_available(self._port):
B
barriery 已提交
85 86
            raise SystemExit("Failed to prepare_server: prot {} "
                             "is already used".format(self._port))
87 88
        self._worker_num = conf["worker_num"]
        self._build_dag_each_worker = conf["build_dag_each_worker"]
B
barriery 已提交
89

B
barrierye 已提交
90
        _LOGGER.info("============= PIPELINE SERVER =============")
91 92 93
        _LOGGER.info("\n{}".format(
            json.dumps(
                conf, indent=4, separators=(',', ':'))))
94
        if self._build_dag_each_worker is True:
B
barriery 已提交
95 96
            _LOGGER.info(
                "(Make sure that install grpcio whl with --no-binary flag)")
B
barrierye 已提交
97
        _LOGGER.info("-------------------------------------------")
98

B
barriery 已提交
99
        self._conf = conf
B
barrierye 已提交
100

101
    def run_server(self):
102
        if self._build_dag_each_worker:
B
barrierye 已提交
103 104 105 106 107 108 109
            with _reserve_port(self._port) as port:
                bind_address = 'localhost:{}'.format(port)
                workers = []
                for i in range(self._worker_num):
                    show_info = (i == 0)
                    worker = multiprocessing.Process(
                        target=self._run_server_func,
B
barriery 已提交
110
                        args=(bind_address, self._response_op, self._conf))
B
barrierye 已提交
111 112 113 114 115 116 117 118
                    worker.start()
                    workers.append(worker)
                for worker in workers:
                    worker.join()
        else:
            server = grpc.server(
                futures.ThreadPoolExecutor(max_workers=self._worker_num))
            pipeline_service_pb2_grpc.add_PipelineServiceServicer_to_server(
B
barriery 已提交
119
                PipelineServicer(self._response_op, self._conf), server)
B
barrierye 已提交
120 121 122 123
            server.add_insecure_port('[::]:{}'.format(self._port))
            server.start()
            server.wait_for_termination()

124
    def _run_server_func(self, bind_address, response_op, dag_conf):
B
barrierye 已提交
125
        options = (('grpc.so_reuseport', 1), )
126
        server = grpc.server(
B
barrierye 已提交
127
            futures.ThreadPoolExecutor(
B
barrierye 已提交
128
                max_workers=1, ), options=options)
B
barrierye 已提交
129
        pipeline_service_pb2_grpc.add_PipelineServiceServicer_to_server(
130
            PipelineServicer(response_op, dag_conf), server)
B
barrierye 已提交
131
        server.add_insecure_port(bind_address)
132 133
        server.start()
        server.wait_for_termination()
134 135 136 137 138 139 140 141 142 143 144 145


class ServerYamlConfChecker(object):
    def __init__(self):
        pass

    @staticmethod
    def load_server_yaml_conf(yml_file):
        with open(yml_file) as f:
            conf = yaml.load(f.read())
        ServerYamlConfChecker.check_server_conf(conf)
        ServerYamlConfChecker.check_dag_conf(conf["dag"])
B
barriery 已提交
146
        ServerYamlConfChecker.check_tracer_conf(conf["dag"]["tracer"])
147 148
        return conf

B
barriery 已提交
149 150 151 152 153 154
    @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)

155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
    @staticmethod
    def check_server_conf(conf):
        default_conf = {
            "port": 9292,
            "worker_num": 1,
            "build_dag_each_worker": False,
            "dag": {},
        }

        conf_type = {
            "port": int,
            "worker_num": int,
            "build_dag_each_worker": bool,
        }

        conf_qualification = {
            "port": [(">=", 1024), ("<=", 65535)],
            "worker_num": (">=", 1),
        }

B
barriery 已提交
175 176 177 178 179 180 181 182 183 184 185 186 187
        ServerYamlConfChecker.check_conf(conf, default_conf, conf_type,
                                         conf_qualification)

    @staticmethod
    def check_tracer_conf(conf):
        default_conf = {"interval_s": 600, }

        conf_type = {"interval_s": int, }

        conf_qualification = {}

        ServerYamlConfChecker.check_conf(conf, default_conf, conf_type,
                                         conf_qualification)
188 189 190 191 192 193 194 195

    @staticmethod
    def check_dag_conf(conf):
        default_conf = {
            "retry": 1,
            "client_type": "brpc",
            "use_profile": False,
            "channel_size": 0,
B
barriery 已提交
196 197
            "is_thread_op": True,
            "tracer": {},
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
        }

        conf_type = {
            "retry": int,
            "client_type": str,
            "use_profile": bool,
            "channel_size": int,
            "is_thread_op": bool,
        }

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

B
barriery 已提交
214 215
        ServerYamlConfChecker.check_conf(conf, default_conf, conf_type,
                                         conf_qualification)
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268

    @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():
            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():
            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