Merge branch 'master' into health

pull/9205/head
yang-g 8 years ago
commit 0a4e83a12e
  1. 3
      examples/python/helloworld/greeter_client.py
  2. 5
      examples/python/helloworld/greeter_server.py
  3. 193
      examples/python/helloworld/helloworld_pb2.py
  4. 47
      examples/python/helloworld/helloworld_pb2_grpc.py
  5. 193
      examples/python/multiplex/helloworld_pb2.py
  6. 47
      examples/python/multiplex/helloworld_pb2_grpc.py
  7. 6
      examples/python/multiplex/multiplex_client.py
  8. 10
      examples/python/multiplex/multiplex_server.py
  9. 485
      examples/python/multiplex/route_guide_pb2.py
  10. 114
      examples/python/multiplex/route_guide_pb2_grpc.py
  11. 0
      examples/python/multiplex/run_codegen.py
  12. 3
      examples/python/route_guide/route_guide_client.py
  13. 485
      examples/python/route_guide/route_guide_pb2.py
  14. 114
      examples/python/route_guide/route_guide_pb2_grpc.py
  15. 5
      examples/python/route_guide/route_guide_server.py
  16. 3
      src/compiler/python_generator.cc
  17. 38
      src/core/lib/security/credentials/jwt/jwt_verifier.c
  18. 5
      src/core/lib/security/credentials/jwt/jwt_verifier.h
  19. 12
      src/core/lib/support/string.c
  20. 2
      src/core/lib/support/string.h
  21. 2
      src/core/lib/surface/validate_metadata.c
  22. 11
      src/php/lib/Grpc/AbstractCall.php
  23. 54
      src/php/lib/Grpc/BaseStub.php
  24. 15
      src/php/lib/Grpc/BidiStreamingCall.php
  25. 11
      src/php/lib/Grpc/ClientStreamingCall.php
  26. 15
      src/php/lib/Grpc/ServerStreamingCall.php
  27. 11
      src/php/lib/Grpc/UnaryCall.php
  28. 1
      src/python/grpcio/commands.py
  29. 6
      src/python/grpcio_tests/tests/interop/_insecure_intraop_test.py
  30. 2
      src/python/grpcio_tests/tests/interop/_intraop_test_case.py
  31. 6
      src/python/grpcio_tests/tests/interop/_secure_intraop_test.py
  32. 4
      src/python/grpcio_tests/tests/tests.json
  33. 24
      test/core/end2end/invalid_call_argument_test.c
  34. 2
      test/core/security/create_jwt.c
  35. 54
      test/core/security/jwt_verifier_test.c
  36. 2
      test/core/security/verify_jwt.c
  37. 16
      test/core/support/string_test.c
  38. 18
      tools/distrib/check_copyright.py
  39. 1
      tools/distrib/python/docgen.py

@ -34,11 +34,12 @@ from __future__ import print_function
import grpc import grpc
import helloworld_pb2 import helloworld_pb2
import helloworld_pb2_grpc
def run(): def run():
channel = grpc.insecure_channel('localhost:50051') channel = grpc.insecure_channel('localhost:50051')
stub = helloworld_pb2.GreeterStub(channel) stub = helloworld_pb2_grpc.GreeterStub(channel)
response = stub.SayHello(helloworld_pb2.HelloRequest(name='you')) response = stub.SayHello(helloworld_pb2.HelloRequest(name='you'))
print("Greeter client received: " + response.message) print("Greeter client received: " + response.message)

@ -35,11 +35,12 @@ import time
import grpc import grpc
import helloworld_pb2 import helloworld_pb2
import helloworld_pb2_grpc
_ONE_DAY_IN_SECONDS = 60 * 60 * 24 _ONE_DAY_IN_SECONDS = 60 * 60 * 24
class Greeter(helloworld_pb2.GreeterServicer): class Greeter(helloworld_pb2_grpc.GreeterServicer):
def SayHello(self, request, context): def SayHello(self, request, context):
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name) return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
@ -47,7 +48,7 @@ class Greeter(helloworld_pb2.GreeterServicer):
def serve(): def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
helloworld_pb2.add_GreeterServicer_to_server(Greeter(), server) helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
server.add_insecure_port('[::]:50051') server.add_insecure_port('[::]:50051')
server.start() server.start()
try: try:

