Python grpc 模块,server() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用grpc.server()

项目:python-grpc-demo    作者:amitsaha    | 项目源码 | 文件源码
def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    metric_interceptor = MetricInterceptor()
    logging_interceptor = LoggingInterceptor()
    server = intercept_server(server, metric_interceptor, logging_interceptor)
    users_service.add_UsersServicer_to_server(UsersService(), server)

    # read in key and certificate
    with open(os.path.join(os.path.split(__file__)[0], 'server.key')) as f:
        private_key = f.read().encode()
    with open(os.path.join(os.path.split(__file__)[0], 'server.crt')) as f:
        certificate_chain = f.read().encode()
    # create server credentials
    server_creds = grpc.ssl_server_credentials(
        ((private_key, certificate_chain,),))
    server.add_secure_port('localhost:50051', server_creds)
    server.start()
    try:
        while True:
            time.sleep(_ONE_DAY_IN_SECONDS)
    except KeyboardInterrupt:
        server.stop(0)
项目:rules_protobuf    作者:pubref    | 项目源码 | 文件源码
def await_termination(self):
        """
        server.start() doesn't block so we explicitly block here unless someone keyboard-exits us.
        :return:
        """
        try:
            while True:
                time.sleep(_ONE_DAY_IN_SECONDS)
        except KeyboardInterrupt:
            self.server.stop(0)
        pass
项目:ngraph    作者:NervanaSystems    | 项目源码 | 文件源码
def GetResults(self, request, context):
        logger.debug("server: get_results")
        if request.comp_id not in self.results:
            message = 'unknown computation id {}'.format(request.comp_id)
            return hetr_pb2.GetResultsReply(status=False, message=message)

        try:
            pb_results = []
            for r in self.results[request.comp_id]:
                pb_val = hetr_pb2.Value()
                if is_scalar_type(r):
                    assign_scalar(pb_val.scalar, r)
                else:
                    pb_val.tensor.CopyFrom(tensor_to_protobuf(r))
                pb_results.append(pb_val)
            return hetr_pb2.GetResultsReply(status=True, results=pb_results)
        except Exception:
            return hetr_pb2.GetResultsReply(status=False, message=traceback.format_exc())
项目:gRPC-Makerboards    作者:PeridotYouClod    | 项目源码 | 文件源码
def serve():
  protoConfig = ProtoConfig.getConfig()
  arduino = protoConfig.arduinos[0]

  server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
  sensors_pb2.add_ArduinoServicer_to_server(Arduino(arduino), server)
  port = protoConfig.ports.arduinoPort
  server.add_insecure_port('[::]:%s' % port)
  server.start()
  print('Started Arduino Server on Port %s ' % port)

  try:
    while True:
      time.sleep(_ONE_DAY_IN_SECONDS)
  except KeyboardInterrupt:
    server.stop(0)
项目:gRPC-Makerboards    作者:PeridotYouClod    | 项目源码 | 文件源码
def serve():
  protoConfig = ProtoConfig.getConfig()
  sensor_db = Mongo()
  sensor_db.GetClient() # initalize the Db
  server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
  dao_pb2.add_DaoServicer_to_server(Dao(sensor_db), server)
  port = protoConfig.ports.daoPort
  server.add_insecure_port('[::]:%s' % port)
  server.start()
  print('Started Dao Server on Port %s ' % port)

  try:
    while True:
      time.sleep(_ONE_DAY_IN_SECONDS)
  except KeyboardInterrupt:
    server.stop(0)
项目:gRPC-Makerboards    作者:PeridotYouClod    | 项目源码 | 文件源码
def serve():
  protoConfig = ProtoConfig.getConfig()
  server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
  pushServer = Push(accessToken=protoConfig.wioLinks['havok'].accessToken)
  sensors_pb2.add_PushServicer_to_server(pushServer, server)
  port = protoConfig.ports.pushPort
  server.add_insecure_port('[::]:%s' % port)
  server.start()
  print('Started Push Server on Port %s ' % port)

  websocket.enableTrace(True)
  ws = websocket.WebSocketApp(
    "wss://us.wio.seeed.io/v1/node/event",
    on_message = pushServer.on_message,
    on_error = pushServer.on_error,
    on_close = pushServer.on_close)
  ws.on_open = pushServer.on_open
  ws.run_forever()

  try:
    while True:
      time.sleep(_ONE_DAY_IN_SECONDS)
  except KeyboardInterrupt:
    server.stop(0)
