Resolved merge conflicts with master

pull/3558/head
murgatroid99 9 years ago
commit cc545461c0
  1. 1
      .gitignore
  2. 9
      BUILD
  3. 4
      Makefile
  4. 38
      README.md
  5. 2729
      build.json
  6. 3
      build.yaml
  7. 2
      examples/csharp/helloworld/.nuget/packages.config
  8. 14
      examples/csharp/helloworld/Greeter/Greeter.csproj
  9. 6
      examples/csharp/helloworld/Greeter/packages.config
  10. 14
      examples/csharp/helloworld/GreeterClient/GreeterClient.csproj
  11. 6
      examples/csharp/helloworld/GreeterClient/packages.config
  12. 14
      examples/csharp/helloworld/GreeterServer/GreeterServer.csproj
  13. 6
      examples/csharp/helloworld/GreeterServer/packages.config
  14. 46
      examples/csharp/helloworld/README.md
  15. 2
      examples/csharp/route_guide/.nuget/packages.config
  16. 388
      examples/csharp/route_guide/README.md
  17. 16
      examples/csharp/route_guide/RouteGuide/RouteGuide.csproj
  18. 8
      examples/csharp/route_guide/RouteGuide/packages.config
  19. 6
      examples/csharp/route_guide/RouteGuideClient/App.config
  20. 19
      examples/csharp/route_guide/RouteGuideClient/RouteGuideClient.csproj
  21. 7
      examples/csharp/route_guide/RouteGuideClient/packages.config
  22. 6
      examples/csharp/route_guide/RouteGuideServer/App.config
  23. 19
      examples/csharp/route_guide/RouteGuideServer/RouteGuideServer.csproj
  24. 7
      examples/csharp/route_guide/RouteGuideServer/packages.config
  25. 19
      examples/node/README.md
  26. 2
      examples/node/package.json
  27. 364
      examples/node/route_guide/README.md
  28. 3
      examples/php/README.md
  29. 2
      examples/php/composer.json
  30. 3
      examples/php/greeter_client.php
  31. 14
      examples/php/helloworld.php
  32. 264
      examples/php/route_guide/README.md
  33. 2
      examples/php/route_guide/route_guide.php
  34. 45
      examples/php/route_guide/route_guide_client.php
  35. 4
      examples/php/route_guide/run_route_guide_client.sh
  36. 5
      examples/php/run_greeter_client.sh
  37. 2
      examples/ruby/Gemfile
  38. 8
      examples/ruby/README.md
  39. 4
      examples/ruby/greeter_server.rb
  40. 4
      examples/ruby/grpc-demo.gemspec
  41. 30
      examples/ruby/lib/route_guide.rb
  42. 6
      examples/ruby/lib/route_guide_services.rb
  43. 287
      examples/ruby/route_guide/README.md
  44. 2
      examples/ruby/route_guide/route_guide_client.rb
  45. 6
      examples/ruby/route_guide/route_guide_server.rb
  46. 12
      gRPC.podspec
  47. 4
      grpc.gyp
  48. 2
      include/grpc/support/port_platform.h
  49. 3
      include/grpc/support/slice_buffer.h
  50. 3
      src/core/README.md
  51. 4
      src/core/census/grpc_context.c
  52. 13
      src/core/channel/client_channel.c
  53. 13
      src/core/channel/compress_filter.c
  54. 13
      src/core/channel/connected_channel.c
  55. 14
      src/core/channel/noop_filter.c
  56. 9
      src/core/client_config/lb_policies/pick_first.c
  57. 9
      src/core/client_config/lb_policies/round_robin.c
  58. 2
      src/core/client_config/resolvers/zookeeper_resolver.c
  59. 46
      src/core/client_config/subchannel.c
  60. 7
      src/core/client_config/subchannel.h
  61. 13
      src/core/compression/algorithm.c
  62. 2
      src/core/iomgr/exec_ctx.h
  63. 13
      src/core/iomgr/iocp_windows.c
  64. 7
      src/core/iomgr/iomgr.c
  65. 7
      src/core/iomgr/iomgr_posix.c
  66. 4
      src/core/iomgr/iomgr_windows.c
  67. 29
      src/core/iomgr/pollset_multipoller_with_epoll.c
  68. 22
      src/core/iomgr/pollset_multipoller_with_poll_posix.c
  69. 54
      src/core/iomgr/pollset_posix.c
  70. 1
      src/core/iomgr/pollset_posix.h
  71. 76
      src/core/iomgr/pollset_windows.c
  72. 14
      src/core/iomgr/tcp_client_posix.c
  73. 4
      src/core/iomgr/tcp_posix.c
  74. 2
      src/core/iomgr/tcp_server_windows.c
  75. 6
      src/core/iomgr/tcp_windows.c
  76. 4
      src/core/iomgr/udp_server.c
  77. 9
      src/core/security/client_auth_filter.c
  78. 45
      src/core/security/credentials.c
  79. 4
      src/core/security/google_default_credentials.c
  80. 5
      src/core/security/secure_endpoint.c
  81. 24
      src/core/security/security_context.c
  82. 9
      src/core/security/server_auth_filter.c
  83. 6
      src/core/security/server_secure_chttp2.c
  84. 4
      src/core/statistics/census_rpc_stats.c
  85. 7
      src/core/statistics/census_tracing.c
  86. 3
      src/core/support/slice_buffer.c
  87. 4
      src/core/surface/api_trace.c
  88. 65
      src/core/surface/api_trace.h
  89. 13
      src/core/surface/call.c
  90. 10
      src/core/surface/call.h
  91. 4
      src/core/surface/call_details.c
  92. 2
      src/core/surface/call_log_batch.c
  93. 24
      src/core/surface/channel.c
  94. 12
      src/core/surface/channel_connectivity.c
  95. 4
      src/core/surface/channel_create.c
  96. 18
      src/core/surface/completion_queue.c
  97. 8
      src/core/surface/init.c
  98. 18
      src/core/surface/lame_client.c
  99. 4
      src/core/surface/metadata_array.c
  100. 6
      src/core/surface/secure_channel_create.c
  101. Some files were not shown because too many files have changed in this diff Show More

1
.gitignore vendored

@ -8,6 +8,7 @@ objs
python*_virtual_environment
# gcov coverage data
reports
coverage
*.gcno

