• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2019 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"""An example of compression on the server side with gRPC."""
15
16from __future__ import absolute_import
17from __future__ import division
18from __future__ import print_function
19
20from concurrent import futures
21import argparse
22import logging
23import threading
24import grpc
25
26from examples import helloworld_pb2
27from examples import helloworld_pb2_grpc
28
29_DESCRIPTION = 'A server capable of compression.'
30_COMPRESSION_OPTIONS = {
31    "none": grpc.Compression.NoCompression,
32    "deflate": grpc.Compression.Deflate,
33    "gzip": grpc.Compression.Gzip,
34}
35_LOGGER = logging.getLogger(__name__)
36
37_SERVER_HOST = 'localhost'
38
39
40class Greeter(helloworld_pb2_grpc.GreeterServicer):
41
42    def __init__(self, no_compress_every_n):
43        super(Greeter, self).__init__()
44        self._no_compress_every_n = 0
45        self._request_counter = 0
46        self._counter_lock = threading.RLock()
47
48    def _should_suppress_compression(self):
49        suppress_compression = False
50        with self._counter_lock:
51            if self._no_compress_every_n and self._request_counter % self._no_compress_every_n == 0:
52                suppress_compression = True
53            self._request_counter += 1
54        return suppress_compression
55
56    def SayHello(self, request, context):
57        if self._should_suppress_compression():
58            context.set_response_compression(grpc.Compression.NoCompression)
59        return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
60
61
62def run_server(server_compression, no_compress_every_n, port):
63    server = grpc.server(futures.ThreadPoolExecutor(),
64                         compression=server_compression,
65                         options=(('grpc.so_reuseport', 1),))
66    helloworld_pb2_grpc.add_GreeterServicer_to_server(
67        Greeter(no_compress_every_n), server)
68    address = '{}:{}'.format(_SERVER_HOST, port)
69    server.add_insecure_port(address)
70    server.start()
71    print("Server listening at '{}'".format(address))
72    server.wait_for_termination()
73
74
75def main():
76    parser = argparse.ArgumentParser(description=_DESCRIPTION)
77    parser.add_argument('--server_compression',
78                        default='none',
79                        nargs='?',
80                        choices=_COMPRESSION_OPTIONS.keys(),
81                        help='The default compression method for the server.')
82    parser.add_argument('--no_compress_every_n',
83                        type=int,
84                        default=0,
85                        nargs='?',
86                        help='If set, every nth reply will be uncompressed.')
87    parser.add_argument('--port',
88                        type=int,
89                        default=50051,
90                        nargs='?',
91                        help='The port on which the server will listen.')
92    args = parser.parse_args()
93    run_server(_COMPRESSION_OPTIONS[args.server_compression],
94               args.no_compress_every_n, args.port)
95
96
97if __name__ == "__main__":
98    logging.basicConfig()
99    main()
100