项目:loopchain    作者:theloopkr    | 项目源码 | 文件源码
def __init__(self, gRPC_module, inner_service_port=None):
        self.__peer_id = None if ObjectManager().peer_service is None else ObjectManager().peer_service.peer_id

        # for peer_service, it refers to peer_inner_service / for rs_service, it refers to rs_admin_service
        self.inner_server = grpc.server(futures.ThreadPoolExecutor(max_workers=conf.MAX_WORKERS))
        self.outer_server = grpc.server(futures.ThreadPoolExecutor(max_workers=conf.MAX_WORKERS))

        # members for private, It helps simplicity of code intelligence
        self.__gRPC_module = gRPC_module
        self.__port = 0
        self.__inner_service_port = inner_service_port
        self.__peer_target = None
        if inner_service_port is not None:  # It means this is Peer's CommonService not RS.
            peer_port = inner_service_port - conf.PORT_DIFF_INNER_SERVICE
            self.__peer_target = util.get_private_ip() + ":" + str(peer_port)
        self.__subscriptions = queue.Queue()  # tuple with (channel, stub)
        self.__group_id = ""

        # broadcast process
        self.__broadcast_process = self.__run_broadcast_process()

        self.__loop_functions = []
项目:quant    作者:yutiansut    | 项目源码 | 文件源码
def serve():
  server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
  helloworld_pb2_grpc.add_GreeterServicer_to_server(_GreeterServicer(), server)
  route_guide_pb2_grpc.add_RouteGuideServicer_to_server(
      _RouteGuideServicer(), server)
  server.add_insecure_port('[::]:50051')
  server.start()
  try:
    while True:
      time.sleep(_ONE_DAY_IN_SECONDS)
  except KeyboardInterrupt:
    server.stop(0)
项目:opencensus-python    作者:census-instrumentation    | 项目源码 | 文件源码
def serve():
    sampler = always_on.AlwaysOnSampler()
    exporter = stackdriver_exporter.StackdriverExporter()
    tracer_interceptor = server_interceptor.OpenCensusServerInterceptor(
        sampler, exporter)
    server = grpc.server(
        futures.ThreadPoolExecutor(max_workers=10),
        interceptors=(tracer_interceptor,))
    hello_world_pb2_grpc.add_HelloWorldServicer_to_server(HelloWorld(), server)
    server.add_insecure_port('[::]:50051')
    server.start()
    try:
        while True:
            time.sleep(_ONE_DAY_IN_SECONDS)
    except KeyboardInterrupt:
        server.stop(0)
项目:aiogrpc    作者:hubo1016    | 项目源码 | 文件源码
def main(listen_addrs=['127.0.0.1:9901']):
    s = create_server(listen_addrs)
    print("Server created on", listen_addrs)
    s.start()
    print("Server started")
    import signal
    old1 = signal.signal(signal.SIGINT, signal_handler)
    old2 = signal.signal(signal.SIGTERM, signal_handler)
    import time
    # signal.pause is not valid in windows
    try:
        while True:
            time.sleep(3600 * 24)
    except QuitException:
        print("Quit server")
        shutdown_event = s.stop(5)
        shutdown_event.wait()
    finally:
        signal.signal(signal.SIGINT, old1)
        signal.signal(signal.SIGTERM, old2)