@ -220,6 +220,7 @@ cc_library(
"src/core/profiling/timers.h",
"src/core/statistics/census_interface.h",
"src/core/statistics/census_rpc_stats.h",
"src/core/surface/api_trace.h",
"src/core/surface/byte_buffer_queue.h",
"src/core/surface/call.h",
"src/core/surface/channel.h",
@ -356,6 +357,7 @@ cc_library(
"src/core/json/json_writer.c",
"src/core/profiling/basic_timers.c",
"src/core/profiling/stap_timers.c",
"src/core/surface/api_trace.c",
"src/core/surface/byte_buffer.c",
"src/core/surface/byte_buffer_queue.c",
"src/core/surface/byte_buffer_reader.c",
@ -373,7 +375,6 @@ cc_library(
"src/core/surface/server.c",
"src/core/surface/server_chttp2.c",
"src/core/surface/server_create.c",
"src/core/surface/surface_trace.c",
"src/core/surface/version.c",
"src/core/transport/chttp2/alpn.c",
"src/core/transport/chttp2/bin_encoder.c",
@ -505,6 +506,7 @@ cc_library(
"src/core/profiling/timers.h",
"src/core/statistics/census_interface.h",
"src/core/statistics/census_rpc_stats.h",
"src/core/surface/api_trace.h",
"src/core/surface/byte_buffer_queue.h",
"src/core/surface/call.h",
"src/core/surface/channel.h",
@ -621,6 +623,7 @@ cc_library(
"src/core/json/json_writer.c",
"src/core/profiling/basic_timers.c",
"src/core/profiling/stap_timers.c",
"src/core/surface/api_trace.c",
"src/core/surface/byte_buffer.c",
"src/core/surface/byte_buffer_queue.c",
"src/core/surface/byte_buffer_reader.c",
@ -638,7 +641,6 @@ cc_library(
"src/core/surface/server.c",
"src/core/surface/server_chttp2.c",
"src/core/surface/server_create.c",
"src/core/surface/surface_trace.c",
"src/core/surface/version.c",
"src/core/transport/chttp2/alpn.c",
"src/core/transport/chttp2/bin_encoder.c",
@ -1145,6 +1147,7 @@ objc_library(
"src/core/json/json_writer.c",
"src/core/profiling/basic_timers.c",
"src/core/profiling/stap_timers.c",
"src/core/surface/api_trace.c",
"src/core/surface/byte_buffer.c",
"src/core/surface/byte_buffer_queue.c",
"src/core/surface/byte_buffer_reader.c",
@ -1162,7 +1165,6 @@ objc_library(
"src/core/surface/server.c",
"src/core/surface/server_chttp2.c",
"src/core/surface/server_create.c",
"src/core/surface/surface_trace.c",
"src/core/surface/version.c",
"src/core/transport/chttp2/alpn.c",
"src/core/transport/chttp2/bin_encoder.c",
@ -1291,6 +1293,7 @@ objc_library(
"src/core/profiling/timers.h",
"src/core/statistics/census_interface.h",
"src/core/statistics/census_rpc_stats.h",
"src/core/surface/api_trace.h",
"src/core/surface/byte_buffer_queue.h",
"src/core/surface/call.h",
"src/core/surface/channel.h",

@ -4119,6 +4119,7 @@ LIBGRPC_SRC = \
src/core/json/json_writer.c \
src/core/profiling/basic_timers.c \
src/core/profiling/stap_timers.c \
src/core/surface/api_trace.c \
src/core/surface/byte_buffer.c \
src/core/surface/byte_buffer_queue.c \
src/core/surface/byte_buffer_reader.c \
@ -4136,7 +4137,6 @@ LIBGRPC_SRC = \
src/core/surface/server.c \
src/core/surface/server_chttp2.c \
src/core/surface/server_create.c \
src/core/surface/surface_trace.c \
src/core/surface/version.c \
src/core/transport/chttp2/alpn.c \
src/core/transport/chttp2/bin_encoder.c \
@ -4401,6 +4401,7 @@ LIBGRPC_UNSECURE_SRC = \
src/core/json/json_writer.c \
src/core/profiling/basic_timers.c \
src/core/profiling/stap_timers.c \
src/core/surface/api_trace.c \
src/core/surface/byte_buffer.c \
src/core/surface/byte_buffer_queue.c \
src/core/surface/byte_buffer_reader.c \
@ -4418,7 +4419,6 @@ LIBGRPC_UNSECURE_SRC = \
src/core/surface/server.c \
src/core/surface/server_chttp2.c \
src/core/surface/server_create.c \
src/core/surface/surface_trace.c \
src/core/surface/version.c \
src/core/transport/chttp2/alpn.c \
src/core/transport/chttp2/bin_encoder.c \

@ -26,31 +26,31 @@ of shared C core library [src/core] (src/core).
* PHP source code: [src/php] (src/php)
* C# source code: [src/csharp] (src/csharp)
* Objective-C source code: [src/objective-c] (src/objective-c)
Java source code is in [grpc-java] (http://github.com/grpc/grpc-java) repository.
Java source code is in [grpc-java] (http://github.com/grpc/grpc-java) repository.
Go source code is in [grpc-go] (http://github.com/grpc/grpc-go) repository.
#Current Status of libraries
Libraries in different languages are in different state of development. We are seeking contributions for all of these libraries.
* shared C core library [src/core] (src/core) : Early adopter ready - Alpha.
* C++ Library: [src/cpp] (src/cpp) : Early adopter ready - Alpha.
* Ruby Library: [src/ruby] (src/ruby) : Early adopter ready - Alpha.
* NodeJS Library: [src/node] (src/node) : Early adopter ready - Alpha.
* Python Library: [src/python] (src/python) : Early adopter ready - Alpha.
* C# Library: [src/csharp] (src/csharp) : Early adopter ready - Alpha.
* Objective-C Library: [src/objective-c] (src/objective-c): Early adopter ready - Alpha.
* PHP Library: [src/php] (src/php) : Pre-Alpha.
* shared C core library [src/core] (src/core) : Beta - the surface API is stable
* C++ Library: [src/cpp] (src/cpp) : Beta - the surface API is stable
* Ruby Library: [src/ruby] (src/ruby) : Beta - the surface API is stable
* NodeJS Library: [src/node] (src/node) : Beta - the surface API is stable
* Python Library: [src/python] (src/python) : Beta - the surface API is stable
* C# Library: [src/csharp] (src/csharp) : Beta - the surface API is stable
* Objective-C Library: [src/objective-c] (src/objective-c): Beta - the surface API is stable
* PHP Library: [src/php] (src/php) : Beta - the surface API is stable
#Overview
Remote Procedure Calls (RPCs) provide a useful abstraction for building
Remote Procedure Calls (RPCs) provide a useful abstraction for building
distributed applications and services. The libraries in this repository
provide a concrete implementation of the gRPC protocol, layered over HTTP/2.
These libraries enable communication between clients and servers using any
combination of the supported languages.
combination of the supported languages.
##Interface
@ -62,12 +62,12 @@ which they use on the client-side and implement on the server side.
By default, gRPC uses [Protocol Buffers](https://github.com/google/protobuf) as the
Interface Definition Language (IDL) for describing both the service interface
and the structure of the payload messages. It is possible to use other
and the structure of the payload messages. It is possible to use other
alternatives if desired.
###Surface API
Starting from an interface definition in a .proto file, gRPC provides
Protocol Compiler plugins that generate Client- and Server-side APIs.
Protocol Compiler plugins that generate Client- and Server-side APIs.
gRPC users typically call into these APIs on the Client side and implement
the corresponding API on the server side.
@ -76,9 +76,9 @@ Synchronous RPC calls, that block until a response arrives from the server, are
the closest approximation to the abstraction of a procedure call that RPC
aspires to.
On the other hand, networks are inherently asynchronous and in many scenarios,
On the other hand, networks are inherently asynchronous and in many scenarios,
it is desirable to have the ability to start RPCs without blocking the current
thread.
thread.
The gRPC programming surface in most languages comes in both synchronous and
asynchronous flavors.
@ -87,8 +87,8 @@ asynchronous flavors.
## Streaming
gRPC supports streaming semantics, where either the client or the server (or both)
send a stream of messages on a single RPC call. The most general case is
Bidirectional Streaming where a single gRPC call establishes a stream where both
send a stream of messages on a single RPC call. The most general case is
Bidirectional Streaming where a single gRPC call establishes a stream where both
the client and the server can send a stream of messages to each other. The streamed
messages are delivered in the order they were sent.
@ -103,7 +103,7 @@ fleshing out the details of each of the required operations.
A gRPC RPC comprises of a bidirectional stream of messages, initiated by the client. In the client-to-server direction, this stream begins with a mandatory `Call Header`, followed by optional `Initial-Metadata`, followed by zero or more `Payload Messages`. The server-to-client direction contains an optional `Initial-Metadata`, followed by zero or more `Payload Messages` terminated with a mandatory `Status` and optional `Status-Metadata` (a.k.a.,`Trailing-Metadata`).
## Implementation over HTTP/2
The abstract protocol defined above is implemented over [HTTP/2](https://http2.github.io/). gRPC bidirectional streams are mapped to HTTP/2 streams. The contents of `Call Header` and `Initial Metadata` are sent as HTTP/2 headers and subject to HPACK compression. `Payload Messages` are serialized into a byte stream of length prefixed gRPC frames which are then fragmented into HTTP/2 frames at the sender and reassembled at the receiver. `Status` and `Trailing-Metadata` are sent as HTTP/2 trailing headers (a.k.a., trailers).
The abstract protocol defined above is implemented over [HTTP/2](https://http2.github.io/). gRPC bidirectional streams are mapped to HTTP/2 streams. The contents of `Call Header` and `Initial Metadata` are sent as HTTP/2 headers and subject to HPACK compression. `Payload Messages` are serialized into a byte stream of length prefixed gRPC frames which are then fragmented into HTTP/2 frames at the sender and reassembled at the receiver. `Status` and `Trailing-Metadata` are sent as HTTP/2 trailing headers (a.k.a., trailers).
## Flow Control
gRPC inherits the flow control mechanisms in HTTP/2 and uses them to enable fine-grained control of the amount of memory used for buffering in-flight messages.

File diff suppressed because it is too large Load Diff

@ -180,6 +180,7 @@ filegroups:
- src/core/profiling/timers.h
- src/core/statistics/census_interface.h
- src/core/statistics/census_rpc_stats.h
- src/core/surface/api_trace.h
- src/core/surface/byte_buffer_queue.h
- src/core/surface/call.h
- src/core/surface/channel.h
@ -293,6 +294,7 @@ filegroups:
- src/core/json/json_writer.c
- src/core/profiling/basic_timers.c
- src/core/profiling/stap_timers.c
- src/core/surface/api_trace.c
- src/core/surface/byte_buffer.c
- src/core/surface/byte_buffer_queue.c
- src/core/surface/byte_buffer_reader.c
@ -310,7 +312,6 @@ filegroups:
- src/core/surface/server.c
- src/core/surface/server_chttp2.c
- src/core/surface/server_create.c
- src/core/surface/surface_trace.c
- src/core/surface/version.c
- src/core/transport/chttp2/alpn.c
- src/core/transport/chttp2/bin_encoder.c

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Grpc.Tools" version="0.7.0" />
<package id="Grpc.Tools" version="0.7.1" />
</packages>

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.props" Condition="Exists('..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.props')" />
<Import Project="..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.props" Condition="Exists('..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.props')" />
<Import Project="..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.props" Condition="Exists('..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.props')" />
<Import Project="..\packages\grpc.dependencies.zlib.redist.1.2.8.9\build\portable-net45\grpc.dependencies.zlib.redist.props" Condition="Exists('..\packages\grpc.dependencies.zlib.redist.1.2.8.9\build\portable-net45\grpc.dependencies.zlib.redist.props')" />
<PropertyGroup>
@ -13,7 +13,7 @@
<RootNamespace>Greeter</RootNamespace>
<AssemblyName>Greeter</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<NuGetPackageImportStamp>3ef64a6a</NuGetPackageImportStamp>
<NuGetPackageImportStamp>e423e365</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
@ -37,9 +37,9 @@
<Reference Include="Google.Protobuf">
<HintPath>..\packages\Google.Protobuf.3.0.0-alpha4\lib\portable-net45+netcore45+wpa81+wp8\Google.Protobuf.dll</HintPath>
</Reference>
<Reference Include="Grpc.Core, Version=0.7.0.0, Culture=neutral, PublicKeyToken=d754f35622e28bad, processorArchitecture=MSIL">
<Reference Include="Grpc.Core, Version=0.7.1.0, Culture=neutral, PublicKeyToken=d754f35622e28bad, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\Grpc.Core.0.7.0\lib\net45\Grpc.Core.dll</HintPath>
<HintPath>..\packages\Grpc.Core.0.7.1\lib\net45\Grpc.Core.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Interactive.Async">
@ -65,10 +65,10 @@
<Error Condition="!Exists('..\packages\grpc.dependencies.zlib.redist.1.2.8.9\build\portable-net45\grpc.dependencies.zlib.redist.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.dependencies.zlib.redist.1.2.8.9\build\portable-net45\grpc.dependencies.zlib.redist.targets'))" />
<Error Condition="!Exists('..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.props'))" />
<Error Condition="!Exists('..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.targets'))" />
<Error Condition="!Exists('..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.props'))" />
<Error Condition="!Exists('..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.targets'))" />
<Error Condition="!Exists('..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.props'))" />
<Error Condition="!Exists('..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.targets'))" />
</Target>
<Import Project="..\packages\grpc.dependencies.zlib.redist.1.2.8.9\build\portable-net45\grpc.dependencies.zlib.redist.targets" Condition="Exists('..\packages\grpc.dependencies.zlib.redist.1.2.8.9\build\portable-net45\grpc.dependencies.zlib.redist.targets')" />
<Import Project="..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.targets" Condition="Exists('..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.targets')" />
<Import Project="..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.targets" Condition="Exists('..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.targets')" />
<Import Project="..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.targets" Condition="Exists('..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.targets')" />
</Project>

@ -1,10 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Google.Protobuf" version="3.0.0-alpha4" targetFramework="net45" />
<package id="Grpc" version="0.7.0" targetFramework="net45" />
<package id="Grpc.Core" version="0.7.0" targetFramework="net45" />
<package id="Grpc" version="0.7.1" targetFramework="net45" />
<package id="Grpc.Core" version="0.7.1" targetFramework="net45" />
<package id="grpc.dependencies.openssl.redist" version="1.0.2.3" targetFramework="net45" />
<package id="grpc.dependencies.zlib.redist" version="1.2.8.9" targetFramework="net45" />
<package id="grpc.native.csharp_ext" version="0.11.0" targetFramework="net45" />
<package id="grpc.native.csharp_ext" version="0.11.1" targetFramework="net45" />
<package id="Ix-Async" version="1.2.3" targetFramework="net45" />
</packages>

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.props" Condition="Exists('..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.props')" />
<Import Project="..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.props" Condition="Exists('..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.props')" />
<Import Project="..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.props" Condition="Exists('..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.props')" />
<Import Project="..\packages\grpc.dependencies.zlib.redist.1.2.8.9\build\portable-net45\grpc.dependencies.zlib.redist.props" Condition="Exists('..\packages\grpc.dependencies.zlib.redist.1.2.8.9\build\portable-net45\grpc.dependencies.zlib.redist.props')" />
<PropertyGroup>
@ -13,7 +13,7 @@
<RootNamespace>GreeterClient</RootNamespace>
<AssemblyName>GreeterClient</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<NuGetPackageImportStamp>c4057b0a</NuGetPackageImportStamp>
<NuGetPackageImportStamp>2dcf22af</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
@ -37,9 +37,9 @@
<Reference Include="Google.Protobuf">
<HintPath>..\packages\Google.Protobuf.3.0.0-alpha4\lib\portable-net45+netcore45+wpa81+wp8\Google.Protobuf.dll</HintPath>
</Reference>
<Reference Include="Grpc.Core, Version=0.7.0.0, Culture=neutral, PublicKeyToken=d754f35622e28bad, processorArchitecture=MSIL">
<Reference Include="Grpc.Core, Version=0.7.1.0, Culture=neutral, PublicKeyToken=d754f35622e28bad, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\Grpc.Core.0.7.0\lib\net45\Grpc.Core.dll</HintPath>
<HintPath>..\packages\Grpc.Core.0.7.1\lib\net45\Grpc.Core.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Interactive.Async">
@ -68,10 +68,10 @@
<Error Condition="!Exists('..\packages\grpc.dependencies.zlib.redist.1.2.8.9\build\portable-net45\grpc.dependencies.zlib.redist.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.dependencies.zlib.redist.1.2.8.9\build\portable-net45\grpc.dependencies.zlib.redist.targets'))" />
<Error Condition="!Exists('..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.props'))" />
<Error Condition="!Exists('..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.targets'))" />
<Error Condition="!Exists('..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.props'))" />
<Error Condition="!Exists('..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.targets'))" />
<Error Condition="!Exists('..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.props'))" />
<Error Condition="!Exists('..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.targets'))" />
</Target>
<Import Project="..\packages\grpc.dependencies.zlib.redist.1.2.8.9\build\portable-net45\grpc.dependencies.zlib.redist.targets" Condition="Exists('..\packages\grpc.dependencies.zlib.redist.1.2.8.9\build\portable-net45\grpc.dependencies.zlib.redist.targets')" />
<Import Project="..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.targets" Condition="Exists('..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.targets')" />
<Import Project="..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.targets" Condition="Exists('..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.targets')" />
<Import Project="..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.targets" Condition="Exists('..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.targets')" />
</Project>

@ -1,10 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Google.Protobuf" version="3.0.0-alpha4" targetFramework="net45" />
<package id="Grpc" version="0.7.0" targetFramework="net45" />
<package id="Grpc.Core" version="0.7.0" targetFramework="net45" />
<package id="Grpc" version="0.7.1" targetFramework="net45" />
<package id="Grpc.Core" version="0.7.1" targetFramework="net45" />
<package id="grpc.dependencies.openssl.redist" version="1.0.2.3" targetFramework="net45" />
<package id="grpc.dependencies.zlib.redist" version="1.2.8.9" targetFramework="net45" />
<package id="grpc.native.csharp_ext" version="0.11.0" targetFramework="net45" />
<package id="grpc.native.csharp_ext" version="0.11.1" targetFramework="net45" />
<package id="Ix-Async" version="1.2.3" targetFramework="net45" />
</packages>

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.props" Condition="Exists('..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.props')" />
<Import Project="..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.props" Condition="Exists('..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.props')" />
<Import Project="..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.props" Condition="Exists('..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.props')" />
<Import Project="..\packages\grpc.dependencies.zlib.redist.1.2.8.9\build\portable-net45\grpc.dependencies.zlib.redist.props" Condition="Exists('..\packages\grpc.dependencies.zlib.redist.1.2.8.9\build\portable-net45\grpc.dependencies.zlib.redist.props')" />
<PropertyGroup>
@ -13,7 +13,7 @@
<RootNamespace>GreeterServer</RootNamespace>
<AssemblyName>GreeterServer</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<NuGetPackageImportStamp>cc15afe5</NuGetPackageImportStamp>
<NuGetPackageImportStamp>53a3a588</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
@ -37,9 +37,9 @@
<Reference Include="Google.Protobuf">
<HintPath>..\packages\Google.Protobuf.3.0.0-alpha4\lib\portable-net45+netcore45+wpa81+wp8\Google.Protobuf.dll</HintPath>
</Reference>
<Reference Include="Grpc.Core, Version=0.7.0.0, Culture=neutral, PublicKeyToken=d754f35622e28bad, processorArchitecture=MSIL">
<Reference Include="Grpc.Core, Version=0.7.1.0, Culture=neutral, PublicKeyToken=d754f35622e28bad, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\Grpc.Core.0.7.0\lib\net45\Grpc.Core.dll</HintPath>
<HintPath>..\packages\Grpc.Core.0.7.1\lib\net45\Grpc.Core.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Interactive.Async">
@ -68,10 +68,10 @@
<Error Condition="!Exists('..\packages\grpc.dependencies.zlib.redist.1.2.8.9\build\portable-net45\grpc.dependencies.zlib.redist.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.dependencies.zlib.redist.1.2.8.9\build\portable-net45\grpc.dependencies.zlib.redist.targets'))" />
<Error Condition="!Exists('..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.props'))" />
<Error Condition="!Exists('..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.targets'))" />
<Error Condition="!Exists('..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.props'))" />
<Error Condition="!Exists('..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.targets'))" />
<Error Condition="!Exists('..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.props'))" />
<Error Condition="!Exists('..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.targets'))" />
</Target>
<Import Project="..\packages\grpc.dependencies.zlib.redist.1.2.8.9\build\portable-net45\grpc.dependencies.zlib.redist.targets" Condition="Exists('..\packages\grpc.dependencies.zlib.redist.1.2.8.9\build\portable-net45\grpc.dependencies.zlib.redist.targets')" />
<Import Project="..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.targets" Condition="Exists('..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.targets')" />
<Import Project="..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.targets" Condition="Exists('..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.targets')" />
<Import Project="..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.targets" Condition="Exists('..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.targets')" />
</Project>

@ -1,10 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Google.Protobuf" version="3.0.0-alpha4" targetFramework="net45" />
<package id="Grpc" version="0.7.0" targetFramework="net45" />
<package id="Grpc.Core" version="0.7.0" targetFramework="net45" />
<package id="Grpc" version="0.7.1" targetFramework="net45" />
<package id="Grpc.Core" version="0.7.1" targetFramework="net45" />
<package id="grpc.dependencies.openssl.redist" version="1.0.2.3" targetFramework="net45" />
<package id="grpc.dependencies.zlib.redist" version="1.2.8.9" targetFramework="net45" />
<package id="grpc.native.csharp_ext" version="0.11.0" targetFramework="net45" />
<package id="grpc.native.csharp_ext" version="0.11.1" targetFramework="net45" />
<package id="Ix-Async" version="1.2.3" targetFramework="net45" />
</packages>

@ -3,49 +3,52 @@ gRPC in 3 minutes (C#)
BACKGROUND
-------------
For this sample, we've already generated the server and client stubs from `helloworld.proto`.
Example projects depend on NuGet packages `Grpc` and `Google.ProtocolBuffers` which have been already added to the project for you.
For this sample, we've already generated the server and client stubs from [helloworld.proto][].
Example projects depend on the [Grpc](https://www.nuget.org/packages/Grpc/)
and [Google.Protobuf](https://www.nuget.org/packages/Google.Protobuf/) NuGet packages
which have been already added to the project for you.
PREREQUISITES
-------------
**Windows**
- .NET 4.5+
- VS 2013 (with NuGet plugin installed)
- Visual Studio 2013 or 2015
**Linux (Mono)**
**Linux**
- Mono
- Monodevelop 5.9 with NuGet Add-in installed (older versions might work)
- Monodevelop 5.9 with NuGet Add-in installed
**MacOS (Mono)**
**Mac OS X**
- Xamarin Studio (with NuGet plugin installed)
- [homebrew][]
BUILD
-------
**Windows**
- Clone this repository.
- Open solution `Greeter.sln` with Visual Studio
- Build the solution (this will automatically download NuGet dependencies)
**Linux (Mono)**
- Clone this repository.
**Linux (Debian)**
- Install gRPC C core and C# native extension using [How to use gRPC C#][] instructions
- Install gRPC C Core using instructions in https://github.com/grpc/homebrew-grpc
- Open solution `Greeter.sln` in MonoDevelop.
- gRPC C# depends on native shared library `libgrpc_csharp_ext.so`. To make it visible
to Mono runtime, follow instructions in [Using gRPC C# on Linux](https://github.com/grpc/grpc/tree/master/src/csharp#usage-linux-mono)
- Build the solution (you need to manually restore dependencies by using `mono nuget.exe restore` if you don't have NuGet add-in)
- Open solution `Greeter.sln` in MonoDevelop (you need to manually restore dependencies by using `mono nuget.exe restore` if you don't have NuGet add-in)
**Mac OS X**
- Build the solution.
- Install gRPC C core and C# native extension using [How to use gRPC C#][] instructions
**MacOS (Mono)**
- See [Using gRPC C# on MacOS](https://github.com/grpc/grpc/tree/master/src/csharp#usage-macos-mono) for more info
on MacOS support.
- Open solution `Greeter.sln` with Xamarin Studio
Try it!
- Build the solution (this will automatically download NuGet dependencies)
Try it!
-------
- Run the server
@ -69,4 +72,9 @@ On Linux or Mac, use `mono GreeterServer.exe` and `mono GreeterClient.exe` to ru
Tutorial
--------
You can find a more detailed tutorial in [gRPC Basics: C#](route_guide/README.md)
You can find a more detailed tutorial in [gRPC Basics: C#][]
[homebrew]:http://brew.sh
[helloworld.proto]:../../protos/helloworld.proto
[How to use gRPC C#]:../../../src/csharp#how-to-use
[gRPC Basics: C#]:http://www.grpc.io/docs/tutorials/basic/csharp.html

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Grpc.Tools" version="0.7.0" />
<package id="Grpc.Tools" version="0.7.1" />
</packages>

@ -1,386 +1,6 @@
#gRPC Basics: C# #
#gRPC Basics: C# sample code
This tutorial provides a basic C# programmer's introduction to working with gRPC. By walking through this example you'll learn how to:
The files in this folder are the samples used in [gRPC Basics: C#][],
a detailed tutorial for using gRPC in C#.
- Define a service in a .proto file.
- Generate server and client code using the protocol buffer compiler.
- Use the C# gRPC API to write a simple client and server for your service.
It assumes that you have read the [Getting started](https://github.com/grpc/grpc/tree/master/examples) guide and are familiar with [protocol buffers] (https://developers.google.com/protocol-buffers/docs/overview). Note that the example in this tutorial only uses the proto2 version of the protocol buffers language, as proto3 support for C# is not ready yet (see [protobuf C# README](https://github.com/google/protobuf/tree/master/csharp#proto2--proto3)).
This isn't a comprehensive guide to using gRPC in C#: more reference documentation is coming soon.
## Why use gRPC?
Our example is a simple route mapping application that lets clients get information about features on their route, create a summary of their route, and exchange route information such as traffic updates with the server and other clients.
With gRPC we can define our service once in a .proto file and implement clients and servers in any of gRPC's supported languages, which in turn can be run in environments ranging from servers inside Google to your own tablet - all the complexity of communication between different languages and environments is handled for you by gRPC. We also get all the advantages of working with protocol buffers, including efficient serialization, a simple IDL, and easy interface updating.
## Example code and setup
The example code for our tutorial is in [examples/csharp/route_guide](.). To download the example, clone this repository by running the following command:
```shell
$ git clone https://github.com/grpc/grpc.git
```
All the files for this tutorial are in the directory `examples/csharp/route_guide`.
Open the solution `examples/csharp/route_guide/RouteGuide.sln` from Visual Studio (or Monodevelop on Linux).
On Windows, you should not need to do anything besides opening the solution. All the needed dependencies will be restored
for you automatically by the `Grpc` NuGet package upon building the solution.
On Linux (or MacOS), you will first need to install protobuf and gRPC C Core using Linuxbrew (or Homebrew) tool in order to be
able to generate the server and client interface code and run the examples. Follow the instructions for [Linux](https://github.com/grpc/grpc/tree/master/src/csharp#usage-linux-mono) or [MacOS](https://github.com/grpc/grpc/tree/master/src/csharp#usage-macos-mono).
## Defining the service
Our first step (as you'll know from [Getting started](https://github.com/grpc/grpc/tree/master/examples)) is to define the gRPC *service* and the method *request* and *response* types using [protocol buffers] (https://developers.google.com/protocol-buffers/docs/overview). You can see the complete .proto file in [`RouteGuide/protos/route_guide.proto`](RouteGuide/protos/route_guide.proto).
To define a service, you specify a named `service` in your .proto file:
```protobuf
service RouteGuide {
...
}
```
Then you define `rpc` methods inside your service definition, specifying their request and response types. gRPC lets you define four kinds of service method, all of which are used in the `RouteGuide` service:
- A *simple RPC* where the client sends a request to the server using the stub and waits for a response to come back, just like a normal function call.
```protobuf
// Obtains the feature at a given position.
rpc GetFeature(Point) returns (Feature) {}
```
- A *server-side streaming RPC* where the client sends a request to the server and gets a stream to read a sequence of messages back. The client reads from the returned stream until there are no more messages. As you can see in our example, you specify a server-side streaming method by placing the `stream` keyword before the *response* type.
```protobuf
// 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.
rpc ListFeatures(Rectangle) returns (stream Feature) {}
```
- A *client-side streaming RPC* where the client writes a sequence of messages and sends them to the server, again using a provided stream. Once the client has finished writing the messages, it waits for the server to read them all and return its response. You specify a server-side streaming method by placing the `stream` keyword before the *request* type.
```protobuf
// Accepts a stream of Points on a route being traversed, returning a
// RouteSummary when traversal is completed.
rpc RecordRoute(stream Point) returns (RouteSummary) {}
```
- A *bidirectional streaming RPC* where both sides send a sequence of messages using a read-write stream. The two streams operate independently, so clients and servers can read and write in whatever order they like: for example, the server could wait to receive all the client messages before writing its responses, or it could alternately read a message then write a message, or some other combination of reads and writes. The order of messages in each stream is preserved. You specify this type of method by placing the `stream` keyword before both the request and the response.
```protobuf
// Accepts a stream of RouteNotes sent while a route is being traversed,
// while receiving other RouteNotes (e.g. from other users).
rpc RouteChat(stream RouteNote) returns (stream RouteNote) {}
```
Our .proto file also contains protocol buffer message type definitions for all the request and response types used in our service methods - for example, here's the `Point` message type:
```protobuf
// Points are represented as latitude-longitude pairs in the E7 representation
// (degrees multiplied by 10**7 and rounded to the nearest integer).
// Latitudes should be in the range +/- 90 degrees and longitude should be in
// the range +/- 180 degrees (inclusive).
message Point {
int32 latitude = 1;
int32 longitude = 2;
}
```
## Generating client and server code
Next we need to generate the gRPC client and server interfaces from our .proto service definition. We do this using the protocol buffer compiler `protoc` with a special gRPC C# plugin.
If you want to run this yourself, make sure you've installed protoc and gRPC C# plugin. The instructions vary based on your OS:
- For Windows, the `Grpc.Tools` and `Google.Protobuf` NuGet packages contain the binaries you will need to generate the code.
- For Linux, make sure you've [installed gRPC C Core using Linuxbrew](https://github.com/grpc/grpc/tree/master/src/csharp#usage-linux-mono)
- For MacOS, make sure you've [installed gRPC C Core using Homebrew](https://github.com/grpc/grpc/tree/master/src/csharp#usage-macos-mono)
Once that's done, the following command can be used to generate the C# code.
To generate the code on Windows, we use `protoc.exe` from the `Google.Protobuf` NuGet package and `grpc_csharp_plugin.exe` from the `Grpc.Tools` NuGet package (both under the `tools` directory).
Normally you would need to add the `Grpc.Tools` package to the solution yourself, but in this tutorial it has been already done for you. Following command should be run from the `csharp/route_guide` directory:
```
> packages\Google.Protobuf.3.0.0-alpha4\tools\protoc -I RouteGuide/protos --csharp_out=RouteGuide --grpc_out=RouteGuide --plugin=protoc-gen-grpc=packages\Grpc.Tools.0.7.0\tools\grpc_csharp_plugin.exe RouteGuide/protos/route_guide.proto
```
On Linux/MacOS, we rely on `protoc` and `grpc_csharp_plugin` being installed by Linuxbrew/Homebrew. Run this command from the route_guide directory:
```shell
$ protoc -I RouteGuide/protos --csharp_out=RouteGuide --grpc_out=RouteGuide --plugin=protoc-gen-grpc=`which grpc_csharp_plugin` RouteGuide/protos/route_guide.proto
```
Running one of the previous commands regenerates the following files in the RouteGuide directory:
- `RouteGuide/RouteGuide.cs` defines a namespace `examples`
- This contains all the protocol buffer code to populate, serialize, and retrieve our request and response message types
- `RouteGuide/RouteGuideGrpc.cs`, provides stub and service classes
- an interface `RouteGuide.IRouteGuide` to inherit from when defining RouteGuide service implementations
- a class `RouteGuide.RouteGuideClient` that can be used to access remote RouteGuide instances
<a name="server"></a>
## Creating the server
First let's look at how we create a `RouteGuide` server. If you're only interested in creating gRPC clients, you can skip this section and go straight to [Creating the client](#client) (though you might find it interesting anyway!).
There are two parts to making our `RouteGuide` service do its job:
- Implementing the service interface generated from our service definition: doing the actual "work" of our service.
- Running a gRPC server to listen for requests from clients and return the service responses.
You can find our example `RouteGuide` server in [RouteGuideServer/RouteGuideImpl.cs](RouteGuideServer/RouteGuideServerImpl.cs). Let's take a closer look at how it works.
### Implementing RouteGuide
As you can see, our server has a `RouteGuideImpl` class that implements the generated `RouteGuide.IRouteGuide`:
```csharp
// RouteGuideImpl provides an implementation of the RouteGuide service.
public class RouteGuideImpl : RouteGuide.IRouteGuide
```
#### Simple RPC
`RouteGuideImpl` implements all our service methods. Let's look at the simplest type first, `GetFeature`, which just gets a `Point` from the client and returns the corresponding feature information from its database in a `Feature`.
```csharp
public Task<Feature> GetFeature(Point request, Grpc.Core.ServerCallContext context)
{
return Task.FromResult(CheckFeature(request));
}
```
The method is passed a context for the RPC (which is empty in the alpha release), the client's `Point` protocol buffer request, and returns a `Feature` protocol buffer. In the method we create the `Feature` with the appropriate information, and then return it. To allow asynchronous
implementation, the method returns `Task<Feature>` rather than just `Feature`. You are free to perform your computations synchronously and return
the result once you've finished, just as we do in the example.
#### Server-side streaming RPC
Now let's look at something a bit more complicated - a streaming RPC. `ListFeatures` is a server-side streaming RPC, so we need to send back multiple `Feature` protocol buffers to our client.
```csharp
// in RouteGuideImpl
public async Task ListFeatures(Rectangle request,
Grpc.Core.IServerStreamWriter<Feature> responseStream,
Grpc.Core.ServerCallContext context)
{
var responses = features.FindAll( (feature) => feature.Exists() && request.Contains(feature.Location) );
foreach (var response in responses)
{
await responseStream.WriteAsync(response);
}
}
```
As you can see, here the request object is a `Rectangle` in which our client wants to find `Feature`s, but instead of returning a simple response we need to write responses to an asynchronous stream `IServerStreamWriter` using async method `WriteAsync`.
#### Client-side streaming RPC
Similarly, the client-side streaming method `RecordRoute` uses an [IAsyncEnumerator](https://github.com/Reactive-Extensions/Rx.NET/blob/master/Ix.NET/Source/System.Interactive.Async/IAsyncEnumerator.cs), to read the stream of requests using the async method `MoveNext` and the `Current` property.
```csharp
public async Task<RouteSummary> RecordRoute(Grpc.Core.IAsyncStreamReader<Point> requestStream,
Grpc.Core.ServerCallContext context)
{
int pointCount = 0;
int featureCount = 0;
int distance = 0;
Point previous = null;
var stopwatch = new Stopwatch();
stopwatch.Start();
while (await requestStream.MoveNext())
{
var point = requestStream.Current;
pointCount++;
if (CheckFeature(point).Exists())
{
featureCount++;
}
if (previous != null)
{
distance += (int) previous.GetDistance(point);
}
previous = point;
}
stopwatch.Stop();
return new RouteSummary
{
PointCount = pointCount,
FeatureCount = featureCount,
Distance = distance,
ElapsedTime = (int)(stopwatch.ElapsedMilliseconds / 1000)
};
}
```
#### Bidirectional streaming RPC
Finally, let's look at our bidirectional streaming RPC `RouteChat`.
```csharp
public async Task RouteChat(Grpc.Core.IAsyncStreamReader<RouteNote> requestStream,
Grpc.Core.IServerStreamWriter<RouteNote> responseStream,
Grpc.Core.ServerCallContext context,)
{
while (await requestStream.MoveNext())
{
var note = requestStream.Current;
List<RouteNote> prevNotes = AddNoteForLocation(note.Location, note);
foreach (var prevNote in prevNotes)
{
await responseStream.WriteAsync(prevNote);
}
}
}
```
Here the method receives both `requestStream` and `responseStream` arguments. Reading the requests is done the same way as in the client-side streaming method `RecordRoute`. Writing the responses is done the same way as in the server-side streaming method `ListFeatures`.
### Starting the server
Once we've implemented all our methods, we also need to start up a gRPC server so that clients can actually use our service. The following snippet shows how we do this for our `RouteGuide` service:
```csharp
var features = RouteGuideUtil.ParseFeatures(RouteGuideUtil.DefaultFeaturesFile);
Server server = new Server
{
Services = { RouteGuide.BindService(new RouteGuideImpl(features)) },
Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) }
};
server.Start();
Console.WriteLine("RouteGuide server listening on port " + port);
Console.WriteLine("Press any key to stop the server...");
Console.ReadKey();
server.ShutdownAsync().Wait();
```
As you can see, we build and start our server using `Grpc.Core.Server` class. To do this, we:
1. Create an instance of `Grpc.Core.Server`.
1. Create an instance of our service implementation class `RouteGuideImpl`.
3. Register our service implementation by adding its service definition to `Services` collection (We obtain the service definition from the generated `RouteGuide.BindService` method).
2. Specify the address and port we want to use to listen for client requests. This is done by adding `ServerPort` to `Ports` collection.
4. Call `Start` on the server instance to start an RPC server for our service.
<a name="client"></a>
## Creating the client
In this section, we'll look at creating a C# client for our `RouteGuide` service. You can see our complete example client code in [RouteGuideClient/Program.cs](RouteGuideClient/Program.cs).
### Creating a stub
To call service methods, we first need to create a *stub*.
First, we need to create a gRPC client channel that will connect to gRPC server. Then, we use the `RouteGuide.NewClient` method of the `RouteGuide` class generated from our .proto.
```csharp
Channel channel = new Channel("127.0.0.1:50052", Credentials.Insecure)
var client = new RouteGuideClient(RouteGuide.NewClient(channel));
// YOUR CODE GOES HERE
channel.ShutdownAsync().Wait();
```
### Calling service methods
Now let's look at how we call our service methods. gRPC C# provides asynchronous versions of each of the supported method types. For convenience,
gRPC C# also provides a synchronous method stub, but only for simple (single request/single response) RPCs.
#### Simple RPC
Calling the simple RPC `GetFeature` in a synchronous way is nearly as straightforward as calling a local method.
```csharp
Point request = new Point { Latitude = 409146138, Longitude = -746188906 };
Feature feature = client.GetFeature(request);
```
As you can see, we create and populate a request protocol buffer object (in our case `Point`), and call the desired method on the client object, passing it the request. If the RPC finishes with success, the response protocol buffer (in our case `Feature`) will be returned. Otherwise, an exception of type `RpcException` will be thrown, indicating the status code of the problem.
Alternatively, if you are in async context, you can call an asynchronous version of the method (and use `await` keyword to await the result):
```csharp
Point request = new Point { Latitude = 409146138, Longitude = -746188906 };
Feature feature = await client.GetFeatureAsync(request);
```
#### Streaming RPCs
Now let's look at our streaming methods. If you've already read [Creating the server](#server) some of this may look very familiar - streaming RPCs are implemented in a similar way on both sides. The difference with respect to simple call is that the client methods return an instance of a call object, that provides access to request/response streams and/or asynchronous result (depending on the streaming type you are using).
Here's where we call the server-side streaming method `ListFeatures`, which has property `ReponseStream` of type `IAsyncEnumerator<Feature>`
```csharp
using (var call = client.ListFeatures(request))
{
while (await call.ResponseStream.MoveNext())
{
Feature feature = call.ResponseStream.Current;
Console.WriteLine("Received " + feature.ToString());
}
}
```
The client-side streaming method `RecordRoute` is similar, except we use the property `RequestStream` to write the requests one by one using `WriteAsync` and eventually signal that no more request will be send using `CompleteAsync`. The method result can be obtained through the property
`ResponseAsync`.
```csharp
using (var call = client.RecordRoute())
{
foreach (var point in points)
{
await call.RequestStream.WriteAsync(point);
}
await call.RequestStream.CompleteAsync();
RouteSummary summary = await call.ResponseAsync;
}
```
Finally, let's look at our bidirectional streaming RPC `RouteChat`. In this case, we write the request to `RequestStream` and receive the responses from `ResponseStream`. As you can see from the example, the streams are independent of each other.
```csharp
using (var call = client.RouteChat())
{
var responseReaderTask = Task.Run(async () =>
{
while (await call.ResponseStream.MoveNext())
{
var note = call.ResponseStream.Current;
Console.WriteLine("Received " + note);
}
});
foreach (RouteNote request in requests)
{
await call.RequestStream.WriteAsync(request);
}
await call.RequestStream.CompleteAsync();
await responseReaderTask;
}
```
## Try it out!
Build client and server:
Open the solution `examples/csharp/route_guide/RouteGuide.sln` from Visual Studio (or Monodevelop on Linux) and hit "Build".
Run the server, which will listen on port 50052:
```
> cd RouteGuideServer/bin/Debug
> RouteGuideServer.exe
```
Run the client (in a different terminal):
```
> cd RouteGuideClient/bin/Debug
> RouteGuideClient.exe
```
You can also run the server and client directly from Visual Studio.
On Linux or Mac, use `mono RouteGuideServer.exe` and `mono RouteGuideClient.exe` to run the server and client.
[gRPC Basics: C#]:http://www.grpc.io/docs/tutorials/basic/csharp.html

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.props" Condition="Exists('..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.props')" />
<Import Project="..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.props" Condition="Exists('..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.props')" />
<Import Project="..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.props" Condition="Exists('..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.props')" />
<Import Project="..\packages\grpc.dependencies.zlib.redist.1.2.8.9\build\portable-net45\grpc.dependencies.zlib.redist.props" Condition="Exists('..\packages\grpc.dependencies.zlib.redist.1.2.8.9\build\portable-net45\grpc.dependencies.zlib.redist.props')" />
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
@ -14,7 +14,7 @@
<AssemblyName>RouteGuide</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<NuGetPackageImportStamp>443bbc38</NuGetPackageImportStamp>
<NuGetPackageImportStamp>256a7eeb</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
@ -37,13 +37,13 @@
<Reference Include="Google.Protobuf">
<HintPath>..\packages\Google.Protobuf.3.0.0-alpha4\lib\portable-net45+netcore45+wpa81+wp8\Google.Protobuf.dll</HintPath>
</Reference>
<Reference Include="Grpc.Core, Version=0.7.0.0, Culture=neutral, PublicKeyToken=d754f35622e28bad, processorArchitecture=MSIL">
<Reference Include="Grpc.Core, Version=0.7.1.0, Culture=neutral, PublicKeyToken=d754f35622e28bad, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\Grpc.Core.0.7.0\lib\net45\Grpc.Core.dll</HintPath>
<HintPath>..\packages\Grpc.Core.0.7.1\lib\net45\Grpc.Core.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=7.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\Newtonsoft.Json.7.0.1-beta2\lib\net45\Newtonsoft.Json.dll</HintPath>
<HintPath>..\packages\Newtonsoft.Json.7.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
@ -77,12 +77,12 @@
<Error Condition="!Exists('..\packages\grpc.dependencies.zlib.redist.1.2.8.9\build\portable-net45\grpc.dependencies.zlib.redist.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.dependencies.zlib.redist.1.2.8.9\build\portable-net45\grpc.dependencies.zlib.redist.targets'))" />
<Error Condition="!Exists('..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.props'))" />
<Error Condition="!Exists('..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.targets'))" />
<Error Condition="!Exists('..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.props'))" />
<Error Condition="!Exists('..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.targets'))" />
<Error Condition="!Exists('..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.props'))" />
<Error Condition="!Exists('..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.targets'))" />
</Target>
<Import Project="..\packages\grpc.dependencies.zlib.redist.1.2.8.9\build\portable-net45\grpc.dependencies.zlib.redist.targets" Condition="Exists('..\packages\grpc.dependencies.zlib.redist.1.2.8.9\build\portable-net45\grpc.dependencies.zlib.redist.targets')" />
<Import Project="..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.targets" Condition="Exists('..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.targets')" />
<Import Project="..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.targets" Condition="Exists('..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.targets')" />
<Import Project="..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.targets" Condition="Exists('..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.targets')" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">

@ -1,11 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Google.Protobuf" version="3.0.0-alpha4" targetFramework="net45" />
<package id="Grpc" version="0.7.0" targetFramework="net45" />
<package id="Grpc.Core" version="0.7.0" targetFramework="net45" />
<package id="Grpc" version="0.7.1" targetFramework="net45" />
<package id="Grpc.Core" version="0.7.1" targetFramework="net45" />
<package id="grpc.dependencies.openssl.redist" version="1.0.2.3" targetFramework="net45" />
<package id="grpc.dependencies.zlib.redist" version="1.2.8.9" targetFramework="net45" />
<package id="grpc.native.csharp_ext" version="0.11.0" targetFramework="net45" />
<package id="grpc.native.csharp_ext" version="0.11.1" targetFramework="net45" />
<package id="Ix-Async" version="1.2.3" targetFramework="net45" />
<package id="Newtonsoft.Json" version="7.0.1-beta2" targetFramework="net45" />
<package id="Newtonsoft.Json" version="7.0.1" targetFramework="net45" />
</packages>

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.props" Condition="Exists('..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.props')" />
<Import Project="..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.props" Condition="Exists('..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.props')" />
<Import Project="..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.props" Condition="Exists('..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.props')" />
<Import Project="..\packages\grpc.dependencies.zlib.redist.1.2.8.9\build\portable-net45\grpc.dependencies.zlib.redist.props" Condition="Exists('..\packages\grpc.dependencies.zlib.redist.1.2.8.9\build\portable-net45\grpc.dependencies.zlib.redist.props')" />
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
@ -14,7 +14,7 @@
<AssemblyName>RouteGuideClient</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<NuGetPackageImportStamp>77622de6</NuGetPackageImportStamp>
<NuGetPackageImportStamp>d40daa42</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
@ -39,9 +39,13 @@
<Reference Include="Google.Protobuf">
<HintPath>..\packages\Google.Protobuf.3.0.0-alpha4\lib\portable-net45+netcore45+wpa81+wp8\Google.Protobuf.dll</HintPath>
</Reference>
<Reference Include="Grpc.Core, Version=0.7.0.0, Culture=neutral, PublicKeyToken=d754f35622e28bad, processorArchitecture=MSIL">
<Reference Include="Grpc.Core, Version=0.7.1.0, Culture=neutral, PublicKeyToken=d754f35622e28bad, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\Grpc.Core.0.7.0\lib\net45\Grpc.Core.dll</HintPath>
<HintPath>..\packages\Grpc.Core.0.7.1\lib\net45\Grpc.Core.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=7.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\Newtonsoft.Json.7.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
@ -59,7 +63,6 @@
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
@ -77,12 +80,12 @@
<Error Condition="!Exists('..\packages\grpc.dependencies.zlib.redist.1.2.8.9\build\portable-net45\grpc.dependencies.zlib.redist.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.dependencies.zlib.redist.1.2.8.9\build\portable-net45\grpc.dependencies.zlib.redist.targets'))" />
<Error Condition="!Exists('..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.props'))" />
<Error Condition="!Exists('..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.targets'))" />
<Error Condition="!Exists('..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.props'))" />
<Error Condition="!Exists('..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.targets'))" />
<Error Condition="!Exists('..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.props'))" />
<Error Condition="!Exists('..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.targets'))" />
</Target>
<Import Project="..\packages\grpc.dependencies.zlib.redist.1.2.8.9\build\portable-net45\grpc.dependencies.zlib.redist.targets" Condition="Exists('..\packages\grpc.dependencies.zlib.redist.1.2.8.9\build\portable-net45\grpc.dependencies.zlib.redist.targets')" />
<Import Project="..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.targets" Condition="Exists('..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.targets')" />
<Import Project="..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.targets" Condition="Exists('..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.targets')" />
<Import Project="..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.targets" Condition="Exists('..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.targets')" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">

@ -1,10 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Google.Protobuf" version="3.0.0-alpha4" targetFramework="net45" />
<package id="Grpc" version="0.7.0" targetFramework="net45" />
<package id="Grpc.Core" version="0.7.0" targetFramework="net45" />
<package id="Grpc" version="0.7.1" targetFramework="net45" />
<package id="Grpc.Core" version="0.7.1" targetFramework="net45" />
<package id="grpc.dependencies.openssl.redist" version="1.0.2.3" targetFramework="net45" />
<package id="grpc.dependencies.zlib.redist" version="1.2.8.9" targetFramework="net45" />
<package id="grpc.native.csharp_ext" version="0.11.0" targetFramework="net45" />
<package id="grpc.native.csharp_ext" version="0.11.1" targetFramework="net45" />
<package id="Ix-Async" version="1.2.3" targetFramework="net45" />
<package id="Newtonsoft.Json" version="7.0.1" targetFramework="net45" />
</packages>

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.props" Condition="Exists('..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.props')" />
<Import Project="..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.props" Condition="Exists('..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.props')" />
<Import Project="..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.props" Condition="Exists('..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.props')" />
<Import Project="..\packages\grpc.dependencies.zlib.redist.1.2.8.9\build\portable-net45\grpc.dependencies.zlib.redist.props" Condition="Exists('..\packages\grpc.dependencies.zlib.redist.1.2.8.9\build\portable-net45\grpc.dependencies.zlib.redist.props')" />
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
@ -14,7 +14,7 @@
<AssemblyName>RouteGuideServer</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<NuGetPackageImportStamp>568005e2</NuGetPackageImportStamp>
<NuGetPackageImportStamp>e44ce7bb</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
@ -39,9 +39,13 @@
<Reference Include="Google.Protobuf">
<HintPath>..\packages\Google.Protobuf.3.0.0-alpha4\lib\portable-net45+netcore45+wpa81+wp8\Google.Protobuf.dll</HintPath>
</Reference>
<Reference Include="Grpc.Core, Version=0.7.0.0, Culture=neutral, PublicKeyToken=d754f35622e28bad, processorArchitecture=MSIL">
<Reference Include="Grpc.Core, Version=0.7.1.0, Culture=neutral, PublicKeyToken=d754f35622e28bad, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\Grpc.Core.0.7.0\lib\net45\Grpc.Core.dll</HintPath>
<HintPath>..\packages\Grpc.Core.0.7.1\lib\net45\Grpc.Core.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=7.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\Newtonsoft.Json.7.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
@ -60,7 +64,6 @@
<Compile Include="RouteGuideImpl.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
@ -78,12 +81,12 @@
<Error Condition="!Exists('..\packages\grpc.dependencies.zlib.redist.1.2.8.9\build\portable-net45\grpc.dependencies.zlib.redist.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.dependencies.zlib.redist.1.2.8.9\build\portable-net45\grpc.dependencies.zlib.redist.targets'))" />
<Error Condition="!Exists('..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.props'))" />
<Error Condition="!Exists('..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.targets'))" />
<Error Condition="!Exists('..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.props'))" />
<Error Condition="!Exists('..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.targets'))" />
<Error Condition="!Exists('..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.props'))" />
<Error Condition="!Exists('..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.targets'))" />
</Target>
<Import Project="..\packages\grpc.dependencies.zlib.redist.1.2.8.9\build\portable-net45\grpc.dependencies.zlib.redist.targets" Condition="Exists('..\packages\grpc.dependencies.zlib.redist.1.2.8.9\build\portable-net45\grpc.dependencies.zlib.redist.targets')" />
<Import Project="..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.targets" Condition="Exists('..\packages\grpc.dependencies.openssl.redist.1.0.2.3\build\portable-net45\grpc.dependencies.openssl.redist.targets')" />
<Import Project="..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.targets" Condition="Exists('..\packages\grpc.native.csharp_ext.0.11.0\build\portable-net45\grpc.native.csharp_ext.targets')" />
<Import Project="..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.targets" Condition="Exists('..\packages\grpc.native.csharp_ext.0.11.1\build\portable-net45\grpc.native.csharp_ext.targets')" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">

@ -1,10 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Google.Protobuf" version="3.0.0-alpha4" targetFramework="net45" />
<package id="Grpc" version="0.7.0" targetFramework="net45" />
<package id="Grpc.Core" version="0.7.0" targetFramework="net45" />
<package id="Grpc" version="0.7.1" targetFramework="net45" />
<package id="Grpc.Core" version="0.7.1" targetFramework="net45" />
<package id="grpc.dependencies.openssl.redist" version="1.0.2.3" targetFramework="net45" />
<package id="grpc.dependencies.zlib.redist" version="1.2.8.9" targetFramework="net45" />
<package id="grpc.native.csharp_ext" version="0.11.0" targetFramework="net45" />
<package id="grpc.native.csharp_ext" version="0.11.1" targetFramework="net45" />
<package id="Ix-Async" version="1.2.3" targetFramework="net45" />
<package id="Newtonsoft.Json" version="7.0.1" targetFramework="net45" />
</packages>

@ -5,21 +5,11 @@ PREREQUISITES
-------------
- `node`: This requires Node 10.x or greater.
- [homebrew][] on Mac OS X, [linuxbrew][] on Linux. These simplify the installation of the gRPC C core.
- [homebrew][] on Mac OS X. This simplifies the installation of the gRPC C core.
INSTALL
-------
- On Mac OS X, install [homebrew][]. On Linux, install [linuxbrew][]. Run the following command to install gRPC Node.js.
```sh
$ curl -fsSL https://goo.gl/getgrpc | bash -s nodejs
```
This will download and run the [gRPC install script][], then install the latest version of gRPC Nodejs npm package.
- Clone this repository
```sh
$ git clone https://github.com/grpc/grpc.git
```
- [Install gRPC Node][]
- Install this package's dependencies
@ -55,6 +45,5 @@ TUTORIAL
You can find a more detailed tutorial in [gRPC Basics: Node.js][]
[homebrew]:http://brew.sh
[linuxbrew]:https://github.com/Homebrew/linuxbrew#installation
[gRPC install script]:https://raw.githubusercontent.com/grpc/homebrew-grpc/master/scripts/install
[gRPC Basics: Node.js]:https://github.com/grpc/grpc/blob/master/examples/node/route_guide/README.md
[Install gRPC Node]:../../src/node
[gRPC Basics: Node.js]:http://www.grpc.io/docs/tutorials/basic/node.html

@ -1,6 +1,6 @@
{
"name": "grpc-demo",
"version": "0.5.0",
"version": "0.11.0",
"dependencies": {
"async": "^0.9.0",
"grpc": "~0.11.0",

@ -1,363 +1,5 @@
#gRPC Basics: Node.js
#gRPC Basics: Node.js sample code
This tutorial provides a basic Node.js programmer's introduction to working with gRPC. By walking through this example you'll learn how to:
The files in this folder are the samples used in [gRPC Basics: Node.js][], a detailed tutorial for using gRPC in Node.js.
- Define a service in a .proto file.
- Use the Node.js gRPC API to write a simple client and server for your service.
It assumes that you have read the [Getting started](https://github.com/grpc/grpc/tree/master/examples) guide and are familiar with [protocol buffers] (https://developers.google.com/protocol-buffers/docs/overview). Note that the example in this tutorial uses the proto3 version of the protocol buffers language, which is currently in alpha release:you can find out more in the [proto3 language guide](https://developers.google.com/protocol-buffers/docs/proto3) and see the [release notes](https://github.com/google/protobuf/releases) for the new version in the protocol buffers Github repository.
This isn't a comprehensive guide to using gRPC in Node.js: more reference documentation is coming soon.
## Why use gRPC?
Our example is a simple route mapping application that lets clients get information about features on their route, create a summary of their route, and exchange route information such as traffic updates with the server and other clients.
With gRPC we can define our service once in a .proto file and implement clients and servers in any of gRPC's supported languages, which in turn can be run in environments ranging from servers inside Google to your own tablet - all the complexity of communication between different languages and environments is handled for you by gRPC. We also get all the advantages of working with protocol buffers, including efficient serialization, a simple IDL, and easy interface updating.
## Example code and setup
The example code for our tutorial is in [examples/node/route_guide](.). To download the example, clone this repository by running the following command:
```shell
$ git clone https://github.com/grpc/grpc.git
```
Then change your current directory to `examples/node/route_guide`:
```shell
$ cd examples/node/route_guide
```
You also should have the relevant tools installed to generate the server and client interface code - if you don't already, follow the setup instructions in [the Node.js quick start guide](..).
## Defining the service
Our first step (as you'll know from [Getting started](https://github.com/grpc/grpc/tree/master/examples)) is to define the gRPC *service* and the method *request* and *response* types using [protocol buffers] (https://developers.google.com/protocol-buffers/docs/overview). You can see the complete .proto file in [`examples/protos/route_guide.proto`](../../route_guide.proto).
To define a service, you specify a named `service` in your .proto file:
```protobuf
service RouteGuide {
...
}
```
Then you define `rpc` methods inside your service definition, specifying their request and response types. gRPC lets you define four kinds of service method, all of which are used in the `RouteGuide` service:
- A *simple RPC* where the client sends a request to the server using the stub and waits for a response to come back, just like a normal function call.
```protobuf
// Obtains the feature at a given position.
rpc GetFeature(Point) returns (Feature) {}
```
- A *server-side streaming RPC* where the client sends a request to the server and gets a stream to read a sequence of messages back. The client reads from the returned stream until there are no more messages. As you can see in our example, you specify a server-side streaming method by placing the `stream` keyword before the *response* type.
```protobuf
// 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.
rpc ListFeatures(Rectangle) returns (stream Feature) {}
```
- A *client-side streaming RPC* where the client writes a sequence of messages and sends them to the server, again using a provided stream. Once the client has finished writing the messages, it waits for the server to read them all and return its response. You specify a server-side streaming method by placing the `stream` keyword before the *request* type.
```protobuf
// Accepts a stream of Points on a route being traversed, returning a
// RouteSummary when traversal is completed.
rpc RecordRoute(stream Point) returns (RouteSummary) {}
```
- A *bidirectional streaming RPC* where both sides send a sequence of messages using a read-write stream. The two streams operate independently, so clients and servers can read and write in whatever order they like: for example, the server could wait to receive all the client messages before writing its responses, or it could alternately read a message then write a message, or some other combination of reads and writes. The order of messages in each stream is preserved. You specify this type of method by placing the `stream` keyword before both the request and the response.
```protobuf
// Accepts a stream of RouteNotes sent while a route is being traversed,
// while receiving other RouteNotes (e.g. from other users).
rpc RouteChat(stream RouteNote) returns (stream RouteNote) {}
```
Our .proto file also contains protocol buffer message type definitions for all the request and response types used in our service methods - for example, here's the `Point` message type:
```protobuf
// Points are represented as latitude-longitude pairs in the E7 representation
// (degrees multiplied by 10**7 and rounded to the nearest integer).
// Latitudes should be in the range +/- 90 degrees and longitude should be in
// the range +/- 180 degrees (inclusive).
message Point {
int32 latitude = 1;
int32 longitude = 2;
}
```
## Loading service descriptors from proto files
The Node.js library dynamically generates service descriptors and client stub definitions from `.proto` files loaded at runtime.
To load a `.proto` file, simply `require` the gRPC library, then use its `load()` method:
```node
var grpc = require('grpc');
var protoDescriptor = grpc.load(__dirname + '/route_guide.proto');
// The protoDescriptor object has the full package hierarchy
var example = protoDescriptor.routeguide;
```
Once you've done this, the stub constructor is in the `routeguide` namespace (`protoDescriptor.routeguide.RouteGuide`) and the service descriptor (which is used to create a server) is a property of the stub (`protoDescriptor.routeguide.RouteGuide.service`);
<a name="server"></a>
## Creating the server
First let's look at how we create a `RouteGuide` server. If you're only interested in creating gRPC clients, you can skip this section and go straight to [Creating the client](#client) (though you might find it interesting anyway!).
There are two parts to making our `RouteGuide` service do its job:
- Implementing the service interface generated from our service definition: doing the actual "work" of our service.
- Running a gRPC server to listen for requests from clients and return the service responses.
You can find our example `RouteGuide` server in [route_guide_server.js](route_guide_server.js). Let's take a closer look at how it works.
### Implementing RouteGuide
As you can see, our server has a `Server` constructor generated from the `RouteGuide.service` descriptor object
```node
var Server = grpc.buildServer([routeguide.RouteGuide.service]);
```
In this case we're implementing the *asynchronous* version of `RouteGuide`, which provides our default gRPC server behaviour.
The functions in `route_guide_server.js` implement all our service methods. Let's look at the simplest type first, `getFeature`, which just gets a `Point` from the client and returns the corresponding feature information from its database in a `Feature`.
```node
function checkFeature(point) {
var feature;
// Check if there is already a feature object for the given point
for (var i = 0; i < feature_list.length; i++) {
feature = feature_list[i];
if (feature.location.latitude === point.latitude &&
feature.location.longitude === point.longitude) {
return feature;
}
}
var name = '';
feature = {
name: name,
location: point
};
return feature;
}
function getFeature(call, callback) {
callback(null, checkFeature(call.request));
}
```
The method is passed a call object for the RPC, which has the `Point` parameter as a property, and a callback to which we can pass our returned `Feature`. In the method body we populate a `Feature` corresponding to the given point and pass it to the callback, with a null first parameter to indicate that there is no error.
Now let's look at something a bit more complicated - a streaming RPC. `listFeatures` is a server-side streaming RPC, so we need to send back multiple `Feature`s to our client.
```node
function listFeatures(call) {
var lo = call.request.lo;
var hi = call.request.hi;
var left = _.min([lo.longitude, hi.longitude]);
var right = _.max([lo.longitude, hi.longitude]);
var top = _.max([lo.latitude, hi.latitude]);
var bottom = _.min([lo.latitude, hi.latitude]);
// For each feature, check if it is in the given bounding box
_.each(feature_list, function(feature) {
if (feature.name === '') {
return;
}
if (feature.location.longitude >= left &&
feature.location.longitude <= right &&
feature.location.latitude >= bottom &&
feature.location.latitude <= top) {
call.write(feature);
}
});
call.end();
}
```
As you can see, instead of getting the call object and callback in our method parameters, this time we get a `call` object that implements the `Writable` interface. In the method, we create as many `Feature` objects as we need to return, writing them to the `call` using its `write()` method. Finally, we call `call.end()` to indicate that we have sent all messages.
If you look at the client-side streaming method `RecordRoute` you'll see it's quite similar to the unary call, except this time the `call` parameter implements the `Reader` interface. The `call`'s `'data'` event fires every time there is new data, and the `'end'` event fires when all data has been read. Like the unary case, we respond by calling the callback
```node
call.on('data', function(point) {
// Process user data
});
call.on('end', function() {
callback(null, result);
});
```
Finally, let's look at our bidirectional streaming RPC `RouteChat()`.
```node
function routeChat(call) {
call.on('data', function(note) {
var key = pointKey(note.location);
/* For each note sent, respond with all previous notes that correspond to
* the same point */
if (route_notes.hasOwnProperty(key)) {
_.each(route_notes[key], function(note) {
call.write(note);
});
} else {
route_notes[key] = [];
}
// Then add the new note to the list
route_notes[key].push(JSON.parse(JSON.stringify(note)));
});
call.on('end', function() {
call.end();
});
}
```
This time we get a `call` implementing `Duplex` that can be used to read *and* write messages. The syntax for reading and writing here is exactly the same as for our client-streaming and server-streaming methods. Although each side will always get the other's messages in the order they were written, both the client and server can read and write in any order — the streams operate completely independently.
### Starting the server
Once we've implemented all our methods, we also need to start up a gRPC server so that clients can actually use our service. The following snippet shows how we do this for our `RouteGuide` service:
```node
function getServer() {
var server = new grpc.Server();
server.addProtoService(routeguide.RouteGuide.service, {
getFeature: getFeature,
listFeatures: listFeatures,
recordRoute: recordRoute,
routeChat: routeChat
});
return server;
}
var routeServer = getServer();
routeServer.bind('0.0.0.0:50051', grpc.ServerCredentials.createInsecure());
routeServer.start();
```
As you can see, we build and start our server with the following steps:
1. Create a `Server` constructor from the `RouteGuide` service descriptor.
2. Implement the service methods.
3. Create an instance of the server by calling the `Server` constructor with the method implementations.
4. Specify the address and port we want to use to listen for client requests using the instance's `bind()` method.
5. Call `listen()` on the instance to start the RPC server.
<a name="client"></a>
## Creating the client
In this section, we'll look at creating a Node.js client for our `RouteGuide` service. You can see our complete example client code in [route_guide_client.js](route_guide_client.js).
### Creating a stub
To call service methods, we first need to create a *stub*. To do this, we just need to call the RouteGuide stub constructor, specifying the server address and port.
```node
var client = new routeguide.RouteGuide('localhost:50051',
grpc.Credentials.createInsecure());
```
### Calling service methods
Now let's look at how we call our service methods. Note that all of these methods are asynchronous: they use either events or callbacks to retrieve results.
#### Simple RPC
Calling the simple RPC `GetFeature` is nearly as straightforward as calling a local asynchronous method.
```node
var point = {latitude: 409146138, longitude: -746188906};
stub.getFeature(point, function(err, feature) {
if (err) {
// process error
} else {
// process feature
}
});
```
As you can see, we create and populate a request object. Finally, we call the method on the stub, passing it the request and callback. If there is no error, then we can read the response information from the server from our response object.
```node
console.log('Found feature called "' + feature.name + '" at ' +
feature.location.latitude/COORD_FACTOR + ', ' +
feature.location.longitude/COORD_FACTOR);
```
#### Streaming RPCs
Now let's look at our streaming methods. If you've already read [Creating the server](#server) some of this may look very familiar - streaming RPCs are implemented in a similar way on both sides. Here's where we call the server-side streaming method `ListFeatures`, which returns a stream of geographical `Feature`s:
```node
var call = client.listFeatures(rectangle);
call.on('data', function(feature) {
console.log('Found feature called "' + feature.name + '" at ' +
feature.location.latitude/COORD_FACTOR + ', ' +
feature.location.longitude/COORD_FACTOR);
});
call.on('end', function() {
// The server has finished sending
});
call.on('status', function(status) {
// process status
});
```
Instead of passing the method a request and callback, we pass it a request and get a `Readable` stream object back. The client can use the `Readable`'s `'data'` event to read the server's responses. This event fires with each `Feature` message object until there are no more messages: the `'end'` event indicates that the call is done. Finally, the status event fires when the server sends the status.
The client-side streaming method `RecordRoute` is similar, except there we pass the method a callback and get back a `Writable`.
```node
var call = client.recordRoute(function(error, stats) {
if (error) {
callback(error);
}
console.log('Finished trip with', stats.point_count, 'points');
console.log('Passed', stats.feature_count, 'features');
console.log('Travelled', stats.distance, 'meters');
console.log('It took', stats.elapsed_time, 'seconds');
});
function pointSender(lat, lng) {
return function(callback) {
console.log('Visiting point ' + lat/COORD_FACTOR + ', ' +
lng/COORD_FACTOR);
call.write({
latitude: lat,
longitude: lng
});
_.delay(callback, _.random(500, 1500));
};
}
var point_senders = [];
for (var i = 0; i < num_points; i++) {
var rand_point = feature_list[_.random(0, feature_list.length - 1)];
point_senders[i] = pointSender(rand_point.location.latitude,
rand_point.location.longitude);
}
async.series(point_senders, function() {
call.end();
});
```
Once we've finished writing our client's requests to the stream using `write()`, we need to call `end()` on the stream to let gRPC know that we've finished writing. If the status is `OK`, the `stats` object will be populated with the server's response.
Finally, let's look at our bidirectional streaming RPC `routeChat()`. In this case, we just pass a context to the method and get back a `Duplex` stream object, which we can use to both write and read messages.
```node
var call = client.routeChat();
```
The syntax for reading and writing here is exactly the same as for our client-streaming and server-streaming methods. Although each side will always get the other's messages in the order they were written, both the client and server can read and write in any order — the streams operate completely independently.
## Try it out!
Build client and server:
```shell
$ npm install
```
Run the server, which will listen on port 50051:
```shell
$ node ./route_guide_server.js --db_path=route_guide_db.json
```
Run the client (in a different terminal):
```shell
$ node ./route_guide_client.js --db_path=route_guide_db.json
```
[gRPC Basics: Node.js]:http://www.grpc.io/docs/tutorials/basic/node.html

@ -56,9 +56,10 @@ some Protocol Buffer 2.0 syntax. There is no proto3 support for PHP yet.
TUTORIAL
--------
Coming soon
You can find a more detailed tutorial in [gRPC Basics: PHP][]
[homebrew]:http://brew.sh
[linuxbrew]:https://github.com/Homebrew/linuxbrew#installation
[gRPC install script]:https://raw.githubusercontent.com/grpc/homebrew-grpc/master/scripts/install
[Node]:https://github.com/grpc/grpc/tree/master/examples/node
[gRPC Basics: PHP]:http://www.grpc.io/docs/tutorials/basic/php.html

@ -12,6 +12,6 @@
"php": ">=5.5.0",
"datto/protobuf-php": "dev-master",
"google/auth": "dev-master",
"grpc/grpc": "dev-master"
"grpc/grpc": "dev-release-0_11"
}
}

@ -36,8 +36,7 @@ require dirname(__FILE__) . '/vendor/autoload.php';
require dirname(__FILE__) . '/helloworld.php';
function greet($name) {
$client = new helloworld\GreeterClient(
new Grpc\BaseStub('localhost:50051', []));
$client = new helloworld\GreeterClient('localhost:50051', []);
$request = new helloworld\HelloRequest();
$request->setName($name);
list($reply, $status) = $client->SayHello($request)->wait();

@ -1,7 +1,7 @@
<?php
// DO NOT EDIT! Generated by Protobuf-PHP protoc plugin 1.0
// Source: helloworld.proto
// Date: 2015-05-29 21:39:19
// Date: 2015-09-24 20:40:14
namespace helloworld {
@ -143,18 +143,16 @@ namespace helloworld {
namespace helloworld {
class GreeterClient{
class GreeterClient extends \Grpc\BaseStub {
private $rpc_impl;
public function __construct($rpc_impl) {
$this->rpc_impl = $rpc_impl;
public function __construct($hostname, $opts) {
parent::__construct($hostname, $opts);
}
/**
* @param helloworld\HelloRequest $input
*/
public function SayHello(\helloworld\HelloRequest $argument, $metadata = array()) {
return $this->rpc_impl->_simpleRequest('/helloworld.Greeter/SayHello', $argument, '\helloworld\HelloReply::deserialize', $metadata);
public function SayHello(\helloworld\HelloRequest $argument, $metadata = array(), $options = array()) {
return $this->_simpleRequest('/helloworld.Greeter/SayHello', $argument, '\helloworld\HelloReply::deserialize', $metadata, $options);
}
}
}

@ -1,262 +1,6 @@
#gRPC Basics: PHP
#gRPC Basics: PHP sample code
This tutorial provides a basic PHP programmer's introduction to working with gRPC. By walking through this example you'll learn how to:
The files in this folder are the samples used in [gRPC Basics: PHP][],
a detailed tutorial for using gRPC in Ruby.
- Define a service in a .proto file.
- Generate client code using the protocol buffer compiler.
- Use the PHP gRPC API to write a simple client for your service.
It assumes a passing familiarity with [protocol buffers](https://developers.google.com/protocol-buffers/docs/overview). Note that the example in this tutorial uses the proto2 version of the protocol buffers language.
Also note that currently you can only create clients in PHP for gRPC services - you can find out how to create gRPC servers in our other tutorials, e.g. [Node.js](../node/route_guide).
This isn't a comprehensive guide to using gRPC in PHP: more reference documentation is coming soon.
- [Why use gRPC?](#why-grpc)
- [Example code and setup](#setup)
- [Try it out!](#try)
- [Defining the service](#proto)
- [Generating client code](#protoc)
- [Creating the client](#client)
<a name="why-grpc"></a>
## Why use gRPC?
With gRPC you can define your service once in a .proto file and implement clients and servers in any of gRPC's supported languages, which in turn can be run in environments ranging from servers inside Google to your own tablet - all the complexity of communication between different languages and environments is handled for you by gRPC. You also get all the advantages of working with protocol buffers, including efficient serialization, a simple IDL, and easy interface updating.
<a name="setup"></a>
## Example code and setup
The example code for our tutorial is in [examples/php/route_guide](.). To download the example, clone this repository by running the following command:
```shell
$ git clone https://github.com/grpc/grpc.git
```
Then change your current directory to `examples/php/route_guide`:
```shell
$ cd examples/php/route_guide
```
Our example is a simple route mapping application that lets clients get information about features on their route, create a summary of their route, and exchange route information such as traffic updates with the server and other clients.
You also should have the relevant tools installed to generate the client interface code (and a server in another language, for testing). You can obtain the latter by following [these setup instructions](https://github.com/grpc/homebrew-grpc).
<a name="try"></a>
## Try it out!
To try the sample app, we need a gRPC server running locally. Let's compile and run, for example, the Node.js server in this repository:
```shell
$ cd ../../node
$ npm install
$ cd route_guide
$ nodejs ./route_guide_server.js --db_path=route_guide_db.json
```
Run the PHP client (in a different terminal):
```shell
$ ./run_route_guide_client.sh
```
The next sections guide you step-by-step through how this proto service is defined, how to generate a client library from it, and how to create a client stub that uses that library.
<a name="proto"></a>
## Defining the service
First let's look at how the service we're using is defined. A gRPC *service* and its method *request* and *response* types using [protocol buffers](https://developers.google.com/protocol-buffers/docs/overview). You can see the complete .proto file for our example in [`route_guide.proto`](route_guide.proto).
To define a service, you specify a named `service` in your .proto file:
```protobuf
service RouteGuide {
...
}
```
Then you define `rpc` methods inside your service definition, specifying their request and response types. Protocol buffers let you define four kinds of service method, all of which are used in the `RouteGuide` service:
- A *simple RPC* where the client sends a request to the server and receives a response later, just like a normal remote procedure call.
```protobuf
// Obtains the feature at a given position.
rpc GetFeature(Point) returns (Feature) {}
```
- A *response-streaming RPC* where the client sends a request to the server and gets back a stream of response messages. You specify a response-streaming method by placing the `stream` keyword before the *response* type.
```protobuf
// 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.
rpc ListFeatures(Rectangle) returns (stream Feature) {}
```
- A *request-streaming RPC* where the client sends a sequence of messages to the server. Once the client has finished writing the messages, it waits for the server to read them all and return its response. You specify a request-streaming method by placing the `stream` keyword before the *request* type.
```protobuf
// Accepts a stream of Points on a route being traversed, returning a
// RouteSummary when traversal is completed.
rpc RecordRoute(stream Point) returns (RouteSummary) {}
```
- A *bidirectional streaming RPC* where both sides send a sequence of messages to the other. The two streams operate independently, so clients and servers can read and write in whatever order they like: for example, the server could wait to receive all the client messages before writing its responses, or it could alternately read a message then write a message, or some other combination of reads and writes. The order of messages in each stream is preserved. You specify this type of method by placing the `stream` keyword before both the request and the response.
```protobuf
// Accepts a stream of RouteNotes sent while a route is being traversed,
// while receiving other RouteNotes (e.g. from other users).
rpc RouteChat(stream RouteNote) returns (stream RouteNote) {}
```
Our .proto file also contains protocol buffer message type definitions for all the request and response types used in our service methods - for example, here's the `Point` message type:
```protobuf
// Points are represented as latitude-longitude pairs in the E7 representation
// (degrees multiplied by 10**7 and rounded to the nearest integer).
// Latitudes should be in the range +/- 90 degrees and longitude should be in
// the range +/- 180 degrees (inclusive).
message Point {
int32 latitude = 1;
int32 longitude = 2;
}
```
<a name="protoc"></a>
## Generating client code
The PHP client stub implementation of the proto files can be generated by the [`protoc-gen-php`](https://github.com/datto/protobuf-php) tool. To install the tool:
```sh
$ cd examples/php
$ php composer.phar install
$ cd vendor/datto/protobuf-php
$ gem install rake ronn
$ rake pear:package version=1.0
$ sudo pear install Protobuf-1.0.tgz
```
To generate the client stub implementation .php file:
```sh
$ cd php/route_guide
$ protoc-gen-php -i . -o . ./route_guide.proto
```
A `route_guide.php` file will be generated in the `php/route_guide` directory. You do not need to modify the file.
To load the generated client stub file, simply `require` it in your PHP application:
```php
require dirname(__FILE__) . '/route_guide.php';
```
The file contains:
- All the protocol buffer code to populate, serialize, and retrieve our request and response message types.
- A class called `routeguide\RouteGuideClient` that lets clients call the methods defined in the `RouteGuide` service.
<a name="client"></a>
## Creating the client
In this section, we'll look at creating a PHP client for our `RouteGuide` service. You can see our complete example client code in [route_guide_client.php](route_guide_client.php).
### Constructing a client object
To call service methods, we first need to create a client object, an instance of the generated `RouteGuideClient` class. The constructor of the class expects the server address and port we want to connect to:
```php
$client = new routeguide\RouteGuideClient(new Grpc\BaseStub('localhost:50051', []));
```
### Calling service methods
Now let's look at how we call our service methods.
#### Simple RPC
Calling the simple RPC `GetFeature` is nearly as straightforward as calling a local asynchronous method.
```php
$point = new routeguide\Point();
$point->setLatitude(409146138);
$point->setLongitude(-746188906);
list($feature, $status) = $client->GetFeature($point)->wait();
```
As you can see, we create and populate a request object, i.e. an `routeguide\Point` object. Then, we call the method on the stub, passing it the request object. If there is no error, then we can read the response information from the server from our response object, i.e. an `routeguide\Feature` object.
```php
print sprintf("Found %s \n at %f, %f\n", $feature->getName(),
$feature->getLocation()->getLatitude() / COORD_FACTOR,
$feature->getLocation()->getLongitude() / COORD_FACTOR);
```
#### Streaming RPCs
Now let's look at our streaming methods. Here's where we call the server-side streaming method `ListFeatures`, which returns a stream of geographical `Feature`s:
```php
$lo_point = new routeguide\Point();
$hi_point = new routeguide\Point();
$lo_point->setLatitude(400000000);
$lo_point->setLongitude(-750000000);
$hi_point->setLatitude(420000000);
$hi_point->setLongitude(-730000000);
$rectangle = new routeguide\Rectangle();
$rectangle->setLo($lo_point);
$rectangle->setHi($hi_point);
$call = $client->ListFeatures($rectangle);
// an iterator over the server streaming responses
$features = $call->responses();
foreach ($features as $feature) {
// process each feature
} // the loop will end when the server indicates there is no more responses to be sent.
```
The `$call->responses()` method call returns an iterator. When the server sends a response, a `$feature` object will be returned in the `foreach` loop, until the server indiciates that there will be no more responses to be sent.
The client-side streaming method `RecordRoute` is similar, except there we pass the method an iterator and get back a `routeguide\RouteSummary`.
```php
$points_iter = function($db) {
for ($i = 0; $i < $num_points; $i++) {
$point = new routeguide\Point();
$point->setLatitude($lat);
$point->setLongitude($long);
yield $point;
}
};
// $points_iter is an iterator simulating client streaming
list($route_summary, $status) =
$client->RecordRoute($points_iter($db))->wait();
```
Finally, let's look at our bidirectional streaming RPC `routeChat()`. In this case, we just pass a context to the method and get back a `BidiStreamingCall` stream object, which we can use to both write and read messages.
```php
$call = $client->RouteChat();
```
To write messages from the client:
```php
foreach ($notes as $n) {
$route_note = new routerguide\RouteNote();
$call->write($route_note);
}
$call->writesDone();
```
To read messages from the server:
```php
while ($route_note_reply = $call->read()) {
// process $route_note_reply
}
```
Each side will always get the other's messages in the order they were written, both the client and server can read and write in any order — the streams operate completely independently.
[gRPC Basics: PHP]:http://www.grpc.io/docs/tutorials/basic/php.html

@ -1,7 +1,7 @@
<?php
// DO NOT EDIT! Generated by Protobuf-PHP protoc plugin 1.0
// Source: route_guide.proto
// Date: 2015-08-31 21:11:45
// Date: 2015-09-24 21:21:51
namespace routeguide {

@ -37,8 +37,7 @@ require dirname(__FILE__) . '/route_guide.php';
define('COORD_FACTOR', 1e7);
$client = new routeguide\RouteGuideClient(
new Grpc\BaseStub('localhost:50051', []));
$client = new routeguide\RouteGuideClient('localhost:50051', []);
function printFeature($feature) {
$name = $feature->getName();
@ -96,6 +95,7 @@ function runListFeatures() {
$rectangle->setLo($lo_point);
$rectangle->setHi($hi_point);
// start the server streaming call
$call = $client->ListFeatures($rectangle);
// an iterator over the server streaming responses
$features = $call->responses();
@ -113,28 +113,27 @@ function runRecordRoute() {
print "Running RecordRoute...\n";
global $client, $argv;
// start the client streaming call
$call = $client->RecordRoute();
$db = json_decode(file_get_contents($argv[1]), true);
$points_iter = function($db) {
$num_points_in_db = count($db);
$num_points = 10;
for ($i = 0; $i < $num_points; $i++) {
$point = new routeguide\Point();
$index = rand(0, $num_points_in_db - 1);
$lat = $db[$index]['location']['latitude'];
$long = $db[$index]['location']['longitude'];
$feature_name = $db[$index]['name'];
$point->setLatitude($lat);
$point->setLongitude($long);
print sprintf("Visiting point %f, %f,\n with feature name: %s\n",
$lat / COORD_FACTOR, $long / COORD_FACTOR,
$feature_name ? $feature_name : '<empty>');
usleep(rand(300000, 800000));
yield $point;
}
};
// $points_iter is an iterator simulating client streaming
list($route_summary, $status) =
$client->RecordRoute($points_iter($db))->wait();
$num_points_in_db = count($db);
$num_points = 10;
for ($i = 0; $i < $num_points; $i++) {
$point = new routeguide\Point();
$index = rand(0, $num_points_in_db - 1);
$lat = $db[$index]['location']['latitude'];
$long = $db[$index]['location']['longitude'];
$feature_name = $db[$index]['name'];
$point->setLatitude($lat);
$point->setLongitude($long);
print sprintf("Visiting point %f, %f,\n with feature name: %s\n",
$lat / COORD_FACTOR, $long / COORD_FACTOR,
$feature_name ? $feature_name : '<empty>');
usleep(rand(300000, 800000));
$call->write($point);
}
list($route_summary, $status) = $call->wait();
print sprintf("Finished trip with %d points\nPassed %d features\n".
"Travelled %d meters\nIt took %d seconds\n",
$route_summary->getPointCount(),

@ -30,7 +30,5 @@
set -e
cd $(dirname $0)
command -v brew >/dev/null 2>&1 && \
extension_dir="-d extension_dir="`brew --prefix`/opt/grpc-php
php $extension_dir -d extension=grpc.so \
php $extension_dir -d extension=grpc.so -d max_execution_time=300 \
route_guide_client.php ../../node/route_guide/route_guide_db.json

@ -30,6 +30,5 @@
set -e
cd $(dirname $0)
command -v brew >/dev/null 2>&1 && \
extension_dir="-d extension_dir="`brew --prefix`/opt/grpc-php
php $extension_dir -d extension=grpc.so greeter_client.php $1
php $extension_dir -d extension=grpc.so -d max_execution_time=300 \
greeter_client.php $1

@ -3,4 +3,4 @@
source 'https://rubygems.org/'
gem 'grpc', :git => 'https://github.com/grpc/grpc.git', :submodules => true, glob: 'src/ruby/*.gemspec'
gemspec

@ -25,8 +25,8 @@ RVM is also useful if you don't have the necessary privileges to update your sys
INSTALL
-------
- [Install gRPC Ruby][]
- Clone this repository
- Use bundler to install the example package's dependencies
```sh
@ -35,7 +35,7 @@ INSTALL
$ bundle install
```
Try it!
Try it!
-------
- Run the server
@ -55,7 +55,9 @@ Try it!
Tutorial
--------
You can find a more detailed tutorial in [gRPC Basics: Ruby](route_guide/README.md)
You can find a more detailed tutorial in [gRPC Basics: Ruby][]
[helloworld.proto]:../protos/helloworld.proto
[RVM]:https://www.rvm.io/
[Install gRPC ruby]:../../src/ruby#installation
[gRPC Basics: Ruby]:http://www.grpc.io/docs/tutorials/basic/ruby.html

@ -52,9 +52,9 @@ end
# server port.
def main
s = GRPC::RpcServer.new
s.add_http2_port('0.0.0.0:50051')
s.add_http2_port('0.0.0.0:50051', :this_port_is_insecure)
s.handle(GreeterServer)
s.run
s.run_till_terminated
end
main

@ -3,7 +3,7 @@
Gem::Specification.new do |s|
s.name = 'grpc-demo'
s.version = '0.5.0'
s.version = '0.11.0'
s.authors = ['gRPC Authors']
s.email = 'temiola@google.com'
s.homepage = 'https://github.com/grpc/grpc'
@ -17,7 +17,7 @@ Gem::Specification.new do |s|
s.require_paths = ['lib']
s.platform = Gem::Platform::RUBY
s.add_dependency 'grpc', '~> 0.6'
s.add_dependency 'grpc', '~> 0.11'
s.add_development_dependency 'bundler', '~> 1.7'
end

@ -4,23 +4,23 @@
require 'google/protobuf'
Google::Protobuf::DescriptorPool.generated_pool.build do
add_message "examples.Point" do
add_message "routeguide.Point" do
optional :latitude, :int32, 1
optional :longitude, :int32, 2
end
add_message "examples.Rectangle" do
optional :lo, :message, 1, "examples.Point"
optional :hi, :message, 2, "examples.Point"
add_message "routeguide.Rectangle" do
optional :lo, :message, 1, "routeguide.Point"
optional :hi, :message, 2, "routeguide.Point"
end
add_message "examples.Feature" do
add_message "routeguide.Feature" do
optional :name, :string, 1
optional :location, :message, 2, "examples.Point"
optional :location, :message, 2, "routeguide.Point"
end
add_message "examples.RouteNote" do
optional :location, :message, 1, "examples.Point"
add_message "routeguide.RouteNote" do
optional :location, :message, 1, "routeguide.Point"
optional :message, :string, 2
end
add_message "examples.RouteSummary" do
add_message "routeguide.RouteSummary" do
optional :point_count, :int32, 1
optional :feature_count, :int32, 2
optional :distance, :int32, 3
@ -28,10 +28,10 @@ Google::Protobuf::DescriptorPool.generated_pool.build do
end
end
module Examples
Point = Google::Protobuf::DescriptorPool.generated_pool.lookup("examples.Point").msgclass
Rectangle = Google::Protobuf::DescriptorPool.generated_pool.lookup("examples.Rectangle").msgclass
Feature = Google::Protobuf::DescriptorPool.generated_pool.lookup("examples.Feature").msgclass
RouteNote = Google::Protobuf::DescriptorPool.generated_pool.lookup("examples.RouteNote").msgclass
RouteSummary = Google::Protobuf::DescriptorPool.generated_pool.lookup("examples.RouteSummary").msgclass
module Routeguide
Point = Google::Protobuf::DescriptorPool.generated_pool.lookup("routeguide.Point").msgclass
Rectangle = Google::Protobuf::DescriptorPool.generated_pool.lookup("routeguide.Rectangle").msgclass
Feature = Google::Protobuf::DescriptorPool.generated_pool.lookup("routeguide.Feature").msgclass
RouteNote = Google::Protobuf::DescriptorPool.generated_pool.lookup("routeguide.RouteNote").msgclass
RouteSummary = Google::Protobuf::DescriptorPool.generated_pool.lookup("routeguide.RouteSummary").msgclass
end

@ -1,10 +1,10 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# Source: route_guide.proto for package 'examples'
# Source: route_guide.proto for package 'routeguide'
require 'grpc'
require 'route_guide'
module Examples
module Routeguide
module RouteGuide
# TODO: add proto service documentation here
@ -14,7 +14,7 @@ module Examples
self.marshal_class_method = :encode
self.unmarshal_class_method = :decode
self.service_name = 'examples.RouteGuide'
self.service_name = 'routeguide.RouteGuide'
rpc :GetFeature, Point, Feature
rpc :ListFeatures, Rectangle, stream(Feature)

@ -1,285 +1,6 @@
#gRPC Basics: Ruby
#gRPC Basics: Ruby sample code
This tutorial provides a basic Ruby programmer's introduction to working with gRPC. By walking through this example you'll learn how to:
- Define a service in a .proto file.
- Generate server and client code using the protocol buffer compiler.
- Use the Ruby gRPC API to write a simple client and server for your service.
It assumes that you have read the [Getting started](https://github.com/grpc/grpc/tree/master/examples) guide and are familiar with [protocol buffers] (https://developers.google.com/protocol-buffers/docs/overview). Note that the example in this tutorial uses the proto3 version of the protocol buffers language, which is currently in alpha release:you can find out more in the [proto3 language guide](https://developers.google.com/protocol-buffers/docs/proto3) and see the [release notes](https://github.com/google/protobuf/releases) for the new version in the protocol buffers Github repository.
This isn't a comprehensive guide to using gRPC in Ruby: more reference documentation is coming soon.
## Why use gRPC?
Our example is a simple route mapping application that lets clients get information about features on their route, create a summary of their route, and exchange route information such as traffic updates with the server and other clients.
With gRPC we can define our service once in a .proto file and implement clients and servers in any of gRPC's supported languages, which in turn can be run in environments ranging from servers inside Google to your own tablet - all the complexity of communication between different languages and environments is handled for you by gRPC. We also get all the advantages of working with protocol buffers, including efficient serialization, a simple IDL, and easy interface updating.
## Example code and setup
The example code for our tutorial is in [examples/ruby/route_guide](.). To download the example, clone this repository by running the following command:
```shell
$ git clone https://github.com/grpc/grpc.git
```
Then change your current directory to `examples/ruby/route_guide`:
```shell
$ cd examples/ruby/route_guide
```
You also should have the relevant tools installed to generate the server and client interface code - if you don't already, follow the setup instructions in [the Ruby quick start guide](..).
## Defining the service
Our first step (as you'll know from [Getting started](https://github.com/grpc/grpc/tree/master/examples)) is to define the gRPC *service* and the method *request* and *response* types using [protocol buffers] (https://developers.google.com/protocol-buffers/docs/overview). You can see the complete .proto file in [`examples/protos/route_guide.proto`](../../route_guide.proto).
To define a service, you specify a named `service` in your .proto file:
```protobuf
service RouteGuide {
...
}
```
Then you define `rpc` methods inside your service definition, specifying their request and response types. gRPC lets you define four kinds of service method, all of which are used in the `RouteGuide` service:
- A *simple RPC* where the client sends a request to the server using the stub and waits for a response to come back, just like a normal function call.
```protobuf
// Obtains the feature at a given position.
rpc GetFeature(Point) returns (Feature) {}
```
- A *server-side streaming RPC* where the client sends a request to the server and gets a stream to read a sequence of messages back. The client reads from the returned stream until there are no more messages. As you can see in our example, you specify a server-side streaming method by placing the `stream` keyword before the *response* type.
```protobuf
// 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.
rpc ListFeatures(Rectangle) returns (stream Feature) {}
```
- A *client-side streaming RPC* where the client writes a sequence of messages and sends them to the server, again using a provided stream. Once the client has finished writing the messages, it waits for the server to read them all and return its response. You specify a server-side streaming method by placing the `stream` keyword before the *request* type.
```protobuf
// Accepts a stream of Points on a route being traversed, returning a
// RouteSummary when traversal is completed.
rpc RecordRoute(stream Point) returns (RouteSummary) {}
```
- A *bidirectional streaming RPC* where both sides send a sequence of messages using a read-write stream. The two streams operate independently, so clients and servers can read and write in whatever order they like: for example, the server could wait to receive all the client messages before writing its responses, or it could alternately read a message then write a message, or some other combination of reads and writes. The order of messages in each stream is preserved. You specify this type of method by placing the `stream` keyword before both the request and the response.
```protobuf
// Accepts a stream of RouteNotes sent while a route is being traversed,
// while receiving other RouteNotes (e.g. from other users).
rpc RouteChat(stream RouteNote) returns (stream RouteNote) {}
```
Our .proto file also contains protocol buffer message type definitions for all the request and response types used in our service methods - for example, here's the `Point` message type:
```protobuf
// Points are represented as latitude-longitude pairs in the E7 representation
// (degrees multiplied by 10**7 and rounded to the nearest integer).
// Latitudes should be in the range +/- 90 degrees and longitude should be in
// the range +/- 180 degrees (inclusive).
message Point {
int32 latitude = 1;
int32 longitude = 2;
}
```
## Generating client and server code
Next we need to generate the gRPC client and server interfaces from our .proto service definition. We do this using the protocol buffer compiler `protoc` with a special gRPC Ruby plugin.
If you want to run this yourself, make sure you've installed protoc and followed the gRPC Ruby plugin [installation instructions](https://github.com/grpc/grpc/blob/master/INSTALL) first):
Once that's done, the following command can be used to generate the ruby code.
```shell
$ protoc -I ../../protos --ruby_out=lib --grpc_out=lib --plugin=protoc-gen-grpc=`which grpc_ruby_plugin` ../../protos/route_guide.proto
```
Running this command regenerates the following files in the lib directory:
- `lib/route_guide.pb` defines a module `Examples::RouteGuide`
- This contain all the protocol buffer code to populate, serialize, and retrieve our request and response message types
- `lib/route_guide_services.pb`, extends `Examples::RouteGuide` with stub and service classes
- a class `Service` for use as a base class when defining RouteGuide service implementations
- a class `Stub` that can be used to access remote RouteGuide instances
<a name="server"></a>
## Creating the server
First let's look at how we create a `RouteGuide` server. If you're only interested in creating gRPC clients, you can skip this section and go straight to [Creating the client](#client) (though you might find it interesting anyway!).
There are two parts to making our `RouteGuide` service do its job:
- Implementing the service interface generated from our service definition: doing the actual "work" of our service.
- Running a gRPC server to listen for requests from clients and return the service responses.
You can find our example `RouteGuide` server in [route_guide_server.rb](route_guide_server.rb). Let's take a closer look at how it works.
### Implementing RouteGuide
As you can see, our server has a `ServerImpl` class that extends the generated `RouteGuide::Service`:
```ruby
# ServerImpl provides an implementation of the RouteGuide service.
class ServerImpl < RouteGuide::Service
```
`ServerImpl` implements all our service methods. Let's look at the simplest type first, `GetFeature`, which just gets a `Point` from the client and returns the corresponding feature information from its database in a `Feature`.
```ruby
def get_feature(point, _call)
name = @feature_db[{
'longitude' => point.longitude,
'latitude' => point.latitude }] || ''
Feature.new(location: point, name: name)
end
```
The method is passed a _call for the RPC, the client's `Point` protocol buffer request, and returns a `Feature` protocol buffer. In the method we create the `Feature` with the appropriate information, and then `return` it.
Now let's look at something a bit more complicated - a streaming RPC. `ListFeatures` is a server-side streaming RPC, so we need to send back multiple `Feature`s to our client.
```ruby
# in ServerImpl
def list_features(rectangle, _call)
RectangleEnum.new(@feature_db, rectangle).each
end
```
As you can see, here the request object is a `Rectangle` in which our client wants to find `Feature`s, but instead of returning a simple response we need to return an [Enumerator](http://ruby-doc.org//core-2.2.0/Enumerator.html) that yields the responses. In the method, we use a helper class `RectangleEnum`, to act as an Enumerator implementation.
Similarly, the client-side streaming method `record_route` uses an [Enumerable](http://ruby-doc.org//core-2.2.0/Enumerable.html), but here it's obtained from the call object, which we've ignored in the earlier examples. `call.each_remote_read` yields each message sent by the client in turn.
```ruby
call.each_remote_read do |point|
...
end
```
Finally, let's look at our bidirectional streaming RPC `route_chat`.
```ruby
def route_chat(notes)
q = EnumeratorQueue.new(self)
t = Thread.new do
begin
notes.each do |n|
...
end
end
q = EnumeratorQueue.new(self)
...
return q.each_item
end
```
Here the method receives an [Enumerable](http://ruby-doc.org//core-2.2.0/Enumerable.html), but also returns an [Enumerator](http://ruby-doc.org//core-2.2.0/Enumerator.html) that yields the responses. The implementation demonstrates how to set these up so that the requests and responses can be handled concurrently. Although each side will always get the other's messages in the order they were written, both the client and server can read and write in any order — the streams operate completely independently.
### Starting the server
Once we've implemented all our methods, we also need to start up a gRPC server so that clients can actually use our service. The following snippet shows how we do this for our `RouteGuide` service:
```ruby
s = GRPC::RpcServer.new
s.add_http2_port(port)
logger.info("... running insecurely on #{port}")
s.handle(ServerImpl.new(feature_db))
s.run
```
As you can see, we build and start our server using a `GRPC::RpcServer`. To do this, we:
1. Create an instance of our service implementation class `ServerImpl`.
2. Specify the address and port we want to use to listen for client requests using the builder's `add_http2_port` method.
3. Register our service implementation with the `GRPC::RpcServer`.
4. Call `run` on the`GRPC::RpcServer` to create and start an RPC server for our service.
<a name="client"></a>
## Creating the client
In this section, we'll look at creating a Ruby client for our `RouteGuide` service. You can see our complete example client code in [route_guide_client.rb](route_guide_client.rb).
### Creating a stub
To call service methods, we first need to create a *stub*.
We use the `Stub` class of the `RouteGuide` module generated from our .proto.
```ruby
stub = RouteGuide::Stub.new('localhost:50051')
```
### Calling service methods
Now let's look at how we call our service methods. Note that the gRPC Ruby only provides *blocking/synchronous* versions of each method: this means that the RPC call waits for the server to respond, and will either return a response or raise an exception.
#### Simple RPC
Calling the simple RPC `GetFeature` is nearly as straightforward as calling a local method.
```ruby
GET_FEATURE_POINTS = [
Point.new(latitude: 409_146_138, longitude: -746_188_906),
Point.new(latitude: 0, longitude: 0)
]
..
GET_FEATURE_POINTS.each do |pt|
resp = stub.get_feature(pt)
...
p "- found '#{resp.name}' at #{pt.inspect}"
end
```
As you can see, we create and populate a request protocol buffer object (in our case `Point`), and create a response protocol buffer object for the server to fill in. Finally, we call the method on the stub, passing it the context, request, and response. If the method returns `OK`, then we can read the response information from the server from our response object.
#### Streaming RPCs
Now let's look at our streaming methods. If you've already read [Creating the server](#server) some of this may look very familiar - streaming RPCs are implemented in a similar way on both sides. Here's where we call the server-side streaming method `list_features`, which returns an `Enumerable` of `Features`
```ruby
resps = stub.list_features(LIST_FEATURES_RECT)
resps.each do |r|
p "- found '#{r.name}' at #{r.location.inspect}"
end
```
The client-side streaming method `record_route` is similar, except there we pass the server an `Enumerable`.
```ruby
...
reqs = RandomRoute.new(features, points_on_route)
resp = stub.record_route(reqs.each, deadline)
...
```
Finally, let's look at our bidirectional streaming RPC `route_chat`. In this case, we pass `Enumerable` to the method and get back an `Enumerable`.
```ruby
resps = stub.route_chat(ROUTE_CHAT_NOTES)
resps.each { |r| p "received #{r.inspect}" }
```
Although it's not shown well by this example, each enumerable is independent of the other - both the client and server can read and write in any order — the streams operate completely independently.
## Try it out!
Build client and server:
```shell
$ # from examples/ruby
$ gem install bundler && bundle install
```
Run the server, which will listen on port 50051:
```shell
$ # from examples/ruby
$ bundle exec route_guide/route_guide_server.rb ../node/route_guide/route_guide_db.json &
```
Run the client (in a different terminal):
```shell
$ # from examples/ruby
$ bundle exec route_guide/route_guide_client.rb ../node/route_guide/route_guide_db.json &
```
The files in this folder are the samples used in [gRPC Basics: Ruby][],
a detailed tutorial for using gRPC in Ruby.
[gRPC Basics: Ruby]:http://www.grpc.io/docs/tutorials/basic/ruby.html

@ -40,7 +40,7 @@ $LOAD_PATH.unshift(lib_dir) unless $LOAD_PATH.include?(lib_dir)
require 'grpc'
require 'route_guide_services'
include Examples
include Routeguide
GET_FEATURE_POINTS = [
Point.new(latitude: 409_146_138, longitude: -746_188_906),

@ -42,7 +42,7 @@ require 'grpc'
require 'multi_json'
require 'route_guide_services'
include Examples
include Routeguide
COORD_FACTOR = 1e7
RADIUS = 637_100
@ -202,10 +202,10 @@ def main
feature_db = Hash[raw_data.map { |x| [x['location'], x['name']] }]
port = '0.0.0.0:50051'
s = GRPC::RpcServer.new
s.add_http2_port(port)
s.add_http2_port(port, :this_port_is_insecure)
GRPC.logger.info("... running insecurely on #{port}")
s.handle(ServerImpl.new(feature_db))
s.run
s.run_till_terminated
end
main

@ -36,14 +36,16 @@
Pod::Spec.new do |s|
s.name = 'gRPC'
s.version = '0.11.0'
version = '0.11.1'
s.version = version
s.summary = 'gRPC client library for iOS/OSX'
s.homepage = 'http://www.grpc.io'
s.license = 'New BSD'
s.authors = { 'The gRPC contributors' => 'grpc-packages@google.com' }
# s.source = { :git => 'https://github.com/grpc/grpc.git',
# :tag => 'release-0_11_0-objectivec-0.11.0' }
s.source = { :git => 'https://github.com/grpc/grpc.git',
:tag => "release-#{version.gsub(/\./, '_')}-objectivec-#{version}" }
s.ios.deployment_target = '7.1'
s.osx.deployment_target = '10.9'
@ -222,6 +224,7 @@ Pod::Spec.new do |s|
'src/core/profiling/timers.h',
'src/core/statistics/census_interface.h',
'src/core/statistics/census_rpc_stats.h',
'src/core/surface/api_trace.h',
'src/core/surface/byte_buffer_queue.h',
'src/core/surface/call.h',
'src/core/surface/channel.h',
@ -365,6 +368,7 @@ Pod::Spec.new do |s|
'src/core/json/json_writer.c',
'src/core/profiling/basic_timers.c',
'src/core/profiling/stap_timers.c',
'src/core/surface/api_trace.c',
'src/core/surface/byte_buffer.c',
'src/core/surface/byte_buffer_queue.c',
'src/core/surface/byte_buffer_reader.c',
@ -382,7 +386,6 @@ Pod::Spec.new do |s|
'src/core/surface/server.c',
'src/core/surface/server_chttp2.c',
'src/core/surface/server_create.c',
'src/core/surface/surface_trace.c',
'src/core/surface/version.c',
'src/core/transport/chttp2/alpn.c',
'src/core/transport/chttp2/bin_encoder.c',
@ -512,6 +515,7 @@ Pod::Spec.new do |s|
'src/core/profiling/timers.h',
'src/core/statistics/census_interface.h',
'src/core/statistics/census_rpc_stats.h',
'src/core/surface/api_trace.h',
'src/core/surface/byte_buffer_queue.h',
'src/core/surface/call.h',
'src/core/surface/channel.h',

@ -248,6 +248,7 @@
'src/core/json/json_writer.c',
'src/core/profiling/basic_timers.c',
'src/core/profiling/stap_timers.c',
'src/core/surface/api_trace.c',
'src/core/surface/byte_buffer.c',
'src/core/surface/byte_buffer_queue.c',
'src/core/surface/byte_buffer_reader.c',
@ -265,7 +266,6 @@
'src/core/surface/server.c',
'src/core/surface/server_chttp2.c',
'src/core/surface/server_create.c',
'src/core/surface/surface_trace.c',
'src/core/surface/version.c',
'src/core/transport/chttp2/alpn.c',
'src/core/transport/chttp2/bin_encoder.c',
@ -434,6 +434,7 @@
'src/core/json/json_writer.c',
'src/core/profiling/basic_timers.c',
'src/core/profiling/stap_timers.c',
'src/core/surface/api_trace.c',
'src/core/surface/byte_buffer.c',
'src/core/surface/byte_buffer_queue.c',
'src/core/surface/byte_buffer_reader.c',
@ -451,7 +452,6 @@
'src/core/surface/server.c',
'src/core/surface/server_chttp2.c',
'src/core/surface/server_create.c',
'src/core/surface/surface_trace.c',
'src/core/surface/version.c',
'src/core/transport/chttp2/alpn.c',
'src/core/transport/chttp2/bin_encoder.c',

@ -178,8 +178,6 @@
#endif /* _LP64 */
#elif defined(__APPLE__)
#include <TargetConditionals.h>
/* Provides IPV6_RECVPKTINFO */
#define __APPLE_USE_RFC_3542
#ifndef _BSD_SOURCE
#define _BSD_SOURCE
#endif

@ -87,7 +87,8 @@ void gpr_slice_buffer_swap(gpr_slice_buffer *a, gpr_slice_buffer *b);
/* move all of the elements of src into dst */
void gpr_slice_buffer_move_into(gpr_slice_buffer *src, gpr_slice_buffer *dst);
/* remove n bytes from the end of a slice buffer */
void gpr_slice_buffer_trim_end(gpr_slice_buffer *src, size_t n, gpr_slice_buffer *garbage);
void gpr_slice_buffer_trim_end(gpr_slice_buffer *src, size_t n,
gpr_slice_buffer *garbage);
#ifdef __cplusplus
}

@ -5,5 +5,4 @@ Python, PHP, NodeJS, Objective-C) are layered on top of this library.
#Status
Alpha : Ready for early adopters
Beta

@ -33,9 +33,12 @@
#include <grpc/census.h>
#include <grpc/grpc.h>
#include "src/core/surface/api_trace.h"
#include "src/core/surface/call.h"
void grpc_census_call_set_context(grpc_call *call, census_context *context) {
GRPC_API_TRACE("grpc_census_call_set_context(call=%p, census_context=%p)", 2,
(call, context));
if (census_enabled() == CENSUS_FEATURE_NONE) {
return;
}
@ -45,5 +48,6 @@ void grpc_census_call_set_context(grpc_call *call, census_context *context) {
}
census_context *grpc_census_call_get_context(grpc_call *call) {
GRPC_API_TRACE("grpc_census_call_get_context(call=%p)", 1, (call));
return (census_context *)grpc_call_context_get(call, GRPC_CONTEXT_TRACING);
}

@ -692,16 +692,9 @@ static void destroy_channel_elem(grpc_exec_ctx *exec_ctx,
}
const grpc_channel_filter grpc_client_channel_filter = {
cc_start_transport_stream_op,
cc_start_transport_op,
sizeof(call_data),
init_call_elem,
destroy_call_elem,
sizeof(channel_data),
init_channel_elem,
destroy_channel_elem,
cc_get_peer,
"client-channel",
cc_start_transport_stream_op, cc_start_transport_op, sizeof(call_data),
init_call_elem, destroy_call_elem, sizeof(channel_data), init_channel_elem,
destroy_channel_elem, cc_get_peer, "client-channel",
};
void grpc_client_channel_set_resolver(grpc_exec_ctx *exec_ctx,

@ -387,13 +387,6 @@ static void destroy_channel_elem(grpc_exec_ctx *exec_ctx,
}
const grpc_channel_filter grpc_compress_filter = {
compress_start_transport_stream_op,
grpc_channel_next_op,
sizeof(call_data),
init_call_elem,
destroy_call_elem,
sizeof(channel_data),
init_channel_elem,
destroy_channel_elem,
grpc_call_next_get_peer,
"compress"};
compress_start_transport_stream_op, grpc_channel_next_op, sizeof(call_data),
init_call_elem, destroy_call_elem, sizeof(channel_data), init_channel_elem,
destroy_channel_elem, grpc_call_next_get_peer, "compress"};

@ -130,16 +130,9 @@ static char *con_get_peer(grpc_exec_ctx *exec_ctx, grpc_call_element *elem) {
}
const grpc_channel_filter grpc_connected_channel_filter = {
con_start_transport_stream_op,
con_start_transport_op,
sizeof(call_data),
init_call_elem,
destroy_call_elem,
sizeof(channel_data),
init_channel_elem,
destroy_channel_elem,
con_get_peer,
"connected",
con_start_transport_stream_op, con_start_transport_op, sizeof(call_data),
init_call_elem, destroy_call_elem, sizeof(channel_data), init_channel_elem,
destroy_channel_elem, con_get_peer, "connected",
};
void grpc_connected_channel_bind_transport(grpc_channel_stack *channel_stack,

@ -116,13 +116,7 @@ static void destroy_channel_elem(grpc_exec_ctx *exec_ctx,
ignore_unused(channeld);
}
const grpc_channel_filter grpc_no_op_filter = {noop_start_transport_stream_op,
grpc_channel_next_op,
sizeof(call_data),
init_call_elem,
destroy_call_elem,
sizeof(channel_data),
init_channel_elem,
destroy_channel_elem,
grpc_call_next_get_peer,
"no-op"};
const grpc_channel_filter grpc_no_op_filter = {
noop_start_transport_stream_op, grpc_channel_next_op, sizeof(call_data),
init_call_elem, destroy_call_elem, sizeof(channel_data), init_channel_elem,
destroy_channel_elem, grpc_call_next_get_peer, "no-op"};

@ -317,13 +317,8 @@ void pf_notify_on_state_change(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol,
}
static const grpc_lb_policy_vtable pick_first_lb_policy_vtable = {
pf_destroy,
pf_shutdown,
pf_pick,
pf_exit_idle,
pf_broadcast,
pf_check_connectivity,
pf_notify_on_state_change};
pf_destroy, pf_shutdown, pf_pick, pf_exit_idle, pf_broadcast,
pf_check_connectivity, pf_notify_on_state_change};
static void pick_first_factory_ref(grpc_lb_policy_factory *factory) {}

@ -487,13 +487,8 @@ static void rr_notify_on_state_change(grpc_exec_ctx *exec_ctx,
}
static const grpc_lb_policy_vtable round_robin_lb_policy_vtable = {
rr_destroy,
rr_shutdown,
rr_pick,
rr_exit_idle,
rr_broadcast,
rr_check_connectivity,
rr_notify_on_state_change};
rr_destroy, rr_shutdown, rr_pick, rr_exit_idle, rr_broadcast,
rr_check_connectivity, rr_notify_on_state_change};
static void round_robin_factory_ref(grpc_lb_policy_factory *factory) {}

@ -45,6 +45,7 @@
#include "src/core/client_config/resolver_registry.h"
#include "src/core/iomgr/resolve_address.h"
#include "src/core/support/string.h"
#include "src/core/surface/api_trace.h"
#include "src/core/json/json.h"
/** Zookeeper session expiration time in milliseconds */
@ -487,6 +488,7 @@ static void zookeeper_plugin_init() {
}
void grpc_zookeeper_register() {
GRPC_API_TRACE("grpc_zookeeper_register(void)", 0, ());
grpc_register_plugin(zookeeper_plugin_init, NULL);
}

@ -153,8 +153,8 @@ static gpr_timespec compute_connect_deadline(grpc_subchannel *c);
static void subchannel_connected(grpc_exec_ctx *exec_ctx, void *subchannel,
int iomgr_success);
static void subchannel_ref_locked(
grpc_subchannel *c GRPC_SUBCHANNEL_REF_EXTRA_ARGS);
static void subchannel_ref_locked(grpc_subchannel *c
GRPC_SUBCHANNEL_REF_EXTRA_ARGS);
static int subchannel_unref_locked(
grpc_subchannel *c GRPC_SUBCHANNEL_REF_EXTRA_ARGS) GRPC_MUST_USE_RESULT;
static void connection_ref_locked(connection *c GRPC_SUBCHANNEL_REF_EXTRA_ARGS);
@ -203,8 +203,8 @@ static void connection_destroy(grpc_exec_ctx *exec_ctx, connection *c) {
gpr_free(c);
}
static void connection_ref_locked(
connection *c GRPC_SUBCHANNEL_REF_EXTRA_ARGS) {
static void connection_ref_locked(connection *c
GRPC_SUBCHANNEL_REF_EXTRA_ARGS) {
REF_LOG("CONNECTION", c);
subchannel_ref_locked(c->subchannel REF_PASS_ARGS);
++c->refs;
@ -227,14 +227,14 @@ static grpc_subchannel *connection_unref_locked(
* grpc_subchannel implementation
*/
static void subchannel_ref_locked(
grpc_subchannel *c GRPC_SUBCHANNEL_REF_EXTRA_ARGS) {
static void subchannel_ref_locked(grpc_subchannel *c
GRPC_SUBCHANNEL_REF_EXTRA_ARGS) {
REF_LOG("SUBCHANNEL", c);
++c->refs;
}
static int subchannel_unref_locked(
grpc_subchannel *c GRPC_SUBCHANNEL_REF_EXTRA_ARGS) {
static int subchannel_unref_locked(grpc_subchannel *c
GRPC_SUBCHANNEL_REF_EXTRA_ARGS) {
UNREF_LOG("SUBCHANNEL", c);
return --c->refs == 0;
}
@ -413,6 +413,17 @@ void grpc_subchannel_notify_on_state_change(grpc_exec_ctx *exec_ctx,
}
}
int grpc_subchannel_state_change_unsubscribe(grpc_exec_ctx *exec_ctx,
grpc_subchannel *c,
grpc_closure *subscribed_notify) {
int success;
gpr_mu_lock(&c->mu);
success = grpc_connectivity_state_change_unsubscribe(
exec_ctx, &c->state_tracker, subscribed_notify);
gpr_mu_unlock(&c->mu);
return success;
}
void grpc_subchannel_process_transport_op(grpc_exec_ctx *exec_ctx,
grpc_subchannel *c,
grpc_transport_op *op) {
@ -645,11 +656,24 @@ static void on_alarm(grpc_exec_ctx *exec_ctx, void *arg, int iomgr_success) {
iomgr_success = 0;
}
connectivity_state_changed_locked(exec_ctx, c, "alarm");
gpr_mu_unlock(&c->mu);
if (iomgr_success) {
gpr_mu_unlock(&c->mu);
update_reconnect_parameters(c);
continue_connect(exec_ctx, c);
} else {
waiting_for_connect *w4c;
w4c = c->waiting;
c->waiting = NULL;
gpr_mu_unlock(&c->mu);
while (w4c != NULL) {
waiting_for_connect *next = w4c->next;
grpc_subchannel_del_interested_party(exec_ctx, w4c->subchannel,
w4c->pollset);
w4c->notify->cb(exec_ctx, w4c->notify->cb_arg, 0);
GRPC_SUBCHANNEL_UNREF(exec_ctx, w4c->subchannel, "waiting_for_connect");
gpr_free(w4c);
w4c = next;
}
GRPC_CHANNEL_INTERNAL_UNREF(exec_ctx, c->master, "connecting");
GRPC_SUBCHANNEL_UNREF(exec_ctx, c, "connecting");
}
@ -709,8 +733,8 @@ static void connectivity_state_changed_locked(grpc_exec_ctx *exec_ctx,
* grpc_subchannel_call implementation
*/
void grpc_subchannel_call_ref(
grpc_subchannel_call *c GRPC_SUBCHANNEL_REF_EXTRA_ARGS) {
void grpc_subchannel_call_ref(grpc_subchannel_call *c
GRPC_SUBCHANNEL_REF_EXTRA_ARGS) {
gpr_ref(&c->refs);
}

@ -98,6 +98,13 @@ void grpc_subchannel_notify_on_state_change(grpc_exec_ctx *exec_ctx,
grpc_connectivity_state *state,
grpc_closure *notify);
/** Remove \a subscribed_notify from the list of closures to be called on a
* state change if present, returning 1. Otherwise, nothing is done and return
* 0. */
int grpc_subchannel_state_change_unsubscribe(grpc_exec_ctx *exec_ctx,
grpc_subchannel *channel,
grpc_closure *subscribed_notify);
/** express interest in \a channel's activities through \a pollset. */
void grpc_subchannel_add_interested_party(grpc_exec_ctx *exec_ctx,
grpc_subchannel *channel,

@ -37,12 +37,19 @@
#include <grpc/compression.h>
#include <grpc/support/useful.h>
#include "src/core/surface/api_trace.h"
int grpc_compression_algorithm_parse(const char *name, size_t name_length,
grpc_compression_algorithm *algorithm) {
/* we use strncmp not only because it's safer (even though in this case it
* doesn't matter, given that we are comparing against string literals, but
* because this way we needn't have "name" nil-terminated (useful for slice
* data, for example) */
GRPC_API_TRACE(
"grpc_compression_algorithm_parse("
"name=%*.*s, name_length=%lu, algorithm=%p)",
5, ((int)name_length, (int)name_length, name, (unsigned long)name_length,
algorithm));
if (name_length == 0) {
return 0;
}
@ -60,6 +67,8 @@ int grpc_compression_algorithm_parse(const char *name, size_t name_length,
int grpc_compression_algorithm_name(grpc_compression_algorithm algorithm,
char **name) {
GRPC_API_TRACE("grpc_compression_algorithm_parse(algorithm=%d, name=%p)", 2,
((int)algorithm, name));
switch (algorithm) {
case GRPC_COMPRESS_NONE:
*name = "identity";
@ -80,6 +89,8 @@ int grpc_compression_algorithm_name(grpc_compression_algorithm algorithm,
* compression algorithms */
grpc_compression_algorithm grpc_compression_algorithm_for_level(
grpc_compression_level level) {
GRPC_API_TRACE("grpc_compression_algorithm_for_level(level=%d)", 1,
((int)level));
switch (level) {
case GRPC_COMPRESS_LEVEL_NONE:
return GRPC_COMPRESS_NONE;
@ -96,6 +107,8 @@ grpc_compression_algorithm grpc_compression_algorithm_for_level(
grpc_compression_level grpc_compression_level_for_algorithm(
grpc_compression_algorithm algorithm) {
grpc_compression_level clevel;
GRPC_API_TRACE("grpc_compression_level_for_algorithm(algorithm=%d)", 1,
((int)algorithm));
for (clevel = GRPC_COMPRESS_LEVEL_NONE; clevel < GRPC_COMPRESS_LEVEL_COUNT;
++clevel) {
if (grpc_compression_algorithm_for_level(clevel) == algorithm) {

@ -61,7 +61,7 @@ struct grpc_exec_ctx {
{ GRPC_CLOSURE_LIST_INIT }
/** Flush any work that has been enqueued onto this grpc_exec_ctx.
* Caller must guarantee that no interfering locks are held.
* Caller must guarantee that no interfering locks are held.
* Returns 1 if work was performed, 0 otherwise. */
int grpc_exec_ctx_flush(grpc_exec_ctx *exec_ctx);
/** Finish any pending work for a grpc_exec_ctx. Must be called before

@ -62,13 +62,13 @@ static DWORD deadline_to_millis_timeout(gpr_timespec deadline,
return INFINITE;
}
if (gpr_time_cmp(deadline, gpr_time_add(now, gpr_time_from_micros(
max_spin_polling_us,
GPR_TIMESPAN))) <= 0) {
max_spin_polling_us,
GPR_TIMESPAN))) <= 0) {
return 0;
}
timeout = gpr_time_sub(deadline, now);
return gpr_time_to_millis(gpr_time_add(
timeout, gpr_time_from_nanos(GPR_NS_PER_MS - 1, GPR_TIMESPAN)));
timeout, gpr_time_from_nanos(GPR_NS_PER_MS - 1, GPR_TIMESPAN)));
}
void grpc_iocp_work(grpc_exec_ctx *exec_ctx, gpr_timespec deadline) {
@ -80,8 +80,9 @@ void grpc_iocp_work(grpc_exec_ctx *exec_ctx, gpr_timespec deadline) {
grpc_winsocket *socket;
grpc_winsocket_callback_info *info;
grpc_closure *closure = NULL;
success = GetQueuedCompletionStatus(g_iocp, &bytes, &completion_key,
&overlapped, deadline_to_millis_timeout(deadline, gpr_now(deadline.clock_type)));
success = GetQueuedCompletionStatus(
g_iocp, &bytes, &completion_key, &overlapped,
deadline_to_millis_timeout(deadline, gpr_now(deadline.clock_type)));
if (success == 0 && overlapped == NULL) {
return;
}
@ -139,7 +140,7 @@ void grpc_iocp_kick(void) {
void grpc_iocp_flush(void) {
grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
do {
grpc_iocp_work(&exec_ctx, gpr_inf_past(GPR_CLOCK_MONOTONIC));
} while (grpc_exec_ctx_flush(&exec_ctx));

@ -51,13 +51,6 @@ static gpr_cv g_rcv;
static int g_shutdown;
static grpc_iomgr_object g_root_object;
void grpc_kick_poller(void) {
/* Empty. The background callback executor polls periodically. The activity
* the kicker is trying to draw the executor's attention to will be picked up
* either by one of the periodic wakeups or by one of the polling application
* threads. */
}
void grpc_iomgr_init(void) {
g_shutdown = 0;
gpr_mu_init(&g_mu);

@ -45,11 +45,8 @@ void grpc_iomgr_platform_init(void) {
grpc_register_tracer("tcp", &grpc_tcp_trace);
}
void grpc_iomgr_platform_flush(void) {
}
void grpc_iomgr_platform_flush(void) {}
void grpc_iomgr_platform_shutdown(void) {
grpc_fd_global_shutdown();
}
void grpc_iomgr_platform_shutdown(void) { grpc_fd_global_shutdown(); }
#endif /* GRPC_POSIX_SOCKET */

@ -63,9 +63,7 @@ void grpc_iomgr_platform_init(void) {
grpc_iocp_init();
}
void grpc_iomgr_platform_flush(void) {
grpc_iocp_flush();
}
void grpc_iomgr_platform_flush(void) { grpc_iocp_flush(); }
void grpc_iomgr_platform_shutdown(void) {
grpc_iocp_shutdown();

@ -198,7 +198,7 @@ static void multipoll_with_epoll_pollset_maybe_work_and_unlock(
}
if (pfds[1].revents) {
do {
/* The following epoll_wait never blocks; it has a timeout of 0 */
/* The following epoll_wait never blocks; it has a timeout of 0 */
ep_rv = epoll_wait(h->epoll_fd, ep_ev, GRPC_EPOLL_MAX_EVENTS, 0);
if (ep_rv < 0) {
if (errno != EINTR) {
@ -213,11 +213,15 @@ static void multipoll_with_epoll_pollset_maybe_work_and_unlock(
int cancel = ep_ev[i].events & (EPOLLERR | EPOLLHUP);
int read_ev = ep_ev[i].events & (EPOLLIN | EPOLLPRI);
int write_ev = ep_ev[i].events & EPOLLOUT;
if (read_ev || cancel) {
grpc_fd_become_readable(exec_ctx, fd);
}
if (write_ev || cancel) {
grpc_fd_become_writable(exec_ctx, fd);
if (fd == NULL) {
grpc_wakeup_fd_consume_wakeup(&grpc_global_wakeup_fd);
} else {
if (read_ev || cancel) {
grpc_fd_become_readable(exec_ctx, fd);
}
if (write_ev || cancel) {
grpc_fd_become_writable(exec_ctx, fd);
}
}
}
}
@ -246,6 +250,8 @@ static void epoll_become_multipoller(grpc_exec_ctx *exec_ctx,
size_t nfds) {
size_t i;
pollset_hdr *h = gpr_malloc(sizeof(pollset_hdr));
struct epoll_event ev;
int err;
pollset->vtable = &multipoll_with_epoll_pollset;
pollset->data.ptr = h;
@ -255,6 +261,17 @@ static void epoll_become_multipoller(grpc_exec_ctx *exec_ctx,
gpr_log(GPR_ERROR, "epoll_create1 failed: %s", strerror(errno));
abort();
}
ev.events = (uint32_t)(EPOLLIN | EPOLLET);
ev.data.ptr = NULL;
err = epoll_ctl(h->epoll_fd, EPOLL_CTL_ADD,
GRPC_WAKEUP_FD_GET_READ_FD(&grpc_global_wakeup_fd), &ev);
if (err < 0) {
gpr_log(GPR_ERROR, "epoll_ctl add for %d failed: %s",
GRPC_WAKEUP_FD_GET_READ_FD(&grpc_global_wakeup_fd),
strerror(errno));
}
for (i = 0; i < nfds; i++) {
multipoll_with_epoll_pollset_add_fd(exec_ctx, pollset, fds[i], 0);
}

@ -114,13 +114,16 @@ static void multipoll_with_poll_pollset_maybe_work_and_unlock(
h = pollset->data.ptr;
timeout = grpc_poll_deadline_to_millis_timeout(deadline, now);
/* TODO(ctiller): perform just one malloc here if we exceed the inline case */
pfds = gpr_malloc(sizeof(*pfds) * (h->fd_count + 1));
watchers = gpr_malloc(sizeof(*watchers) * (h->fd_count + 1));
pfds = gpr_malloc(sizeof(*pfds) * (h->fd_count + 2));
watchers = gpr_malloc(sizeof(*watchers) * (h->fd_count + 2));
fd_count = 0;
pfd_count = 1;
pfds[0].fd = GRPC_WAKEUP_FD_GET_READ_FD(&worker->wakeup_fd);
pfd_count = 2;
pfds[0].fd = GRPC_WAKEUP_FD_GET_READ_FD(&grpc_global_wakeup_fd);
pfds[0].events = POLLIN;
pfds[0].revents = POLLOUT;
pfds[0].revents = 0;
pfds[1].fd = GRPC_WAKEUP_FD_GET_READ_FD(&worker->wakeup_fd);
pfds[1].events = POLLIN;
pfds[1].revents = 0;
for (i = 0; i < h->fd_count; i++) {
int remove = grpc_fd_is_orphaned(h->fds[i]);
for (j = 0; !remove && j < h->del_count; j++) {
@ -143,7 +146,7 @@ static void multipoll_with_poll_pollset_maybe_work_and_unlock(
h->fd_count = fd_count;
gpr_mu_unlock(&pollset->mu);
for (i = 1; i < pfd_count; i++) {
for (i = 2; i < pfd_count; i++) {
pfds[i].events = (short)grpc_fd_begin_poll(watchers[i].fd, pollset, POLLIN,
POLLOUT, &watchers[i]);
}
@ -154,7 +157,7 @@ static void multipoll_with_poll_pollset_maybe_work_and_unlock(
r = grpc_poll_function(pfds, pfd_count, timeout);
GRPC_SCHEDULING_END_BLOCKING_REGION;
for (i = 1; i < pfd_count; i++) {
for (i = 2; i < pfd_count; i++) {
grpc_fd_end_poll(exec_ctx, &watchers[i], pfds[i].revents & POLLIN,
pfds[i].revents & POLLOUT);
}
@ -167,9 +170,12 @@ static void multipoll_with_poll_pollset_maybe_work_and_unlock(
/* do nothing */
} else {
if (pfds[0].revents & POLLIN) {
grpc_wakeup_fd_consume_wakeup(&grpc_global_wakeup_fd);
}
if (pfds[1].revents & POLLIN) {
grpc_wakeup_fd_consume_wakeup(&worker->wakeup_fd);
}
for (i = 1; i < pfd_count; i++) {
for (i = 2; i < pfd_count; i++) {
if (watchers[i].fd == NULL) {
continue;
}

@ -57,8 +57,16 @@
GPR_TLS_DECL(g_current_thread_poller);
GPR_TLS_DECL(g_current_thread_worker);
/** Default poll() function - a pointer so that it can be overridden by some
* tests */
grpc_poll_function_type grpc_poll_function = poll;
/** The alarm system needs to be able to wakeup 'some poller' sometimes
* (specifically when a new alarm needs to be triggered earlier than the next
* alarm 'epoch').
* This wakeup_fd gives us something to alert on when such a case occurs. */
grpc_wakeup_fd grpc_global_wakeup_fd;
static void remove_worker(grpc_pollset *p, grpc_pollset_worker *worker) {
worker->prev->next = worker->next;
worker->next->prev = worker->prev;
@ -121,14 +129,18 @@ void grpc_pollset_global_init(void) {
gpr_tls_init(&g_current_thread_poller);
gpr_tls_init(&g_current_thread_worker);
grpc_wakeup_fd_global_init();
grpc_wakeup_fd_init(&grpc_global_wakeup_fd);
}
void grpc_pollset_global_shutdown(void) {
grpc_wakeup_fd_destroy(&grpc_global_wakeup_fd);
grpc_wakeup_fd_global_destroy();
gpr_tls_destroy(&g_current_thread_poller);
gpr_tls_destroy(&g_current_thread_worker);
grpc_wakeup_fd_global_destroy();
}
void grpc_kick_poller(void) { grpc_wakeup_fd_wakeup(&grpc_global_wakeup_fd); }
/* main interface */
static void become_basic_pollset(grpc_pollset *pollset, grpc_fd *fd_or_null);
@ -193,6 +205,8 @@ void grpc_pollset_work(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset,
goto done;
}
if (grpc_alarm_check(exec_ctx, now, &deadline)) {
gpr_mu_unlock(&pollset->mu);
locked = 0;
goto done;
}
if (pollset->shutting_down) {
@ -294,7 +308,7 @@ int grpc_poll_deadline_to_millis_timeout(gpr_timespec deadline,
}
timeout = gpr_time_sub(deadline, now);
return gpr_time_to_millis(gpr_time_add(
timeout, gpr_time_from_nanos(GPR_NS_PER_SEC - 1, GPR_TIMESPAN)));
timeout, gpr_time_from_nanos(GPR_NS_PER_MS - 1, GPR_TIMESPAN)));
}
/*
@ -338,6 +352,7 @@ static void basic_do_promote(grpc_exec_ctx *exec_ctx, void *args, int success) {
if (pollset->shutting_down) {
/* We don't care about this pollset anymore. */
if (pollset->in_flight_cbs == 0 && !pollset->called_shutdown) {
pollset->called_shutdown = 1;
finish_shutdown(exec_ctx, pollset);
}
} else if (grpc_fd_is_orphaned(fd)) {
@ -439,7 +454,7 @@ static void basic_pollset_maybe_work_and_unlock(grpc_exec_ctx *exec_ctx,
grpc_pollset_worker *worker,
gpr_timespec deadline,
gpr_timespec now) {
struct pollfd pfd[2];
struct pollfd pfd[3];
grpc_fd *fd;
grpc_fd_watcher fd_watcher;
int timeout;
@ -452,17 +467,21 @@ static void basic_pollset_maybe_work_and_unlock(grpc_exec_ctx *exec_ctx,
fd = pollset->data.ptr = NULL;
}
timeout = grpc_poll_deadline_to_millis_timeout(deadline, now);
pfd[0].fd = GRPC_WAKEUP_FD_GET_READ_FD(&worker->wakeup_fd);
pfd[0].fd = GRPC_WAKEUP_FD_GET_READ_FD(&grpc_global_wakeup_fd);
pfd[0].events = POLLIN;
pfd[0].revents = 0;
nfds = 1;
pfd[1].fd = GRPC_WAKEUP_FD_GET_READ_FD(&worker->wakeup_fd);
pfd[1].events = POLLIN;
pfd[1].revents = 0;
nfds = 2;
if (fd) {
pfd[1].fd = fd->fd;
pfd[1].revents = 0;
pfd[2].fd = fd->fd;
pfd[2].revents = 0;
GRPC_FD_REF(fd, "basicpoll_begin");
gpr_mu_unlock(&pollset->mu);
pfd[1].events =
pfd[2].events =
(short)grpc_fd_begin_poll(fd, pollset, POLLIN, POLLOUT, &fd_watcher);
if (pfd[1].events != 0) {
if (pfd[2].events != 0) {
nfds++;
}
} else {
@ -479,8 +498,8 @@ static void basic_pollset_maybe_work_and_unlock(grpc_exec_ctx *exec_ctx,
GRPC_TIMER_MARK(GRPC_PTAG_POLL_FINISHED, r);
if (fd) {
grpc_fd_end_poll(exec_ctx, &fd_watcher, pfd[1].revents & POLLIN,
pfd[1].revents & POLLOUT);
grpc_fd_end_poll(exec_ctx, &fd_watcher, pfd[2].revents & POLLIN,
pfd[2].revents & POLLOUT);
}
if (r < 0) {
@ -491,17 +510,24 @@ static void basic_pollset_maybe_work_and_unlock(grpc_exec_ctx *exec_ctx,
/* do nothing */
} else {
if (pfd[0].revents & POLLIN) {
grpc_wakeup_fd_consume_wakeup(&grpc_global_wakeup_fd);
}
if (pfd[1].revents & POLLIN) {
grpc_wakeup_fd_consume_wakeup(&worker->wakeup_fd);
}
if (nfds > 1) {
if (pfd[1].revents & (POLLIN | POLLHUP | POLLERR)) {
if (nfds > 2) {
if (pfd[2].revents & (POLLIN | POLLHUP | POLLERR)) {
grpc_fd_become_readable(exec_ctx, fd);
}
if (pfd[1].revents & (POLLOUT | POLLHUP | POLLERR)) {
if (pfd[2].revents & (POLLOUT | POLLHUP | POLLERR)) {
grpc_fd_become_writable(exec_ctx, fd);
}
}
}
if (fd) {
GRPC_FD_UNREF(fd, "basicpoll_begin");
}
}
static void basic_pollset_destroy(grpc_pollset *pollset) {

@ -129,5 +129,6 @@ int grpc_pollset_has_workers(grpc_pollset *pollset);
/* override to allow tests to hook poll() usage */
typedef int (*grpc_poll_function_type)(struct pollfd *, nfds_t, int);
extern grpc_poll_function_type grpc_poll_function;
extern grpc_wakeup_fd grpc_global_wakeup_fd;
#endif /* GRPC_INTERNAL_CORE_IOMGR_POLLSET_POSIX_H */

@ -51,22 +51,21 @@ void grpc_pollset_global_init() {
gpr_mu_init(&grpc_polling_mu);
g_active_poller = NULL;
g_global_root_worker.links[GRPC_POLLSET_WORKER_LINK_GLOBAL].next =
g_global_root_worker.links[GRPC_POLLSET_WORKER_LINK_GLOBAL].prev =
&g_global_root_worker;
g_global_root_worker.links[GRPC_POLLSET_WORKER_LINK_GLOBAL].prev =
&g_global_root_worker;
}
void grpc_pollset_global_shutdown() {
gpr_mu_destroy(&grpc_polling_mu);
}
void grpc_pollset_global_shutdown() { gpr_mu_destroy(&grpc_polling_mu); }
static void remove_worker(grpc_pollset_worker *worker,
static void remove_worker(grpc_pollset_worker *worker,
grpc_pollset_worker_link_type type) {
worker->links[type].prev->links[type].next = worker->links[type].next;
worker->links[type].next->links[type].prev = worker->links[type].prev;
worker->links[type].next = worker->links[type].prev = worker;
}
static int has_workers(grpc_pollset_worker *root, grpc_pollset_worker_link_type type) {
static int has_workers(grpc_pollset_worker *root,
grpc_pollset_worker_link_type type) {
return root->links[type].next != root;
}
@ -81,24 +80,22 @@ static grpc_pollset_worker *pop_front_worker(
}
}
static void push_back_worker(grpc_pollset_worker *root,
grpc_pollset_worker_link_type type,
static void push_back_worker(grpc_pollset_worker *root,
grpc_pollset_worker_link_type type,
grpc_pollset_worker *worker) {
worker->links[type].next = root;
worker->links[type].prev = worker->links[type].next->links[type].prev;
worker->links[type].prev->links[type].next =
worker->links[type].next->links[type].prev =
worker;
worker->links[type].prev->links[type].next =
worker->links[type].next->links[type].prev = worker;
}
static void push_front_worker(grpc_pollset_worker *root,
grpc_pollset_worker_link_type type,
static void push_front_worker(grpc_pollset_worker *root,
grpc_pollset_worker_link_type type,
grpc_pollset_worker *worker) {
worker->links[type].prev = root;
worker->links[type].next = worker->links[type].prev->links[type].next;
worker->links[type].prev->links[type].next =
worker->links[type].next->links[type].prev =
worker;
worker->links[type].prev->links[type].next =
worker->links[type].next->links[type].prev = worker;
}
/* There isn't really any such thing as a pollset under Windows, due to the
@ -108,9 +105,9 @@ static void push_front_worker(grpc_pollset_worker *root,
void grpc_pollset_init(grpc_pollset *pollset) {
memset(pollset, 0, sizeof(*pollset));
pollset->root_worker.links[GRPC_POLLSET_WORKER_LINK_POLLSET].next =
pollset->root_worker.links[GRPC_POLLSET_WORKER_LINK_POLLSET].prev =
&pollset->root_worker;
pollset->root_worker.links[GRPC_POLLSET_WORKER_LINK_POLLSET].next =
pollset->root_worker.links[GRPC_POLLSET_WORKER_LINK_POLLSET].prev =
&pollset->root_worker;
}
void grpc_pollset_shutdown(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset,
@ -126,18 +123,16 @@ void grpc_pollset_shutdown(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset,
gpr_mu_unlock(&grpc_polling_mu);
}
void grpc_pollset_destroy(grpc_pollset *pollset) {
}
void grpc_pollset_destroy(grpc_pollset *pollset) {}
void grpc_pollset_work(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset,
grpc_pollset_worker *worker, gpr_timespec now,
gpr_timespec deadline) {
int added_worker = 0;
worker->links[GRPC_POLLSET_WORKER_LINK_POLLSET].next =
worker->links[GRPC_POLLSET_WORKER_LINK_POLLSET].prev =
worker->links[GRPC_POLLSET_WORKER_LINK_GLOBAL].next =
worker->links[GRPC_POLLSET_WORKER_LINK_GLOBAL].prev =
NULL;
worker->links[GRPC_POLLSET_WORKER_LINK_POLLSET].next =
worker->links[GRPC_POLLSET_WORKER_LINK_POLLSET].prev =
worker->links[GRPC_POLLSET_WORKER_LINK_GLOBAL].next =
worker->links[GRPC_POLLSET_WORKER_LINK_GLOBAL].prev = NULL;
worker->kicked = 0;
worker->pollset = pollset;
gpr_cv_init(&worker->cv);
@ -157,9 +152,13 @@ void grpc_pollset_work(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset,
pollset->is_iocp_worker = 0;
g_active_poller = NULL;
/* try to get a worker from this pollsets worker list */
next_worker = pop_front_worker(&pollset->root_worker, GRPC_POLLSET_WORKER_LINK_POLLSET);
/* try to get a worker from the global list */
next_worker = pop_front_worker(&g_global_root_worker, GRPC_POLLSET_WORKER_LINK_GLOBAL);
next_worker = pop_front_worker(&pollset->root_worker,
GRPC_POLLSET_WORKER_LINK_POLLSET);
if (next_worker == NULL) {
/* try to get a worker from the global list */
next_worker = pop_front_worker(&g_global_root_worker,
GRPC_POLLSET_WORKER_LINK_GLOBAL);
}
if (next_worker != NULL) {
next_worker->kicked = 1;
gpr_cv_signal(&next_worker->cv);
@ -171,8 +170,10 @@ void grpc_pollset_work(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset,
}
goto done;
}
push_front_worker(&g_global_root_worker, GRPC_POLLSET_WORKER_LINK_GLOBAL, worker);
push_front_worker(&pollset->root_worker, GRPC_POLLSET_WORKER_LINK_POLLSET, worker);
push_front_worker(&g_global_root_worker, GRPC_POLLSET_WORKER_LINK_GLOBAL,
worker);
push_front_worker(&pollset->root_worker, GRPC_POLLSET_WORKER_LINK_POLLSET,
worker);
added_worker = 1;
while (!worker->kicked) {
if (gpr_cv_wait(&worker->cv, &grpc_polling_mu, deadline)) {
@ -198,9 +199,11 @@ done:
void grpc_pollset_kick(grpc_pollset *p, grpc_pollset_worker *specific_worker) {
if (specific_worker != NULL) {
if (specific_worker == GRPC_POLLSET_KICK_BROADCAST) {
for (specific_worker = p->root_worker.links[GRPC_POLLSET_WORKER_LINK_POLLSET].next;
for (specific_worker =
p->root_worker.links[GRPC_POLLSET_WORKER_LINK_POLLSET].next;
specific_worker != &p->root_worker;
specific_worker = specific_worker->links[GRPC_POLLSET_WORKER_LINK_POLLSET].next) {
specific_worker =
specific_worker->links[GRPC_POLLSET_WORKER_LINK_POLLSET].next) {
specific_worker->kicked = 1;
gpr_cv_signal(&specific_worker->cv);
}
@ -219,7 +222,8 @@ void grpc_pollset_kick(grpc_pollset *p, grpc_pollset_worker *specific_worker) {
}
}
} else {
specific_worker = pop_front_worker(&p->root_worker, GRPC_POLLSET_WORKER_LINK_POLLSET);
specific_worker =
pop_front_worker(&p->root_worker, GRPC_POLLSET_WORKER_LINK_POLLSET);
if (specific_worker != NULL) {
grpc_pollset_kick(p, specific_worker);
} else if (p->is_iocp_worker) {
@ -230,4 +234,6 @@ void grpc_pollset_kick(grpc_pollset *p, grpc_pollset_worker *specific_worker) {
}
}
void grpc_kick_poller(void) { grpc_iocp_kick(); }
#endif /* GPR_WINSOCK_SOCKET */

@ -141,7 +141,8 @@ static void on_writable(grpc_exec_ctx *exec_ctx, void *acp, int success) {
err = getsockopt(fd->fd, SOL_SOCKET, SO_ERROR, &so_error, &so_error_size);
} while (err < 0 && errno == EINTR);
if (err < 0) {
gpr_log(GPR_ERROR, "getsockopt(ERROR): %s", strerror(errno));
gpr_log(GPR_ERROR, "failed to connect to '%s': getsockopt(ERROR): %s",
ac->addr_str, strerror(errno));
goto finish;
} else if (so_error != 0) {
if (so_error == ENOBUFS) {
@ -166,10 +167,14 @@ static void on_writable(grpc_exec_ctx *exec_ctx, void *acp, int success) {
} else {
switch (so_error) {
case ECONNREFUSED:
gpr_log(GPR_ERROR, "socket error: connection refused");
gpr_log(
GPR_ERROR,
"failed to connect to '%s': socket error: connection refused",
ac->addr_str);
break;
default:
gpr_log(GPR_ERROR, "socket error: %d", so_error);
gpr_log(GPR_ERROR, "failed to connect to '%s': socket error: %d",
ac->addr_str, so_error);
break;
}
goto finish;
@ -181,7 +186,8 @@ static void on_writable(grpc_exec_ctx *exec_ctx, void *acp, int success) {
goto finish;
}
} else {
gpr_log(GPR_ERROR, "on_writable failed during connect");
gpr_log(GPR_ERROR, "failed to connect to '%s': timeout occurred",
ac->addr_str);
goto finish;
}

@ -292,7 +292,7 @@ static flush_result tcp_flush(grpc_tcp *tcp) {
unwind_slice_idx = tcp->outgoing_slice_idx;
unwind_byte_idx = tcp->outgoing_byte_idx;
for (iov_size = 0; tcp->outgoing_slice_idx != tcp->outgoing_buffer->count &&
iov_size != MAX_WRITE_IOVEC;
iov_size != MAX_WRITE_IOVEC;
iov_size++) {
iov[iov_size].iov_base =
GPR_SLICE_START_PTR(
@ -441,7 +441,7 @@ static char *tcp_get_peer(grpc_endpoint *ep) {
}
static const grpc_endpoint_vtable vtable = {
tcp_read, tcp_write, tcp_add_to_pollset, tcp_add_to_pollset_set,
tcp_read, tcp_write, tcp_add_to_pollset, tcp_add_to_pollset_set,
tcp_shutdown, tcp_destroy, tcp_get_peer};
grpc_endpoint *grpc_tcp_create(grpc_fd *em_fd, size_t slice_size,

@ -382,7 +382,7 @@ static int add_socket_to_server(grpc_tcp_server *s, SOCKET sock,
if (s->nports == s->port_capacity) {
/* too many ports, and we need to store their address in a closure */
/* TODO(ctiller): make server_port a linked list */
abort();
abort();
}
sp = &s->ports[s->nports++];
sp->server = s;

@ -382,9 +382,9 @@ static char *win_get_peer(grpc_endpoint *ep) {
return gpr_strdup(tcp->peer_string);
}
static grpc_endpoint_vtable vtable = {
win_read, win_write, win_add_to_pollset, win_add_to_pollset_set,
win_shutdown, win_destroy, win_get_peer};
static grpc_endpoint_vtable vtable = {win_read, win_write, win_add_to_pollset,
win_add_to_pollset_set, win_shutdown,
win_destroy, win_get_peer};
grpc_endpoint *grpc_tcp_create(grpc_winsocket *socket, char *peer_string) {
grpc_tcp *tcp = (grpc_tcp *)gpr_malloc(sizeof(grpc_tcp));

@ -118,7 +118,7 @@ struct grpc_udp_server {
/* number of pollsets in the pollsets array */
size_t pollset_count;
/* The parent grpc server */
grpc_server* grpc_server;
grpc_server *grpc_server;
};
grpc_udp_server *grpc_udp_server_create(void) {
@ -232,7 +232,7 @@ static int prepare_socket(int fd, const struct sockaddr *addr,
rc = setsockopt(fd, IPPROTO_IP, IP_PKTINFO, &get_local_ip,
sizeof(get_local_ip));
if (rc == 0 && addr->sa_family == AF_INET6) {
#if !TARGET_OS_IPHONE
#if !defined(__APPLE__)
rc = setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &get_local_ip,
sizeof(get_local_ip));
#endif

@ -355,8 +355,7 @@ static void destroy_channel_elem(grpc_exec_ctx *exec_ctx,
}
const grpc_channel_filter grpc_client_auth_filter = {
auth_start_transport_op, grpc_channel_next_op,
sizeof(call_data), init_call_elem,
destroy_call_elem, sizeof(channel_data),
init_channel_elem, destroy_channel_elem,
grpc_call_next_get_peer, "client-auth"};
auth_start_transport_op, grpc_channel_next_op, sizeof(call_data),
init_call_elem, destroy_call_elem, sizeof(channel_data),
init_channel_elem, destroy_channel_elem, grpc_call_next_get_peer,
"client-auth"};

@ -41,6 +41,7 @@
#include "src/core/json/json.h"
#include "src/core/httpcli/httpcli.h"
#include "src/core/iomgr/iomgr.h"
#include "src/core/surface/api_trace.h"
#include "src/core/support/string.h"
#include <grpc/support/alloc.h>
@ -91,6 +92,7 @@ void grpc_credentials_unref(grpc_credentials *creds) {
}
void grpc_credentials_release(grpc_credentials *creds) {
GRPC_API_TRACE("grpc_credentials_release(creds=%p)", 1, (creds));
grpc_credentials_unref(creds);
}
@ -152,6 +154,7 @@ void grpc_server_credentials_unref(grpc_server_credentials *creds) {
}
void grpc_server_credentials_release(grpc_server_credentials *creds) {
GRPC_API_TRACE("grpc_server_credentials_release(creds=%p)", 1, (creds));
grpc_server_credentials_unref(creds);
}
@ -166,6 +169,11 @@ grpc_security_status grpc_server_credentials_create_security_connector(
void grpc_server_credentials_set_auth_metadata_processor(
grpc_server_credentials *creds, grpc_auth_metadata_processor processor) {
GRPC_API_TRACE(
"grpc_server_credentials_set_auth_metadata_processor("
"creds=%p, "
"processor=grpc_auth_metadata_processor { process: %lx, state: %p })",
3, (creds, (unsigned long)processor.process, processor.state));
if (creds == NULL) return;
if (creds->processor.destroy != NULL && creds->processor.state != NULL) {
creds->processor.destroy(creds->processor.state);
@ -317,6 +325,11 @@ grpc_credentials *grpc_ssl_credentials_create(
const char *pem_root_certs, grpc_ssl_pem_key_cert_pair *pem_key_cert_pair,
void *reserved) {
grpc_ssl_credentials *c = gpr_malloc(sizeof(grpc_ssl_credentials));
GRPC_API_TRACE(
"grpc_ssl_credentials_create(pem_root_certs=%s, "
"pem_key_cert_pair=%p, "
"reserved=%p)",
3, (pem_root_certs, pem_key_cert_pair, reserved));
GPR_ASSERT(reserved == NULL);
memset(c, 0, sizeof(grpc_ssl_credentials));
c->base.type = GRPC_CREDENTIALS_TYPE_SSL;
@ -331,6 +344,12 @@ grpc_server_credentials *grpc_ssl_server_credentials_create(
size_t num_key_cert_pairs, int force_client_auth, void *reserved) {
grpc_ssl_server_credentials *c =
gpr_malloc(sizeof(grpc_ssl_server_credentials));
GRPC_API_TRACE(
"grpc_ssl_server_credentials_create("
"pem_root_certs=%s, pem_key_cert_pairs=%p, num_key_cert_pairs=%lu, "
"force_client_auth=%d, reserved=%p)",
5, (pem_root_certs, pem_key_cert_pairs, (unsigned long)num_key_cert_pairs,
force_client_auth, reserved));
GPR_ASSERT(reserved == NULL);
memset(c, 0, sizeof(grpc_ssl_server_credentials));
c->base.type = GRPC_CREDENTIALS_TYPE_SSL;
@ -449,6 +468,14 @@ grpc_service_account_jwt_access_credentials_create_from_auth_json_key(
grpc_credentials *grpc_service_account_jwt_access_credentials_create(
const char *json_key, gpr_timespec token_lifetime, void *reserved) {
GRPC_API_TRACE(
"grpc_service_account_jwt_access_credentials_create("
"json_key=%s, "
"token_lifetime="
"gpr_timespec { tv_sec: %ld, tv_nsec: %d, clock_type: %d }, "
"reserved=%p)",
5, (json_key, (long)token_lifetime.tv_sec, token_lifetime.tv_nsec,
(int)token_lifetime.clock_type, reserved));
GPR_ASSERT(reserved == NULL);
return grpc_service_account_jwt_access_credentials_create_from_auth_json_key(
grpc_auth_json_key_create_from_string(json_key), token_lifetime);
@ -659,6 +686,8 @@ grpc_credentials *grpc_google_compute_engine_credentials_create(
void *reserved) {
grpc_oauth2_token_fetcher_credentials *c =
gpr_malloc(sizeof(grpc_oauth2_token_fetcher_credentials));
GRPC_API_TRACE("grpc_compute_engine_credentials_create(reserved=%p)", 1,
(reserved));
GPR_ASSERT(reserved == NULL);
init_oauth2_token_fetcher(c, compute_engine_fetch_oauth2);
c->base.vtable = &compute_engine_vtable;
@ -720,6 +749,10 @@ grpc_credentials *grpc_refresh_token_credentials_create_from_auth_refresh_token(
grpc_credentials *grpc_google_refresh_token_credentials_create(
const char *json_refresh_token, void *reserved) {
GRPC_API_TRACE(
"grpc_refresh_token_credentials_create(json_refresh_token=%s, "
"reserved=%p)",
2, (json_refresh_token, reserved));
GPR_ASSERT(reserved == NULL);
return grpc_refresh_token_credentials_create_from_auth_refresh_token(
grpc_auth_refresh_token_create_from_string(json_refresh_token));
@ -820,6 +853,10 @@ grpc_credentials *grpc_access_token_credentials_create(const char *access_token,
grpc_access_token_credentials *c =
gpr_malloc(sizeof(grpc_access_token_credentials));
char *token_md_value;
GRPC_API_TRACE(
"grpc_access_token_credentials_create(access_token=%s, "
"reserved=%p)",
2, (access_token, reserved));
GPR_ASSERT(reserved == NULL);
memset(c, 0, sizeof(grpc_access_token_credentials));
c->base.type = GRPC_CREDENTIALS_TYPE_OAUTH2;
@ -1056,6 +1093,10 @@ grpc_credentials *grpc_composite_credentials_create(grpc_credentials *creds1,
grpc_credentials_array creds1_array;
grpc_credentials_array creds2_array;
grpc_composite_credentials *c;
GRPC_API_TRACE(
"grpc_composite_credentials_create(creds1=%p, creds2=%p, "
"reserved=%p)",
3, (creds1, creds2, reserved));
GPR_ASSERT(reserved == NULL);
GPR_ASSERT(creds1 != NULL);
GPR_ASSERT(creds2 != NULL);
@ -1158,6 +1199,10 @@ static grpc_credentials_vtable iam_vtable = {
grpc_credentials *grpc_google_iam_credentials_create(
const char *token, const char *authority_selector, void *reserved) {
grpc_google_iam_credentials *c;
GRPC_API_TRACE(
"grpc_iam_credentials_create(token=%s, authority_selector=%s, "
"reserved=%p)",
3, (token, authority_selector, reserved));
GPR_ASSERT(reserved == NULL);
GPR_ASSERT(token != NULL);
GPR_ASSERT(authority_selector != NULL);

@ -42,6 +42,7 @@
#include "src/core/httpcli/httpcli.h"
#include "src/core/support/env.h"
#include "src/core/support/file.h"
#include "src/core/surface/api_trace.h"
/* -- Constants. -- */
@ -178,6 +179,9 @@ end:
grpc_credentials *grpc_google_default_credentials_create(void) {
grpc_credentials *result = NULL;
int serving_cached_credentials = 0;
GRPC_API_TRACE("grpc_google_default_credentials_create(void)", 0, ());
gpr_once_init(&g_once, init_default_credentials);
gpr_mu_lock(&g_mu);

@ -354,9 +354,8 @@ static char *endpoint_get_peer(grpc_endpoint *secure_ep) {
}
static const grpc_endpoint_vtable vtable = {
endpoint_read, endpoint_write,
endpoint_add_to_pollset, endpoint_add_to_pollset_set,
endpoint_shutdown, endpoint_destroy,
endpoint_read, endpoint_write, endpoint_add_to_pollset,
endpoint_add_to_pollset_set, endpoint_shutdown, endpoint_destroy,
endpoint_get_peer};
grpc_endpoint *grpc_secure_endpoint_create(

@ -34,6 +34,7 @@
#include <string.h>
#include "src/core/security/security_context.h"
#include "src/core/surface/api_trace.h"
#include "src/core/surface/call.h"
#include "src/core/support/string.h"
@ -47,6 +48,8 @@
grpc_call_error grpc_call_set_credentials(grpc_call *call,
grpc_credentials *creds) {
grpc_client_security_context *ctx = NULL;
GRPC_API_TRACE("grpc_call_set_credentials(call=%p, creds=%p)", 2,
(call, creds));
if (!grpc_call_is_client(call)) {
gpr_log(GPR_ERROR, "Method is client-side only.");
return GRPC_CALL_ERROR_NOT_ON_SERVER;
@ -71,6 +74,7 @@ grpc_call_error grpc_call_set_credentials(grpc_call *call,
grpc_auth_context *grpc_call_auth_context(grpc_call *call) {
void *sec_ctx = grpc_call_context_get(call, GRPC_CONTEXT_SECURITY);
GRPC_API_TRACE("grpc_call_auth_context(call=%p)", 1, (call));
if (sec_ctx == NULL) return NULL;
return grpc_call_is_client(call)
? GRPC_AUTH_CONTEXT_REF(
@ -82,6 +86,7 @@ grpc_auth_context *grpc_call_auth_context(grpc_call *call) {
}
void grpc_auth_context_release(grpc_auth_context *context) {
GRPC_API_TRACE("grpc_auth_context_release(context=%p)", 1, (context));
GRPC_AUTH_CONTEXT_UNREF(context, "grpc_auth_context_unref");
}
@ -174,6 +179,8 @@ void grpc_auth_context_unref(grpc_auth_context *ctx) {
const char *grpc_auth_context_peer_identity_property_name(
const grpc_auth_context *ctx) {
GRPC_API_TRACE("grpc_auth_context_peer_identity_property_name(ctx=%p)", 1,
(ctx));
return ctx->peer_identity_property_name;
}
@ -182,6 +189,9 @@ int grpc_auth_context_set_peer_identity_property_name(grpc_auth_context *ctx,
grpc_auth_property_iterator it =
grpc_auth_context_find_properties_by_name(ctx, name);
const grpc_auth_property *prop = grpc_auth_property_iterator_next(&it);
GRPC_API_TRACE(
"grpc_auth_context_set_peer_identity_property_name(ctx=%p, name=%s)", 2,
(ctx, name));
if (prop == NULL) {
gpr_log(GPR_ERROR, "Property name %s not found in auth context.",
name != NULL ? name : "NULL");
@ -192,12 +202,14 @@ int grpc_auth_context_set_peer_identity_property_name(grpc_auth_context *ctx,
}
int grpc_auth_context_peer_is_authenticated(const grpc_auth_context *ctx) {
GRPC_API_TRACE("grpc_auth_context_peer_is_authenticated(ctx=%p)", 1, (ctx));
return ctx->peer_identity_property_name == NULL ? 0 : 1;
}
grpc_auth_property_iterator grpc_auth_context_property_iterator(
const grpc_auth_context *ctx) {
grpc_auth_property_iterator it = empty_iterator;
GRPC_API_TRACE("grpc_auth_context_property_iterator(ctx=%p)", 1, (ctx));
if (ctx == NULL) return it;
it.ctx = ctx;
return it;
@ -205,6 +217,7 @@ grpc_auth_property_iterator grpc_auth_context_property_iterator(
const grpc_auth_property *grpc_auth_property_iterator_next(
grpc_auth_property_iterator *it) {
GRPC_API_TRACE("grpc_auth_property_iterator_next(it=%p)", 1, (it));
if (it == NULL || it->ctx == NULL) return NULL;
while (it->index == it->ctx->properties.count) {
if (it->ctx->chained == NULL) return NULL;
@ -229,6 +242,8 @@ const grpc_auth_property *grpc_auth_property_iterator_next(
grpc_auth_property_iterator grpc_auth_context_find_properties_by_name(
const grpc_auth_context *ctx, const char *name) {
grpc_auth_property_iterator it = empty_iterator;
GRPC_API_TRACE("grpc_auth_context_find_properties_by_name(ctx=%p, name=%s)",
2, (ctx, name));
if (ctx == NULL || name == NULL) return empty_iterator;
it.ctx = ctx;
it.name = name;
@ -237,6 +252,7 @@ grpc_auth_property_iterator grpc_auth_context_find_properties_by_name(
grpc_auth_property_iterator grpc_auth_context_peer_identity(
const grpc_auth_context *ctx) {
GRPC_API_TRACE("grpc_auth_context_peer_identity(ctx=%p)", 1, (ctx));
if (ctx == NULL) return empty_iterator;
return grpc_auth_context_find_properties_by_name(
ctx, ctx->peer_identity_property_name);
@ -255,6 +271,11 @@ static void ensure_auth_context_capacity(grpc_auth_context *ctx) {
void grpc_auth_context_add_property(grpc_auth_context *ctx, const char *name,
const char *value, size_t value_length) {
grpc_auth_property *prop;
GRPC_API_TRACE(
"grpc_auth_context_add_property(ctx=%p, name=%s, value=%*.*s, "
"value_length=%lu)",
6, (ctx, name, (int)value_length, (int)value_length, value,
(unsigned long)value_length));
ensure_auth_context_capacity(ctx);
prop = &ctx->properties.array[ctx->properties.count++];
prop->name = gpr_strdup(name);
@ -268,6 +289,9 @@ void grpc_auth_context_add_cstring_property(grpc_auth_context *ctx,
const char *name,
const char *value) {
grpc_auth_property *prop;
GRPC_API_TRACE(
"grpc_auth_context_add_cstring_property(ctx=%p, name=%s, value=%s)", 3,
(ctx, name, value));
ensure_auth_context_capacity(ctx);
prop = &ctx->properties.array[ctx->properties.count++];
prop->name = gpr_strdup(name);

@ -273,8 +273,7 @@ static void destroy_channel_elem(grpc_exec_ctx *exec_ctx,
}
const grpc_channel_filter grpc_server_auth_filter = {
auth_start_transport_op, grpc_channel_next_op,
sizeof(call_data), init_call_elem,
destroy_call_elem, sizeof(channel_data),
init_channel_elem, destroy_channel_elem,
grpc_call_next_get_peer, "server-auth"};
auth_start_transport_op, grpc_channel_next_op, sizeof(call_data),
init_call_elem, destroy_call_elem, sizeof(channel_data),
init_channel_elem, destroy_channel_elem, grpc_call_next_get_peer,
"server-auth"};

@ -44,6 +44,7 @@
#include "src/core/security/credentials.h"
#include "src/core/security/security_connector.h"
#include "src/core/security/security_context.h"
#include "src/core/surface/api_trace.h"
#include "src/core/surface/server.h"
#include "src/core/transport/chttp2_transport.h"
#include <grpc/support/alloc.h>
@ -222,6 +223,11 @@ int grpc_server_add_secure_http2_port(grpc_server *server, const char *addr,
grpc_security_connector *sc = NULL;
grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
GRPC_API_TRACE(
"grpc_server_add_secure_http2_port("
"server=%p, addr=%s, creds=%p)",
3, (server, addr, creds));
/* create security context */
if (creds == NULL) goto error;
status = grpc_server_credentials_create_security_connector(creds, &sc);

@ -85,8 +85,8 @@ static void delete_key(void *key) { gpr_free(key); }
static const census_ht_option ht_opt = {
CENSUS_HT_POINTER /* key type */, 1999 /* n_of_buckets */,
simple_hash /* hash function */, cmp_str_keys /* key comparator */,
delete_stats /* data deleter */, delete_key /* key deleter */
simple_hash /* hash function */, cmp_str_keys /* key comparator */,
delete_stats /* data deleter */, delete_key /* key deleter */
};
static void init_rpc_stats(void *stats) {

@ -60,11 +60,8 @@ static void delete_trace_obj(void *obj) {
}
static const census_ht_option ht_opt = {
CENSUS_HT_UINT64 /* key type */,
571 /* n_of_buckets */,
NULL /* hash */,
NULL /* compare_keys */,
delete_trace_obj /* delete data */,
CENSUS_HT_UINT64 /* key type */, 571 /* n_of_buckets */, NULL /* hash */,
NULL /* compare_keys */, delete_trace_obj /* delete data */,
NULL /* delete key */
};

@ -208,7 +208,8 @@ void gpr_slice_buffer_move_into(gpr_slice_buffer *src, gpr_slice_buffer *dst) {
src->length = 0;
}
void gpr_slice_buffer_trim_end(gpr_slice_buffer *sb, size_t n, gpr_slice_buffer *garbage) {
void gpr_slice_buffer_trim_end(gpr_slice_buffer *sb, size_t n,
gpr_slice_buffer *garbage) {
GPR_ASSERT(n <= sb->length);
sb->length -= n;
for (;;) {

@ -31,6 +31,6 @@
*
*/
#include "src/core/surface/surface_trace.h"
#include "src/core/surface/api_trace.h"
int grpc_surface_trace = 0;
int grpc_api_trace = 0;

@ -0,0 +1,65 @@
/*
*
* Copyright 2015, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef GRPC_INTERNAL_CORE_SURFACE_API_TRACE_H
#define GRPC_INTERNAL_CORE_SURFACE_API_TRACE_H
#include "src/core/debug/trace.h"
#include <grpc/support/log.h>
extern int grpc_api_trace;
/* Provide unwrapping macros because we're in C89 and variadic macros weren't
introduced until C99... */
#define GRPC_API_TRACE_UNWRAP0()
#define GRPC_API_TRACE_UNWRAP1(a) , a
#define GRPC_API_TRACE_UNWRAP2(a, b) , a, b
#define GRPC_API_TRACE_UNWRAP3(a, b, c) , a, b, c
#define GRPC_API_TRACE_UNWRAP4(a, b, c, d) , a, b, c, d
#define GRPC_API_TRACE_UNWRAP5(a, b, c, d, e) , a, b, c, d, e
#define GRPC_API_TRACE_UNWRAP6(a, b, c, d, e, f) , a, b, c, d, e, f
#define GRPC_API_TRACE_UNWRAP7(a, b, c, d, e, f, g) , a, b, c, d, e, f, g
#define GRPC_API_TRACE_UNWRAP8(a, b, c, d, e, f, g, h) , a, b, c, d, e, f, g, h
#define GRPC_API_TRACE_UNWRAP9(a, b, c, d, e, f, g, h, i) \
, a, b, c, d, e, f, g, h, i
#define GRPC_API_TRACE_UNWRAP10(a, b, c, d, e, f, g, h, i, j) \
, a, b, c, d, e, f, g, h, i, j
/* Due to the limitations of C89's preprocessor, the arity of the var-arg list
'nargs' must be specified. */
#define GRPC_API_TRACE(fmt, nargs, args) \
if (grpc_api_trace) { \
gpr_log(GPR_INFO, fmt GRPC_API_TRACE_UNWRAP##nargs args); \
}
#endif /* GRPC_INTERNAL_CORE_SURFACE_API_TRACE_H */

@ -45,6 +45,7 @@
#include "src/core/iomgr/alarm.h"
#include "src/core/profiling/timers.h"
#include "src/core/support/string.h"
#include "src/core/surface/api_trace.h"
#include "src/core/surface/byte_buffer_queue.h"
#include "src/core/surface/call.h"
#include "src/core/surface/channel.h"
@ -1280,6 +1281,8 @@ void grpc_call_destroy(grpc_call *c) {
grpc_call *parent = c->parent;
grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
GRPC_API_TRACE("grpc_call_destroy(c=%p)", 1, (c));
if (parent) {
gpr_mu_lock(&parent->mu);
if (c == parent->first_child) {
@ -1308,6 +1311,7 @@ void grpc_call_destroy(grpc_call *c) {
}
grpc_call_error grpc_call_cancel(grpc_call *call, void *reserved) {
GRPC_API_TRACE("grpc_call_cancel(call=%p, reserved=%p)", 2, (call, reserved));
GPR_ASSERT(!reserved);
return grpc_call_cancel_with_status(call, GRPC_STATUS_CANCELLED, "Cancelled",
NULL);
@ -1319,6 +1323,10 @@ grpc_call_error grpc_call_cancel_with_status(grpc_call *c,
void *reserved) {
grpc_call_error r;
grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
GRPC_API_TRACE(
"grpc_call_cancel_with_status("
"c=%p, status=%d, description=%s, reserved=%p)",
4, (c, (int)status, description, reserved));
GPR_ASSERT(reserved == NULL);
lock(c);
r = cancel_with_status(c, status, description);
@ -1386,6 +1394,7 @@ char *grpc_call_get_peer(grpc_call *call) {
grpc_call_element *elem = CALL_ELEM_FROM_CALL(call, 0);
grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
char *result = elem->filter->get_peer(&exec_ctx, elem);
GRPC_API_TRACE("grpc_call_get_peer(%p)", 1, (call));
grpc_exec_ctx_finish(&exec_ctx);
return result;
}
@ -1580,6 +1589,10 @@ grpc_call_error grpc_call_start_batch(grpc_call *call, const grpc_op *ops,
grpc_call_error error;
grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
GRPC_API_TRACE(
"grpc_call_start_batch(call=%p, ops=%p, nops=%lu, tag=%p, reserved=%p)",
5, (call, ops, (unsigned long)nops, tag, reserved));
if (reserved != NULL) {
error = GRPC_CALL_ERROR;
goto done;

@ -36,6 +36,8 @@
#include "src/core/channel/channel_stack.h"
#include "src/core/channel/context.h"
#include "src/core/surface/api_trace.h"
#include "src/core/surface/surface_trace.h"
#include <grpc/grpc.h>
#ifdef __cplusplus
@ -128,8 +130,6 @@ grpc_call_stack *grpc_call_get_call_stack(grpc_call *call);
/* Given the top call_element, get the call object. */
grpc_call *grpc_call_from_top_element(grpc_call_element *surface_element);
extern int grpc_trace_batch;
void grpc_call_log_batch(char *file, int line, gpr_log_severity severity,
grpc_call *call, const grpc_op *ops, size_t nops,
void *tag);
@ -155,17 +155,17 @@ void grpc_call_context_set(grpc_call *call, grpc_context_index elem,
void *grpc_call_context_get(grpc_call *call, grpc_context_index elem);
#define GRPC_CALL_LOG_BATCH(sev, call, ops, nops, tag) \
if (grpc_trace_batch) grpc_call_log_batch(sev, call, ops, nops, tag)
if (grpc_api_trace) grpc_call_log_batch(sev, call, ops, nops, tag)
#define GRPC_SERVER_LOG_REQUEST_CALL(sev, server, call, details, \
initial_metadata, cq_bound_to_call, \
cq_for_notifications, tag) \
if (grpc_trace_batch) \
if (grpc_api_trace) \
grpc_server_log_request_call(sev, server, call, details, initial_metadata, \
cq_bound_to_call, cq_for_notifications, tag)
#define GRPC_SERVER_LOG_SHUTDOWN(sev, server, cq, tag) \
if (grpc_trace_batch) grpc_server_log_shutdown(sev, server, cq, tag)
if (grpc_api_trace) grpc_server_log_shutdown(sev, server, cq, tag)
gpr_uint8 grpc_call_is_client(grpc_call *call);

@ -36,11 +36,15 @@
#include <string.h>
#include "src/core/surface/api_trace.h"
void grpc_call_details_init(grpc_call_details* cd) {
GRPC_API_TRACE("grpc_call_details_init(cd=%p)", 1, (cd));
memset(cd, 0, sizeof(*cd));
}
void grpc_call_details_destroy(grpc_call_details* cd) {
GRPC_API_TRACE("grpc_call_details_destroy(cd=%p)", 1, (cd));
gpr_free(cd->method);
gpr_free(cd->host);
}

@ -37,8 +37,6 @@
#include <grpc/support/alloc.h>
#include <grpc/support/string_util.h>
int grpc_trace_batch = 0;
static void add_metadata(gpr_strvec *b, const grpc_metadata *md, size_t count) {
size_t i;
for (i = 0; i < count; i++) {

@ -43,6 +43,7 @@
#include "src/core/client_config/resolver_registry.h"
#include "src/core/iomgr/iomgr.h"
#include "src/core/support/string.h"
#include "src/core/surface/api_trace.h"
#include "src/core/surface/call.h"
#include "src/core/surface/init.h"
@ -184,6 +185,7 @@ grpc_channel *grpc_channel_create_from_filters(
}
char *grpc_channel_get_target(grpc_channel *channel) {
GRPC_API_TRACE("grpc_channel_get_target(channel=%p)", 1, (channel));
return gpr_strdup(channel->target);
}
@ -213,6 +215,15 @@ grpc_call *grpc_channel_create_call(grpc_channel *channel,
grpc_completion_queue *cq,
const char *method, const char *host,
gpr_timespec deadline, void *reserved) {
GRPC_API_TRACE(
"grpc_channel_create_call("
"channel=%p, parent_call=%p, propagation_mask=%x, cq=%p, method=%s, "
"host=%s, "
"deadline=gpr_timespec { tv_sec: %ld, tv_nsec: %d, clock_type: %d }, "
"reserved=%p)",
10, (channel, parent_call, (unsigned)propagation_mask, cq, method, host,
(long)deadline.tv_sec, deadline.tv_nsec, (int)deadline.clock_type,
reserved));
GPR_ASSERT(!reserved);
return grpc_channel_create_call_internal(
channel, parent_call, propagation_mask, cq,
@ -230,6 +241,9 @@ grpc_call *grpc_channel_create_call(grpc_channel *channel,
void *grpc_channel_register_call(grpc_channel *channel, const char *method,
const char *host, void *reserved) {
registered_call *rc = gpr_malloc(sizeof(registered_call));
GRPC_API_TRACE(
"grpc_channel_register_call(channel=%p, method=%s, host=%s, reserved=%p)",
4, (channel, method, host, reserved));
GPR_ASSERT(!reserved);
rc->path = grpc_mdelem_from_metadata_strings(
channel->metadata_context, GRPC_MDSTR_REF(channel->path_string),
@ -252,6 +266,15 @@ grpc_call *grpc_channel_create_registered_call(
grpc_completion_queue *completion_queue, void *registered_call_handle,
gpr_timespec deadline, void *reserved) {
registered_call *rc = registered_call_handle;
GRPC_API_TRACE(
"grpc_channel_create_registered_call("
"channel=%p, parent_call=%p, propagation_mask=%x, completion_queue=%p, "
"registered_call_handle=%p, "
"deadline=gpr_timespec { tv_sec: %ld, tv_nsec: %d, clock_type: %d }, "
"reserved=%p)",
9, (channel, parent_call, (unsigned)propagation_mask, completion_queue,
registered_call_handle, (long)deadline.tv_sec, deadline.tv_nsec,
(int)deadline.clock_type, reserved));
GPR_ASSERT(!reserved);
return grpc_channel_create_call_internal(
channel, parent_call, propagation_mask, completion_queue,
@ -317,6 +340,7 @@ void grpc_channel_destroy(grpc_channel *channel) {
grpc_transport_op op;
grpc_channel_element *elem;
grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
GRPC_API_TRACE("grpc_channel_destroy(channel=%p)", 1, (channel));
memset(&op, 0, sizeof(op));
op.disconnect = 1;
elem = grpc_channel_stack_element(CHANNEL_STACK_FROM_CHANNEL(channel), 0);

@ -38,6 +38,7 @@
#include "src/core/channel/client_channel.h"
#include "src/core/iomgr/alarm.h"
#include "src/core/surface/api_trace.h"
#include "src/core/surface/completion_queue.h"
grpc_connectivity_state grpc_channel_check_connectivity_state(
@ -47,6 +48,9 @@ grpc_connectivity_state grpc_channel_check_connectivity_state(
grpc_channel_stack_last_element(grpc_channel_get_channel_stack(channel));
grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
grpc_connectivity_state state;
GRPC_API_TRACE(
"grpc_channel_check_connectivity_state(channel=%p, try_to_connect=%d)", 2,
(channel, try_to_connect));
if (client_channel_elem->filter != &grpc_client_channel_filter) {
gpr_log(GPR_ERROR,
"grpc_channel_check_connectivity_state called on something that is "
@ -175,6 +179,14 @@ void grpc_channel_watch_connectivity_state(
grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
state_watcher *w = gpr_malloc(sizeof(*w));
GRPC_API_TRACE(
"grpc_channel_watch_connectivity_state("
"channel=%p, last_observed_state=%d, "
"deadline=gpr_timespec { tv_sec: %ld, tv_nsec: %d, clock_type: %d }, "
"cq=%p, tag=%p)",
7, (channel, (int)last_observed_state, (long)deadline.tv_sec,
deadline.tv_nsec, (int)deadline.clock_type, cq, tag));
grpc_cq_begin_op(cq);
gpr_mu_init(&w->mu);

@ -45,6 +45,7 @@
#include "src/core/channel/http_client_filter.h"
#include "src/core/client_config/resolver_registry.h"
#include "src/core/iomgr/tcp_client.h"
#include "src/core/surface/api_trace.h"
#include "src/core/surface/channel.h"
#include "src/core/transport/chttp2_transport.h"
@ -184,6 +185,9 @@ grpc_channel *grpc_insecure_channel_create(const char *target,
grpc_mdctx *mdctx = grpc_mdctx_create();
grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
size_t n = 0;
GRPC_API_TRACE(
"grpc_insecure_channel_create(target=%p, args=%p, reserved=%p)", 3,
(target, args, reserved));
GPR_ASSERT(!reserved);
if (grpc_channel_args_is_census_enabled(args)) {
filters[n++] = &grpc_client_census_filter;

@ -38,6 +38,7 @@
#include "src/core/iomgr/pollset.h"
#include "src/core/support/string.h"
#include "src/core/surface/api_trace.h"
#include "src/core/surface/call.h"
#include "src/core/surface/event_string.h"
#include "src/core/surface/surface_trace.h"
@ -75,6 +76,7 @@ static void on_pollset_destroy_done(grpc_exec_ctx *exec_ctx, void *cc,
grpc_completion_queue *grpc_completion_queue_create(void *reserved) {
grpc_completion_queue *cc = gpr_malloc(sizeof(grpc_completion_queue));
GRPC_API_TRACE("grpc_completion_queue_create(reserved=%p)", 1, (reserved));
GPR_ASSERT(!reserved);
memset(cc, 0, sizeof(*cc));
/* Initial ref is dropped by grpc_completion_queue_shutdown */
@ -182,6 +184,13 @@ grpc_event grpc_completion_queue_next(grpc_completion_queue *cc,
gpr_timespec now;
grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
GRPC_API_TRACE(
"grpc_completion_queue_next("
"cc=%p, "
"deadline=gpr_timespec { tv_sec: %ld, tv_nsec: %d, clock_type: %d }, "
"reserved=%p)",
5, (cc, (long)deadline.tv_sec, deadline.tv_nsec, (int)deadline.clock_type,
reserved));
GPR_ASSERT(!reserved);
deadline = gpr_convert_clock_type(deadline, GPR_CLOCK_MONOTONIC);
@ -259,6 +268,13 @@ grpc_event grpc_completion_queue_pluck(grpc_completion_queue *cc, void *tag,
int first_loop = 1;
grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
GRPC_API_TRACE(
"grpc_completion_queue_pluck("
"cc=%p, tag=%p, "
"deadline=gpr_timespec { tv_sec: %ld, tv_nsec: %d, clock_type: %d }, "
"reserved=%p)",
6, (cc, tag, (long)deadline.tv_sec, deadline.tv_nsec,
(int)deadline.clock_type, reserved));
GPR_ASSERT(!reserved);
deadline = gpr_convert_clock_type(deadline, GPR_CLOCK_MONOTONIC);
@ -324,6 +340,7 @@ done:
to zero here, then enter shutdown mode and wake up any waiters */
void grpc_completion_queue_shutdown(grpc_completion_queue *cc) {
grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
GRPC_API_TRACE("grpc_completion_queue_shutdown(cc=%p)", 1, (cc));
gpr_mu_lock(GRPC_POLLSET_MU(&cc->pollset));
if (cc->shutdown_called) {
gpr_mu_unlock(GRPC_POLLSET_MU(&cc->pollset));
@ -343,6 +360,7 @@ void grpc_completion_queue_shutdown(grpc_completion_queue *cc) {
}
void grpc_completion_queue_destroy(grpc_completion_queue *cc) {
GRPC_API_TRACE("grpc_completion_queue_destroy(cc=%p)", 1, (cc));
grpc_completion_queue_shutdown(cc);
GRPC_CQ_INTERNAL_UNREF(cc, "destroy");
}

@ -49,6 +49,7 @@
#include "src/core/debug/trace.h"
#include "src/core/iomgr/iomgr.h"
#include "src/core/profiling/timers.h"
#include "src/core/surface/api_trace.h"
#include "src/core/surface/call.h"
#include "src/core/surface/init.h"
#include "src/core/surface/surface_trace.h"
@ -75,6 +76,8 @@ static grpc_plugin g_all_of_the_plugins[MAX_PLUGINS];
static int g_number_of_plugins = 0;
void grpc_register_plugin(void (*init)(void), void (*destroy)(void)) {
GRPC_API_TRACE("grpc_register_plugin(init=%lx, destroy=%lx)", 2,
((unsigned long)init, (unsigned long)destroy));
GPR_ASSERT(g_number_of_plugins != MAX_PLUGINS);
g_all_of_the_plugins[g_number_of_plugins].init = init;
g_all_of_the_plugins[g_number_of_plugins].destroy = destroy;
@ -98,11 +101,10 @@ void grpc_init(void) {
#ifdef GPR_POSIX_SOCKET
grpc_register_resolver_type(grpc_unix_resolver_factory_create());
#endif
grpc_register_tracer("api", &grpc_api_trace);
grpc_register_tracer("channel", &grpc_trace_channel);
grpc_register_tracer("surface", &grpc_surface_trace);
grpc_register_tracer("http", &grpc_http_trace);
grpc_register_tracer("flowctl", &grpc_flowctl_trace);
grpc_register_tracer("batch", &grpc_trace_batch);
grpc_register_tracer("connectivity_state", &grpc_connectivity_state_trace);
grpc_security_pre_init();
grpc_iomgr_init();
@ -121,10 +123,12 @@ void grpc_init(void) {
}
}
gpr_mu_unlock(&g_init_mu);
GRPC_API_TRACE("grpc_init(void)", 0, ());
}
void grpc_shutdown(void) {
int i;
GRPC_API_TRACE("grpc_shutdown(void)", 0, ());
gpr_mu_lock(&g_init_mu);
if (--g_initializations == 0) {
grpc_iomgr_shutdown();

@ -37,6 +37,7 @@
#include "src/core/channel/channel_stack.h"
#include "src/core/support/string.h"
#include "src/core/surface/api_trace.h"
#include "src/core/surface/channel.h"
#include "src/core/surface/call.h"
#include <grpc/support/alloc.h>
@ -133,16 +134,9 @@ static void destroy_channel_elem(grpc_exec_ctx *exec_ctx,
grpc_channel_element *elem) {}
static const grpc_channel_filter lame_filter = {
lame_start_transport_stream_op,
lame_start_transport_op,
sizeof(call_data),
init_call_elem,
destroy_call_elem,
sizeof(channel_data),
init_channel_elem,
destroy_channel_elem,
lame_get_peer,
"lame-client",
lame_start_transport_stream_op, lame_start_transport_op, sizeof(call_data),
init_call_elem, destroy_call_elem, sizeof(channel_data), init_channel_elem,
destroy_channel_elem, lame_get_peer, "lame-client",
};
#define CHANNEL_STACK_FROM_CHANNEL(c) ((grpc_channel_stack *)((c) + 1))
@ -158,6 +152,10 @@ grpc_channel *grpc_lame_client_channel_create(const char *target,
channel = grpc_channel_create_from_filters(&exec_ctx, target, filters, 1,
NULL, grpc_mdctx_create(), 1);
elem = grpc_channel_stack_element(grpc_channel_get_channel_stack(channel), 0);
GRPC_API_TRACE(
"grpc_lame_client_channel_create(target=%s, error_code=%d, "
"error_message=%s)",
3, (target, (int)error_code, error_message));
GPR_ASSERT(elem->filter == &lame_filter);
chand = (channel_data *)elem->channel_data;
chand->error_code = error_code;

@ -36,10 +36,14 @@
#include <string.h>
#include "src/core/surface/api_trace.h"
void grpc_metadata_array_init(grpc_metadata_array* array) {
GRPC_API_TRACE("grpc_metadata_array_init(array=%p)", 1, (array));
memset(array, 0, sizeof(*array));
}
void grpc_metadata_array_destroy(grpc_metadata_array* array) {
GRPC_API_TRACE("grpc_metadata_array_destroy(array=%p)", 1, (array));
gpr_free(array->metadata);
}

@ -47,6 +47,7 @@
#include "src/core/iomgr/tcp_client.h"
#include "src/core/security/auth_filters.h"
#include "src/core/security/credentials.h"
#include "src/core/surface/api_trace.h"
#include "src/core/surface/channel.h"
#include "src/core/transport/chttp2_transport.h"
#include "src/core/tsi/transport_security_interface.h"
@ -246,7 +247,12 @@ grpc_channel *grpc_secure_channel_create(grpc_credentials *creds,
grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
size_t n = 0;
GRPC_API_TRACE(
"grpc_secure_channel_create(creds=%p, target=%s, args=%p, "
"reserved=%p)",
4, (creds, target, args, reserved));
GPR_ASSERT(reserved == NULL);
if (grpc_find_security_connector_in_args(args) != NULL) {
gpr_log(GPR_ERROR, "Cannot set security context in channel args.");
grpc_exec_ctx_finish(&exec_ctx);

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save