Python grpc.ssl_server_credentials() Examples

The following are 12 code examples of grpc.ssl_server_credentials(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module grpc , or try the search function .
Example #1
Source File: grpc_server.py    From xos with Apache License 2.0 6 votes vote down vote up
def __init__(self, port=50055, model_status=0, model_output=""):
        self.port = port
        self.model_status = model_status
        self.model_output = model_output
        log.info("Initializing GRPC Server", port=port)
        self.thread_pool = futures.ThreadPoolExecutor(max_workers=10)
        self.server = grpc.server(self.thread_pool)
        self.django_initialized = False
        self.django_apps = []

        server_key = open(SERVER_KEY, "r").read()
        server_cert = open(SERVER_CERT, "r").read()
        server_ca = open(SERVER_CA, "r").read()

        self.credentials = grpc.ssl_server_credentials(
            [(server_key, server_cert)], server_ca, False
        )

        self.delayed_shutdown_timer = None
        self.exit_event = threading.Event()

        self.services = [] 
Example #2
Source File: remote_executor_service.py    From federated with Apache License 2.0 6 votes vote down vote up
def main(argv):
  del argv
  executor_factory = tff.framework.local_executor_factory(
      num_clients=FLAGS.clients, max_fanout=FLAGS.fanout)
  if FLAGS.private_key:
    if FLAGS.certificate_chain:
      with open(FLAGS.private_key, 'rb') as f:
        private_key = f.read()
      with open(FLAGS.certificate_chain, 'rb') as f:
        certificate_chain = f.read()
      credentials = grpc.ssl_server_credentials(((
          private_key,
          certificate_chain,
      ),))
    else:
      raise ValueError(
          'Private key has been specified, but the certificate chain missing.')
  else:
    credentials = None
  tff.simulation.run_server(
      executor_factory.create_executor({}), FLAGS.threads, FLAGS.port,
      credentials) 
Example #3
Source File: grpc_server.py    From xos with Apache License 2.0 6 votes vote down vote up
def __init__(self, port=50055, model_status=0, model_output=""):
        self.port = port
        self.model_status = model_status
        self.model_output = model_output
        log.info("Initializing GRPC Server", port=port)
        self.thread_pool = futures.ThreadPoolExecutor(max_workers=10)
        self.server = grpc.server(self.thread_pool)
        self.django_initialized = False
        self.django_apps = []

        server_key = open(SERVER_KEY, "r").read()
        server_cert = open(SERVER_CERT, "r").read()
        server_ca = open(SERVER_CA, "r").read()

        self.credentials = grpc.ssl_server_credentials(
            [(server_key, server_cert)], server_ca, False
        )

        self.delayed_shutdown_timer = None
        self.exit_event = threading.Event()

        self.services = [] 
Example #4
Source File: server.py    From python-grpc-demo with MIT License 6 votes vote down vote up
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) 
Example #5
Source File: server.py    From ssl_grpc_example with MIT License 6 votes vote down vote up
def main():
    port = '1337'

    with open('server.key', 'rb') as f:
        private_key = f.read()
    with open('server.crt', 'rb') as f:
        certificate_chain = f.read()

    server_credentials = grpc.ssl_server_credentials(
      ((private_key, certificate_chain,),))

    server = grpc.server(futures.ThreadPoolExecutor(max_workers=1))
    service_pb2_grpc.add_ServerServicer_to_server(ServerServicer(), server)

    server.add_secure_port('[::]:'+port, server_credentials)

    server.start()
    try:
        while True:
            signal.pause()
    except KeyboardInterrupt:
        pass
    server.stop(0) 
Example #6
Source File: untrusted.py    From clusterfuzz with Apache License 2.0 5 votes vote down vote up
def start_server():
  """Start the server."""
  # Check overall free disk space. If we are running too low, clear all
  # data directories like builds, fuzzers, data bundles, etc.
  shell.clear_data_directories_on_low_disk_space()

  cert_contents, key_contents = _get_tls_cert_and_key()
  assert cert_contents and key_contents
  server_credentials = grpc.ssl_server_credentials([(key_contents,
                                                     cert_contents)])
  _worker_state.server = grpc.server(
      futures.ThreadPoolExecutor(max_workers=config.NUM_WORKER_THREADS),
      options=config.GRPC_OPTIONS)

  untrusted_runner_pb2_grpc.add_UntrustedRunnerServicer_to_server(
      UntrustedRunnerServicer(), _worker_state.server)
  heartbeat_pb2_grpc.add_HeartbeatServicer_to_server(HeartbeatServicer(),
                                                     _worker_state.server)

  _worker_state.server.add_secure_port('[::]:%d' % config.PORT,
                                       server_credentials)

  _worker_state.start_time = int(time.time())
  _worker_state.server.start()

  logs.log('Server started.')

  # Run forever until shutdown.
  _worker_state.shutting_down.wait()

  logs.log('Server shutting down.')
  stopped = _worker_state.server.stop(SHUTDOWN_GRACE_SECONDS)
  stopped.wait()

  # Prevent python GIL deadlocks on shutdown. See https://crbug.com/744680.
  # pylint: disable=protected-access
  os._exit(0) 
Example #7
Source File: grpc_connector.py    From loopchain with Apache License 2.0 5 votes vote down vote up
def add_server_port(cls, keys: GRPCSecureKeyCollection, server, host, ssl_auth_type: conf.SSLAuthType):
        credentials = grpc.ssl_server_credentials(
            [(keys.ssl_pk, keys.ssl_crt)],
            root_certificates=None,
            require_client_auth=False)
        server.add_secure_port(host, credentials) 