项目:QRL    作者:theQRL    | 项目源码 | 文件源码
def start_services(node: QRLNode):
    p2p_node = P2PNode(node)

    public_server = grpc.server(ThreadPoolExecutor(max_workers=1),
                                maximum_concurrent_rpcs=config.user.max_peers_limit)
    add_BaseServicer_to_server(BaseService(node), public_server)
    add_P2PAPIServicer_to_server(p2p_node.service, public_server)
    add_PublicAPIServicer_to_server(PublicAPIService(node), public_server)

    public_server.add_insecure_port("[::]:9009")
    public_server.start()

    logger.info("grpc public service - started !")

    admin_server = grpc.server(ThreadPoolExecutor(max_workers=1),
                               maximum_concurrent_rpcs=config.user.max_peers_limit)
    add_AdminAPIServicer_to_server(AdminAPIService(node), admin_server)

    admin_server.add_insecure_port("127.0.0.1:9008")
    admin_server.start()
    logger.info("grpc admin service - started !")

    return admin_server, public_server, p2p_node
项目:PowerSpikeGG    作者:PowerSpikeGG    | 项目源码 | 文件源码
def start_server(riot_api_token, listening_port, max_workers):
    """Starts a server."""
    service = MatchFetcher(riot_api_token)

    server = grpc.server(futures.ThreadPoolExecutor(max_workers=max_workers))
    service_pb2.add_MatchFetcherServicer_to_server(service, server)
    server.add_insecure_port('[::]:%s' % listening_port)
    server.start()

    return server, service
项目:PowerSpikeGG    作者:PowerSpikeGG    | 项目源码 | 文件源码
def main():
    """Parse command line arguments and start the server."""
    if FLAGS.riot_api_token == "":
        logging.critical("Required argument 'riot_api_token' is empty.")
        return 1

    server, _ = start_server(FLAGS.riot_api_token, FLAGS.port,
        FLAGS.max_workers)

    try:
        while True:
            time.sleep(60 * 60 * 24)
    except KeyboardInterrupt:
        server.stop(0)
项目:rules_protobuf    作者:pubref    | 项目源码 | 文件源码
def __init__(self, greeter_service, server_port):
        self.server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
        helloworld_pb2_grpc.add_GreeterServicer_to_server(greeter_service, self.server)
        self.server.add_insecure_port('[::]:{server_port}'.format(server_port=server_port))
项目:rules_protobuf    作者:pubref    | 项目源码 | 文件源码
def start(self):
        self.server.start()
项目:rules_protobuf    作者:pubref    | 项目源码 | 文件源码
def stop(self):
        self.server.stop(0)
项目:rules_protobuf    作者:pubref    | 项目源码 | 文件源码
def SayHello(self, hello_request, context):
        print("Greeter server received: " + hello_request.name)
        hello_reply = helloworld_pb2.HelloReply()
        hello_reply.message = 'Hello {name}'.format(name=hello_request.name)
        return hello_reply
项目:grpc-resolver    作者:justdoit0823    | 项目源码 | 文件源码
def grpc_server(grpc_addr):
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=2))
    hello_pb2_grpc.add_HelloServicer_to_server(rpc.HelloGRpcServer(), server)
    for addr in grpc_addr:
        server.add_insecure_port(addr)

    server.start()

    yield server

    server.stop(0)
项目:oaktree    作者:emonty    | 项目源码 | 文件源码
def serve():
    shade.simple_logging(debug=True)
    logging.getLogger().setLevel(logging.INFO)
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    oaktree_pb2.add_OaktreeServicer_to_server(OaktreeServicer(), server)
    server.add_insecure_port('[::]:50051')
    logging.info("Starting server")
    server.start()
    try:
        while True:
            time.sleep(_ONE_DAY_IN_SECONDS)
    except KeyboardInterrupt:
        server.stop(0)
项目:ngraph    作者:NervanaSystems    | 项目源码 | 文件源码
def __init__(self, comm, server):
        self.results = dict()
        self.computations = dict()
        self.comp_id_ctr = 0
        self.comm = comm
        self.server = server
        self.transformer_type = None
项目:ngraph    作者:NervanaSystems    | 项目源码 | 文件源码
def BuildTransformer(self, request, context):
        logger.debug("server: build_transformer")
        self.transformer_type = request.transformer_type[:3]
        if self.transformer_type not in ['gpu', 'cpu']:
            message = 'unknown transformer type {}'.format(self.transformer_type)
            return hetr_pb2.BuildTransformerReply(status=False, message=message)

        try:
            self.transformer = build_transformer(name=request.transformer_type, comm=self.comm)
            return hetr_pb2.BuildTransformerReply(status=True)
        except Exception:
            return hetr_pb2.BuildTransformerReply(status=False, message=traceback.format_exc())