@ -107,98 +107,123 @@ _sym_db.RegisterMessage(HelloReply)
DESCRIPTOR.has_options = True DESCRIPTOR.has_options = True
DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n\033io.grpc.examples.helloworldB\017HelloWorldProtoP\001\242\002\003HLW')) DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n\033io.grpc.examples.helloworldB\017HelloWorldProtoP\001\242\002\003HLW'))
import grpc try:
from grpc.beta import implementations as beta_implementations # THESE ELEMENTS WILL BE DEPRECATED.
from grpc.beta import interfaces as beta_interfaces # Please use the generated *_pb2_grpc.py files instead.
from grpc.framework.common import cardinality import grpc
from grpc.framework.interfaces.face import utilities as face_utilities from grpc.framework.common import cardinality
from grpc.framework.interfaces.face import utilities as face_utilities
from grpc.beta import implementations as beta_implementations
from grpc.beta import interfaces as beta_interfaces
class GreeterStub(object):
"""The greeting service definition.
"""
def __init__(self, channel):
"""Constructor.
class GreeterStub(object): Args:
"""The greeting service definition. channel: A grpc.Channel.
""" """
self.SayHello = channel.unary_unary(
'/helloworld.Greeter/SayHello',
request_serializer=HelloRequest.SerializeToString,
response_deserializer=HelloReply.FromString,
)
def __init__(self, channel):
"""Constructor.
Args: class GreeterServicer(object):
channel: A grpc.Channel. """The greeting service definition.
""" """
self.SayHello = channel.unary_unary(
'/helloworld.Greeter/SayHello',
request_serializer=HelloRequest.SerializeToString,
response_deserializer=HelloReply.FromString,
)
class GreeterServicer(object):
"""The greeting service definition.
"""
def SayHello(self, request, context): def SayHello(self, request, context):
"""Sends a greeting """Sends a greeting
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_GreeterServicer_to_server(servicer, server):
rpc_method_handlers = {
'SayHello': grpc.unary_unary_rpc_method_handler(
servicer.SayHello,
request_deserializer=HelloRequest.FromString,
response_serializer=HelloReply.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'helloworld.Greeter', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
class BetaGreeterServicer(object):
"""The Beta API is deprecated for 0.15.0 and later.
It is recommended to use the GA API (classes and functions in this
file not marked beta) for all further purposes. This class was generated
only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0."""
"""The greeting service definition.
""" """
context.set_code(grpc.StatusCode.UNIMPLEMENTED) def SayHello(self, request, context):
context.set_details('Method not implemented!') """Sends a greeting
raise NotImplementedError('Method not implemented!') """
context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)
def add_GreeterServicer_to_server(servicer, server):
rpc_method_handlers = {
'SayHello': grpc.unary_unary_rpc_method_handler(
servicer.SayHello,
request_deserializer=HelloRequest.FromString,
response_serializer=HelloReply.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'helloworld.Greeter', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
class BetaGreeterServicer(object):
"""The greeting service definition.
"""
def SayHello(self, request, context):
"""Sends a greeting
"""
context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)
class BetaGreeterStub(object):
"""The Beta API is deprecated for 0.15.0 and later.
class BetaGreeterStub(object): It is recommended to use the GA API (classes and functions in this
"""The greeting service definition. file not marked beta) for all further purposes. This class was generated
""" only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0."""
def SayHello(self, request, timeout, metadata=None, with_call=False, protocol_options=None): """The greeting service definition.
"""Sends a greeting
""" """
raise NotImplementedError() def SayHello(self, request, timeout, metadata=None, with_call=False, protocol_options=None):
SayHello.future = None """Sends a greeting
"""
raise NotImplementedError()
def beta_create_Greeter_server(servicer, pool=None, pool_size=None, default_timeout=None, maximum_timeout=None): SayHello.future = None
request_deserializers = {
('helloworld.Greeter', 'SayHello'): HelloRequest.FromString,
} def beta_create_Greeter_server(servicer, pool=None, pool_size=None, default_timeout=None, maximum_timeout=None):
response_serializers = { """The Beta API is deprecated for 0.15.0 and later.
('helloworld.Greeter', 'SayHello'): HelloReply.SerializeToString,
} It is recommended to use the GA API (classes and functions in this
method_implementations = { file not marked beta) for all further purposes. This function was
('helloworld.Greeter', 'SayHello'): face_utilities.unary_unary_inline(servicer.SayHello), generated only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0"""
} request_deserializers = {
server_options = beta_implementations.server_options(request_deserializers=request_deserializers, response_serializers=response_serializers, thread_pool=pool, thread_pool_size=pool_size, default_timeout=default_timeout, maximum_timeout=maximum_timeout) ('helloworld.Greeter', 'SayHello'): HelloRequest.FromString,
return beta_implementations.server(method_implementations, options=server_options) }
response_serializers = {
('helloworld.Greeter', 'SayHello'): HelloReply.SerializeToString,
def beta_create_Greeter_stub(channel, host=None, metadata_transformer=None, pool=None, pool_size=None): }
request_serializers = { method_implementations = {
('helloworld.Greeter', 'SayHello'): HelloRequest.SerializeToString, ('helloworld.Greeter', 'SayHello'): face_utilities.unary_unary_inline(servicer.SayHello),
} }
response_deserializers = { server_options = beta_implementations.server_options(request_deserializers=request_deserializers, response_serializers=response_serializers, thread_pool=pool, thread_pool_size=pool_size, default_timeout=default_timeout, maximum_timeout=maximum_timeout)
('helloworld.Greeter', 'SayHello'): HelloReply.FromString, return beta_implementations.server(method_implementations, options=server_options)
}
cardinalities = {
'SayHello': cardinality.Cardinality.UNARY_UNARY, def beta_create_Greeter_stub(channel, host=None, metadata_transformer=None, pool=None, pool_size=None):
} """The Beta API is deprecated for 0.15.0 and later.
stub_options = beta_implementations.stub_options(host=host, metadata_transformer=metadata_transformer, request_serializers=request_serializers, response_deserializers=response_deserializers, thread_pool=pool, thread_pool_size=pool_size)
return beta_implementations.dynamic_stub(channel, 'helloworld.Greeter', cardinalities, options=stub_options) It is recommended to use the GA API (classes and functions in this
file not marked beta) for all further purposes. This function was
generated only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0"""
request_serializers = {
('helloworld.Greeter', 'SayHello'): HelloRequest.SerializeToString,
}
response_deserializers = {
('helloworld.Greeter', 'SayHello'): HelloReply.FromString,
}
cardinalities = {
'SayHello': cardinality.Cardinality.UNARY_UNARY,
}
stub_options = beta_implementations.stub_options(host=host, metadata_transformer=metadata_transformer, request_serializers=request_serializers, response_deserializers=response_deserializers, thread_pool=pool, thread_pool_size=pool_size)
return beta_implementations.dynamic_stub(channel, 'helloworld.Greeter', cardinalities, options=stub_options)
except ImportError:
pass
# @@protoc_insertion_point(module_scope) # @@protoc_insertion_point(module_scope)

@ -0,0 +1,47 @@
import grpc
from grpc.framework.common import cardinality
from grpc.framework.interfaces.face import utilities as face_utilities
import helloworld_pb2 as helloworld__pb2
class GreeterStub(object):
"""The greeting service definition.
"""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.SayHello = channel.unary_unary(
'/helloworld.Greeter/SayHello',
request_serializer=helloworld__pb2.HelloRequest.SerializeToString,
response_deserializer=helloworld__pb2.HelloReply.FromString,
)
class GreeterServicer(object):
"""The greeting service definition.
"""
def SayHello(self, request, context):
"""Sends a greeting
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_GreeterServicer_to_server(servicer, server):
rpc_method_handlers = {
'SayHello': grpc.unary_unary_rpc_method_handler(
servicer.SayHello,
request_deserializer=helloworld__pb2.HelloRequest.FromString,
response_serializer=helloworld__pb2.HelloReply.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'helloworld.Greeter', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))

@ -107,98 +107,123 @@ _sym_db.RegisterMessage(HelloReply)
DESCRIPTOR.has_options = True DESCRIPTOR.has_options = True
DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n\033io.grpc.examples.helloworldB\017HelloWorldProtoP\001\242\002\003HLW')) DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n\033io.grpc.examples.helloworldB\017HelloWorldProtoP\001\242\002\003HLW'))
import grpc try:
from grpc.beta import implementations as beta_implementations # THESE ELEMENTS WILL BE DEPRECATED.
from grpc.beta import interfaces as beta_interfaces # Please use the generated *_pb2_grpc.py files instead.
from grpc.framework.common import cardinality import grpc
from grpc.framework.interfaces.face import utilities as face_utilities from grpc.framework.common import cardinality
from grpc.framework.interfaces.face import utilities as face_utilities
from grpc.beta import implementations as beta_implementations
from grpc.beta import interfaces as beta_interfaces
class GreeterStub(object):
"""The greeting service definition.
"""
def __init__(self, channel):
"""Constructor.
class GreeterStub(object): Args:
"""The greeting service definition. channel: A grpc.Channel.
""" """
self.SayHello = channel.unary_unary(
'/helloworld.Greeter/SayHello',
request_serializer=HelloRequest.SerializeToString,
response_deserializer=HelloReply.FromString,
)
def __init__(self, channel):
"""Constructor.
Args: class GreeterServicer(object):
channel: A grpc.Channel. """The greeting service definition.
""" """
self.SayHello = channel.unary_unary(
'/helloworld.Greeter/SayHello',
request_serializer=HelloRequest.SerializeToString,
response_deserializer=HelloReply.FromString,
)
class GreeterServicer(object):
"""The greeting service definition.
"""
def SayHello(self, request, context): def SayHello(self, request, context):
"""Sends a greeting """Sends a greeting
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_GreeterServicer_to_server(servicer, server):
rpc_method_handlers = {
'SayHello': grpc.unary_unary_rpc_method_handler(
servicer.SayHello,
request_deserializer=HelloRequest.FromString,
response_serializer=HelloReply.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'helloworld.Greeter', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
class BetaGreeterServicer(object):
"""The Beta API is deprecated for 0.15.0 and later.
It is recommended to use the GA API (classes and functions in this
file not marked beta) for all further purposes. This class was generated
only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0."""
"""The greeting service definition.
""" """
context.set_code(grpc.StatusCode.UNIMPLEMENTED) def SayHello(self, request, context):
context.set_details('Method not implemented!') """Sends a greeting
raise NotImplementedError('Method not implemented!') """
context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)
def add_GreeterServicer_to_server(servicer, server):
rpc_method_handlers = {
'SayHello': grpc.unary_unary_rpc_method_handler(
servicer.SayHello,
request_deserializer=HelloRequest.FromString,
response_serializer=HelloReply.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'helloworld.Greeter', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
class BetaGreeterServicer(object):
"""The greeting service definition.
"""
def SayHello(self, request, context):
"""Sends a greeting
"""
context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)
class BetaGreeterStub(object):
"""The Beta API is deprecated for 0.15.0 and later.
class BetaGreeterStub(object): It is recommended to use the GA API (classes and functions in this
"""The greeting service definition. file not marked beta) for all further purposes. This class was generated
""" only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0."""
def SayHello(self, request, timeout, metadata=None, with_call=False, protocol_options=None): """The greeting service definition.
"""Sends a greeting
""" """
raise NotImplementedError() def SayHello(self, request, timeout, metadata=None, with_call=False, protocol_options=None):
SayHello.future = None """Sends a greeting
"""
raise NotImplementedError()
def beta_create_Greeter_server(servicer, pool=None, pool_size=None, default_timeout=None, maximum_timeout=None): SayHello.future = None
request_deserializers = {
('helloworld.Greeter', 'SayHello'): HelloRequest.FromString,
} def beta_create_Greeter_server(servicer, pool=None, pool_size=None, default_timeout=None, maximum_timeout=None):
response_serializers = { """The Beta API is deprecated for 0.15.0 and later.
('helloworld.Greeter', 'SayHello'): HelloReply.SerializeToString,
} It is recommended to use the GA API (classes and functions in this
method_implementations = { file not marked beta) for all further purposes. This function was
('helloworld.Greeter', 'SayHello'): face_utilities.unary_unary_inline(servicer.SayHello), generated only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0"""
} request_deserializers = {
server_options = beta_implementations.server_options(request_deserializers=request_deserializers, response_serializers=response_serializers, thread_pool=pool, thread_pool_size=pool_size, default_timeout=default_timeout, maximum_timeout=maximum_timeout) ('helloworld.Greeter', 'SayHello'): HelloRequest.FromString,
return beta_implementations.server(method_implementations, options=server_options) }
response_serializers = {
('helloworld.Greeter', 'SayHello'): HelloReply.SerializeToString,
def beta_create_Greeter_stub(channel, host=None, metadata_transformer=None, pool=None, pool_size=None): }
request_serializers = { method_implementations = {
('helloworld.Greeter', 'SayHello'): HelloRequest.SerializeToString, ('helloworld.Greeter', 'SayHello'): face_utilities.unary_unary_inline(servicer.SayHello),
} }
response_deserializers = { server_options = beta_implementations.server_options(request_deserializers=request_deserializers, response_serializers=response_serializers, thread_pool=pool, thread_pool_size=pool_size, default_timeout=default_timeout, maximum_timeout=maximum_timeout)
('helloworld.Greeter', 'SayHello'): HelloReply.FromString, return beta_implementations.server(method_implementations, options=server_options)
}
cardinalities = {
'SayHello': cardinality.Cardinality.UNARY_UNARY, def beta_create_Greeter_stub(channel, host=None, metadata_transformer=None, pool=None, pool_size=None):
} """The Beta API is deprecated for 0.15.0 and later.
stub_options = beta_implementations.stub_options(host=host, metadata_transformer=metadata_transformer, request_serializers=request_serializers, response_deserializers=response_deserializers, thread_pool=pool, thread_pool_size=pool_size)
return beta_implementations.dynamic_stub(channel, 'helloworld.Greeter', cardinalities, options=stub_options) It is recommended to use the GA API (classes and functions in this
file not marked beta) for all further purposes. This function was
generated only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0"""
request_serializers = {
('helloworld.Greeter', 'SayHello'): HelloRequest.SerializeToString,
}
response_deserializers = {
('helloworld.Greeter', 'SayHello'): HelloReply.FromString,
}
cardinalities = {
'SayHello': cardinality.Cardinality.UNARY_UNARY,
}
stub_options = beta_implementations.stub_options(host=host, metadata_transformer=metadata_transformer, request_serializers=request_serializers, response_deserializers=response_deserializers, thread_pool=pool, thread_pool_size=pool_size)
return beta_implementations.dynamic_stub(channel, 'helloworld.Greeter', cardinalities, options=stub_options)
except ImportError:
pass
# @@protoc_insertion_point(module_scope) # @@protoc_insertion_point(module_scope)

@ -0,0 +1,47 @@
import grpc
from grpc.framework.common import cardinality
from grpc.framework.interfaces.face import utilities as face_utilities
import helloworld_pb2 as helloworld__pb2
class GreeterStub(object):
"""The greeting service definition.
"""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.SayHello = channel.unary_unary(
'/helloworld.Greeter/SayHello',
request_serializer=helloworld__pb2.HelloRequest.SerializeToString,
response_deserializer=helloworld__pb2.HelloReply.FromString,
)
class GreeterServicer(object):
"""The greeting service definition.
"""
def SayHello(self, request, context):
"""Sends a greeting
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_GreeterServicer_to_server(servicer, server):
rpc_method_handlers = {
'SayHello': grpc.unary_unary_rpc_method_handler(
servicer.SayHello,
request_deserializer=helloworld__pb2.HelloRequest.FromString,
response_serializer=helloworld__pb2.HelloReply.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'helloworld.Greeter', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))

@ -37,7 +37,9 @@ import time
import grpc import grpc
import helloworld_pb2 import helloworld_pb2
import helloworld_pb2_grpc
import route_guide_pb2 import route_guide_pb2
import route_guide_pb2_grpc
import route_guide_resources import route_guide_resources
@ -120,8 +122,8 @@ def guide_route_chat(route_guide_stub):
def run(): def run():
channel = grpc.insecure_channel('localhost:50051') channel = grpc.insecure_channel('localhost:50051')
greeter_stub = helloworld_pb2.GreeterStub(channel) greeter_stub = helloworld_pb2_grpc.GreeterStub(channel)
route_guide_stub = route_guide_pb2.RouteGuideStub(channel) route_guide_stub = route_guide_pb2_grpc.RouteGuideStub(channel)
greeter_response = greeter_stub.SayHello( greeter_response = greeter_stub.SayHello(
helloworld_pb2.HelloRequest(name='you')) helloworld_pb2.HelloRequest(name='you'))
print("Greeter client received: " + greeter_response.message) print("Greeter client received: " + greeter_response.message)

@ -36,7 +36,9 @@ import math
import grpc import grpc
import helloworld_pb2 import helloworld_pb2
import helloworld_pb2_grpc
import route_guide_pb2 import route_guide_pb2
import route_guide_pb2_grpc
import route_guide_resources import route_guide_resources
_ONE_DAY_IN_SECONDS = 60 * 60 * 24 _ONE_DAY_IN_SECONDS = 60 * 60 * 24
@ -70,13 +72,13 @@ def _get_distance(start, end):
return R * c; return R * c;
class _GreeterServicer(helloworld_pb2.GreeterServicer): class _GreeterServicer(helloworld_pb2_grpc.GreeterServicer):
def SayHello(self, request, context): def SayHello(self, request, context):
return helloworld_pb2.HelloReply(message='Hello, {}!'.format(request.name)) return helloworld_pb2.HelloReply(message='Hello, {}!'.format(request.name))
class _RouteGuideServicer(route_guide_pb2.RouteGuideServicer): class _RouteGuideServicer(route_guide_pb2_grpc.RouteGuideServicer):
"""Provides methods that implement functionality of route guide server.""" """Provides methods that implement functionality of route guide server."""
def __init__(self): def __init__(self):
@ -133,8 +135,8 @@ class _RouteGuideServicer(route_guide_pb2.RouteGuideServicer):
def serve(): def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
helloworld_pb2.add_GreeterServicer_to_server(_GreeterServicer(), server) helloworld_pb2_grpc.add_GreeterServicer_to_server(_GreeterServicer(), server)
route_guide_pb2.add_RouteGuideServicer_to_server( route_guide_pb2_grpc.add_RouteGuideServicer_to_server(
_RouteGuideServicer(), server) _RouteGuideServicer(), server)
server.add_insecure_port('[::]:50051') server.add_insecure_port('[::]:50051')
server.start() server.start()

@ -277,240 +277,265 @@ _sym_db.RegisterMessage(RouteSummary)
DESCRIPTOR.has_options = True DESCRIPTOR.has_options = True
DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n\033io.grpc.examples.routeguideB\017RouteGuideProtoP\001\242\002\003RTG')) DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n\033io.grpc.examples.routeguideB\017RouteGuideProtoP\001\242\002\003RTG'))
import grpc try:
from grpc.beta import implementations as beta_implementations # THESE ELEMENTS WILL BE DEPRECATED.
from grpc.beta import interfaces as beta_interfaces # Please use the generated *_pb2_grpc.py files instead.
from grpc.framework.common import cardinality import grpc
from grpc.framework.interfaces.face import utilities as face_utilities from grpc.framework.common import cardinality
from grpc.framework.interfaces.face import utilities as face_utilities
from grpc.beta import implementations as beta_implementations
class RouteGuideStub(object): from grpc.beta import interfaces as beta_interfaces
"""Interface exported by the server.
"""
class RouteGuideStub(object):
def __init__(self, channel): """Interface exported by the server.
"""Constructor.
Args:
channel: A grpc.Channel.
""" """
self.GetFeature = channel.unary_unary(
'/routeguide.RouteGuide/GetFeature',
request_serializer=Point.SerializeToString,
response_deserializer=Feature.FromString,
)
self.ListFeatures = channel.unary_stream(
'/routeguide.RouteGuide/ListFeatures',
request_serializer=Rectangle.SerializeToString,
response_deserializer=Feature.FromString,
)
self.RecordRoute = channel.stream_unary(
'/routeguide.RouteGuide/RecordRoute',
request_serializer=Point.SerializeToString,
response_deserializer=RouteSummary.FromString,
)
self.RouteChat = channel.stream_stream(
'/routeguide.RouteGuide/RouteChat',
request_serializer=RouteNote.SerializeToString,
response_deserializer=RouteNote.FromString,
)
class RouteGuideServicer(object):
"""Interface exported by the server.
"""
def GetFeature(self, request, context):
"""A simple RPC.
Obtains the feature at a given position.
A feature with an empty name is returned if there's no feature at the given
position.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def ListFeatures(self, request, context):
"""A server-to-client streaming RPC.
Obtains the Features available within the given Rectangle. Results are def __init__(self, channel):
streamed rather than returned at once (e.g. in a response message with a """Constructor.
repeated field), as the rectangle may cover a large area and contain a
huge number of features. Args:
channel: A grpc.Channel.
"""
self.GetFeature = channel.unary_unary(
'/routeguide.RouteGuide/GetFeature',
request_serializer=Point.SerializeToString,
response_deserializer=Feature.FromString,
)
self.ListFeatures = channel.unary_stream(
'/routeguide.RouteGuide/ListFeatures',
request_serializer=Rectangle.SerializeToString,
response_deserializer=Feature.FromString,
)
self.RecordRoute = channel.stream_unary(
'/routeguide.RouteGuide/RecordRoute',
request_serializer=Point.SerializeToString,
response_deserializer=RouteSummary.FromString,
)
self.RouteChat = channel.stream_stream(
'/routeguide.RouteGuide/RouteChat',
request_serializer=RouteNote.SerializeToString,
response_deserializer=RouteNote.FromString,
)
class RouteGuideServicer(object):
"""Interface exported by the server.
""" """
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def RecordRoute(self, request_iterator, context):
"""A client-to-server streaming RPC.
Accepts a stream of Points on a route being traversed, returning a def GetFeature(self, request, context):
RouteSummary when traversal is completed. """A simple RPC.
Obtains the feature at a given position.
A feature with an empty name is returned if there's no feature at the given
position.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def ListFeatures(self, request, context):
"""A server-to-client streaming RPC.
Obtains the Features available within the given Rectangle. Results are
streamed rather than returned at once (e.g. in a response message with a
repeated field), as the rectangle may cover a large area and contain a
huge number of features.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def RecordRoute(self, request_iterator, context):
"""A client-to-server streaming RPC.
Accepts a stream of Points on a route being traversed, returning a
RouteSummary when traversal is completed.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def RouteChat(self, request_iterator, context):
"""A Bidirectional streaming RPC.
Accepts a stream of RouteNotes sent while a route is being traversed,
while receiving other RouteNotes (e.g. from other users).
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_RouteGuideServicer_to_server(servicer, server):
rpc_method_handlers = {
'GetFeature': grpc.unary_unary_rpc_method_handler(
servicer.GetFeature,
request_deserializer=Point.FromString,
response_serializer=Feature.SerializeToString,
),
'ListFeatures': grpc.unary_stream_rpc_method_handler(
servicer.ListFeatures,
request_deserializer=Rectangle.FromString,
response_serializer=Feature.SerializeToString,
),
'RecordRoute': grpc.stream_unary_rpc_method_handler(
servicer.RecordRoute,
request_deserializer=Point.FromString,
response_serializer=RouteSummary.SerializeToString,
),
'RouteChat': grpc.stream_stream_rpc_method_handler(
servicer.RouteChat,
request_deserializer=RouteNote.FromString,
response_serializer=RouteNote.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'routeguide.RouteGuide', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
class BetaRouteGuideServicer(object):
"""The Beta API is deprecated for 0.15.0 and later.
It is recommended to use the GA API (classes and functions in this
file not marked beta) for all further purposes. This class was generated
only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0."""
"""Interface exported by the server.
""" """
context.set_code(grpc.StatusCode.UNIMPLEMENTED) def GetFeature(self, request, context):
context.set_details('Method not implemented!') """A simple RPC.
raise NotImplementedError('Method not implemented!')
Obtains the feature at a given position.
def RouteChat(self, request_iterator, context):
"""A Bidirectional streaming RPC. A feature with an empty name is returned if there's no feature at the given
position.
Accepts a stream of RouteNotes sent while a route is being traversed, """
while receiving other RouteNotes (e.g. from other users). context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)
""" def ListFeatures(self, request, context):
context.set_code(grpc.StatusCode.UNIMPLEMENTED) """A server-to-client streaming RPC.
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') Obtains the Features available within the given Rectangle. Results are
streamed rather than returned at once (e.g. in a response message with a
repeated field), as the rectangle may cover a large area and contain a
def add_RouteGuideServicer_to_server(servicer, server): huge number of features.
rpc_method_handlers = { """
'GetFeature': grpc.unary_unary_rpc_method_handler( context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)
servicer.GetFeature, def RecordRoute(self, request_iterator, context):
request_deserializer=Point.FromString, """A client-to-server streaming RPC.
response_serializer=Feature.SerializeToString,
), Accepts a stream of Points on a route being traversed, returning a
'ListFeatures': grpc.unary_stream_rpc_method_handler( RouteSummary when traversal is completed.
servicer.ListFeatures, """
request_deserializer=Rectangle.FromString, context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)
response_serializer=Feature.SerializeToString, def RouteChat(self, request_iterator, context):
), """A Bidirectional streaming RPC.
'RecordRoute': grpc.stream_unary_rpc_method_handler(
servicer.RecordRoute, Accepts a stream of RouteNotes sent while a route is being traversed,
request_deserializer=Point.FromString, while receiving other RouteNotes (e.g. from other users).
response_serializer=RouteSummary.SerializeToString, """
), context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)
'RouteChat': grpc.stream_stream_rpc_method_handler(
servicer.RouteChat,
request_deserializer=RouteNote.FromString, class BetaRouteGuideStub(object):
response_serializer=RouteNote.SerializeToString, """The Beta API is deprecated for 0.15.0 and later.
),
} It is recommended to use the GA API (classes and functions in this
generic_handler = grpc.method_handlers_generic_handler( file not marked beta) for all further purposes. This class was generated
'routeguide.RouteGuide', rpc_method_handlers) only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0."""
server.add_generic_rpc_handlers((generic_handler,)) """Interface exported by the server.
class BetaRouteGuideServicer(object):
"""Interface exported by the server.
"""
def GetFeature(self, request, context):
"""A simple RPC.
Obtains the feature at a given position.
A feature with an empty name is returned if there's no feature at the given
position.
"""
context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)
def ListFeatures(self, request, context):
"""A server-to-client streaming RPC.
Obtains the Features available within the given Rectangle. Results are
streamed rather than returned at once (e.g. in a response message with a
repeated field), as the rectangle may cover a large area and contain a
huge number of features.
"""
context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)
def RecordRoute(self, request_iterator, context):
"""A client-to-server streaming RPC.
Accepts a stream of Points on a route being traversed, returning a
RouteSummary when traversal is completed.
"""
context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)
def RouteChat(self, request_iterator, context):
"""A Bidirectional streaming RPC.
Accepts a stream of RouteNotes sent while a route is being traversed,
while receiving other RouteNotes (e.g. from other users).
"""
context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)
class BetaRouteGuideStub(object):
"""Interface exported by the server.
"""
def GetFeature(self, request, timeout, metadata=None, with_call=False, protocol_options=None):
"""A simple RPC.
Obtains the feature at a given position.
A feature with an empty name is returned if there's no feature at the given
position.
"""
raise NotImplementedError()
GetFeature.future = None
def ListFeatures(self, request, timeout, metadata=None, with_call=False, protocol_options=None):
"""A server-to-client streaming RPC.
Obtains the Features available within the given Rectangle. Results are
streamed rather than returned at once (e.g. in a response message with a
repeated field), as the rectangle may cover a large area and contain a
huge number of features.
"""
raise NotImplementedError()
def RecordRoute(self, request_iterator, timeout, metadata=None, with_call=False, protocol_options=None):
"""A client-to-server streaming RPC.
Accepts a stream of Points on a route being traversed, returning a
RouteSummary when traversal is completed.
"""
raise NotImplementedError()
RecordRoute.future = None
def RouteChat(self, request_iterator, timeout, metadata=None, with_call=False, protocol_options=None):
"""A Bidirectional streaming RPC.
Accepts a stream of RouteNotes sent while a route is being traversed,
while receiving other RouteNotes (e.g. from other users).
""" """
raise NotImplementedError() def GetFeature(self, request, timeout, metadata=None, with_call=False, protocol_options=None):
"""A simple RPC.
def beta_create_RouteGuide_server(servicer, pool=None, pool_size=None, default_timeout=None, maximum_timeout=None): Obtains the feature at a given position.
request_deserializers = {
('routeguide.RouteGuide', 'GetFeature'): Point.FromString, A feature with an empty name is returned if there's no feature at the given
('routeguide.RouteGuide', 'ListFeatures'): Rectangle.FromString, position.
('routeguide.RouteGuide', 'RecordRoute'): Point.FromString, """
('routeguide.RouteGuide', 'RouteChat'): RouteNote.FromString, raise NotImplementedError()
} GetFeature.future = None
response_serializers = { def ListFeatures(self, request, timeout, metadata=None, with_call=False, protocol_options=None):
('routeguide.RouteGuide', 'GetFeature'): Feature.SerializeToString, """A server-to-client streaming RPC.
('routeguide.RouteGuide', 'ListFeatures'): Feature.SerializeToString,
('routeguide.RouteGuide', 'RecordRoute'): RouteSummary.SerializeToString, Obtains the Features available within the given Rectangle. Results are
('routeguide.RouteGuide', 'RouteChat'): RouteNote.SerializeToString, streamed rather than returned at once (e.g. in a response message with a
} repeated field), as the rectangle may cover a large area and contain a
method_implementations = { huge number of features.
('routeguide.RouteGuide', 'GetFeature'): face_utilities.unary_unary_inline(servicer.GetFeature), """
('routeguide.RouteGuide', 'ListFeatures'): face_utilities.unary_stream_inline(servicer.ListFeatures), raise NotImplementedError()
('routeguide.RouteGuide', 'RecordRoute'): face_utilities.stream_unary_inline(servicer.RecordRoute), def RecordRoute(self, request_iterator, timeout, metadata=None, with_call=False, protocol_options=None):
('routeguide.RouteGuide', 'RouteChat'): face_utilities.stream_stream_inline(servicer.RouteChat), """A client-to-server streaming RPC.
}
server_options = beta_implementations.server_options(request_deserializers=request_deserializers, response_serializers=response_serializers, thread_pool=pool, thread_pool_size=pool_size, default_timeout=default_timeout, maximum_timeout=maximum_timeout) Accepts a stream of Points on a route being traversed, returning a
return beta_implementations.server(method_implementations, options=server_options) RouteSummary when traversal is completed.
"""
raise NotImplementedError()
def beta_create_RouteGuide_stub(channel, host=None, metadata_transformer=None, pool=None, pool_size=None): RecordRoute.future = None
request_serializers = { def RouteChat(self, request_iterator, timeout, metadata=None, with_call=False, protocol_options=None):
('routeguide.RouteGuide', 'GetFeature'): Point.SerializeToString, """A Bidirectional streaming RPC.
('routeguide.RouteGuide', 'ListFeatures'): Rectangle.SerializeToString,
('routeguide.RouteGuide', 'RecordRoute'): Point.SerializeToString, Accepts a stream of RouteNotes sent while a route is being traversed,
('routeguide.RouteGuide', 'RouteChat'): RouteNote.SerializeToString, while receiving other RouteNotes (e.g. from other users).
} """
response_deserializers = { raise NotImplementedError()
('routeguide.RouteGuide', 'GetFeature'): Feature.FromString,
('routeguide.RouteGuide', 'ListFeatures'): Feature.FromString,
('routeguide.RouteGuide', 'RecordRoute'): RouteSummary.FromString, def beta_create_RouteGuide_server(servicer, pool=None, pool_size=None, default_timeout=None, maximum_timeout=None):
('routeguide.RouteGuide', 'RouteChat'): RouteNote.FromString, """The Beta API is deprecated for 0.15.0 and later.
}
cardinalities = { It is recommended to use the GA API (classes and functions in this
'GetFeature': cardinality.Cardinality.UNARY_UNARY, file not marked beta) for all further purposes. This function was
'ListFeatures': cardinality.Cardinality.UNARY_STREAM, generated only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0"""
'RecordRoute': cardinality.Cardinality.STREAM_UNARY, request_deserializers = {
'RouteChat': cardinality.Cardinality.STREAM_STREAM, ('routeguide.RouteGuide', 'GetFeature'): Point.FromString,
} ('routeguide.RouteGuide', 'ListFeatures'): Rectangle.FromString,
stub_options = beta_implementations.stub_options(host=host, metadata_transformer=metadata_transformer, request_serializers=request_serializers, response_deserializers=response_deserializers, thread_pool=pool, thread_pool_size=pool_size) ('routeguide.RouteGuide', 'RecordRoute'): Point.FromString,
return beta_implementations.dynamic_stub(channel, 'routeguide.RouteGuide', cardinalities, options=stub_options) ('routeguide.RouteGuide', 'RouteChat'): RouteNote.FromString,
}
response_serializers = {
('routeguide.RouteGuide', 'GetFeature'): Feature.SerializeToString,
('routeguide.RouteGuide', 'ListFeatures'): Feature.SerializeToString,
('routeguide.RouteGuide', 'RecordRoute'): RouteSummary.SerializeToString,
('routeguide.RouteGuide', 'RouteChat'): RouteNote.SerializeToString,
}
method_implementations = {
('routeguide.RouteGuide', 'GetFeature'): face_utilities.unary_unary_inline(servicer.GetFeature),
('routeguide.RouteGuide', 'ListFeatures'): face_utilities.unary_stream_inline(servicer.ListFeatures),
('routeguide.RouteGuide', 'RecordRoute'): face_utilities.stream_unary_inline(servicer.RecordRoute),
('routeguide.RouteGuide', 'RouteChat'): face_utilities.stream_stream_inline(servicer.RouteChat),
}
server_options = beta_implementations.server_options(request_deserializers=request_deserializers, response_serializers=response_serializers, thread_pool=pool, thread_pool_size=pool_size, default_timeout=default_timeout, maximum_timeout=maximum_timeout)
return beta_implementations.server(method_implementations, options=server_options)
def beta_create_RouteGuide_stub(channel, host=None, metadata_transformer=None, pool=None, pool_size=None):
"""The Beta API is deprecated for 0.15.0 and later.
It is recommended to use the GA API (classes and functions in this
file not marked beta) for all further purposes. This function was
generated only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0"""
request_serializers = {
('routeguide.RouteGuide', 'GetFeature'): Point.SerializeToString,
('routeguide.RouteGuide', 'ListFeatures'): Rectangle.SerializeToString,
('routeguide.RouteGuide', 'RecordRoute'): Point.SerializeToString,
('routeguide.RouteGuide', 'RouteChat'): RouteNote.SerializeToString,
}
response_deserializers = {
('routeguide.RouteGuide', 'GetFeature'): Feature.FromString,
('routeguide.RouteGuide', 'ListFeatures'): Feature.FromString,
('routeguide.RouteGuide', 'RecordRoute'): RouteSummary.FromString,
('routeguide.RouteGuide', 'RouteChat'): RouteNote.FromString,
}
cardinalities = {
'GetFeature': cardinality.Cardinality.UNARY_UNARY,
'ListFeatures': cardinality.Cardinality.UNARY_STREAM,
'RecordRoute': cardinality.Cardinality.STREAM_UNARY,
'RouteChat': cardinality.Cardinality.STREAM_STREAM,
}
stub_options = beta_implementations.stub_options(host=host, metadata_transformer=metadata_transformer, request_serializers=request_serializers, response_deserializers=response_deserializers, thread_pool=pool, thread_pool_size=pool_size)
return beta_implementations.dynamic_stub(channel, 'routeguide.RouteGuide', cardinalities, options=stub_options)
except ImportError:
pass
# @@protoc_insertion_point(module_scope) # @@protoc_insertion_point(module_scope)

@ -0,0 +1,114 @@
import grpc
from grpc.framework.common import cardinality
from grpc.framework.interfaces.face import utilities as face_utilities
import route_guide_pb2 as route__guide__pb2
class RouteGuideStub(object):
"""Interface exported by the server.
"""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.GetFeature = channel.unary_unary(
'/routeguide.RouteGuide/GetFeature',
request_serializer=route__guide__pb2.Point.SerializeToString,
response_deserializer=route__guide__pb2.Feature.FromString,
)
self.ListFeatures = channel.unary_stream(
'/routeguide.RouteGuide/ListFeatures',
request_serializer=route__guide__pb2.Rectangle.SerializeToString,
response_deserializer=route__guide__pb2.Feature.FromString,
)
self.RecordRoute = channel.stream_unary(
'/routeguide.RouteGuide/RecordRoute',
request_serializer=route__guide__pb2.Point.SerializeToString,
response_deserializer=route__guide__pb2.RouteSummary.FromString,
)
self.RouteChat = channel.stream_stream(
'/routeguide.RouteGuide/RouteChat',
request_serializer=route__guide__pb2.RouteNote.SerializeToString,
response_deserializer=route__guide__pb2.RouteNote.FromString,
)
class RouteGuideServicer(object):
"""Interface exported by the server.
"""
def GetFeature(self, request, context):
"""A simple RPC.
Obtains the feature at a given position.
A feature with an empty name is returned if there's no feature at the given
position.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def ListFeatures(self, request, context):
"""A server-to-client streaming RPC.
Obtains the Features available within the given Rectangle. Results are
streamed rather than returned at once (e.g. in a response message with a
repeated field), as the rectangle may cover a large area and contain a
huge number of features.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def RecordRoute(self, request_iterator, context):
"""A client-to-server streaming RPC.
Accepts a stream of Points on a route being traversed, returning a
RouteSummary when traversal is completed.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def RouteChat(self, request_iterator, context):
"""A Bidirectional streaming RPC.
Accepts a stream of RouteNotes sent while a route is being traversed,
while receiving other RouteNotes (e.g. from other users).
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_RouteGuideServicer_to_server(servicer, server):
rpc_method_handlers = {
'GetFeature': grpc.unary_unary_rpc_method_handler(
servicer.GetFeature,
request_deserializer=route__guide__pb2.Point.FromString,
response_serializer=route__guide__pb2.Feature.SerializeToString,
),
'ListFeatures': grpc.unary_stream_rpc_method_handler(
servicer.ListFeatures,
request_deserializer=route__guide__pb2.Rectangle.FromString,
response_serializer=route__guide__pb2.Feature.SerializeToString,
),
'RecordRoute': grpc.stream_unary_rpc_method_handler(
servicer.RecordRoute,
request_deserializer=route__guide__pb2.Point.FromString,
response_serializer=route__guide__pb2.RouteSummary.SerializeToString,
),
'RouteChat': grpc.stream_stream_rpc_method_handler(
servicer.RouteChat,
request_deserializer=route__guide__pb2.RouteNote.FromString,
response_serializer=route__guide__pb2.RouteNote.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'routeguide.RouteGuide', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))

@ -37,6 +37,7 @@ import time
import grpc import grpc
import route_guide_pb2 import route_guide_pb2
import route_guide_pb2_grpc
import route_guide_resources import route_guide_resources
@ -116,7 +117,7 @@ def guide_route_chat(stub):
def run(): def run():
channel = grpc.insecure_channel('localhost:50051') channel = grpc.insecure_channel('localhost:50051')
stub = route_guide_pb2.RouteGuideStub(channel) stub = route_guide_pb2_grpc.RouteGuideStub(channel)
print("-------------- GetFeature --------------") print("-------------- GetFeature --------------")
guide_get_feature(stub) guide_get_feature(stub)
print("-------------- ListFeatures --------------") print("-------------- ListFeatures --------------")

@ -277,240 +277,265 @@ _sym_db.RegisterMessage(RouteSummary)
DESCRIPTOR.has_options = True DESCRIPTOR.has_options = True
DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n\033io.grpc.examples.routeguideB\017RouteGuideProtoP\001\242\002\003RTG')) DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n\033io.grpc.examples.routeguideB\017RouteGuideProtoP\001\242\002\003RTG'))
import grpc try:
from grpc.beta import implementations as beta_implementations # THESE ELEMENTS WILL BE DEPRECATED.
from grpc.beta import interfaces as beta_interfaces # Please use the generated *_pb2_grpc.py files instead.
from grpc.framework.common import cardinality import grpc
from grpc.framework.interfaces.face import utilities as face_utilities from grpc.framework.common import cardinality
from grpc.framework.interfaces.face import utilities as face_utilities
from grpc.beta import implementations as beta_implementations
class RouteGuideStub(object): from grpc.beta import interfaces as beta_interfaces
"""Interface exported by the server.
"""
class RouteGuideStub(object):
def __init__(self, channel): """Interface exported by the server.
"""Constructor.
Args:
channel: A grpc.Channel.
""" """
self.GetFeature = channel.unary_unary(
'/routeguide.RouteGuide/GetFeature',
request_serializer=Point.SerializeToString,
response_deserializer=Feature.FromString,
)
self.ListFeatures = channel.unary_stream(
'/routeguide.RouteGuide/ListFeatures',
request_serializer=Rectangle.SerializeToString,
response_deserializer=Feature.FromString,
)
self.RecordRoute = channel.stream_unary(
'/routeguide.RouteGuide/RecordRoute',
request_serializer=Point.SerializeToString,
response_deserializer=RouteSummary.FromString,
)
self.RouteChat = channel.stream_stream(
'/routeguide.RouteGuide/RouteChat',
request_serializer=RouteNote.SerializeToString,
response_deserializer=RouteNote.FromString,
)
class RouteGuideServicer(object):
"""Interface exported by the server.
"""
def GetFeature(self, request, context):
"""A simple RPC.
Obtains the feature at a given position.
A feature with an empty name is returned if there's no feature at the given
position.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def ListFeatures(self, request, context):
"""A server-to-client streaming RPC.
Obtains the Features available within the given Rectangle. Results are def __init__(self, channel):
streamed rather than returned at once (e.g. in a response message with a """Constructor.
repeated field), as the rectangle may cover a large area and contain a
huge number of features. Args:
channel: A grpc.Channel.
"""
self.GetFeature = channel.unary_unary(
'/routeguide.RouteGuide/GetFeature',
request_serializer=Point.SerializeToString,
response_deserializer=Feature.FromString,
)
self.ListFeatures = channel.unary_stream(
'/routeguide.RouteGuide/ListFeatures',
request_serializer=Rectangle.SerializeToString,
response_deserializer=Feature.FromString,
)
self.RecordRoute = channel.stream_unary(
'/routeguide.RouteGuide/RecordRoute',
request_serializer=Point.SerializeToString,
response_deserializer=RouteSummary.FromString,
)
self.RouteChat = channel.stream_stream(
'/routeguide.RouteGuide/RouteChat',
request_serializer=RouteNote.SerializeToString,
response_deserializer=RouteNote.FromString,
)
class RouteGuideServicer(object):
"""Interface exported by the server.
""" """
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def RecordRoute(self, request_iterator, context):
"""A client-to-server streaming RPC.
Accepts a stream of Points on a route being traversed, returning a def GetFeature(self, request, context):
RouteSummary when traversal is completed. """A simple RPC.
Obtains the feature at a given position.
A feature with an empty name is returned if there's no feature at the given
position.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def ListFeatures(self, request, context):
"""A server-to-client streaming RPC.
Obtains the Features available within the given Rectangle. Results are
streamed rather than returned at once (e.g. in a response message with a
repeated field), as the rectangle may cover a large area and contain a
huge number of features.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def RecordRoute(self, request_iterator, context):
"""A client-to-server streaming RPC.
Accepts a stream of Points on a route being traversed, returning a
RouteSummary when traversal is completed.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def RouteChat(self, request_iterator, context):
"""A Bidirectional streaming RPC.
Accepts a stream of RouteNotes sent while a route is being traversed,
while receiving other RouteNotes (e.g. from other users).
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_RouteGuideServicer_to_server(servicer, server):
rpc_method_handlers = {
'GetFeature': grpc.unary_unary_rpc_method_handler(
servicer.GetFeature,
request_deserializer=Point.FromString,
response_serializer=Feature.SerializeToString,
),
'ListFeatures': grpc.unary_stream_rpc_method_handler(
servicer.ListFeatures,
request_deserializer=Rectangle.FromString,
response_serializer=Feature.SerializeToString,
),
'RecordRoute': grpc.stream_unary_rpc_method_handler(
servicer.RecordRoute,
request_deserializer=Point.FromString,
response_serializer=RouteSummary.SerializeToString,
),
'RouteChat': grpc.stream_stream_rpc_method_handler(
servicer.RouteChat,
request_deserializer=RouteNote.FromString,
response_serializer=RouteNote.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'routeguide.RouteGuide', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
class BetaRouteGuideServicer(object):
"""The Beta API is deprecated for 0.15.0 and later.
It is recommended to use the GA API (classes and functions in this
file not marked beta) for all further purposes. This class was generated
only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0."""
"""Interface exported by the server.
""" """
context.set_code(grpc.StatusCode.UNIMPLEMENTED) def GetFeature(self, request, context):
context.set_details('Method not implemented!') """A simple RPC.
raise NotImplementedError('Method not implemented!')
Obtains the feature at a given position.
def RouteChat(self, request_iterator, context):
"""A Bidirectional streaming RPC. A feature with an empty name is returned if there's no feature at the given
position.
Accepts a stream of RouteNotes sent while a route is being traversed, """
while receiving other RouteNotes (e.g. from other users). context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)
""" def ListFeatures(self, request, context):
context.set_code(grpc.StatusCode.UNIMPLEMENTED) """A server-to-client streaming RPC.
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') Obtains the Features available within the given Rectangle. Results are
streamed rather than returned at once (e.g. in a response message with a
repeated field), as the rectangle may cover a large area and contain a
def add_RouteGuideServicer_to_server(servicer, server): huge number of features.
rpc_method_handlers = { """
'GetFeature': grpc.unary_unary_rpc_method_handler( context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)
servicer.GetFeature, def RecordRoute(self, request_iterator, context):
request_deserializer=Point.FromString, """A client-to-server streaming RPC.
response_serializer=Feature.SerializeToString,
), Accepts a stream of Points on a route being traversed, returning a
'ListFeatures': grpc.unary_stream_rpc_method_handler( RouteSummary when traversal is completed.
servicer.ListFeatures, """
request_deserializer=Rectangle.FromString, context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)
response_serializer=Feature.SerializeToString, def RouteChat(self, request_iterator, context):
), """A Bidirectional streaming RPC.
'RecordRoute': grpc.stream_unary_rpc_method_handler(
servicer.RecordRoute, Accepts a stream of RouteNotes sent while a route is being traversed,
request_deserializer=Point.FromString, while receiving other RouteNotes (e.g. from other users).
response_serializer=RouteSummary.SerializeToString, """
), context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)
'RouteChat': grpc.stream_stream_rpc_method_handler(
servicer.RouteChat,
request_deserializer=RouteNote.FromString, class BetaRouteGuideStub(object):
response_serializer=RouteNote.SerializeToString, """The Beta API is deprecated for 0.15.0 and later.
),
} It is recommended to use the GA API (classes and functions in this
generic_handler = grpc.method_handlers_generic_handler( file not marked beta) for all further purposes. This class was generated
'routeguide.RouteGuide', rpc_method_handlers) only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0."""
server.add_generic_rpc_handlers((generic_handler,)) """Interface exported by the server.
class BetaRouteGuideServicer(object):
"""Interface exported by the server.
"""
def GetFeature(self, request, context):
"""A simple RPC.
Obtains the feature at a given position.
A feature with an empty name is returned if there's no feature at the given
position.
"""
context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)
def ListFeatures(self, request, context):
"""A server-to-client streaming RPC.
Obtains the Features available within the given Rectangle. Results are
streamed rather than returned at once (e.g. in a response message with a
repeated field), as the rectangle may cover a large area and contain a
huge number of features.
"""
context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)
def RecordRoute(self, request_iterator, context):
"""A client-to-server streaming RPC.
Accepts a stream of Points on a route being traversed, returning a
RouteSummary when traversal is completed.
"""
context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)
def RouteChat(self, request_iterator, context):
"""A Bidirectional streaming RPC.
Accepts a stream of RouteNotes sent while a route is being traversed,
while receiving other RouteNotes (e.g. from other users).
"""
context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)
class BetaRouteGuideStub(object):
"""Interface exported by the server.
"""
def GetFeature(self, request, timeout, metadata=None, with_call=False, protocol_options=None):
"""A simple RPC.
Obtains the feature at a given position.
A feature with an empty name is returned if there's no feature at the given
position.
"""
raise NotImplementedError()
GetFeature.future = None
def ListFeatures(self, request, timeout, metadata=None, with_call=False, protocol_options=None):
"""A server-to-client streaming RPC.
Obtains the Features available within the given Rectangle. Results are
streamed rather than returned at once (e.g. in a response message with a
repeated field), as the rectangle may cover a large area and contain a
huge number of features.
"""
raise NotImplementedError()
def RecordRoute(self, request_iterator, timeout, metadata=None, with_call=False, protocol_options=None):
"""A client-to-server streaming RPC.
Accepts a stream of Points on a route being traversed, returning a
RouteSummary when traversal is completed.
"""
raise NotImplementedError()
RecordRoute.future = None
def RouteChat(self, request_iterator, timeout, metadata=None, with_call=False, protocol_options=None):
"""A Bidirectional streaming RPC.
Accepts a stream of RouteNotes sent while a route is being traversed,
while receiving other RouteNotes (e.g. from other users).
""" """
raise NotImplementedError() def GetFeature(self, request, timeout, metadata=None, with_call=False, protocol_options=None):
"""A simple RPC.
def beta_create_RouteGuide_server(servicer, pool=None, pool_size=None, default_timeout=None, maximum_timeout=None): Obtains the feature at a given position.
request_deserializers = {
('routeguide.RouteGuide', 'GetFeature'): Point.FromString, A feature with an empty name is returned if there's no feature at the given
('routeguide.RouteGuide', 'ListFeatures'): Rectangle.FromString, position.
('routeguide.RouteGuide', 'RecordRoute'): Point.FromString, """
('routeguide.RouteGuide', 'RouteChat'): RouteNote.FromString, raise NotImplementedError()
} GetFeature.future = None
response_serializers = { def ListFeatures(self, request, timeout, metadata=None, with_call=False, protocol_options=None):
('routeguide.RouteGuide', 'GetFeature'): Feature.SerializeToString, """A server-to-client streaming RPC.
('routeguide.RouteGuide', 'ListFeatures'): Feature.SerializeToString,
('routeguide.RouteGuide', 'RecordRoute'): RouteSummary.SerializeToString, Obtains the Features available within the given Rectangle. Results are
('routeguide.RouteGuide', 'RouteChat'): RouteNote.SerializeToString, streamed rather than returned at once (e.g. in a response message with a
} repeated field), as the rectangle may cover a large area and contain a
method_implementations = { huge number of features.
('routeguide.RouteGuide', 'GetFeature'): face_utilities.unary_unary_inline(servicer.GetFeature), """
('routeguide.RouteGuide', 'ListFeatures'): face_utilities.unary_stream_inline(servicer.ListFeatures), raise NotImplementedError()
('routeguide.RouteGuide', 'RecordRoute'): face_utilities.stream_unary_inline(servicer.RecordRoute), def RecordRoute(self, request_iterator, timeout, metadata=None, with_call=False, protocol_options=None):
('routeguide.RouteGuide', 'RouteChat'): face_utilities.stream_stream_inline(servicer.RouteChat), """A client-to-server streaming RPC.
}
server_options = beta_implementations.server_options(request_deserializers=request_deserializers, response_serializers=response_serializers, thread_pool=pool, thread_pool_size=pool_size, default_timeout=default_timeout, maximum_timeout=maximum_timeout) Accepts a stream of Points on a route being traversed, returning a
return beta_implementations.server(method_implementations, options=server_options) RouteSummary when traversal is completed.
"""
raise NotImplementedError()
def beta_create_RouteGuide_stub(channel, host=None, metadata_transformer=None, pool=None, pool_size=None): RecordRoute.future = None
request_serializers = { def RouteChat(self, request_iterator, timeout, metadata=None, with_call=False, protocol_options=None):
('routeguide.RouteGuide', 'GetFeature'): Point.SerializeToString, """A Bidirectional streaming RPC.
('routeguide.RouteGuide', 'ListFeatures'): Rectangle.SerializeToString,
('routeguide.RouteGuide', 'RecordRoute'): Point.SerializeToString, Accepts a stream of RouteNotes sent while a route is being traversed,
('routeguide.RouteGuide', 'RouteChat'): RouteNote.SerializeToString, while receiving other RouteNotes (e.g. from other users).
} """
response_deserializers = { raise NotImplementedError()
('routeguide.RouteGuide', 'GetFeature'): Feature.FromString,
('routeguide.RouteGuide', 'ListFeatures'): Feature.FromString,
('routeguide.RouteGuide', 'RecordRoute'): RouteSummary.FromString, def beta_create_RouteGuide_server(servicer, pool=None, pool_size=None, default_timeout=None, maximum_timeout=None):
('routeguide.RouteGuide', 'RouteChat'): RouteNote.FromString, """The Beta API is deprecated for 0.15.0 and later.
}
cardinalities = { It is recommended to use the GA API (classes and functions in this
'GetFeature': cardinality.Cardinality.UNARY_UNARY, file not marked beta) for all further purposes. This function was
'ListFeatures': cardinality.Cardinality.UNARY_STREAM, generated only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0"""
'RecordRoute': cardinality.Cardinality.STREAM_UNARY, request_deserializers = {
'RouteChat': cardinality.Cardinality.STREAM_STREAM, ('routeguide.RouteGuide', 'GetFeature'): Point.FromString,
} ('routeguide.RouteGuide', 'ListFeatures'): Rectangle.FromString,
stub_options = beta_implementations.stub_options(host=host, metadata_transformer=metadata_transformer, request_serializers=request_serializers, response_deserializers=response_deserializers, thread_pool=pool, thread_pool_size=pool_size) ('routeguide.RouteGuide', 'RecordRoute'): Point.FromString,
return beta_implementations.dynamic_stub(channel, 'routeguide.RouteGuide', cardinalities, options=stub_options) ('routeguide.RouteGuide', 'RouteChat'): RouteNote.FromString,
}
response_serializers = {
('routeguide.RouteGuide', 'GetFeature'): Feature.SerializeToString,
('routeguide.RouteGuide', 'ListFeatures'): Feature.SerializeToString,
('routeguide.RouteGuide', 'RecordRoute'): RouteSummary.SerializeToString,
('routeguide.RouteGuide', 'RouteChat'): RouteNote.SerializeToString,
}
method_implementations = {
('routeguide.RouteGuide', 'GetFeature'): face_utilities.unary_unary_inline(servicer.GetFeature),
('routeguide.RouteGuide', 'ListFeatures'): face_utilities.unary_stream_inline(servicer.ListFeatures),
('routeguide.RouteGuide', 'RecordRoute'): face_utilities.stream_unary_inline(servicer.RecordRoute),
('routeguide.RouteGuide', 'RouteChat'): face_utilities.stream_stream_inline(servicer.RouteChat),
}
server_options = beta_implementations.server_options(request_deserializers=request_deserializers, response_serializers=response_serializers, thread_pool=pool, thread_pool_size=pool_size, default_timeout=default_timeout, maximum_timeout=maximum_timeout)
return beta_implementations.server(method_implementations, options=server_options)
def beta_create_RouteGuide_stub(channel, host=None, metadata_transformer=None, pool=None, pool_size=None):
"""The Beta API is deprecated for 0.15.0 and later.
It is recommended to use the GA API (classes and functions in this
file not marked beta) for all further purposes. This function was
generated only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0"""
request_serializers = {
('routeguide.RouteGuide', 'GetFeature'): Point.SerializeToString,
('routeguide.RouteGuide', 'ListFeatures'): Rectangle.SerializeToString,
('routeguide.RouteGuide', 'RecordRoute'): Point.SerializeToString,
('routeguide.RouteGuide', 'RouteChat'): RouteNote.SerializeToString,
}
response_deserializers = {
('routeguide.RouteGuide', 'GetFeature'): Feature.FromString,
('routeguide.RouteGuide', 'ListFeatures'): Feature.FromString,
('routeguide.RouteGuide', 'RecordRoute'): RouteSummary.FromString,
('routeguide.RouteGuide', 'RouteChat'): RouteNote.FromString,
}
cardinalities = {
'GetFeature': cardinality.Cardinality.UNARY_UNARY,
'ListFeatures': cardinality.Cardinality.UNARY_STREAM,
'RecordRoute': cardinality.Cardinality.STREAM_UNARY,
'RouteChat': cardinality.Cardinality.STREAM_STREAM,
}
stub_options = beta_implementations.stub_options(host=host, metadata_transformer=metadata_transformer, request_serializers=request_serializers, response_deserializers=response_deserializers, thread_pool=pool, thread_pool_size=pool_size)
return beta_implementations.dynamic_stub(channel, 'routeguide.RouteGuide', cardinalities, options=stub_options)
except ImportError:
pass
# @@protoc_insertion_point(module_scope) # @@protoc_insertion_point(module_scope)

@ -0,0 +1,114 @@
import grpc
from grpc.framework.common import cardinality
from grpc.framework.interfaces.face import utilities as face_utilities
import route_guide_pb2 as route__guide__pb2
class RouteGuideStub(object):
"""Interface exported by the server.
"""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.GetFeature = channel.unary_unary(
'/routeguide.RouteGuide/GetFeature',
request_serializer=route__guide__pb2.Point.SerializeToString,
response_deserializer=route__guide__pb2.Feature.FromString,
)
self.ListFeatures = channel.unary_stream(
'/routeguide.RouteGuide/ListFeatures',
request_serializer=route__guide__pb2.Rectangle.SerializeToString,
response_deserializer=route__guide__pb2.Feature.FromString,
)
self.RecordRoute = channel.stream_unary(
'/routeguide.RouteGuide/RecordRoute',
request_serializer=route__guide__pb2.Point.SerializeToString,
response_deserializer=route__guide__pb2.RouteSummary.FromString,
)
self.RouteChat = channel.stream_stream(
'/routeguide.RouteGuide/RouteChat',
request_serializer=route__guide__pb2.RouteNote.SerializeToString,
response_deserializer=route__guide__pb2.RouteNote.FromString,
)
class RouteGuideServicer(object):
"""Interface exported by the server.
"""
def GetFeature(self, request, context):
"""A simple RPC.
Obtains the feature at a given position.
A feature with an empty name is returned if there's no feature at the given
position.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def ListFeatures(self, request, context):
"""A server-to-client streaming RPC.
Obtains the Features available within the given Rectangle. Results are
streamed rather than returned at once (e.g. in a response message with a
repeated field), as the rectangle may cover a large area and contain a
huge number of features.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def RecordRoute(self, request_iterator, context):
"""A client-to-server streaming RPC.
Accepts a stream of Points on a route being traversed, returning a
RouteSummary when traversal is completed.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def RouteChat(self, request_iterator, context):
"""A Bidirectional streaming RPC.
Accepts a stream of RouteNotes sent while a route is being traversed,
while receiving other RouteNotes (e.g. from other users).
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_RouteGuideServicer_to_server(servicer, server):
rpc_method_handlers = {
'GetFeature': grpc.unary_unary_rpc_method_handler(
servicer.GetFeature,
request_deserializer=route__guide__pb2.Point.FromString,
response_serializer=route__guide__pb2.Feature.SerializeToString,
),
'ListFeatures': grpc.unary_stream_rpc_method_handler(
servicer.ListFeatures,
request_deserializer=route__guide__pb2.Rectangle.FromString,
response_serializer=route__guide__pb2.Feature.SerializeToString,
),
'RecordRoute': grpc.stream_unary_rpc_method_handler(
servicer.RecordRoute,
request_deserializer=route__guide__pb2.Point.FromString,
response_serializer=route__guide__pb2.RouteSummary.SerializeToString,
),
'RouteChat': grpc.stream_stream_rpc_method_handler(
servicer.RouteChat,
request_deserializer=route__guide__pb2.RouteNote.FromString,
response_serializer=route__guide__pb2.RouteNote.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'routeguide.RouteGuide', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))

@ -36,6 +36,7 @@ import math
import grpc import grpc
import route_guide_pb2 import route_guide_pb2
import route_guide_pb2_grpc
import route_guide_resources import route_guide_resources
_ONE_DAY_IN_SECONDS = 60 * 60 * 24 _ONE_DAY_IN_SECONDS = 60 * 60 * 24
@ -68,7 +69,7 @@ def get_distance(start, end):
R = 6371000; # metres R = 6371000; # metres
return R * c; return R * c;
class RouteGuideServicer(route_guide_pb2.RouteGuideServicer): class RouteGuideServicer(route_guide_pb2_grpc.RouteGuideServicer):
"""Provides methods that implement functionality of route guide server.""" """Provides methods that implement functionality of route guide server."""
def __init__(self): def __init__(self):
@ -125,7 +126,7 @@ class RouteGuideServicer(route_guide_pb2.RouteGuideServicer):
def serve(): def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
route_guide_pb2.add_RouteGuideServicer_to_server( route_guide_pb2_grpc.add_RouteGuideServicer_to_server(
RouteGuideServicer(), server) RouteGuideServicer(), server)
server.add_insecure_port('[::]:50051') server.add_insecure_port('[::]:50051')
server.start() server.start()

@ -724,6 +724,9 @@ pair<bool, grpc::string> PrivateGenerator::GetGrpcServices() {
out = &out_printer; out = &out_printer;
if (generate_in_pb2_grpc) { if (generate_in_pb2_grpc) {
out->Print(
"# Generated by the gRPC Python protocol compiler plugin. "
"DO NOT EDIT!\n");
if (!PrintPreamble()) { if (!PrintPreamble()) {
return make_pair(false, ""); return make_pair(false, "");
} }

@ -39,6 +39,7 @@
#include "src/core/lib/http/httpcli.h" #include "src/core/lib/http/httpcli.h"
#include "src/core/lib/iomgr/polling_entity.h" #include "src/core/lib/iomgr/polling_entity.h"
#include "src/core/lib/security/util/b64.h" #include "src/core/lib/security/util/b64.h"
#include "src/core/lib/support/string.h"
#include "src/core/lib/tsi/ssl_types.h" #include "src/core/lib/tsi/ssl_types.h"
#include <grpc/support/alloc.h> #include <grpc/support/alloc.h>
@ -305,6 +306,17 @@ grpc_jwt_verifier_status grpc_jwt_claims_check(const grpc_jwt_claims *claims,
return GRPC_JWT_VERIFIER_TIME_CONSTRAINT_FAILURE; return GRPC_JWT_VERIFIER_TIME_CONSTRAINT_FAILURE;
} }
/* This should be probably up to the upper layer to decide but let's harcode
the 99% use case here for email issuers, where the JWT must be self
issued. */
if (grpc_jwt_issuer_email_domain(claims->iss) != NULL &&
claims->sub != NULL && strcmp(claims->iss, claims->sub) != 0) {
gpr_log(GPR_ERROR,
"Email issuer (%s) cannot assert another subject (%s) than itself.",
claims->iss, claims->sub);
return GRPC_JWT_VERIFIER_BAD_SUBJECT;
}
if (audience == NULL) { if (audience == NULL) {
audience_ok = claims->aud == NULL; audience_ok = claims->aud == NULL;
} else { } else {
@ -705,10 +717,26 @@ static void verifier_put_mapping(grpc_jwt_verifier *v, const char *email_domain,
GPR_ASSERT(v->num_mappings <= v->allocated_mappings); GPR_ASSERT(v->num_mappings <= v->allocated_mappings);
} }
/* Very non-sophisticated way to detect an email address. Should be good
enough for now... */
const char *grpc_jwt_issuer_email_domain(const char *issuer) {
const char *at_sign = strchr(issuer, '@');
if (at_sign == NULL) return NULL;
const char *email_domain = at_sign + 1;
if (*email_domain == '\0') return NULL;
const char *dot = strrchr(email_domain, '.');
if (dot == NULL || dot == email_domain) return email_domain;
GPR_ASSERT(dot > email_domain);
/* There may be a subdomain, we just want the domain. */
dot = gpr_memrchr(email_domain, '.', (size_t)(dot - email_domain));
if (dot == NULL) return email_domain;
return dot + 1;
}
/* Takes ownership of ctx. */ /* Takes ownership of ctx. */
static void retrieve_key_and_verify(grpc_exec_ctx *exec_ctx, static void retrieve_key_and_verify(grpc_exec_ctx *exec_ctx,
verifier_cb_ctx *ctx) { verifier_cb_ctx *ctx) {
const char *at_sign; const char *email_domain;
grpc_closure *http_cb; grpc_closure *http_cb;
char *path_prefix = NULL; char *path_prefix = NULL;
const char *iss; const char *iss;
@ -733,13 +761,9 @@ static void retrieve_key_and_verify(grpc_exec_ctx *exec_ctx,
Nobody seems to implement the account/email/webfinger part 2. of the spec Nobody seems to implement the account/email/webfinger part 2. of the spec
so we will rely instead on email/url mappings if we detect such an issuer. so we will rely instead on email/url mappings if we detect such an issuer.
Part 4, on the other hand is implemented by both google and salesforce. */ Part 4, on the other hand is implemented by both google and salesforce. */
email_domain = grpc_jwt_issuer_email_domain(iss);
/* Very non-sophisticated way to detect an email address. Should be good if (email_domain != NULL) {
enough for now... */
at_sign = strchr(iss, '@');
if (at_sign != NULL) {
email_key_mapping *mapping; email_key_mapping *mapping;
const char *email_domain = at_sign + 1;
GPR_ASSERT(ctx->verifier != NULL); GPR_ASSERT(ctx->verifier != NULL);
mapping = verifier_get_mapping(ctx->verifier, email_domain); mapping = verifier_get_mapping(ctx->verifier, email_domain);
if (mapping == NULL) { if (mapping == NULL) {

@ -43,8 +43,7 @@
/* --- Constants. --- */ /* --- Constants. --- */
#define GRPC_OPENID_CONFIG_URL_SUFFIX "/.well-known/openid-configuration" #define GRPC_OPENID_CONFIG_URL_SUFFIX "/.well-known/openid-configuration"
#define GRPC_GOOGLE_SERVICE_ACCOUNTS_EMAIL_DOMAIN \ #define GRPC_GOOGLE_SERVICE_ACCOUNTS_EMAIL_DOMAIN "gserviceaccount.com"
"developer.gserviceaccount.com"
#define GRPC_GOOGLE_SERVICE_ACCOUNTS_KEY_URL_PREFIX \ #define GRPC_GOOGLE_SERVICE_ACCOUNTS_KEY_URL_PREFIX \
"www.googleapis.com/robot/v1/metadata/x509" "www.googleapis.com/robot/v1/metadata/x509"
@ -57,6 +56,7 @@ typedef enum {
GRPC_JWT_VERIFIER_BAD_AUDIENCE, GRPC_JWT_VERIFIER_BAD_AUDIENCE,
GRPC_JWT_VERIFIER_KEY_RETRIEVAL_ERROR, GRPC_JWT_VERIFIER_KEY_RETRIEVAL_ERROR,
GRPC_JWT_VERIFIER_TIME_CONSTRAINT_FAILURE, GRPC_JWT_VERIFIER_TIME_CONSTRAINT_FAILURE,
GRPC_JWT_VERIFIER_BAD_SUBJECT,
GRPC_JWT_VERIFIER_GENERIC_ERROR GRPC_JWT_VERIFIER_GENERIC_ERROR
} grpc_jwt_verifier_status; } grpc_jwt_verifier_status;
@ -132,5 +132,6 @@ void grpc_jwt_verifier_verify(grpc_exec_ctx *exec_ctx,
grpc_jwt_claims *grpc_jwt_claims_from_json(grpc_json *json, grpc_slice buffer); grpc_jwt_claims *grpc_jwt_claims_from_json(grpc_json *json, grpc_slice buffer);
grpc_jwt_verifier_status grpc_jwt_claims_check(const grpc_jwt_claims *claims, grpc_jwt_verifier_status grpc_jwt_claims_check(const grpc_jwt_claims *claims,
const char *audience); const char *audience);
const char *grpc_jwt_issuer_email_domain(const char *issuer);
#endif /* GRPC_CORE_LIB_SECURITY_CREDENTIALS_JWT_JWT_VERIFIER_H */ #endif /* GRPC_CORE_LIB_SECURITY_CREDENTIALS_JWT_JWT_VERIFIER_H */

@ -275,3 +275,15 @@ int gpr_stricmp(const char *a, const char *b) {
} while (ca == cb && ca && cb); } while (ca == cb && ca && cb);
return ca - cb; return ca - cb;
} }
void *gpr_memrchr(const void *s, int c, size_t n) {
if (s == NULL) return NULL;
char *b = (char *)s;
size_t i;
for (i = 0; i < n; i++) {
if (b[n - i - 1] == c) {
return &b[n - i - 1];
}
}
return NULL;
}

@ -118,6 +118,8 @@ char *gpr_strvec_flatten(gpr_strvec *strs, size_t *total_length);
lower(a)==lower(b), >0 if lower(a)>lower(b) */ lower(a)==lower(b), >0 if lower(a)>lower(b) */
int gpr_stricmp(const char *a, const char *b); int gpr_stricmp(const char *a, const char *b);
void *gpr_memrchr(const void *s, int c, size_t n);
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif

@ -53,7 +53,7 @@ int grpc_header_key_is_legal(const char *key, size_t length) {
0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0xff, 0x03, 0x00, 0x00, 0x00,
0x80, 0xfe, 0xff, 0xff, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xfe, 0xff, 0xff, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
if (length == 0) { if (length == 0 || key[0] == ':') {
return 0; return 0;
} }
return conforms_to(key, length, legal_header_bits); return conforms_to(key, length, legal_header_bits);

@ -62,7 +62,7 @@ abstract class AbstractCall
Channel $channel, Channel $channel,
$method, $method,
$deserialize, $deserialize,
$options = [] array $options = []
) { ) {
if (array_key_exists('timeout', $options) && if (array_key_exists('timeout', $options) &&
is_numeric($timeout = $options['timeout']) is_numeric($timeout = $options['timeout'])
@ -89,7 +89,7 @@ abstract class AbstractCall
} }
/** /**
* @return mixed The metadata sent by the server. * @return mixed The metadata sent by the server
*/ */
public function getMetadata() public function getMetadata()
{ {
@ -97,7 +97,7 @@ abstract class AbstractCall
} }
/** /**
* @return mixed The trailing metadata sent by the server. * @return mixed The trailing metadata sent by the server
*/ */
public function getTrailingMetadata() public function getTrailingMetadata()
{ {
@ -105,7 +105,7 @@ abstract class AbstractCall
} }
/** /**
* @return string The URI of the endpoint. * @return string The URI of the endpoint
*/ */
public function getPeer() public function getPeer()
{ {
@ -167,8 +167,7 @@ abstract class AbstractCall
/** /**
* Set the CallCredentials for the underlying Call. * Set the CallCredentials for the underlying Call.
* *
* @param CallCredentials $call_credentials The CallCredentials * @param CallCredentials $call_credentials The CallCredentials object
* object
*/ */
public function setCallCredentials($call_credentials) public function setCallCredentials($call_credentials)
{ {

@ -48,14 +48,14 @@ class BaseStub
private $update_metadata; private $update_metadata;
/** /**
* @param $hostname string * @param string $hostname
* @param $opts array * @param array $opts
* - 'update_metadata': (optional) a callback function which takes in a * - 'update_metadata': (optional) a callback function which takes in a
* metadata array, and returns an updated metadata array * metadata array, and returns an updated metadata array
* - 'grpc.primary_user_agent': (optional) a user-agent string * - 'grpc.primary_user_agent': (optional) a user-agent string
* @param $channel Channel An already created Channel object * @param Channel $channel An already created Channel object (optional)
*/ */
public function __construct($hostname, $opts, $channel = null) public function __construct($hostname, $opts, Channel $channel = null)
{ {
$ssl_roots = file_get_contents( $ssl_roots = file_get_contents(
dirname(__FILE__).'/../../../../etc/roots.pem'); dirname(__FILE__).'/../../../../etc/roots.pem');
@ -98,7 +98,7 @@ class BaseStub
} }
/** /**
* @return string The URI of the endpoint. * @return string The URI of the endpoint
*/ */
public function getTarget() public function getTarget()
{ {
@ -106,7 +106,7 @@ class BaseStub
} }
/** /**
* @param $try_to_connect bool * @param bool $try_to_connect (optional)
* *
* @return int The grpc connectivity state * @return int The grpc connectivity state
*/ */
@ -145,6 +145,12 @@ class BaseStub
return $this->_checkConnectivityState($new_state); return $this->_checkConnectivityState($new_state);
} }
/**
* @param $new_state Connect state
*
* @return bool true if state is CHANNEL_READY
* @throw Exception if state is CHANNEL_FATAL_FAILURE
*/
private function _checkConnectivityState($new_state) private function _checkConnectivityState($new_state)
{ {
if ($new_state == \Grpc\CHANNEL_READY) { if ($new_state == \Grpc\CHANNEL_READY) {
@ -167,6 +173,10 @@ class BaseStub
/** /**
* constructs the auth uri for the jwt. * constructs the auth uri for the jwt.
*
* @param string $method The method string
*
* @return string The URL string
*/ */
private function _get_jwt_aud_uri($method) private function _get_jwt_aud_uri($method)
{ {
@ -191,7 +201,7 @@ class BaseStub
* *
* @param array $metadata The metadata map * @param array $metadata The metadata map
* *
* @return $metadata Validated and key-normalized metadata map * @return array $metadata Validated and key-normalized metadata map
* @throw InvalidArgumentException if key contains invalid characters * @throw InvalidArgumentException if key contains invalid characters
*/ */
private function _validate_and_normalize_metadata($metadata) private function _validate_and_normalize_metadata($metadata)
@ -220,14 +230,16 @@ class BaseStub
* @param mixed $argument The argument to the method * @param mixed $argument The argument to the method
* @param callable $deserialize A function that deserializes the response * @param callable $deserialize A function that deserializes the response
* @param array $metadata A metadata map to send to the server * @param array $metadata A metadata map to send to the server
* (optional)
* @param array $options An array of options (optional)
* *
* @return SimpleSurfaceActiveCall The active call object * @return SimpleSurfaceActiveCall The active call object
*/ */
public function _simpleRequest($method, public function _simpleRequest($method,
$argument, $argument,
$deserialize, $deserialize,
$metadata = [], array $metadata = [],
$options = []) array $options = [])
{ {
$call = new UnaryCall($this->channel, $call = new UnaryCall($this->channel,
$method, $method,
@ -251,17 +263,17 @@ class BaseStub
* output. * output.
* *
* @param string $method The name of the method to call * @param string $method The name of the method to call
* @param array $arguments An array or Traversable of arguments to stream to the
* server
* @param callable $deserialize A function that deserializes the response * @param callable $deserialize A function that deserializes the response
* @param array $metadata A metadata map to send to the server * @param array $metadata A metadata map to send to the server
* (optional)
* @param array $options An array of options (optional)
* *
* @return ClientStreamingSurfaceActiveCall The active call object * @return ClientStreamingSurfaceActiveCall The active call object
*/ */
public function _clientStreamRequest($method, public function _clientStreamRequest($method,
callable $deserialize, callable $deserialize,
$metadata = [], array $metadata = [],
$options = []) array $options = [])
{ {
$call = new ClientStreamingCall($this->channel, $call = new ClientStreamingCall($this->channel,
$method, $method,
@ -281,21 +293,23 @@ class BaseStub
} }
/** /**
* Call a remote method that takes a single argument and returns a stream of * Call a remote method that takes a single argument and returns a stream
* responses. * of responses.
* *
* @param string $method The name of the method to call * @param string $method The name of the method to call
* @param mixed $argument The argument to the method * @param mixed $argument The argument to the method
* @param callable $deserialize A function that deserializes the responses * @param callable $deserialize A function that deserializes the responses
* @param array $metadata A metadata map to send to the server * @param array $metadata A metadata map to send to the server
* (optional)
* @param array $options An array of options (optional)
* *
* @return ServerStreamingSurfaceActiveCall The active call object * @return ServerStreamingSurfaceActiveCall The active call object
*/ */
public function _serverStreamRequest($method, public function _serverStreamRequest($method,
$argument, $argument,
callable $deserialize, callable $deserialize,
$metadata = [], array $metadata = [],
$options = []) array $options = [])
{ {
$call = new ServerStreamingCall($this->channel, $call = new ServerStreamingCall($this->channel,
$method, $method,
@ -320,13 +334,15 @@ class BaseStub
* @param string $method The name of the method to call * @param string $method The name of the method to call
* @param callable $deserialize A function that deserializes the responses * @param callable $deserialize A function that deserializes the responses
* @param array $metadata A metadata map to send to the server * @param array $metadata A metadata map to send to the server
* (optional)
* @param array $options An array of options (optional)
* *
* @return BidiStreamingSurfaceActiveCall The active call object * @return BidiStreamingSurfaceActiveCall The active call object
*/ */
public function _bidiRequest($method, public function _bidiRequest($method,
callable $deserialize, callable $deserialize,
$metadata = [], array $metadata = [],
$options = []) array $options = [])
{ {
$call = new BidiStreamingCall($this->channel, $call = new BidiStreamingCall($this->channel,
$method, $method,

@ -35,8 +35,8 @@
namespace Grpc; namespace Grpc;
/** /**
* Represents an active call that allows for sending and recieving messages in * Represents an active call that allows for sending and recieving messages
* streams in any order. * in streams in any order.
*/ */
class BidiStreamingCall extends AbstractCall class BidiStreamingCall extends AbstractCall
{ {
@ -44,6 +44,7 @@ class BidiStreamingCall extends AbstractCall
* Start the call. * Start the call.
* *
* @param array $metadata Metadata to send with the call, if applicable * @param array $metadata Metadata to send with the call, if applicable
* (optional)
*/ */
public function start(array $metadata = []) public function start(array $metadata = [])
{ {
@ -76,10 +77,10 @@ class BidiStreamingCall extends AbstractCall
* writesDone is called. * writesDone is called.
* *
* @param ByteBuffer $data The data to write * @param ByteBuffer $data The data to write
* @param array $options an array of options, possible keys: * @param array $options An array of options, possible keys:
* 'flags' => a number * 'flags' => a number (optional)
*/ */
public function write($data, $options = []) public function write($data, array $options = [])
{ {
$message_array = ['message' => $this->serializeMessage($data)]; $message_array = ['message' => $this->serializeMessage($data)];
if (array_key_exists('flags', $options)) { if (array_key_exists('flags', $options)) {
@ -103,8 +104,8 @@ class BidiStreamingCall extends AbstractCall
/** /**
* Wait for the server to send the status, and return it. * Wait for the server to send the status, and return it.
* *
* @return \stdClass The status object, with integer $code, string $details, * @return \stdClass The status object, with integer $code, string
* and array $metadata members * $details, and array $metadata members
*/ */
public function getStatus() public function getStatus()
{ {

@ -35,8 +35,8 @@
namespace Grpc; namespace Grpc;
/** /**
* Represents an active call that sends a stream of messages and then gets a * Represents an active call that sends a stream of messages and then gets
* single response. * a single response.
*/ */
class ClientStreamingCall extends AbstractCall class ClientStreamingCall extends AbstractCall
{ {
@ -44,8 +44,9 @@ class ClientStreamingCall extends AbstractCall
* Start the call. * Start the call.
* *
* @param array $metadata Metadata to send with the call, if applicable * @param array $metadata Metadata to send with the call, if applicable
* (optional)
*/ */
public function start($metadata = []) public function start(array $metadata = [])
{ {
$this->call->startBatch([ $this->call->startBatch([
OP_SEND_INITIAL_METADATA => $metadata, OP_SEND_INITIAL_METADATA => $metadata,
@ -57,8 +58,8 @@ class ClientStreamingCall extends AbstractCall
* wait is called. * wait is called.
* *
* @param ByteBuffer $data The data to write * @param ByteBuffer $data The data to write
* @param array $options an array of options, possible keys: * @param array $options An array of options, possible keys:
* 'flags' => a number * 'flags' => a number (optional)
*/ */
public function write($data, array $options = []) public function write($data, array $options = [])
{ {

@ -35,8 +35,8 @@
namespace Grpc; namespace Grpc;
/** /**
* Represents an active call that sends a single message and then gets a stream * Represents an active call that sends a single message and then gets a
* of responses. * stream of responses.
*/ */
class ServerStreamingCall extends AbstractCall class ServerStreamingCall extends AbstractCall
{ {
@ -45,10 +45,11 @@ class ServerStreamingCall extends AbstractCall
* *
* @param mixed $data The data to send * @param mixed $data The data to send
* @param array $metadata Metadata to send with the call, if applicable * @param array $metadata Metadata to send with the call, if applicable
* @param array $options an array of options, possible keys: * (optional)
* 'flags' => a number * @param array $options An array of options, possible keys:
* 'flags' => a number (optional)
*/ */
public function start($data, $metadata = [], $options = []) public function start($data, array $metadata = [], array $options = [])
{ {
$message_array = ['message' => $this->serializeMessage($data)]; $message_array = ['message' => $this->serializeMessage($data)];
if (array_key_exists('flags', $options)) { if (array_key_exists('flags', $options)) {
@ -82,8 +83,8 @@ class ServerStreamingCall extends AbstractCall
/** /**
* Wait for the server to send the status, and return it. * Wait for the server to send the status, and return it.
* *
* @return \stdClass The status object, with integer $code, string $details, * @return \stdClass The status object, with integer $code, string
* and array $metadata members * $details, and array $metadata members
*/ */
public function getStatus() public function getStatus()
{ {

@ -35,8 +35,8 @@
namespace Grpc; namespace Grpc;
/** /**
* Represents an active call that sends a single message and then gets a single * Represents an active call that sends a single message and then gets a
* response. * single response.
*/ */
class UnaryCall extends AbstractCall class UnaryCall extends AbstractCall
{ {
@ -45,10 +45,11 @@ class UnaryCall extends AbstractCall
* *
* @param mixed $data The data to send * @param mixed $data The data to send
* @param array $metadata Metadata to send with the call, if applicable * @param array $metadata Metadata to send with the call, if applicable
* @param array $options an array of options, possible keys: * (optional)
* 'flags' => a number * @param array $options An array of options, possible keys:
* 'flags' => a number (optional)
*/ */
public function start($data, $metadata = [], $options = []) public function start($data, array $metadata = [], array $options = [])
{ {
$message_array = ['message' => $this->serializeMessage($data)]; $message_array = ['message' => $this->serializeMessage($data)];
if (isset($options['flags'])) { if (isset($options['flags'])) {

@ -62,6 +62,7 @@ napoleon_numpy_docstring = True
napoleon_include_special_with_doc = True napoleon_include_special_with_doc = True
html_theme = 'sphinx_rtd_theme' html_theme = 'sphinx_rtd_theme'
copyright = "2016, The gRPC Authors"
""" """
API_GLOSSARY = """ API_GLOSSARY = """

@ -35,13 +35,13 @@ import unittest
import grpc import grpc
from src.proto.grpc.testing import test_pb2 from src.proto.grpc.testing import test_pb2
from tests.interop import _interop_test_case from tests.interop import _intraop_test_case
from tests.interop import methods from tests.interop import methods
from tests.interop import server from tests.interop import server
class InsecureInteropTest( class InsecureIntraopTest(
_interop_test_case.InteropTestCase, _intraop_test_case.IntraopTestCase,
unittest.TestCase): unittest.TestCase):
def setUp(self): def setUp(self):

@ -32,7 +32,7 @@
from tests.interop import methods from tests.interop import methods
class InteropTestCase(object): class IntraopTestCase(object):
"""Unit test methods. """Unit test methods.
This class must be mixed in with unittest.TestCase and a class that defines This class must be mixed in with unittest.TestCase and a class that defines

@ -35,15 +35,15 @@ import unittest
import grpc import grpc
from src.proto.grpc.testing import test_pb2 from src.proto.grpc.testing import test_pb2
from tests.interop import _interop_test_case from tests.interop import _intraop_test_case
from tests.interop import methods from tests.interop import methods
from tests.interop import resources from tests.interop import resources
_SERVER_HOST_OVERRIDE = 'foo.test.google.fr' _SERVER_HOST_OVERRIDE = 'foo.test.google.fr'
class SecureInteropTest( class SecureIntraopTest(
_interop_test_case.InteropTestCase, _intraop_test_case.IntraopTestCase,
unittest.TestCase): unittest.TestCase):
def setUp(self): def setUp(self):

@ -1,7 +1,7 @@
[ [
"health_check._health_servicer_test.HealthServicerTest", "health_check._health_servicer_test.HealthServicerTest",
"interop._insecure_interop_test.InsecureInteropTest", "interop._insecure_intraop_test.InsecureIntraopTest",
"interop._secure_interop_test.SecureInteropTest", "interop._secure_intraop_test.SecureIntraopTest",
"protoc_plugin._python_plugin_test.PythonPluginTest", "protoc_plugin._python_plugin_test.PythonPluginTest",
"protoc_plugin._split_definitions_test.SameCommonTest", "protoc_plugin._split_definitions_test.SameCommonTest",
"protoc_plugin._split_definitions_test.SameSeparateTest", "protoc_plugin._split_definitions_test.SameSeparateTest",

@ -573,6 +573,29 @@ static void test_recv_close_on_server_twice() {
cleanup_test(); cleanup_test();
} }
static void test_invalid_initial_metadata_reserved_key() {
gpr_log(GPR_INFO, "test_invalid_initial_metadata_reserved_key");
grpc_metadata metadata;
metadata.key = ":start_with_colon";
metadata.value = "value";
metadata.value_length = 6;
grpc_op *op;
prepare_test(1);
op = g_state.ops;
op->op = GRPC_OP_SEND_INITIAL_METADATA;
op->data.send_initial_metadata.count = 1;
op->data.send_initial_metadata.metadata = &metadata;
op->flags = 0;
op->reserved = NULL;
op++;
GPR_ASSERT(GRPC_CALL_ERROR_INVALID_METADATA ==
grpc_call_start_batch(g_state.call, g_state.ops,
(size_t)(op - g_state.ops), tag(1), NULL));
cleanup_test();
}
int main(int argc, char **argv) { int main(int argc, char **argv) {
grpc_test_init(argc, argv); grpc_test_init(argc, argv);
grpc_init(); grpc_init();
@ -595,6 +618,7 @@ int main(int argc, char **argv) {
test_send_server_status_twice(); test_send_server_status_twice();
test_recv_close_on_server_with_invalid_flags(); test_recv_close_on_server_with_invalid_flags();
test_recv_close_on_server_twice(); test_recv_close_on_server_twice();
test_invalid_initial_metadata_reserved_key();
grpc_shutdown(); grpc_shutdown();
return 0; return 0;

@ -72,6 +72,7 @@ int main(int argc, char **argv) {
char *scope = NULL; char *scope = NULL;
char *json_key_file_path = NULL; char *json_key_file_path = NULL;
char *service_url = NULL; char *service_url = NULL;
grpc_init();
gpr_cmdline *cl = gpr_cmdline_create("create_jwt"); gpr_cmdline *cl = gpr_cmdline_create("create_jwt");
gpr_cmdline_add_string(cl, "json_key", "File path of the json key.", gpr_cmdline_add_string(cl, "json_key", "File path of the json key.",
&json_key_file_path); &json_key_file_path);
@ -102,5 +103,6 @@ int main(int argc, char **argv) {
create_jwt(json_key_file_path, service_url, scope); create_jwt(json_key_file_path, service_url, scope);
gpr_cmdline_destroy(cl); gpr_cmdline_destroy(cl);
grpc_shutdown();
return 0; return 0;
} }

@ -166,6 +166,13 @@ static const char claims_without_time_constraint[] =
" \"jti\": \"jwtuniqueid\"," " \"jti\": \"jwtuniqueid\","
" \"foo\": \"bar\"}"; " \"foo\": \"bar\"}";
static const char claims_with_bad_subject[] =
"{ \"aud\": \"https://foo.com\","
" \"iss\": \"evil@blah.foo.com\","
" \"sub\": \"juju@blah.foo.com\","
" \"jti\": \"jwtuniqueid\","
" \"foo\": \"bar\"}";
static const char invalid_claims[] = static const char invalid_claims[] =
"{ \"aud\": \"https://foo.com\"," "{ \"aud\": \"https://foo.com\","
" \"iss\": 46," /* Issuer cannot be a number. */ " \"iss\": 46," /* Issuer cannot be a number. */
@ -179,6 +186,38 @@ typedef struct {
const char *expected_subject; const char *expected_subject;
} verifier_test_config; } verifier_test_config;
static void test_jwt_issuer_email_domain(void) {
const char *d = grpc_jwt_issuer_email_domain("https://foo.com");
GPR_ASSERT(d == NULL);
d = grpc_jwt_issuer_email_domain("foo.com");
GPR_ASSERT(d == NULL);
d = grpc_jwt_issuer_email_domain("");
GPR_ASSERT(d == NULL);
d = grpc_jwt_issuer_email_domain("@");
GPR_ASSERT(d == NULL);
d = grpc_jwt_issuer_email_domain("bar@foo");
GPR_ASSERT(strcmp(d, "foo") == 0);
d = grpc_jwt_issuer_email_domain("bar@foo.com");
GPR_ASSERT(strcmp(d, "foo.com") == 0);
d = grpc_jwt_issuer_email_domain("bar@blah.foo.com");
GPR_ASSERT(strcmp(d, "foo.com") == 0);
d = grpc_jwt_issuer_email_domain("bar.blah@blah.foo.com");
GPR_ASSERT(strcmp(d, "foo.com") == 0);
d = grpc_jwt_issuer_email_domain("bar.blah@baz.blah.foo.com");
GPR_ASSERT(strcmp(d, "foo.com") == 0);
/* This is not a very good parser but make sure we do not crash on these weird
inputs. */
d = grpc_jwt_issuer_email_domain("@foo");
GPR_ASSERT(strcmp(d, "foo") == 0);
d = grpc_jwt_issuer_email_domain("bar@.");
GPR_ASSERT(d != NULL);
d = grpc_jwt_issuer_email_domain("bar@..");
GPR_ASSERT(d != NULL);
d = grpc_jwt_issuer_email_domain("bar@...");
GPR_ASSERT(d != NULL);
}
static void test_claims_success(void) { static void test_claims_success(void) {
grpc_jwt_claims *claims; grpc_jwt_claims *claims;
grpc_slice s = grpc_slice_from_copied_string(claims_without_time_constraint); grpc_slice s = grpc_slice_from_copied_string(claims_without_time_constraint);
@ -242,6 +281,19 @@ static void test_bad_audience_claims_failure(void) {
grpc_jwt_claims_destroy(claims); grpc_jwt_claims_destroy(claims);
} }
static void test_bad_subject_claims_failure(void) {
grpc_jwt_claims *claims;
grpc_slice s = grpc_slice_from_copied_string(claims_with_bad_subject);
grpc_json *json = grpc_json_parse_string_with_len(
(char *)GRPC_SLICE_START_PTR(s), GRPC_SLICE_LENGTH(s));
GPR_ASSERT(json != NULL);
claims = grpc_jwt_claims_from_json(json, s);
GPR_ASSERT(claims != NULL);
GPR_ASSERT(grpc_jwt_claims_check(claims, "https://foo.com") ==
GRPC_JWT_VERIFIER_BAD_SUBJECT);
grpc_jwt_claims_destroy(claims);
}
static char *json_key_str(const char *last_part) { static char *json_key_str(const char *last_part) {
size_t result_len = strlen(json_key_str_part1) + strlen(json_key_str_part2) + size_t result_len = strlen(json_key_str_part1) + strlen(json_key_str_part2) +
strlen(last_part); strlen(last_part);
@ -563,10 +615,12 @@ static void test_jwt_verifier_bad_format(void) {
int main(int argc, char **argv) { int main(int argc, char **argv) {
grpc_test_init(argc, argv); grpc_test_init(argc, argv);
grpc_init(); grpc_init();
test_jwt_issuer_email_domain();
test_claims_success(); test_claims_success();
test_expired_claims_failure(); test_expired_claims_failure();
test_invalid_claims_failure(); test_invalid_claims_failure();
test_bad_audience_claims_failure(); test_bad_audience_claims_failure();
test_bad_subject_claims_failure();
test_jwt_verifier_google_email_issuer_success(); test_jwt_verifier_google_email_issuer_success();
test_jwt_verifier_custom_email_issuer_success(); test_jwt_verifier_custom_email_issuer_success();
test_jwt_verifier_url_issuer_success(); test_jwt_verifier_url_issuer_success();

@ -93,6 +93,7 @@ int main(int argc, char **argv) {
char *aud = NULL; char *aud = NULL;
grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
grpc_init();
cl = gpr_cmdline_create("JWT verifier tool"); cl = gpr_cmdline_create("JWT verifier tool");
gpr_cmdline_add_string(cl, "jwt", "JSON web token to verify", &jwt); gpr_cmdline_add_string(cl, "jwt", "JSON web token to verify", &jwt);
gpr_cmdline_add_string(cl, "aud", "Audience for the JWT", &aud); gpr_cmdline_add_string(cl, "aud", "Audience for the JWT", &aud);
@ -131,5 +132,6 @@ int main(int argc, char **argv) {
grpc_jwt_verifier_destroy(verifier); grpc_jwt_verifier_destroy(verifier);
gpr_cmdline_destroy(cl); gpr_cmdline_destroy(cl);
grpc_shutdown();
return !sync.success; return !sync.success;
} }

@ -243,6 +243,8 @@ static void test_int64toa() {
static void test_leftpad() { static void test_leftpad() {
char *padded; char *padded;
LOG_TEST_NAME("test_leftpad");
padded = gpr_leftpad("foo", ' ', 5); padded = gpr_leftpad("foo", ' ', 5);
GPR_ASSERT(0 == strcmp(" foo", padded)); GPR_ASSERT(0 == strcmp(" foo", padded));
gpr_free(padded); gpr_free(padded);
@ -273,12 +275,25 @@ static void test_leftpad() {
} }
static void test_stricmp(void) { static void test_stricmp(void) {
LOG_TEST_NAME("test_stricmp");
GPR_ASSERT(0 == gpr_stricmp("hello", "hello")); GPR_ASSERT(0 == gpr_stricmp("hello", "hello"));
GPR_ASSERT(0 == gpr_stricmp("HELLO", "hello")); GPR_ASSERT(0 == gpr_stricmp("HELLO", "hello"));
GPR_ASSERT(gpr_stricmp("a", "b") < 0); GPR_ASSERT(gpr_stricmp("a", "b") < 0);
GPR_ASSERT(gpr_stricmp("b", "a") > 0); GPR_ASSERT(gpr_stricmp("b", "a") > 0);
} }
static void test_memrchr(void) {
LOG_TEST_NAME("test_memrchr");
GPR_ASSERT(NULL == gpr_memrchr(NULL, 'a', 0));
GPR_ASSERT(NULL == gpr_memrchr("", 'a', 0));
GPR_ASSERT(NULL == gpr_memrchr("hello", 'b', 5));
GPR_ASSERT(0 == strcmp((const char *)gpr_memrchr("hello", 'h', 5), "hello"));
GPR_ASSERT(0 == strcmp((const char *)gpr_memrchr("hello", 'o', 5), "o"));
GPR_ASSERT(0 == strcmp((const char *)gpr_memrchr("hello", 'l', 5), "lo"));
}
int main(int argc, char **argv) { int main(int argc, char **argv) {
grpc_test_init(argc, argv); grpc_test_init(argc, argv);
test_strdup(); test_strdup();
@ -291,5 +306,6 @@ int main(int argc, char **argv) {
test_int64toa(); test_int64toa();
test_leftpad(); test_leftpad();
test_stricmp(); test_stricmp();
test_memrchr();
return 0; return 0;
} }

@ -92,9 +92,20 @@ LICENSE_PREFIX = {
'LICENSE': '', 'LICENSE': '',
} }
KNOWN_BAD = set([ _EXEMPT = frozenset((
# Generated protocol compiler output.
'examples/python/helloworld/helloworld_pb2.py',
'examples/python/helloworld/helloworld_pb2_grpc.py',
'examples/python/multiplex/helloworld_pb2.py',
'examples/python/multiplex/helloworld_pb2_grpc.py',
'examples/python/multiplex/route_guide_pb2.py',
'examples/python/multiplex/route_guide_pb2_grpc.py',
'examples/python/route_guide/route_guide_pb2.py',
'examples/python/route_guide/route_guide_pb2_grpc.py',
# An older file originally from outside gRPC.
'src/php/tests/bootstrap.php', 'src/php/tests/bootstrap.php',
]) ))
RE_YEAR = r'Copyright (?P<first_year>[0-9]+\-)?(?P<last_year>[0-9]+), Google Inc\.' RE_YEAR = r'Copyright (?P<first_year>[0-9]+\-)?(?P<last_year>[0-9]+), Google Inc\.'
@ -140,7 +151,8 @@ except subprocess.CalledProcessError:
sys.exit(0) sys.exit(0)
for filename in filename_list: for filename in filename_list:
if filename in KNOWN_BAD: continue if filename in _EXEMPT:
continue
ext = os.path.splitext(filename)[1] ext = os.path.splitext(filename)[1]
base = os.path.basename(filename) base = os.path.basename(filename)
if ext in RE_LICENSE: if ext in RE_LICENSE:

@ -94,6 +94,7 @@ if args.submit:
# specified repository, edit it, and push it. It's up to the user to then go # specified repository, edit it, and push it. It's up to the user to then go
# onto GitHub and make a PR against grpc/grpc:gh-pages. # onto GitHub and make a PR against grpc/grpc:gh-pages.
repo_parent_dir = tempfile.mkdtemp() repo_parent_dir = tempfile.mkdtemp()
print('Documentation parent directory: {}'.format(repo_parent_dir))
repo_dir = os.path.join(repo_parent_dir, 'grpc') repo_dir = os.path.join(repo_parent_dir, 'grpc')
python_doc_dir = os.path.join(repo_dir, 'python') python_doc_dir = os.path.join(repo_dir, 'python')
doc_branch = args.doc_branch doc_branch = args.doc_branch

Loading…
Cancel
Save