xref: /aosp_15_r20/external/grpc-grpc/examples/python/auth/tls_server.py (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1 # Copyright 2023 The gRPC Authors
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #     http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 """Server of the Python example of TLS."""
15 
16 from concurrent import futures
17 import logging
18 
19 import _credentials
20 import grpc
21 
22 helloworld_pb2, helloworld_pb2_grpc = grpc.protos_and_services(
23     "helloworld.proto"
24 )
25 
26 _LOGGER = logging.getLogger(__name__)
27 _LOGGER.setLevel(logging.INFO)
28 
29 _PORT = 50051
30 _LISTEN_ADDRESS_TEMPLATE = "localhost:%d"
31 
32 
33 class SimpleGreeter(helloworld_pb2_grpc.GreeterServicer):
34     def SayHello(self, request, unused_context):
35         return helloworld_pb2.HelloReply(message="Hello, %s!" % request.name)
36 
37 
38 def serve():
39     server = grpc.server(futures.ThreadPoolExecutor())
40     helloworld_pb2_grpc.add_GreeterServicer_to_server(SimpleGreeter(), server)
41 
42     # Loading credentials
43     server_credentials = grpc.ssl_server_credentials(
44         (
45             (
46                 _credentials.SERVER_CERTIFICATE_KEY,
47                 _credentials.SERVER_CERTIFICATE,
48             ),
49         )
50     )
51 
52     # Pass down credentials
53     server.add_secure_port(_LISTEN_ADDRESS_TEMPLATE % _PORT, server_credentials)
54 
55     server.start()
56     logging.info("Server is listening at port :%d", _PORT)
57     server.wait_for_termination()
58 
59 
60 if __name__ == "__main__":
61     logging.basicConfig(level=logging.INFO)
62     serve()
63