项目:ngraph    作者:NervanaSystems    | 项目源码 | 文件源码
def Computation(self, request_iterator, context):
        logger.debug("server: computation")
        if not self.transformer:
            return hetr_pb2.ComputationReply(comp_id=-1,
                                             message="build transformer before computation")
        try:
            comp_id = self.new_comp_id()
            pb_ops, pb_edges = [], []
            returns, placeholders = [], []
            reconstructed_returns, reconstructed_placeholders = [], []
            for request in request_iterator:
                pb_ops.extend(request.ops)
                pb_edges.extend(request.edges)
                returns.extend([protobuf_to_op(op) for op in request.returns])
                placeholders.extend([protobuf_to_op(op) for op in request.placeholders])

            subgraph = _deserialize_graph_ops_edges(pb_ops, pb_edges)

            ops = Op.ordered_ops(subgraph)
            for r in returns:
                for op in ops:
                    if op.uuid == r.uuid:
                        reconstructed_returns.append(op)
            for p in placeholders:
                for op in ops:
                    if op.uuid == p.uuid:
                        reconstructed_placeholders.append(op)

            computation = self.transformer.computation(reconstructed_returns,
                                                       *reconstructed_placeholders)
            self.computations[comp_id] = computation
            return hetr_pb2.ComputationReply(comp_id=comp_id)
        except Exception:
            return hetr_pb2.ComputationReply(comp_id=-1, message=traceback.format_exc())
项目:ngraph    作者:NervanaSystems    | 项目源码 | 文件源码
def FeedInput(self, request, context):
        logger.debug("server: feed_input")
        if request.comp_id not in self.computations:
            message = 'unknown computation id {}'.format(request.comp_id)
            return hetr_pb2.FeedInputReply(status=False, message=message)

        try:
            values = []
            for v in request.values:
                if v.HasField('scalar'):
                    values.append(protobuf_scalar_to_python(v.scalar))
                else:
                    values.append(pb_to_tensor(v.tensor))
            computation = self.computations[request.comp_id]
            if self.transformer.transformer_name == "gpu":
                import pycuda.driver as drv
                if self.transformer.runtime and \
                   not self.transformer.runtime.ctx == drv.Context.get_current():
                    self.transformer.runtime.ctx.push()
                # TODO figure out doc for rpdb to pass in port
                # give unique port per device (4444 + device_id)
                outputs = computation(*values)
                self.transformer.runtime.ctx.pop()
            else:
                outputs = computation(*values)

            self.results[request.comp_id] = outputs

            return hetr_pb2.FeedInputReply(status=True)
        except Exception:
            return hetr_pb2.FeedInputReply(status=False, message=traceback.format_exc())
项目:ngraph    作者:NervanaSystems    | 项目源码 | 文件源码
def Close(self, request, context):
        logger.debug("server: close, self.transformer_type %s", self.transformer_type)
        if use_mlsl:
            HetrLocals.close_mlsl()
        self.server.stop(0)
        return hetr_pb2.CloseReply()
项目:ngraph    作者:NervanaSystems    | 项目源码 | 文件源码
def serve():
    parser = argparse.ArgumentParser()
    parser.add_argument("-tf", "--tmpfile", nargs=1)
    parser.add_argument("-p", "--ports", nargs='+')
    args = parser.parse_args()
    comm = MPI.COMM_WORLD

    options = [('grpc.max_send_message_length', -1), ('grpc.max_receive_message_length', -1)]
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=1), options=options)
    hetr_pb2_grpc.add_HetrServicer_to_server(HetrServer(comm, server), server)
    logger.debug("server: rank %d, tmpfile %s, ports %s",
                 comm.Get_rank(), args.tmpfile[0], args.ports if args.ports is not None else "")

    if args.ports is not None and len(args.ports) > comm.Get_rank():
        p = args.ports[comm.Get_rank()]
        if is_port_open(p):
            port = server.add_insecure_port('[::]:' + p)
        else:
            raise RuntimeError("port %s is already in use!", p)
    else:
        port = server.add_insecure_port('[::]:0')

    server.start()
    write_server_info(args.tmpfile[0], port)

    try:
        while True:
            time.sleep(_ONE_DAY_IN_SECONDS)
    except KeyboardInterrupt:
        server.stop(0)