Example #8
Source File: grpc_connector.py    From loopchain with Apache License 2.0 5 votes vote down vote up
def add_server_port(cls, keys: GRPCSecureKeyCollection, server, host, ssl_auth_type: conf.SSLAuthType):
        credentials = grpc.ssl_server_credentials(
            [(keys.ssl_pk, keys.ssl_crt)],
            root_certificates=keys.ssl_root_crt,
            require_client_auth=True)
        server.add_secure_port(host, credentials) 
Example #9
Source File: __main__.py    From qlik-py-tools with MIT License 5 votes vote down vote up
def Serve(self, port, pem_dir):
        """
        Server
        :param port: port to listen on.
        :param pem_dir: Directory including certificates
        :return: None
        """
        server = grpc.server(futures.ThreadPoolExecutor(max_workers=10),\
        options=[('grpc.max_send_message_length', MAX_MESSAGE_LENGTH),('grpc.max_receive_message_length', MAX_MESSAGE_LENGTH)])
        
        SSE.add_ConnectorServicer_to_server(self, server)

        if pem_dir:
            # Secure connection
            with open(os.path.join(pem_dir, 'sse_server_key.pem'), 'rb') as f:
                private_key = f.read()
            with open(os.path.join(pem_dir, 'sse_server_cert.pem'), 'rb') as f:
                cert_chain = f.read()
            with open(os.path.join(pem_dir, 'root_cert.pem'), 'rb') as f:
                root_cert = f.read()
            credentials = grpc.ssl_server_credentials([(private_key, cert_chain)], root_cert, True)
            server.add_secure_port('[::]:{}'.format(port), credentials)
            logging.info('*** Running server in secure mode on port: {} ***'.format(port))
        else:
            # Insecure connection
            server.add_insecure_port('[::]:{}'.format(port))
            logging.info('*** Running server in insecure mode on port: {} ***'.format(port))

        server.start()
        try:
            while True:
                time.sleep(_ONE_DAY_IN_SECONDS)
        except KeyboardInterrupt:
            server.stop(0) 
Example #10
Source File: grpc.py    From dcos with Apache License 2.0 5 votes vote down vote up
def start(self):
        log.debug("gRPC server {} is starting".format(self.id))
        self._server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
        grpc_endpoint_pb2_grpc.add_MockServiceServicer_to_server(
            MockServiceServicer(self.get_context_data),
            self._server,
        )
        if self._is_tls:
            server_credentials = grpc.ssl_server_credentials(
                private_key_certificate_chain_pairs=[(
                    self._load_credential_from_file(self._context.data['keyfile']),
                    self._load_credential_from_file(self._context.data['certfile']),
                )],
                root_certificates=self._load_credential_from_file(
                    self._context.data['cafile']),
                require_client_auth=True,
            )
            self._server.add_secure_port(
                '{}:{}'.format(
                    self._context.data['listen_ip'],
                    self._context.data['listen_port'],
                ),
                server_credentials,
            )
        else:
            self._server.add_insecure_port(
                '{}:{}'.format(
                    self._context.data['listen_ip'],
                    self._context.data['listen_port'],
                )
            )
        self._server.start() 
Example #11
Source File: grpc_server.py    From voltha with Apache License 2.0 5 votes vote down vote up
def start(self):
        if self.device_type == 'ponsim':
            handler = FlowUpdateHandler(self.thread_pool, self.ponsim)
            add_PonSimServicer_to_server(handler, self.server)
            x_pon_handler = XPonHandler(self.thread_pool, self.x_pon_sim)
            add_XPonSimServicer_to_server(x_pon_handler, self.server)
        else:
            handler = BalHandler(self.thread_pool, self.ponsim)
            add_BalServicer_to_server(handler, self.server)

        # read in key and certificate
        try:
           voltha_key = os.path.join(os.environ.get('VOLTHA_BASE'),"pki/voltha.key")
           with open(voltha_key) as f:
               private_key = f.read()

           voltha_cert = os.path.join(os.environ.get('VOLTHA_BASE'),"pki/voltha.crt")
           with open(voltha_cert) as f:
               certificate_chain = f.read()
        except Exception as e:
           log.error('failed-to-read-cert-keys', reason=e)

        # create server credentials
        if self.device_type == 'ponsim':
            server_credentials = grpc.ssl_server_credentials(((private_key, certificate_chain,),))
            self.server.add_secure_port('[::]:%s' % self.port, server_credentials)
        else:
            self.server.add_insecure_port('[::]:%s' % self.port)

        self.server.start()
        log.info('started') 
Example #12
Source File: Tbon.py    From pcocc with GNU General Public License v3.0 4 votes vote down vote up
def __init__(self,
                 vmid,
                 handler,
                 stream_init_handler,
                 port=0):

        self._relay = None
        self._vmid = int(vmid)
        self._port = port
        self._handler = handler
        self._stream_init_handler = stream_init_handler
        self._server = grpc.server(futures.ThreadPoolExecutor(max_workers=25))
        self._ready = threading.Event()

        agent_pb2_grpc.add_pcoccNodeServicer_to_server(self, self._server)

        server_cert = Config().batch.ca_cert.gen_cert(socket.gethostname())
        credential = grpc.ssl_server_credentials(
            ((server_cert.key, server_cert.cert), ),
            server_cert.ca_cert,
            True
        )
        self._port = self._server.add_secure_port(
            "[::]:{0}".format(port),
            credential
        )
        self._server.start()

        logging.debug("Tree node listening on port %s", self._port)

        Config().batch.write_key('cluster/user',
                                 "hostagent/vms/{0}".format(self._vmid),
                                 "{0}:{1}:{2}".format(
                                     self._vmid,
                                     socket.gethostname(),
                                     self._port))


        # Establish connections to adjacent nodes in the tree for relaying
        # messages
        self._relay = TreeNodeRelay(self._vmid)

        self._ready.set()