项目:p2p_grpc_blockchain_package    作者:Lursun    | 项目源码 | 文件源码
def __grpcNetworkStart():
    global PORT
    try:
        PORT = os.environ["GRPC_PORT"]
    except:
        PORT = "8001"
    print("grpc listen port:"+PORT)

    # grpc server
    server = grpc.server(futures.ThreadPoolExecutor(max_workers = 10))
    grpc_pb2_grpc.add_DiscoveryServicer_to_server(Discovery(),server)
    # grpc_pb2_grpc.add_ConsensusServicer_to_server(Discovery(),server)
    grpc_pb2_grpc.add_SynchronizationServicer_to_server(synchronization.Synchronization(),server)

    server.add_insecure_port("[::]:%s" % PORT)
    server.start()

    threading.Thread(target = exchangeLoop).start()

    try:
        ROOT_TARGET = os.environ["ROOT_TARGET"]
    except:
        ROOT_TARGET = "35.185.134.104:8001"

    threading.Thread(target = grpcJoinNode ,args=(ROOT_TARGET,)).start()
    while True:
        time.sleep(1)
项目:gRPC-Makerboards    作者:PeridotYouClod    | 项目源码 | 文件源码
def serve():
  protoConfig = ProtoConfig.getConfig()
  server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
  sensors_pb2.add_FrontEndServicer_to_server(FrontEnd(protoConfig), server)
  port = protoConfig.ports.frontEndPort
  server.add_insecure_port('[::]:%s' % port)
  server.start()
  print('Started FrontEnd Server on Port %s ' % port)

  try:
    while True:
      time.sleep(_ONE_DAY_IN_SECONDS)
  except KeyboardInterrupt:
    server.stop(0)
项目:gRPC-Makerboards    作者:PeridotYouClod    | 项目源码 | 文件源码
def serve():
  protoConfig = ProtoConfig.getConfig()
  server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
  sensors_pb2.add_PushFrontEndServicer_to_server(PushFrontEnd(protoConfig), server)
  port = protoConfig.ports.pushFrontEndPort
  server.add_insecure_port('[::]:%s' % port)
  server.start()
  print('Started PushFrontEnd Server on Port %s ' % port)

  try:
    while True:
      time.sleep(_ONE_DAY_IN_SECONDS)
  except KeyboardInterrupt:
    server.stop(0)
项目:relaax    作者:deeplearninc    | 项目源码 | 文件源码
def __init__(self, bind, metrics_server):
        self.server = grpc.server(concurrent.futures.ThreadPoolExecutor(max_workers=1))
        bridge_pb2.add_BridgeServicer_to_server(Servicer(metrics_server), self.server)
        self.server.add_insecure_port('%s:%d' % bind)
项目:relaax    作者:deeplearninc    | 项目源码 | 文件源码
def start(self):
        self.server.start()
项目:relaax    作者:deeplearninc    | 项目源码 | 文件源码
def __init__(self, bind, ps_factory):
        self.server = grpc.server(concurrent.futures.ThreadPoolExecutor(max_workers=1))
        bridge_pb2.add_BridgeServicer_to_server(Servicer(ps_factory), self.server)
        self.server.add_insecure_port('%s:%d' % bind)
项目:relaax    作者:deeplearninc    | 项目源码 | 文件源码
def start(self):
        self.server.start()
项目:snap-plugin-lib-py    作者:intelsdi-x    | 项目源码 | 文件源码
def __init__(self):
        self.meta = None
        self.proxy = None
        self.server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
        self._port = 0
        self._last_ping = time.time()
        self._shutting_down = False
        self._monitor = None
        self._mode = PluginMode.normal
        self._config = {}
        self._flags = _Flags()
        self.standalone_server = None

        # init argparse module and add arguments
        self._parser = argparse.ArgumentParser(description="%(prog)s - a Snap framework plugin.",
                                               usage="%(prog)s [options]",
                                               formatter_class=lambda prog:
                                               argparse.HelpFormatter(prog, max_help_position=30))
        self._parser.add_argument("framework_config", nargs="?", default=None, help=argparse.SUPPRESS)

        flags = [
            ("config", FlagType.value, "JSON Snap global config"),
            ("port", FlagType.value, "GRPC server port"),
            ("stand-alone", FlagType.toggle, "enable stand alone mode"),
            ("stand-alone-port", FlagType.value, "http port for stand alone mode", 8182),
            Flag("log-level", FlagType.value, "logging level 0:panic - 5:debug", 3, json_name="LogLevel"),
            Flag("tls", FlagType.toggle, "enable tls", json_name="TLSEnabled"),
            Flag("root-cert-paths", FlagType.value, "paths to root certificate; delimited by ':'", json_name="RootCertPaths"),
            Flag("key-path", FlagType.value, "path to server private key", json_name="KeyPath"),
            Flag("cert-path", FlagType.value, "path to server certificate", json_name="CertPath"),
        ]
        self._flags.add_multiple(flags)
项目:snap-plugin-lib-py    作者:intelsdi-x    | 项目源码 | 文件源码
def stop_plugin(self):
        """Stops the plugin"""
        LOG.debug("plugin stopping")
        self._shutting_down = True
        _stop_event = self.server.stop(0)
        while not _stop_event.is_set():
            time.sleep(.1)
        LOG.debug("plugin stopped")
项目:snap-plugin-lib-py    作者:intelsdi-x    | 项目源码 | 文件源码
def _generate_preamble_and_serve(self):
        if self._config.get("TLSEnabled", False) == True:
            try:
                self._tls_setup()
                credentials = self._generate_tls_credentials()
                self._port = self.server.add_secure_port('127.0.0.1:{}'.format(self._port), credentials)
                LOG.info("Configured secure port on {}.".format(self._port))
            except Exception as e:
                raise Exception("TLS setup failed. Unable to add secure port. {}".format(str(e)))
        else:
            self._port = self.server.add_insecure_port('127.0.0.1:{}'.format(self._port))
            LOG.info("Configured insecure port on {}.".format(self._port))
        self.server.start()
        return json.dumps(
            {
                "Meta": {
                    "Name": self.meta.name,
                    "Version": self.meta.version,
                    "Type": self.meta.type,
                    "RPCType": self.meta.rpc_type,
                    "RPCVersion": self.meta.rpc_version,
                    "ConcurrencyCount": self.meta.concurrency_count,
                    "Exclusive": self.meta.exclusive,
                    "CacheTTL": self.meta.cache_ttl,
                    "RoutingStrategy": self.meta.routing_strategy,
                    "RootCertPaths": self.meta.root_cert_paths,
                    "CertPath": self.meta.server_cert_path,
                    "KeyPath": self.meta.private_key_path,
                    "Ciphers": self.meta.cipher_suites,
                    "TLSEnabled": self._config.get("TLSEnabled"),
                },
                "ListenAddress": "127.0.0.1:{!s}".format(self._port),
                "Token": None,
                "PublicKey": None,
                "Type": self.meta.type,
                "ErrorMessage": None,
                "State": PluginResponseState.plugin_success,
            },
            cls=_EnumEncoder
        ) + "\n"
项目:loopchain    作者:theloopkr    | 项目源码 | 文件源码
def run(self, conn):
        logging.debug("Container run...")

        if self._type == ServerType.GRPC:
            server = grpc.server(futures.ThreadPoolExecutor(max_workers=conf.MAX_WORKERS))
            loopchain_pb2_grpc.add_ContainerServicer_to_server(self, server)
            server.add_insecure_port('[::]:' + str(self._port))
        elif self._type == ServerType.REST_PEER:
            server = RestServer(self._port, self._peer_ip)
        else:
            server = RestServerRS(self._port)

        server.start()

        command = None
        while command != "quit":
            try:
                command, param = conn.recv()  # Queue ? ??? ??? ??? ??? ?? ??. ??? Sleep ? ?? ??.
                logging.debug("Container got: " + str(param))
            except Exception as e:
                logging.warning("Container conn.recv() error: " + str(e))

        if self._type == ServerType.GRPC:
            server.stop(0)
        else:
            server.stop()

        logging.info("Server Container Ended.")
项目:loopchain    作者:theloopkr    | 项目源码 | 文件源码
def start_server(self, server, listen_address):
        server.add_insecure_port(listen_address)
        server.start()
        logging.info("Server now listen: " + listen_address)
项目:loopchain    作者:theloopkr    | 项目源码 | 文件源码
def run(self):
        self.start_server(self.outer_server, '[::]:' + str(self.__port))
        # Bind Only loopback address (ip4) - TODO IP6
        self.start_server(self.inner_server, conf.INNER_SERVER_BIND_IP + ':' + str(self.__inner_service_port))

        # Block Generator ? subscribe ?? ?? Block Generator ? peer ? channel ??? ????.
        # ??? peer ? gRPC ??? ??? ??? ? Block Generator ? subscribe ??? ??? ??.
        time.sleep(conf.WAIT_GRPC_SERVICE_START)

        try:
            while self.is_run():
                self.__run_loop_functions()
                time.sleep(conf.SLEEP_SECONDS_IN_SERVICE_NONE)
        except KeyboardInterrupt:
            logging.info("Server Stop by KeyboardInterrupt")
        finally:
            while not self.__subscriptions.empty():
                channel, subscribe_stub = self.__subscriptions.get()
                logging.info(f"Un subscribe to channel({channel}) server({subscribe_stub.target})")
                self.__un_subscribe(channel, self.__port, subscribe_stub)

            self.__stop_broadcast_process()

            if self.__inner_service_port is not None:
                self.inner_server.stop(0)
            self.outer_server.stop(0)

        logging.info("Server thread Ended.")
项目:experiment-manager    作者:softfire-eu    | 项目源码 | 文件源码
def receive_forever():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=int(get_config('system', 'server_threads', 5))))
    messages_pb2_grpc.add_RegistrationServiceServicer_to_server(RegistrationAgent(), server)
    binding = '[::]:%s' % get_config('messaging', 'bind_port', 50051)
    logger.info("Binding rpc registration server to: %s" % binding)
    server.add_insecure_port(binding)
    server.start()
    try:
        while True:
            time.sleep(_ONE_DAY_IN_SECONDS)
    except KeyboardInterrupt:
        logger.debug("Stopping server")
        server.stop(True)
项目:malmomo    作者:matpalm    | 项目源码 | 文件源码
def run_enqueue_server(episodes):
  grpc_server = grpc.server(futures.ThreadPoolExecutor(max_workers=3))
  model_pb2.add_ModelServicer_to_server(EnqueueServer(episodes), grpc_server)
  grpc_server.add_insecure_port("[::]:%d" % opts.trainer_port)
  grpc_server.start()
  while True:
    time.sleep(10)
项目:object-tracking    作者:athenian-robotics    | 项目源码 | 文件源码
def __init__(self, port=None):
        super(LocationServer, self).__init__(port=port, desc="location server")
        self.grpc_server = None
项目:object-tracking    作者:athenian-robotics    | 项目源码 | 文件源码
def _start_server(self):
        logger.info("Starting gRPC {0} listening on {1}".format(self.desc, self.hostname))
        self.grpc_server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
        add_LocationServiceServicer_to_server(self, self.grpc_server)
        self.grpc_server.add_insecure_port(self.hostname)
        self.grpc_server.start()
        try:
            while not self.stopped:
                time.sleep(1)
        except KeyboardInterrupt:
            pass
        finally:
            self.stop()
项目:object-tracking    作者:athenian-robotics    | 项目源码 | 文件源码
def _run_server(port):
        server = LocationServer(port).start()

        for i in range(100):
            server.write_location(x=i, y=i + 1, width=i + 2, height=i + 3, middle_inc=i + 4)
            time.sleep(1)
项目:sea    作者:shanbay    | 项目源码 | 文件源码
def __init__(self, app):
        self.app = app
        self.setup_logger()
        self.workers = self.app.config.get('GRPC_WORKERS')
        self.host = self.app.config.get('GRPC_HOST')
        self.port = self.app.config.get('GRPC_PORT')
        self.server = grpc.server(
            futures.ThreadPoolExecutor(
                max_workers=self.workers))
        self.server.add_insecure_port(
            '{}:{}'.format(self.host, self.port))
        self._stopped = False
项目:sea    作者:shanbay    | 项目源码 | 文件源码
def run(self):
        """run the server
        """
        for name, (add_func, servicer) in self.app.servicers.items():
            add_func(servicer(), self.server)
        self.server.start()
        started.send(self)
        self.register_signal()
        while not self._stopped:
            time.sleep(1)
        stopped.send(self)
        return True
项目:sea    作者:shanbay    | 项目源码 | 文件源码
def _stop_handler(self, signum, frame):
        self.server.stop(0)
        self._stopped = True
项目:grpc-opentracing    作者:grpc-ecosystem    | 项目源码 | 文件源码
def serve():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--log_payloads',
        action='store_true',
        help='log request/response objects to open-tracing spans')
    args = parser.parse_args()

    config = Config(
        config={
            'sampler': {
                'type': 'const',
                'param': 1,
            },
            'logging': True,
        },
        service_name='trivial-server')
    tracer = config.initialize_tracer()
    tracer_interceptor = open_tracing_server_interceptor(
        tracer, log_payloads=args.log_payloads)
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    server = intercept_server(server, tracer_interceptor)

    command_line_pb2.add_CommandLineServicer_to_server(CommandLine(), server)
    server.add_insecure_port('[::]:50051')
    server.start()
    try:
        while True:
            time.sleep(_ONE_DAY_IN_SECONDS)
    except KeyboardInterrupt:
        server.stop(0)

    time.sleep(2)
    tracer.close()
    time.sleep(2)
项目:grpc-opentracing    作者:grpc-ecosystem    | 项目源码 | 文件源码
def serve():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--log_payloads',
        action='store_true',
        help='log request/response objects to open-tracing spans')
    args = parser.parse_args()

    config = Config(
        config={
            'sampler': {
                'type': 'const',
                'param': 1,
            },
            'logging': True,
        },
        service_name='integration-server')
    tracer = config.initialize_tracer()
    tracer_interceptor = open_tracing_server_interceptor(
        tracer, log_payloads=args.log_payloads)
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    server = intercept_server(server, tracer_interceptor)

    command_line_pb2.add_CommandLineServicer_to_server(
        CommandLine(tracer), server)
    server.add_insecure_port('[::]:50051')
    server.start()
    try:
        while True:
            time.sleep(_ONE_DAY_IN_SECONDS)
    except KeyboardInterrupt:
        server.stop(0)

    time.sleep(2)
    tracer.close()
    time.sleep(2)
项目:grpc-opentracing    作者:grpc-ecosystem    | 项目源码 | 文件源码
def __init__(self,
                 client_interceptors,
                 server_interceptors,
                 handler=Handler()):
        self.handler = handler
        self._server_pool = logging_pool.pool(2)
        self._server = grpcext.intercept_server(
            grpc.server(self._server_pool), *server_interceptors)
        port = self._server.add_insecure_port('[::]:0')
        self._server.add_generic_rpc_handlers((_GenericHandler(self.handler),))
        self._server.start()
        self.channel = grpcext.intercept_channel(
            grpc.insecure_channel('localhost:%d' % port), *client_interceptors)
项目:quant    作者:yutiansut    | 项目源码 | 文件源码
def serve():
  server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
  helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
  server.add_insecure_port('[::]:50051')
  server.start()
  try:
    while True:
      time.sleep(_ONE_DAY_IN_SECONDS)
  except KeyboardInterrupt:
    server.stop(0)