From e2860c5bdb98a8574673804628db6ca4dfe7c26b Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Fri, 16 Jan 2015 02:58:41 -0800 Subject: Adds rubocop and fixes most style violations it detected - add rubocop as a dev dependency - fixed many style violations it reported, often using --auto-correct - add a rubocop config - .rubocop.yml shows the exceptions - .rubocopy_todo.yml tracks outstanding style issues - adds a rake task to allow rubocop styling checks to be automated --- src/ruby/.rubocop.yml | 10 + src/ruby/.rubocop_todo.yml | 52 ++ src/ruby/Rakefile | 32 +- src/ruby/bin/interop/interop_client.rb | 57 +- src/ruby/bin/interop/interop_server.rb | 35 +- src/ruby/bin/math_client.rb | 25 +- src/ruby/bin/math_server.rb | 44 +- src/ruby/bin/noproto_client.rb | 12 +- src/ruby/bin/noproto_server.rb | 16 +- src/ruby/ext/grpc/extconf.rb | 26 +- src/ruby/grpc.gemspec | 29 +- src/ruby/lib/grpc/beefcake.rb | 19 +- src/ruby/lib/grpc/core/event.rb | 7 +- src/ruby/lib/grpc/core/time_consts.rb | 18 +- src/ruby/lib/grpc/errors.rb | 9 +- src/ruby/lib/grpc/generic/active_call.rb | 919 +++++++++++++------------- src/ruby/lib/grpc/generic/bidi_call.rb | 337 +++++----- src/ruby/lib/grpc/generic/client_stub.rb | 706 ++++++++++---------- src/ruby/lib/grpc/generic/rpc_desc.rb | 131 ++-- src/ruby/lib/grpc/generic/rpc_server.rb | 648 +++++++++--------- src/ruby/lib/grpc/generic/service.rb | 326 +++++---- src/ruby/lib/grpc/version.rb | 1 + src/ruby/spec/alloc_spec.rb | 2 - src/ruby/spec/byte_buffer_spec.rb | 4 - src/ruby/spec/call_spec.rb | 60 +- src/ruby/spec/channel_spec.rb | 37 +- src/ruby/spec/client_server_spec.rb | 82 +-- src/ruby/spec/completion_queue_spec.rb | 5 - src/ruby/spec/credentials_spec.rb | 14 +- src/ruby/spec/event_spec.rb | 22 +- src/ruby/spec/generic/active_call_spec.rb | 48 +- src/ruby/spec/generic/client_stub_spec.rb | 143 ++-- src/ruby/spec/generic/rpc_desc_spec.rb | 117 ++-- src/ruby/spec/generic/rpc_server_pool_spec.rb | 35 +- src/ruby/spec/generic/rpc_server_spec.rb | 139 ++-- src/ruby/spec/generic/service_spec.rb | 58 +- src/ruby/spec/metadata_spec.rb | 2 - src/ruby/spec/port_picker.rb | 6 +- src/ruby/spec/server_credentials_spec.rb | 13 +- src/ruby/spec/server_spec.rb | 50 +- src/ruby/spec/time_consts_spec.rb | 4 - 41 files changed, 2080 insertions(+), 2220 deletions(-) create mode 100644 src/ruby/.rubocop.yml create mode 100644 src/ruby/.rubocop_todo.yml (limited to 'src') diff --git a/src/ruby/.rubocop.yml b/src/ruby/.rubocop.yml new file mode 100644 index 0000000000..47e382afa7 --- /dev/null +++ b/src/ruby/.rubocop.yml @@ -0,0 +1,10 @@ +# This is the configuration used to check the rubocop source code. + +inherit_from: .rubocop_todo.yml + +AllCops: + Exclude: + - 'bin/apis/**/*' + - 'bin/interop/test/**/*' + - 'bin/math.rb' + - 'bin/math_services.rb' diff --git a/src/ruby/.rubocop_todo.yml b/src/ruby/.rubocop_todo.yml new file mode 100644 index 0000000000..d5bb55e5a8 --- /dev/null +++ b/src/ruby/.rubocop_todo.yml @@ -0,0 +1,52 @@ +# This configuration was generated by `rubocop --auto-gen-config` +# on 2015-01-16 02:30:04 -0800 using RuboCop version 0.28.0. +# The point is for the user to remove these configuration records +# one by one as the offenses are removed from the code base. +# Note that changes in the inspected code, or installation of new +# versions of RuboCop, may require this file to be generated again. + +# Offense count: 3 +# Lint/UselessAssignment: +# Enabled: false + +# Offense count: 33 +Metrics/AbcSize: + Max: 39 + +# Offense count: 3 +# Configuration parameters: CountComments. +Metrics/ClassLength: + Max: 231 + +# Offense count: 2 +Metrics/CyclomaticComplexity: + Max: 8 + +# Offense count: 36 +# Configuration parameters: CountComments. +Metrics/MethodLength: + Max: 37 + +# Offense count: 8 +# Configuration parameters: CountKeywordArgs. +Metrics/ParameterLists: + Max: 8 + +# Offense count: 2 +Metrics/PerceivedComplexity: + Max: 10 + +# Offense count: 7 +# Configuration parameters: AllowedVariables. +Style/GlobalVars: + Enabled: false + +# Offense count: 1 +# Configuration parameters: EnforcedStyle, MinBodyLength, SupportedStyles. +Style/Next: + Enabled: false + +# Offense count: 2 +# Configuration parameters: Methods. +Style/SingleLineBlockParams: + Enabled: false diff --git a/src/ruby/Rakefile b/src/ruby/Rakefile index 0a0fbcecca..6ba9a97c89 100755 --- a/src/ruby/Rakefile +++ b/src/ruby/Rakefile @@ -1,46 +1,44 @@ # -*- ruby -*- require 'rake/extensiontask' require 'rspec/core/rake_task' +require 'rubocop/rake_task' +desc 'Run Rubocop to check for style violations' +RuboCop::RakeTask.new Rake::ExtensionTask.new 'grpc' do |ext| ext.lib_dir = File.join('lib', 'grpc') end SPEC_SUITES = [ - { :id => :wrapper, :title => 'wrapper layer', :files => %w(spec/*.rb) }, - { :id => :idiomatic, :title => 'idiomatic layer', :dir => %w(spec/generic), - :tag => '~bidi' }, - { :id => :bidi, :title => 'bidi tests', :dir => %w(spec/generic), - :tag => 'bidi' } + { id: :wrapper, title: 'wrapper layer', files: %w(spec/*.rb) }, + { id: :idiomatic, title: 'idiomatic layer', dir: %w(spec/generic), + tag: '~bidi' }, + { id: :bidi, title: 'bidi tests', dir: %w(spec/generic), + tag: 'bidi' } ] -desc "Run all RSpec tests" +desc 'Run all RSpec tests' namespace :spec do namespace :suite do SPEC_SUITES.each do |suite| desc "Run all specs in #{suite[:title]} spec suite" RSpec::Core::RakeTask.new(suite[:id]) do |t| spec_files = [] - if suite[:files] - suite[:files].each { |f| spec_files += Dir[f] } - end + suite[:files].each { |f| spec_files += Dir[f] } if suite[:files] if suite[:dirs] suite[:dirs].each { |f| spec_files += Dir["#{f}/**/*_spec.rb"] } end t.pattern = spec_files - - if suite[:tag] - t.rspec_opts = "--tag #{suite[:tag]}" - end + t.rspec_opts = "--tag #{suite[:tag]}" if suite[:tag] end end end end -task :default => "spec:suite:idiomatic" # this should be spec:suite:bidi -task "spec:suite:wrapper" => :compile -task "spec:suite:idiomatic" => "spec:suite:wrapper" -task "spec:suite:bidi" => "spec:suite:idiomatic" +task default: 'spec:suite:idiomatic' # this should be spec:suite:bidi +task 'spec:suite:wrapper' => :compile +task 'spec:suite:idiomatic' => 'spec:suite:wrapper' +task 'spec:suite:bidi' => 'spec:suite:idiomatic' diff --git a/src/ruby/bin/interop/interop_client.rb b/src/ruby/bin/interop/interop_client.rb index 718b0fdb83..0ce10d9e30 100755 --- a/src/ruby/bin/interop/interop_client.rb +++ b/src/ruby/bin/interop/interop_client.rb @@ -65,7 +65,7 @@ end # creates a Credentials from the test certificates. def test_creds certs = load_test_certs - creds = GRPC::Core::Credentials.new(certs[0]) + GRPC::Core::Credentials.new(certs[0]) end # creates a test stub that accesses host:port securely. @@ -73,15 +73,15 @@ def create_stub(host, port) address = "#{host}:#{port}" stub_opts = { :creds => test_creds, - GRPC::Core::Channel::SSL_TARGET => 'foo.test.google.com', + GRPC::Core::Channel::SSL_TARGET => 'foo.test.google.com' } logger.info("... connecting securely to #{address}") - stub = Grpc::Testing::TestService::Stub.new(address, **stub_opts) + Grpc::Testing::TestService::Stub.new(address, **stub_opts) end # produces a string of null chars (\0) of length l. def nulls(l) - raise 'requires #{l} to be +ve' if l < 0 + fail 'requires #{l} to be +ve' if l < 0 [].pack('x' * l).force_encoding('utf-8') end @@ -102,13 +102,13 @@ class PingPongPlayer def each_item return enum_for(:each_item) unless block_given? - req_cls, p_cls= StreamingOutputCallRequest, ResponseParameters # short + req_cls, p_cls = StreamingOutputCallRequest, ResponseParameters # short count = 0 @msg_sizes.each do |m| req_size, resp_size = m - req = req_cls.new(:payload => Payload.new(:body => nulls(req_size)), - :response_type => COMPRESSABLE, - :response_parameters => [p_cls.new(:size => resp_size)]) + req = req_cls.new(payload: Payload.new(body: nulls(req_size)), + response_type: COMPRESSABLE, + response_parameters: [p_cls.new(size: resp_size)]) yield req resp = @queue.pop assert_equal(PayloadType.lookup(COMPRESSABLE), resp.payload.type, @@ -148,11 +148,11 @@ class NamedTests # ruby server # FAILED def large_unary - req_size, wanted_response_size = 271828, 314159 - payload = Payload.new(:type => COMPRESSABLE, :body => nulls(req_size)) - req = SimpleRequest.new(:response_type => COMPRESSABLE, - :response_size => wanted_response_size, - :payload => payload) + req_size, wanted_response_size = 271_828, 314_159 + payload = Payload.new(type: COMPRESSABLE, body: nulls(req_size)) + req = SimpleRequest.new(response_type: COMPRESSABLE, + response_size: wanted_response_size, + payload: payload) resp = @stub.unary_call(req) assert_equal(wanted_response_size, resp.payload.body.length, 'large_unary: payload had the wrong length') @@ -166,27 +166,27 @@ class NamedTests # ruby server # FAILED def client_streaming - msg_sizes = [27182, 8, 1828, 45904] - wanted_aggregate_size = 74922 + msg_sizes = [27_182, 8, 1828, 45_904] + wanted_aggregate_size = 74_922 reqs = msg_sizes.map do |x| - req = Payload.new(:body => nulls(x)) - StreamingInputCallRequest.new(:payload => req) + req = Payload.new(body: nulls(x)) + StreamingInputCallRequest.new(payload: req) end resp = @stub.streaming_input_call(reqs) assert_equal(wanted_aggregate_size, resp.aggregated_payload_size, 'client_streaming: aggregate payload size is incorrect') p 'OK: client_streaming' - end + end # TESTING: # PASSED # ruby server # FAILED def server_streaming - msg_sizes = [31415, 9, 2653, 58979] - response_spec = msg_sizes.map { |s| ResponseParameters.new(:size => s) } - req = StreamingOutputCallRequest.new(:response_type => COMPRESSABLE, - :response_parameters => response_spec) + msg_sizes = [31_415, 9, 2653, 58_979] + response_spec = msg_sizes.map { |s| ResponseParameters.new(size: s) } + req = StreamingOutputCallRequest.new(response_type: COMPRESSABLE, + response_parameters: response_spec) resps = @stub.streaming_output_call(req) resps.each_with_index do |r, i| assert i < msg_sizes.length, 'too many responses' @@ -203,13 +203,12 @@ class NamedTests # ruby server # FAILED def ping_pong - msg_sizes = [[27182, 31415], [8, 9], [1828, 2653], [45904, 58979]] + msg_sizes = [[27_182, 31_415], [8, 9], [1828, 2653], [45_904, 58_979]] ppp = PingPongPlayer.new(msg_sizes) resps = @stub.full_duplex_call(ppp.each_item) resps.each { |r| ppp.queue.push(r) } p 'OK: ping_pong' end - end # validates the the command line options, returning them as a Hash. @@ -217,7 +216,7 @@ def parse_options options = { 'server_host' => nil, 'server_port' => nil, - 'test_case' => nil, + 'test_case' => nil } OptionParser.new do |opts| opts.banner = 'Usage: --server_host --server_port server_port' @@ -228,17 +227,17 @@ def parse_options options['server_port'] = v end # instance_methods(false) gives only the methods defined in that class - test_cases = NamedTests.instance_methods(false).map { |t| t.to_s } + test_cases = NamedTests.instance_methods(false).map(&:to_s) test_case_list = test_cases.join(',') - opts.on("--test_case CODE", test_cases, {}, "select a test_case", + opts.on('--test_case CODE', test_cases, {}, 'select a test_case', " (#{test_case_list})") do |v| options['test_case'] = v end end.parse! - ['server_host', 'server_port', 'test_case'].each do |arg| + %w(server_host, server_port, test_case).each do |arg| if options[arg].nil? - raise OptionParser::MissingArgument.new("please specify --#{arg}") + fail(OptionParser::MissingArgument, "please specify --#{arg}") end end options diff --git a/src/ruby/bin/interop/interop_server.rb b/src/ruby/bin/interop/interop_server.rb index 63071f3ec2..9273dcdf91 100755 --- a/src/ruby/bin/interop/interop_server.rb +++ b/src/ruby/bin/interop/interop_server.rb @@ -62,12 +62,12 @@ end # creates a ServerCredentials from the test certificates. def test_server_creds certs = load_test_certs - server_creds = GRPC::Core::ServerCredentials.new(nil, certs[1], certs[2]) + GRPC::Core::ServerCredentials.new(nil, certs[1], certs[2]) end # produces a string of null chars (\0) of length l. def nulls(l) - raise 'requires #{l} to be +ve' if l < 0 + fail 'requires #{l} to be +ve' if l < 0 [].pack('x' * l).force_encoding('utf-8') end @@ -86,7 +86,7 @@ class EnumeratorQueue loop do r = @q.pop break if r.equal?(@sentinel) - raise r if r.is_a?Exception + fail r if r.is_a? Exception yield r end end @@ -98,27 +98,27 @@ class TestTarget < Grpc::Testing::TestService::Service include Grpc::Testing include Grpc::Testing::PayloadType - def empty_call(empty, call) + def empty_call(_empty, _call) Empty.new end - def unary_call(simple_req, call) + def unary_call(simple_req, _call) req_size = simple_req.response_size - SimpleResponse.new(:payload => Payload.new(:type => COMPRESSABLE, - :body => nulls(req_size))) + SimpleResponse.new(payload: Payload.new(type: COMPRESSABLE, + body: nulls(req_size))) end def streaming_input_call(call) sizes = call.each_remote_read.map { |x| x.payload.body.length } - sum = sizes.inject { |sum,x| sum + x } - StreamingInputCallResponse.new(:aggregated_payload_size => sum) + sum = sizes.inject { |s, x| s + x } + StreamingInputCallResponse.new(aggregated_payload_size: sum) end - def streaming_output_call(req, call) + def streaming_output_call(req, _call) cls = StreamingOutputCallResponse req.response_parameters.map do |p| - cls.new(:payload => Payload.new(:type => req.response_type, - :body => nulls(p.size))) + cls.new(payload: Payload.new(type: req.response_type, + body: nulls(p.size))) end end @@ -126,13 +126,13 @@ class TestTarget < Grpc::Testing::TestService::Service # reqs is a lazy Enumerator of the requests sent by the client. q = EnumeratorQueue.new(self) cls = StreamingOutputCallResponse - t = Thread.new do + Thread.new do begin reqs.each do |req| logger.info("read #{req.inspect}") resp_size = req.response_parameters[0].size - resp = cls.new(:payload => Payload.new(:type => req.response_type, - :body => nulls(resp_size))) + resp = cls.new(payload: Payload.new(type: req.response_type, + body: nulls(resp_size))) q.push(resp) end logger.info('finished reads') @@ -149,13 +149,12 @@ class TestTarget < Grpc::Testing::TestService::Service # currently used in any tests full_duplex_call(reqs) end - end # validates the the command line options, returning them as a Hash. def parse_options options = { - 'port' => nil, + 'port' => nil } OptionParser.new do |opts| opts.banner = 'Usage: --port port' @@ -165,7 +164,7 @@ def parse_options end.parse! if options['port'].nil? - raise OptionParser::MissingArgument.new("please specify --port") + fail(OptionParser::MissingArgument, 'please specify --port') end options end diff --git a/src/ruby/bin/math_client.rb b/src/ruby/bin/math_client.rb index 4df333d085..195406c8b3 100755 --- a/src/ruby/bin/math_client.rb +++ b/src/ruby/bin/math_client.rb @@ -29,7 +29,6 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - # Sample app that accesses a Calc service running on a Ruby gRPC server and # helps validate RpcServer as a gRPC server using proto2 serialization. # @@ -49,9 +48,9 @@ include GRPC::Core::TimeConsts def do_div(stub) logger.info('request_response') logger.info('----------------') - req = Math::DivArgs.new(:dividend => 7, :divisor => 3) + req = Math::DivArgs.new(dividend: 7, divisor: 3) logger.info("div(7/3): req=#{req.inspect}") - resp = stub.div(req, deadline=INFINITE_FUTURE) + resp = stub.div(req, INFINITE_FUTURE) logger.info("Answer: #{resp.inspect}") logger.info('----------------') end @@ -60,7 +59,7 @@ def do_sum(stub) # to make client streaming requests, pass an enumerable of the inputs logger.info('client_streamer') logger.info('---------------') - reqs = [1, 2, 3, 4, 5].map { |x| Math::Num.new(:num => x) } + reqs = [1, 2, 3, 4, 5].map { |x| Math::Num.new(num: x) } logger.info("sum(1, 2, 3, 4, 5): reqs=#{reqs.inspect}") resp = stub.sum(reqs) # reqs.is_a?(Enumerable) logger.info("Answer: #{resp.inspect}") @@ -70,9 +69,9 @@ end def do_fib(stub) logger.info('server_streamer') logger.info('----------------') - req = Math::FibArgs.new(:limit => 11) + req = Math::FibArgs.new(limit: 11) logger.info("fib(11): req=#{req.inspect}") - resp = stub.fib(req, deadline=INFINITE_FUTURE) + resp = stub.fib(req, INFINITE_FUTURE) resp.each do |r| logger.info("Answer: #{r.inspect}") end @@ -83,11 +82,11 @@ def do_div_many(stub) logger.info('bidi_streamer') logger.info('-------------') reqs = [] - reqs << Math::DivArgs.new(:dividend => 7, :divisor => 3) - reqs << Math::DivArgs.new(:dividend => 5, :divisor => 2) - reqs << Math::DivArgs.new(:dividend => 7, :divisor => 2) + reqs << Math::DivArgs.new(dividend: 7, divisor: 3) + reqs << Math::Di5AvArgs.new(dividend: 5, divisor: 2) + reqs << Math::DivArgs.new(dividend: 7, divisor: 2) logger.info("div(7/3), div(5/2), div(7/2): reqs=#{reqs.inspect}") - resp = stub.div_many(reqs, deadline=10) + resp = stub.div_many(reqs, 10) resp.each do |r| logger.info("Answer: #{r.inspect}") end @@ -103,7 +102,7 @@ end def test_creds certs = load_test_certs - creds = GRPC::Core::Credentials.new(certs[0]) + GRPC::Core::Credentials.new(certs[0]) end def main @@ -117,7 +116,7 @@ def main options['host'] = v end opts.on('-s', '--secure', 'access using test creds') do |v| - options['secure'] = true + options['secure'] = v end end.parse! @@ -128,7 +127,7 @@ def main if options['secure'] stub_opts = { :creds => test_creds, - GRPC::Core::Channel::SSL_TARGET => 'foo.test.google.com', + GRPC::Core::Channel::SSL_TARGET => 'foo.test.google.com' } p stub_opts p options['host'] diff --git a/src/ruby/bin/math_server.rb b/src/ruby/bin/math_server.rb index 0e47f71e66..55ee1d3314 100755 --- a/src/ruby/bin/math_server.rb +++ b/src/ruby/bin/math_server.rb @@ -46,9 +46,8 @@ require 'optparse' # Holds state for a fibonacci series class Fibber - def initialize(limit) - raise "bad limit: got #{limit}, want limit > 0" if limit < 1 + fail "bad limit: got #{limit}, want limit > 0" if limit < 1 @limit = limit end @@ -57,14 +56,14 @@ class Fibber idx, current, previous = 0, 1, 1 until idx == @limit if idx == 0 || idx == 1 - yield Math::Num.new(:num => 1) + yield Math::Num.new(num: 1) idx += 1 next end tmp = current current = previous + current previous = tmp - yield Math::Num.new(:num => current) + yield Math::Num.new(num: current) idx += 1 end end @@ -85,43 +84,41 @@ class EnumeratorQueue loop do r = @q.pop break if r.equal?(@sentinel) - raise r if r.is_a?Exception + fail r if r.is_a? Exception yield r end end - end # The Math::Math:: module occurs because the service has the same name as its # package. That practice should be avoided by defining real services. class Calculator < Math::Math::Service - - def div(div_args, call) + def div(div_args, _call) if div_args.divisor == 0 # To send non-OK status handlers raise a StatusError with the code and # and detail they want sent as a Status. - raise GRPC::StatusError.new(GRPC::Status::INVALID_ARGUMENT, - 'divisor cannot be 0') + fail GRPC::StatusError.new(GRPC::Status::INVALID_ARGUMENT, + 'divisor cannot be 0') end - Math::DivReply.new(:quotient => div_args.dividend/div_args.divisor, - :remainder => div_args.dividend % div_args.divisor) + Math::DivReply.new(quotient: div_args.dividend / div_args.divisor, + remainder: div_args.dividend % div_args.divisor) end def sum(call) # the requests are accesible as the Enumerator call#each_request - nums = call.each_remote_read.collect { |x| x.num } - sum = nums.inject { |sum,x| sum + x } - Math::Num.new(:num => sum) + nums = call.each_remote_read.collect(&:num) + sum = nums.inject { |s, x| s + x } + Math::Num.new(num: sum) end - def fib(fib_args, call) + def fib(fib_args, _call) if fib_args.limit < 1 - raise StatusError.new(Status::INVALID_ARGUMENT, 'limit must be >= 0') + fail StatusError.new(Status::INVALID_ARGUMENT, 'limit must be >= 0') end # return an Enumerator of Nums - Fibber.new(fib_args.limit).generator() + Fibber.new(fib_args.limit).generator # just return the generator, GRPC::GenericServer sends each actual response end @@ -132,10 +129,10 @@ class Calculator < Math::Math::Service begin requests.each do |req| logger.info("read #{req.inspect}") - resp = Math::DivReply.new(:quotient => req.dividend/req.divisor, - :remainder => req.dividend % req.divisor) + resp = Math::DivReply.new(quotient: req.dividend / req.divisor, + remainder: req.dividend % req.divisor) q.push(resp) - Thread::pass # let the internal Bidi threads run + Thread.pass # let the internal Bidi threads run end logger.info('finished reads') q.push(self) @@ -147,7 +144,6 @@ class Calculator < Math::Math::Service t.priority = -2 # hint that the div_many thread should not be favoured q.each_item end - end def load_test_certs @@ -159,7 +155,7 @@ end def test_server_creds certs = load_test_certs - server_creds = GRPC::Core::ServerCredentials.new(nil, certs[1], certs[2]) + GRPC::Core::ServerCredentials.new(nil, certs[1], certs[2]) end def main @@ -173,7 +169,7 @@ def main options['host'] = v end opts.on('-s', '--secure', 'access using test creds') do |v| - options['secure'] = true + options['secure'] = v end end.parse! diff --git a/src/ruby/bin/noproto_client.rb b/src/ruby/bin/noproto_client.rb index 34bdf545ee..74bdfbb93a 100755 --- a/src/ruby/bin/noproto_client.rb +++ b/src/ruby/bin/noproto_client.rb @@ -40,16 +40,18 @@ $LOAD_PATH.unshift(lib_dir) unless $LOAD_PATH.include?(lib_dir) require 'grpc' require 'optparse' +# a simple non-protobuf message class. class NoProtoMsg - def self.marshal(o) + def self.marshal(_o) '' end - def self.unmarshal(o) + def self.unmarshal(_o) NoProtoMsg.new end end +# service the uses the non-protobuf message class. class NoProtoService include GRPC::GenericService rpc :AnRPC, NoProtoMsg, NoProtoMsg @@ -66,7 +68,7 @@ end def test_creds certs = load_test_certs - creds = GRPC::Core::Credentials.new(certs[0]) + GRPC::Core::Credentials.new(certs[0]) end def main @@ -80,14 +82,14 @@ def main options['host'] = v end opts.on('-s', '--secure', 'access using test creds') do |v| - options['secure'] = true + options['secure'] = v end end.parse! if options['secure'] stub_opts = { :creds => test_creds, - GRPC::Core::Channel::SSL_TARGET => 'foo.test.google.com', + GRPC::Core::Channel::SSL_TARGET => 'foo.test.google.com' } p stub_opts p options['host'] diff --git a/src/ruby/bin/noproto_server.rb b/src/ruby/bin/noproto_server.rb index 1bdc192f02..e34075c1f0 100755 --- a/src/ruby/bin/noproto_server.rb +++ b/src/ruby/bin/noproto_server.rb @@ -40,26 +40,29 @@ $LOAD_PATH.unshift(lib_dir) unless $LOAD_PATH.include?(lib_dir) require 'grpc' require 'optparse' +# a simple non-protobuf message class. class NoProtoMsg - def self.marshal(o) + def self.marshal(_o) '' end - def self.unmarshal(o) + def self.unmarshal(_o) NoProtoMsg.new end end +# service the uses the non-protobuf message class. class NoProtoService include GRPC::GenericService rpc :AnRPC, NoProtoMsg, NoProtoMsg end +# an implementation of the non-protobuf service. class NoProto < NoProtoService - def initialize(default_var='ignored') + def initialize(_default_var = 'ignored') end - def an_rpc(req, call) + def an_rpc(req, _call) logger.info('echo service received a request') req end @@ -74,7 +77,7 @@ end def test_server_creds certs = load_test_certs - server_creds = GRPC::Core::ServerCredentials.new(nil, certs[1], certs[2]) + GRPC::Core::ServerCredentials.new(nil, certs[1], certs[2]) end def main @@ -88,7 +91,7 @@ def main options['host'] = v end opts.on('-s', '--secure', 'access using test creds') do |v| - options['secure'] = true + options['secure'] = v end end.parse! @@ -106,5 +109,4 @@ def main s.run end - main diff --git a/src/ruby/ext/grpc/extconf.rb b/src/ruby/ext/grpc/extconf.rb index a828b47294..e948504e9e 100644 --- a/src/ruby/ext/grpc/extconf.rb +++ b/src/ruby/ext/grpc/extconf.rb @@ -33,29 +33,29 @@ LIBDIR = RbConfig::CONFIG['libdir'] INCLUDEDIR = RbConfig::CONFIG['includedir'] HEADER_DIRS = [ - # Search /opt/local (Mac source install) - '/opt/local/include', + # Search /opt/local (Mac source install) + '/opt/local/include', - # Search /usr/local (Source install) - '/usr/local/include', + # Search /usr/local (Source install) + '/usr/local/include', - # Check the ruby install locations - INCLUDEDIR, + # Check the ruby install locations + INCLUDEDIR ] LIB_DIRS = [ - # Search /opt/local (Mac source install) - '/opt/local/lib', + # Search /opt/local (Mac source install) + '/opt/local/lib', - # Search /usr/local (Source install) - '/usr/local/lib', + # Search /usr/local (Source install) + '/usr/local/lib', - # Check the ruby install locations - LIBDIR, + # Check the ruby install locations + LIBDIR ] def crash(msg) - print(" extconf failure: %s\n" % msg) + print(" extconf failure: #{msg}\n") exit 1 end diff --git a/src/ruby/grpc.gemspec b/src/ruby/grpc.gemspec index 53fdd29a79..ad4e274b7e 100755 --- a/src/ruby/grpc.gemspec +++ b/src/ruby/grpc.gemspec @@ -1,31 +1,34 @@ # encoding: utf-8 -$:.push File.expand_path("../lib", __FILE__) +$LOAD_PATH.push File.expand_path('../lib', __FILE__) require 'grpc/version' Gem::Specification.new do |s| - s.name = "grpc" + s.name = 'grpc' s.version = Google::RPC::VERSION - s.authors = ["One Platform Team"] - s.email = "stubby-team@google.com" - s.homepage = "http://go/grpc" + s.authors = ['One Platform Team'] + s.email = 'stubby-team@google.com' + s.homepage = 'http://go/grpc' s.summary = 'Google RPC system in Ruby' s.description = 'Send RPCs from Ruby' s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- spec/*`.split("\n") - s.executables = `git ls-files -- examples/*.rb`.split("\n").map{ |f| File.basename(f) } - s.require_paths = ['lib' ] + s.executables = `git ls-files -- bin/*.rb`.split("\n").map do |f| + File.basename(f) + end + s.require_paths = ['lib'] s.platform = Gem::Platform::RUBY s.add_dependency 'xray' s.add_dependency 'logging', '~> 1.8' - s.add_dependency 'google-protobuf', '~> 3.0.0alpha.1.1' - s.add_dependency 'minitest', '~> 5.4' # not a dev dependency, used by the interop tests + s.add_dependency 'google-protobuf', '~> 3.0.0alpha' + s.add_dependency 'minitest', '~> 5.4' # reqd for interop tests - s.add_development_dependency "bundler", "~> 1.7" - s.add_development_dependency "rake", "~> 10.0" + s.add_development_dependency 'bundler', '~> 1.7' + s.add_development_dependency 'rake', '~> 10.0' s.add_development_dependency 'rake-compiler', '~> 0' - s.add_development_dependency 'rspec', "~> 3.0" + s.add_development_dependency 'rubocop', '~> 0.28.0' + s.add_development_dependency 'rspec', '~> 3.0' - s.extensions = %w[ext/grpc/extconf.rb] + s.extensions = %w(ext/grpc/extconf.rb) end diff --git a/src/ruby/lib/grpc/beefcake.rb b/src/ruby/lib/grpc/beefcake.rb index e8d7f0c2cd..fd3ebbf4b8 100644 --- a/src/ruby/lib/grpc/beefcake.rb +++ b/src/ruby/lib/grpc/beefcake.rb @@ -29,25 +29,21 @@ require 'beefcake' -# Re-open the beefcake message module to add a static encode -# -# This is a temporary measure while beefcake is used as the default proto -# library for developing grpc ruby. Once that changes to the official proto -# library this can be removed. It's necessary to allow the update the service -# module to assume a static encode method. -# -# TODO(temiola): remove me, once official code generation is available in protoc module Beefcake + # Re-open the beefcake message module to add a static encode + # + # This is a temporary measure while beefcake is used as the default proto + # library for developing grpc ruby. Once that changes to the official proto + # library this can be removed. It's necessary to allow the update the service + # module to assume a static encode method. + # TODO(temiola): remove this. module Message - # additional mixin module that adds static encode method when include module StaticEncode - # encodes o with its instance#encode method def encode(o) o.encode end - end # extend self.included in Beefcake::Message to include StaticEncode @@ -57,6 +53,5 @@ module Beefcake o.extend Decode o.send(:include, Encode) end - end end diff --git a/src/ruby/lib/grpc/core/event.rb b/src/ruby/lib/grpc/core/event.rb index 29486763d5..9a333589c2 100644 --- a/src/ruby/lib/grpc/core/event.rb +++ b/src/ruby/lib/grpc/core/event.rb @@ -30,9 +30,12 @@ module Google module RPC module Core - class Event # Add an inspect method to C-defined Event class. + # Event is a class defined in the c extension + # + # Here, we add an inspect method. + class Event def inspect - '<%s: type:%s, tag:%s result:%s>' % [self.class, type, tag, result] + "<#{self.class}: type:#{type}, tag:#{tag} result:#{result}>" end end end diff --git a/src/ruby/lib/grpc/core/time_consts.rb b/src/ruby/lib/grpc/core/time_consts.rb index 52e4c3f9b9..6876dcb02e 100644 --- a/src/ruby/lib/grpc/core/time_consts.rb +++ b/src/ruby/lib/grpc/core/time_consts.rb @@ -32,9 +32,10 @@ require 'grpc' module Google module RPC module Core - - module TimeConsts # re-opens a module in the C extension. - + # TimeConsts is a module from the C extension. + # + # Here it's re-opened to add a utility func. + module TimeConsts # Converts a time delta to an absolute deadline. # # Assumes timeish is a relative time, and converts its to an absolute, @@ -48,24 +49,23 @@ module Google # @param timeish [Number|TimeSpec] # @return timeish [Number|TimeSpec] def from_relative_time(timeish) - if timeish.is_a?TimeSpec + if timeish.is_a? TimeSpec timeish elsif timeish.nil? TimeConsts::ZERO - elsif !timeish.is_a?Numeric - raise TypeError('Cannot make an absolute deadline from %s', - timeish.inspect) + elsif !timeish.is_a? Numeric + fail(TypeError, + "Cannot make an absolute deadline from #{timeish.inspect}") elsif timeish < 0 TimeConsts::INFINITE_FUTURE elsif timeish == 0 TimeConsts::ZERO - else !timeish.nil? + else Time.now + timeish end end module_function :from_relative_time - end end end diff --git a/src/ruby/lib/grpc/errors.rb b/src/ruby/lib/grpc/errors.rb index d14e69c65a..70a92bfed7 100644 --- a/src/ruby/lib/grpc/errors.rb +++ b/src/ruby/lib/grpc/errors.rb @@ -30,9 +30,8 @@ require 'grpc' module Google - + # Google::RPC contains the General RPC module. module RPC - # OutOfTime is an exception class that indicates that an RPC exceeded its # deadline. OutOfTime = Class.new(StandardError) @@ -42,12 +41,11 @@ module Google # error should be returned to the other end of a GRPC connection; when # caught it means that this end received a status error. class BadStatus < StandardError - attr_reader :code, :details # @param code [Numeric] the status code # @param details [String] the details of the exception - def initialize(code, details='unknown cause') + def initialize(code, details = 'unknown cause') super("#{code}:#{details}") @code = code @details = details @@ -60,9 +58,6 @@ module Google def to_status Status.new(code, details) end - end - end - end diff --git a/src/ruby/lib/grpc/generic/active_call.rb b/src/ruby/lib/grpc/generic/active_call.rb index 288ea083e6..bd684a8d07 100644 --- a/src/ruby/lib/grpc/generic/active_call.rb +++ b/src/ruby/lib/grpc/generic/active_call.rb @@ -31,519 +31,516 @@ require 'forwardable' require 'grpc/generic/bidi_call' def assert_event_type(ev, want) - raise OutOfTime if ev.nil? + fail OutOfTime if ev.nil? got = ev.type - raise 'Unexpected rpc event: got %s, want %s' % [got, want] unless got == want + fail "Unexpected rpc event: got #{got}, want #{want}" unless got == want end -module Google::RPC - - # The ActiveCall class provides simple methods for sending marshallable - # data to a call - class ActiveCall - include Core::CompletionType - include Core::StatusCodes - include Core::TimeConsts - attr_reader(:deadline) - - # client_start_invoke begins a client invocation. - # - # Flow Control note: this blocks until flow control accepts that client - # request can go ahead. - # - # deadline is the absolute deadline for the call. - # - # == Keyword Arguments == - # any keyword arguments are treated as metadata to be sent to the server - # if a keyword value is a list, multiple metadata for it's key are sent - # - # @param call [Call] a call on which to start and invocation - # @param q [CompletionQueue] used to wait for INVOKE_ACCEPTED - # @param deadline [Fixnum,TimeSpec] the deadline for INVOKE_ACCEPTED - def self.client_start_invoke(call, q, deadline, **kw) - raise ArgumentError.new('not a call') unless call.is_a?Core::Call - if !q.is_a?Core::CompletionQueue - raise ArgumentError.new('not a CompletionQueue') - end - call.add_metadata(kw) if kw.length > 0 - invoke_accepted, client_metadata_read = Object.new, Object.new - finished_tag = Object.new - call.start_invoke(q, invoke_accepted, client_metadata_read, finished_tag) +module Google + # Google::RPC contains the General RPC module. + module RPC + # The ActiveCall class provides simple methods for sending marshallable + # data to a call + class ActiveCall + include Core::CompletionType + include Core::StatusCodes + include Core::TimeConsts + attr_reader(:deadline) + + # client_start_invoke begins a client invocation. + # + # Flow Control note: this blocks until flow control accepts that client + # request can go ahead. + # + # deadline is the absolute deadline for the call. + # + # == Keyword Arguments == + # any keyword arguments are treated as metadata to be sent to the server + # if a keyword value is a list, multiple metadata for it's key are sent + # + # @param call [Call] a call on which to start and invocation + # @param q [CompletionQueue] used to wait for INVOKE_ACCEPTED + # @param deadline [Fixnum,TimeSpec] the deadline for INVOKE_ACCEPTED + def self.client_start_invoke(call, q, _deadline, **kw) + fail(ArgumentError, 'not a call') unless call.is_a? Core::Call + unless q.is_a? Core::CompletionQueue + fail(ArgumentError, 'not a CompletionQueue') + end + call.add_metadata(kw) if kw.length > 0 + invoke_accepted, client_metadata_read = Object.new, Object.new + finished_tag = Object.new + call.start_invoke(q, invoke_accepted, client_metadata_read, + finished_tag) + + # wait for the invocation to be accepted + ev = q.pluck(invoke_accepted, INFINITE_FUTURE) + fail OutOfTime if ev.nil? + ev.close - # wait for the invocation to be accepted - ev = q.pluck(invoke_accepted, INFINITE_FUTURE) - raise OutOfTime if ev.nil? - ev.close + [finished_tag, client_metadata_read] + end - [finished_tag, client_metadata_read] - end + # Creates an ActiveCall. + # + # ActiveCall should only be created after a call is accepted. That means + # different things on a client and a server. On the client, the call is + # accepted after call.start_invoke followed by receipt of the + # corresponding INVOKE_ACCEPTED. on the server, this is after + # call.accept. + # + # #initialize cannot determine if the call is accepted or not; so if a + # call that's not accepted is used here, the error won't be visible until + # the ActiveCall methods are called. + # + # deadline is the absolute deadline for the call. + # + # @param call [Call] the call used by the ActiveCall + # @param q [CompletionQueue] the completion queue used to accept + # the call + # @param marshal [Function] f(obj)->string that marshal requests + # @param unmarshal [Function] f(string)->obj that unmarshals responses + # @param deadline [Fixnum] the deadline for the call to complete + # @param finished_tag [Object] the object used as the call's finish tag, + # if the call has begun + # @param read_metadata_tag [Object] the object used as the call's finish + # tag, if the call has begun + # @param started [true|false] indicates if the call has begun + def initialize(call, q, marshal, unmarshal, deadline, finished_tag: nil, + read_metadata_tag: nil, started: true) + fail(ArgumentError, 'not a call') unless call.is_a? Core::Call + unless q.is_a? Core::CompletionQueue + fail(ArgumentError, 'not a CompletionQueue') + end + @call = call + @cq = q + @deadline = deadline + @finished_tag = finished_tag + @read_metadata_tag = read_metadata_tag + @marshal = marshal + @started = started + @unmarshal = unmarshal + end - # Creates an ActiveCall. - # - # ActiveCall should only be created after a call is accepted. That means - # different things on a client and a server. On the client, the call is - # accepted after call.start_invoke followed by receipt of the - # corresponding INVOKE_ACCEPTED. on the server, this is after - # call.accept. - # - # #initialize cannot determine if the call is accepted or not; so if a - # call that's not accepted is used here, the error won't be visible until - # the ActiveCall methods are called. - # - # deadline is the absolute deadline for the call. - # - # @param call [Call] the call used by the ActiveCall - # @param q [CompletionQueue] the completion queue used to accept - # the call - # @param marshal [Function] f(obj)->string that marshal requests - # @param unmarshal [Function] f(string)->obj that unmarshals responses - # @param deadline [Fixnum] the deadline for the call to complete - # @param finished_tag [Object] the object used as the call's finish tag, - # if the call has begun - # @param read_metadata_tag [Object] the object used as the call's finish - # tag, if the call has begun - # @param started [true|false] (default true) indicates if the call has begun - def initialize(call, q, marshal, unmarshal, deadline, finished_tag: nil, - read_metadata_tag: nil, started: true) - raise ArgumentError.new('not a call') unless call.is_a?Core::Call - if !q.is_a?Core::CompletionQueue - raise ArgumentError.new('not a CompletionQueue') + # Obtains the status of the call. + # + # this value is nil until the call completes + # @return this call's status + def status + @call.status end - @call = call - @cq = q - @deadline = deadline - @finished_tag = finished_tag - @read_metadata_tag = read_metadata_tag - @marshal = marshal - @started = started - @unmarshal = unmarshal - end - # Obtains the status of the call. - # - # this value is nil until the call completes - # @return this call's status - def status - @call.status - end + # Obtains the metadata of the call. + # + # At the start of the call this will be nil. During the call this gets + # some values as soon as the other end of the connection acknowledges the + # request. + # + # @return this calls's metadata + def metadata + @call.metadata + end - # Obtains the metadata of the call. - # - # At the start of the call this will be nil. During the call this gets - # some values as soon as the other end of the connection acknowledges the - # request. - # - # @return this calls's metadata - def metadata - @call.metadata - end + # Cancels the call. + # + # Cancels the call. The call does not return any result, but once this it + # has been called, the call should eventually terminate. Due to potential + # races between the execution of the cancel and the in-flight request, the + # result of the call after calling #cancel is indeterminate: + # + # - the call may terminate with a BadStatus exception, with code=CANCELLED + # - the call may terminate with OK Status, and return a response + # - the call may terminate with a different BadStatus exception if that + # was happening + def cancel + @call.cancel + end - # Cancels the call. - # - # Cancels the call. The call does not return any result, but once this it - # has been called, the call should eventually terminate. Due to potential - # races between the execution of the cancel and the in-flight request, the - # result of the call after calling #cancel is indeterminate: - # - # - the call may terminate with a BadStatus exception, with code=CANCELLED - # - the call may terminate with OK Status, and return a response - # - the call may terminate with a different BadStatus exception if that was - # happening - def cancel - @call.cancel - end + # indicates if the call is shutdown + def shutdown + @shutdown ||= false + end - # indicates if the call is shutdown - def shutdown - @shutdown ||= false - end + # indicates if the call is cancelled. + def cancelled + @cancelled ||= false + end - # indicates if the call is cancelled. - def cancelled - @cancelled ||= false - end + # multi_req_view provides a restricted view of this ActiveCall for use + # in a server client-streaming handler. + def multi_req_view + MultiReqView.new(self) + end - # multi_req_view provides a restricted view of this ActiveCall for use - # in a server client-streaming handler. - def multi_req_view - MultiReqView.new(self) - end + # single_req_view provides a restricted view of this ActiveCall for use in + # a server request-response handler. + def single_req_view + SingleReqView.new(self) + end - # single_req_view provides a restricted view of this ActiveCall for use in - # a server request-response handler. - def single_req_view - SingleReqView.new(self) - end + # operation provides a restricted view of this ActiveCall for use as + # a Operation. + def operation + Operation.new(self) + end - # operation provides a restricted view of this ActiveCall for use as - # a Operation. - def operation - Operation.new(self) - end + # writes_done indicates that all writes are completed. + # + # It blocks until the remote endpoint acknowledges by sending a FINISHED + # event, unless assert_finished is set to false. Any calls to + # #remote_send after this call will fail. + # + # @param assert_finished [true, false] when true(default), waits for + # FINISHED. + def writes_done(assert_finished = true) + @call.writes_done(self) + ev = @cq.pluck(self, INFINITE_FUTURE) + begin + assert_event_type(ev, FINISH_ACCEPTED) + logger.debug("Writes done: waiting for finish? #{assert_finished}") + ensure + ev.close + end - # writes_done indicates that all writes are completed. - # - # It blocks until the remote endpoint acknowledges by sending a FINISHED - # event, unless assert_finished is set to false. Any calls to - # #remote_send after this call will fail. - # - # @param assert_finished [true, false] when true(default), waits for - # FINISHED. - def writes_done(assert_finished=true) - @call.writes_done(self) - ev = @cq.pluck(self, INFINITE_FUTURE) - begin - assert_event_type(ev, FINISH_ACCEPTED) - logger.debug("Writes done: waiting for finish? #{assert_finished}") - ensure + return unless assert_finished + ev = @cq.pluck(@finished_tag, INFINITE_FUTURE) + fail 'unexpected nil event' if ev.nil? ev.close + @call.status end - if assert_finished + # finished waits until the call is completed. + # + # It blocks until the remote endpoint acknowledges by sending a FINISHED + # event. + def finished ev = @cq.pluck(@finished_tag, INFINITE_FUTURE) - raise "unexpected event: #{ev.inspect}" if ev.nil? - ev.close - return @call.status + begin + fail "unexpected event: #{ev.inspect}" unless ev.type == FINISHED + if @call.metadata.nil? + @call.metadata = ev.result.metadata + else + @call.metadata.merge!(ev.result.metadata) + end + + if ev.result.code != Core::StatusCodes::OK + fail BadStatus.new(ev.result.code, ev.result.details) + end + res = ev.result + ensure + ev.close + end + res end - end - # finished waits until the call is completed. - # - # It blocks until the remote endpoint acknowledges by sending a FINISHED - # event. - def finished - ev = @cq.pluck(@finished_tag, INFINITE_FUTURE) - begin - raise "unexpected event: #{ev.inspect}" unless ev.type == FINISHED - if @call.metadata.nil? - @call.metadata = ev.result.metadata + # remote_send sends a request to the remote endpoint. + # + # It blocks until the remote endpoint acknowledges by sending a + # WRITE_ACCEPTED. req can be marshalled already. + # + # @param req [Object, String] the object to send or it's marshal form. + # @param marshalled [false, true] indicates if the object is already + # marshalled. + def remote_send(req, marshalled = false) + assert_queue_is_ready + logger.debug("sending #{req.inspect}, marshalled? #{marshalled}") + if marshalled + payload = req else - @call.metadata.merge!(ev.result.metadata) + payload = @marshal.call(req) end - - if ev.result.code != Core::StatusCodes::OK - raise BadStatus.new(ev.result.code, ev.result.details) + @call.start_write(Core::ByteBuffer.new(payload), self) + + # call queue#pluck, and wait for WRITE_ACCEPTED, so as not to return + # until the flow control allows another send on this call. + ev = @cq.pluck(self, INFINITE_FUTURE) + begin + assert_event_type(ev, WRITE_ACCEPTED) + ensure + ev.close end - res = ev.result - ensure - ev.close end - res - end - # remote_send sends a request to the remote endpoint. - # - # It blocks until the remote endpoint acknowledges by sending a - # WRITE_ACCEPTED. req can be marshalled already. - # - # @param req [Object, String] the object to send or it's marshal form. - # @param marshalled [false, true] indicates if the object is already - # marshalled. - def remote_send(req, marshalled=false) - assert_queue_is_ready - logger.debug("sending payload #{req.inspect}, marshalled? #{marshalled}") - if marshalled - payload = req - else - payload = @marshal.call(req) - end - @call.start_write(Core::ByteBuffer.new(payload), self) - - # call queue#pluck, and wait for WRITE_ACCEPTED, so as not to return - # until the flow control allows another send on this call. - ev = @cq.pluck(self, INFINITE_FUTURE) - begin - assert_event_type(ev, WRITE_ACCEPTED) - ensure - ev.close + # send_status sends a status to the remote endpoint + # + # @param code [int] the status code to send + # @param details [String] details + # @param assert_finished [true, false] when true(default), waits for + # FINISHED. + def send_status(code = OK, details = '', assert_finished = false) + assert_queue_is_ready + @call.start_write_status(code, details, self) + ev = @cq.pluck(self, INFINITE_FUTURE) + begin + assert_event_type(ev, FINISH_ACCEPTED) + ensure + ev.close + end + logger.debug("Status sent: #{code}:'#{details}'") + return finished if assert_finished + nil end - end - # send_status sends a status to the remote endpoint - # - # @param code [int] the status code to send - # @param details [String] details - # @param assert_finished [true, false] when true(default), waits for - # FINISHED. - def send_status(code=OK, details='', assert_finished=false) - assert_queue_is_ready - @call.start_write_status(code, details, self) - ev = @cq.pluck(self, INFINITE_FUTURE) - begin - assert_event_type(ev, FINISH_ACCEPTED) - ensure - ev.close - end - logger.debug("Status sent: #{code}:'#{details}'") - if assert_finished - return finished - end - nil - end - - # remote_read reads a response from the remote endpoint. - # - # It blocks until the remote endpoint sends a READ or FINISHED event. On - # a READ, it returns the response after unmarshalling it. On - # FINISHED, it returns nil if the status is OK, otherwise raising BadStatus - def remote_read - if @call.metadata.nil? && !@read_metadata_tag.nil? - ev = @cq.pluck(@read_metadata_tag, INFINITE_FUTURE) - assert_event_type(ev, CLIENT_METADATA_READ) - @call.metadata = ev.result - @read_metadata_tag = nil - end + # remote_read reads a response from the remote endpoint. + # + # It blocks until the remote endpoint sends a READ or FINISHED event. On + # a READ, it returns the response after unmarshalling it. On + # FINISHED, it returns nil if the status is OK, otherwise raising + # BadStatus + def remote_read + if @call.metadata.nil? && !@read_metadata_tag.nil? + ev = @cq.pluck(@read_metadata_tag, INFINITE_FUTURE) + assert_event_type(ev, CLIENT_METADATA_READ) + @call.metadata = ev.result + @read_metadata_tag = nil + end - @call.start_read(self) - ev = @cq.pluck(self, INFINITE_FUTURE) - begin - assert_event_type(ev, READ) - logger.debug("received req: #{ev.result.inspect}") - if !ev.result.nil? - logger.debug("received req.to_s: #{ev.result.to_s}") - res = @unmarshal.call(ev.result.to_s) - logger.debug("received_req (unmarshalled): #{res.inspect}") - return res + @call.start_read(self) + ev = @cq.pluck(self, INFINITE_FUTURE) + begin + assert_event_type(ev, READ) + logger.debug("received req: #{ev.result.inspect}") + unless ev.result.nil? + logger.debug("received req.to_s: #{ev.result}") + res = @unmarshal.call(ev.result.to_s) + logger.debug("received_req (unmarshalled): #{res.inspect}") + return res + end + ensure + ev.close end - ensure - ev.close + logger.debug('found nil; the final response has been sent') + nil end - logger.debug('found nil; the final response has been sent') - nil - end - # each_remote_read passes each response to the given block or returns an - # enumerator the responses if no block is given. - # - # == Enumerator == - # - # * #next blocks until the remote endpoint sends a READ or FINISHED - # * for each read, enumerator#next yields the response - # * on status - # * if it's is OK, enumerator#next raises StopException - # * if is not OK, enumerator#next raises RuntimeException - # - # == Block == - # - # * if provided it is executed for each response - # * the call blocks until no more responses are provided - # - # @return [Enumerator] if no block was given - def each_remote_read - return enum_for(:each_remote_read) if !block_given? - loop do - resp = remote_read() - break if resp.is_a?Struct::Status # is an OK status, bad statii raise - break if resp.nil? # the last response was received - yield resp + # each_remote_read passes each response to the given block or returns an + # enumerator the responses if no block is given. + # + # == Enumerator == + # + # * #next blocks until the remote endpoint sends a READ or FINISHED + # * for each read, enumerator#next yields the response + # * on status + # * if it's is OK, enumerator#next raises StopException + # * if is not OK, enumerator#next raises RuntimeException + # + # == Block == + # + # * if provided it is executed for each response + # * the call blocks until no more responses are provided + # + # @return [Enumerator] if no block was given + def each_remote_read + return enum_for(:each_remote_read) unless block_given? + loop do + resp = remote_read + break if resp.is_a? Struct::Status # is an OK status + break if resp.nil? # the last response was received + yield resp + end end - end - # each_remote_read_then_finish passes each response to the given block or - # returns an enumerator of the responses if no block is given. - # - # It is like each_remote_read, but it blocks on finishing on detecting - # the final message. - # - # == Enumerator == - # - # * #next blocks until the remote endpoint sends a READ or FINISHED - # * for each read, enumerator#next yields the response - # * on status - # * if it's is OK, enumerator#next raises StopException - # * if is not OK, enumerator#next raises RuntimeException - # - # == Block == - # - # * if provided it is executed for each response - # * the call blocks until no more responses are provided - # - # @return [Enumerator] if no block was given - def each_remote_read_then_finish - return enum_for(:each_remote_read_then_finish) if !block_given? - loop do - resp = remote_read - break if resp.is_a?Struct::Status # is an OK status, bad statii raise - if resp.nil? # the last response was received, but not finished yet - finished - break + # each_remote_read_then_finish passes each response to the given block or + # returns an enumerator of the responses if no block is given. + # + # It is like each_remote_read, but it blocks on finishing on detecting + # the final message. + # + # == Enumerator == + # + # * #next blocks until the remote endpoint sends a READ or FINISHED + # * for each read, enumerator#next yields the response + # * on status + # * if it's is OK, enumerator#next raises StopException + # * if is not OK, enumerator#next raises RuntimeException + # + # == Block == + # + # * if provided it is executed for each response + # * the call blocks until no more responses are provided + # + # @return [Enumerator] if no block was given + def each_remote_read_then_finish + return enum_for(:each_remote_read_then_finish) unless block_given? + loop do + resp = remote_read + break if resp.is_a? Struct::Status # is an OK status + if resp.nil? # the last response was received, but not finished yet + finished + break + end + yield resp end - yield resp end - end - # request_response sends a request to a GRPC server, and returns the - # response. - # - # == Keyword Arguments == - # any keyword arguments are treated as metadata to be sent to the server - # if a keyword value is a list, multiple metadata for it's key are sent - # - # @param req [Object] the request sent to the server - # @return [Object] the response received from the server - def request_response(req, **kw) - start_call(**kw) unless @started - remote_send(req) - writes_done(false) - response = remote_read - if !response.is_a?(Struct::Status) # finish if status not yet received - finished + # request_response sends a request to a GRPC server, and returns the + # response. + # + # == Keyword Arguments == + # any keyword arguments are treated as metadata to be sent to the server + # if a keyword value is a list, multiple metadata for it's key are sent + # + # @param req [Object] the request sent to the server + # @return [Object] the response received from the server + def request_response(req, **kw) + start_call(**kw) unless @started + remote_send(req) + writes_done(false) + response = remote_read + finished unless response.is_a? Struct::Status + response end - response - end - # client_streamer sends a stream of requests to a GRPC server, and - # returns a single response. - # - # requests provides an 'iterable' of Requests. I.e. it follows Ruby's - # #each enumeration protocol. In the simplest case, requests will be an - # array of marshallable objects; in typical case it will be an Enumerable - # that allows dynamic construction of the marshallable objects. - # - # == Keyword Arguments == - # any keyword arguments are treated as metadata to be sent to the server - # if a keyword value is a list, multiple metadata for it's key are sent - # - # @param requests [Object] an Enumerable of requests to send - # @return [Object] the response received from the server - def client_streamer(requests, **kw) - start_call(**kw) unless @started - requests.each { |r| remote_send(r) } - writes_done(false) - response = remote_read - if !response.is_a?(Struct::Status) # finish if status not yet received - finished + # client_streamer sends a stream of requests to a GRPC server, and + # returns a single response. + # + # requests provides an 'iterable' of Requests. I.e. it follows Ruby's + # #each enumeration protocol. In the simplest case, requests will be an + # array of marshallable objects; in typical case it will be an Enumerable + # that allows dynamic construction of the marshallable objects. + # + # == Keyword Arguments == + # any keyword arguments are treated as metadata to be sent to the server + # if a keyword value is a list, multiple metadata for it's key are sent + # + # @param requests [Object] an Enumerable of requests to send + # @return [Object] the response received from the server + def client_streamer(requests, **kw) + start_call(**kw) unless @started + requests.each { |r| remote_send(r) } + writes_done(false) + response = remote_read + finished unless response.is_a? Struct::Status + response end - response - end - # server_streamer sends one request to the GRPC server, which yields a - # stream of responses. - # - # responses provides an enumerator over the streamed responses, i.e. it - # follows Ruby's #each iteration protocol. The enumerator blocks while - # waiting for each response, stops when the server signals that no - # further responses will be supplied. If the implicit block is provided, - # it is executed with each response as the argument and no result is - # returned. - # - # == Keyword Arguments == - # any keyword arguments are treated as metadata to be sent to the server - # if a keyword value is a list, multiple metadata for it's key are sent - # any keyword arguments are treated as metadata to be sent to the server. - # - # @param req [Object] the request sent to the server - # @return [Enumerator|nil] a response Enumerator - def server_streamer(req, **kw) - start_call(**kw) unless @started - remote_send(req) - writes_done(false) - replies = enum_for(:each_remote_read_then_finish) - return replies if !block_given? - replies.each { |r| yield r } - end + # server_streamer sends one request to the GRPC server, which yields a + # stream of responses. + # + # responses provides an enumerator over the streamed responses, i.e. it + # follows Ruby's #each iteration protocol. The enumerator blocks while + # waiting for each response, stops when the server signals that no + # further responses will be supplied. If the implicit block is provided, + # it is executed with each response as the argument and no result is + # returned. + # + # == Keyword Arguments == + # any keyword arguments are treated as metadata to be sent to the server + # if a keyword value is a list, multiple metadata for it's key are sent + # any keyword arguments are treated as metadata to be sent to the server. + # + # @param req [Object] the request sent to the server + # @return [Enumerator|nil] a response Enumerator + def server_streamer(req, **kw) + start_call(**kw) unless @started + remote_send(req) + writes_done(false) + replies = enum_for(:each_remote_read_then_finish) + return replies unless block_given? + replies.each { |r| yield r } + end - # bidi_streamer sends a stream of requests to the GRPC server, and yields - # a stream of responses. - # - # This method takes an Enumerable of requests, and returns and enumerable - # of responses. - # - # == requests == - # - # requests provides an 'iterable' of Requests. I.e. it follows Ruby's #each - # enumeration protocol. In the simplest case, requests will be an array of - # marshallable objects; in typical case it will be an Enumerable that - # allows dynamic construction of the marshallable objects. - # - # == responses == - # - # This is an enumerator of responses. I.e, its #next method blocks - # waiting for the next response. Also, if at any point the block needs - # to consume all the remaining responses, this can be done using #each or - # #collect. Calling #each or #collect should only be done if - # the_call#writes_done has been called, otherwise the block will loop - # forever. - # - # == Keyword Arguments == - # any keyword arguments are treated as metadata to be sent to the server - # if a keyword value is a list, multiple metadata for it's key are sent - # - # @param requests [Object] an Enumerable of requests to send - # @return [Enumerator, nil] a response Enumerator - def bidi_streamer(requests, **kw, &blk) - start_call(**kw) unless @started - bd = BidiCall.new(@call, @cq, @marshal, @unmarshal, @deadline, - @finished_tag) - bd.run_on_client(requests, &blk) - end + # bidi_streamer sends a stream of requests to the GRPC server, and yields + # a stream of responses. + # + # This method takes an Enumerable of requests, and returns and enumerable + # of responses. + # + # == requests == + # + # requests provides an 'iterable' of Requests. I.e. it follows Ruby's + # #each enumeration protocol. In the simplest case, requests will be an + # array of marshallable objects; in typical case it will be an + # Enumerable that allows dynamic construction of the marshallable + # objects. + # + # == responses == + # + # This is an enumerator of responses. I.e, its #next method blocks + # waiting for the next response. Also, if at any point the block needs + # to consume all the remaining responses, this can be done using #each or + # #collect. Calling #each or #collect should only be done if + # the_call#writes_done has been called, otherwise the block will loop + # forever. + # + # == Keyword Arguments == + # any keyword arguments are treated as metadata to be sent to the server + # if a keyword value is a list, multiple metadata for it's key are sent + # + # @param requests [Object] an Enumerable of requests to send + # @return [Enumerator, nil] a response Enumerator + def bidi_streamer(requests, **kw, &blk) + start_call(**kw) unless @started + bd = BidiCall.new(@call, @cq, @marshal, @unmarshal, @deadline, + @finished_tag) + bd.run_on_client(requests, &blk) + end - # run_server_bidi orchestrates a BiDi stream processing on a server. - # - # N.B. gen_each_reply is a func(Enumerable) - # - # It takes an enumerable of requests as an arg, in case there is a - # relationship between the stream of requests and the stream of replies. - # - # This does not mean that must necessarily be one. E.g, the replies - # produced by gen_each_reply could ignore the received_msgs - # - # @param gen_each_reply [Proc] generates the BiDi stream replies - def run_server_bidi(gen_each_reply) - bd = BidiCall.new(@call, @cq, @marshal, @unmarshal, @deadline, - @finished_tag) - bd.run_on_server(gen_each_reply) - end + # run_server_bidi orchestrates a BiDi stream processing on a server. + # + # N.B. gen_each_reply is a func(Enumerable) + # + # It takes an enumerable of requests as an arg, in case there is a + # relationship between the stream of requests and the stream of replies. + # + # This does not mean that must necessarily be one. E.g, the replies + # produced by gen_each_reply could ignore the received_msgs + # + # @param gen_each_reply [Proc] generates the BiDi stream replies + def run_server_bidi(gen_each_reply) + bd = BidiCall.new(@call, @cq, @marshal, @unmarshal, @deadline, + @finished_tag) + bd.run_on_server(gen_each_reply) + end - private + private - def start_call(**kw) - tags = ActiveCall.client_start_invoke(@call, @cq, @deadline, **kw) - @finished_tag, @read_metadata_tag = tags - @started = true - end + def start_call(**kw) + tags = ActiveCall.client_start_invoke(@call, @cq, @deadline, **kw) + @finished_tag, @read_metadata_tag = tags + @started = true + end - def self.view_class(*visible_methods) - Class.new do - extend ::Forwardable - def_delegators :@wrapped, *visible_methods + def self.view_class(*visible_methods) + Class.new do + extend ::Forwardable + def_delegators :@wrapped, *visible_methods - # @param wrapped [ActiveCall] the call whose methods are shielded - def initialize(wrapped) - @wrapped = wrapped + # @param wrapped [ActiveCall] the call whose methods are shielded + def initialize(wrapped) + @wrapped = wrapped + end end end - end - # SingleReqView limits access to an ActiveCall's methods for use in server - # handlers that receive just one request. - SingleReqView = view_class(:cancelled, :deadline) - - # MultiReqView limits access to an ActiveCall's methods for use in - # server client_streamer handlers. - MultiReqView = view_class(:cancelled, :deadline, :each_queued_msg, - :each_remote_read) - - # Operation limits access to an ActiveCall's methods for use as - # a Operation on the client. - Operation = view_class(:cancel, :cancelled, :deadline, :execute, :metadata, - :status) - - # confirms that no events are enqueued, and that the queue is not - # shutdown. - def assert_queue_is_ready - ev = nil - begin - ev = @cq.pluck(self, ZERO) - raise "unexpected event #{ev.inspect}" unless ev.nil? - rescue OutOfTime - # expected, nothing should be on the queue and the deadline was ZERO, - # except things using another tag - ensure - ev.close unless ev.nil? + # SingleReqView limits access to an ActiveCall's methods for use in server + # handlers that receive just one request. + SingleReqView = view_class(:cancelled, :deadline) + + # MultiReqView limits access to an ActiveCall's methods for use in + # server client_streamer handlers. + MultiReqView = view_class(:cancelled, :deadline, :each_queued_msg, + :each_remote_read) + + # Operation limits access to an ActiveCall's methods for use as + # a Operation on the client. + Operation = view_class(:cancel, :cancelled, :deadline, :execute, + :metadata, :status) + + # confirms that no events are enqueued, and that the queue is not + # shutdown. + def assert_queue_is_ready + ev = nil + begin + ev = @cq.pluck(self, ZERO) + fail "unexpected event #{ev.inspect}" unless ev.nil? + rescue OutOfTime + logging.debug('timed out waiting for next event') + # expected, nothing should be on the queue and the deadline was ZERO, + # except things using another tag + ensure + ev.close unless ev.nil? + end end end - end - end diff --git a/src/ruby/lib/grpc/generic/bidi_call.rb b/src/ruby/lib/grpc/generic/bidi_call.rb index 066ec851ac..14ef6c531f 100644 --- a/src/ruby/lib/grpc/generic/bidi_call.rb +++ b/src/ruby/lib/grpc/generic/bidi_call.rb @@ -31,194 +31,195 @@ require 'forwardable' require 'grpc/grpc' def assert_event_type(ev, want) - raise OutOfTime if ev.nil? + fail OutOfTime if ev.nil? got = ev.type - raise 'Unexpected rpc event: got %s, want %s' % [got, want] unless got == want + fail("Unexpected rpc event: got #{got}, want #{want}") unless got == want end -module Google::RPC - - # The BiDiCall class orchestrates exection of a BiDi stream on a client or - # server. - class BidiCall - include Core::CompletionType - include Core::StatusCodes - include Core::TimeConsts - - # Creates a BidiCall. - # - # BidiCall should only be created after a call is accepted. That means - # different things on a client and a server. On the client, the call is - # accepted after call.start_invoke followed by receipt of the corresponding - # INVOKE_ACCEPTED. On the server, this is after call.accept. - # - # #initialize cannot determine if the call is accepted or not; so if a - # call that's not accepted is used here, the error won't be visible until - # the BidiCall#run is called. - # - # deadline is the absolute deadline for the call. - # - # @param call [Call] the call used by the ActiveCall - # @param q [CompletionQueue] the completion queue used to accept - # the call - # @param marshal [Function] f(obj)->string that marshal requests - # @param unmarshal [Function] f(string)->obj that unmarshals responses - # @param deadline [Fixnum] the deadline for the call to complete - # @param finished_tag [Object] the object used as the call's finish tag, - def initialize(call, q, marshal, unmarshal, deadline, finished_tag) - raise ArgumentError.new('not a call') unless call.is_a?Core::Call - if !q.is_a?Core::CompletionQueue - raise ArgumentError.new('not a CompletionQueue') +module Google + # Google::RPC contains the General RPC module. + module RPC + # The BiDiCall class orchestrates exection of a BiDi stream on a client or + # server. + class BidiCall + include Core::CompletionType + include Core::StatusCodes + include Core::TimeConsts + + # Creates a BidiCall. + # + # BidiCall should only be created after a call is accepted. That means + # different things on a client and a server. On the client, the call is + # accepted after call.start_invoke followed by receipt of the + # corresponding INVOKE_ACCEPTED. On the server, this is after + # call.accept. + # + # #initialize cannot determine if the call is accepted or not; so if a + # call that's not accepted is used here, the error won't be visible until + # the BidiCall#run is called. + # + # deadline is the absolute deadline for the call. + # + # @param call [Call] the call used by the ActiveCall + # @param q [CompletionQueue] the completion queue used to accept + # the call + # @param marshal [Function] f(obj)->string that marshal requests + # @param unmarshal [Function] f(string)->obj that unmarshals responses + # @param deadline [Fixnum] the deadline for the call to complete + # @param finished_tag [Object] the object used as the call's finish tag, + def initialize(call, q, marshal, unmarshal, deadline, finished_tag) + fail(ArgumentError, 'not a call') unless call.is_a? Core::Call + unless q.is_a? Core::CompletionQueue + fail(ArgumentError, 'not a CompletionQueue') + end + @call = call + @cq = q + @deadline = deadline + @finished_tag = finished_tag + @marshal = marshal + @readq = Queue.new + @unmarshal = unmarshal end - @call = call - @cq = q - @deadline = deadline - @finished_tag = finished_tag - @marshal = marshal - @readq = Queue.new - @unmarshal = unmarshal - end - # Begins orchestration of the Bidi stream for a client sending requests. - # - # The method either returns an Enumerator of the responses, or accepts a - # block that can be invoked with each response. - # - # @param requests the Enumerable of requests to send - # @return an Enumerator of requests to yield - def run_on_client(requests, &blk) - enq_th = start_write_loop(requests) - loop_th = start_read_loop - replies = each_queued_msg - return replies if blk.nil? - replies.each { |r| blk.call(r) } - enq_th.join - loop_th.join - end - - # Begins orchestration of the Bidi stream for a server generating replies. - # - # N.B. gen_each_reply is a func(Enumerable) - # - # It takes an enumerable of requests as an arg, in case there is a - # relationship between the stream of requests and the stream of replies. - # - # This does not mean that must necessarily be one. E.g, the replies - # produced by gen_each_reply could ignore the received_msgs - # - # @param gen_each_reply [Proc] generates the BiDi stream replies. - def run_on_server(gen_each_reply) - replys = gen_each_reply.call(each_queued_msg) - enq_th = start_write_loop(replys, is_client:false) - loop_th = start_read_loop() - loop_th.join - enq_th.join - end - - private + # Begins orchestration of the Bidi stream for a client sending requests. + # + # The method either returns an Enumerator of the responses, or accepts a + # block that can be invoked with each response. + # + # @param requests the Enumerable of requests to send + # @return an Enumerator of requests to yield + def run_on_client(requests, &blk) + enq_th = start_write_loop(requests) + loop_th = start_read_loop + replies = each_queued_msg + return replies if blk.nil? + replies.each { |r| blk.call(r) } + enq_th.join + loop_th.join + end - END_OF_READS = :end_of_reads - END_OF_WRITES = :end_of_writes + # Begins orchestration of the Bidi stream for a server generating replies. + # + # N.B. gen_each_reply is a func(Enumerable) + # + # It takes an enumerable of requests as an arg, in case there is a + # relationship between the stream of requests and the stream of replies. + # + # This does not mean that must necessarily be one. E.g, the replies + # produced by gen_each_reply could ignore the received_msgs + # + # @param gen_each_reply [Proc] generates the BiDi stream replies. + def run_on_server(gen_each_reply) + replys = gen_each_reply.call(each_queued_msg) + enq_th = start_write_loop(replys, is_client: false) + loop_th = start_read_loop + loop_th.join + enq_th.join + end - # each_queued_msg yields each message on this instances readq - # - # - messages are added to the readq by #read_loop - # - iteration ends when the instance itself is added - def each_queued_msg - return enum_for(:each_queued_msg) if !block_given? - count = 0 - loop do - logger.debug("each_queued_msg: msg##{count}") - count += 1 - req = @readq.pop - throw req if req.is_a?StandardError - break if req.equal?(END_OF_READS) - yield req + private + + END_OF_READS = :end_of_reads + END_OF_WRITES = :end_of_writes + + # each_queued_msg yields each message on this instances readq + # + # - messages are added to the readq by #read_loop + # - iteration ends when the instance itself is added + def each_queued_msg + return enum_for(:each_queued_msg) unless block_given? + count = 0 + loop do + logger.debug("each_queued_msg: msg##{count}") + count += 1 + req = @readq.pop + throw req if req.is_a? StandardError + break if req.equal?(END_OF_READS) + yield req + end end - end - # during bidi-streaming, read the requests to send from a separate thread - # read so that read_loop does not block waiting for requests to read. - def start_write_loop(requests, is_client: true) - Thread.new do # TODO(temiola) run on a thread pool - write_tag = Object.new - begin - count = 0 - requests.each do |req| - count += 1 - payload = @marshal.call(req) - @call.start_write(Core::ByteBuffer.new(payload), write_tag) - ev = @cq.pluck(write_tag, INFINITE_FUTURE) - begin - assert_event_type(ev, WRITE_ACCEPTED) - ensure - ev.close - end - end - if is_client - @call.writes_done(write_tag) - ev = @cq.pluck(write_tag, INFINITE_FUTURE) - begin - assert_event_type(ev, FINISH_ACCEPTED) - ensure - ev.close + # during bidi-streaming, read the requests to send from a separate thread + # read so that read_loop does not block waiting for requests to read. + def start_write_loop(requests, is_client: true) + Thread.new do # TODO(temiola) run on a thread pool + write_tag = Object.new + begin + count = 0 + requests.each do |req| + count += 1 + payload = @marshal.call(req) + @call.start_write(Core::ByteBuffer.new(payload), write_tag) + ev = @cq.pluck(write_tag, INFINITE_FUTURE) + begin + assert_event_type(ev, WRITE_ACCEPTED) + ensure + ev.close + end end - logger.debug("bidi-client: sent #{count} reqs, waiting to finish") - ev = @cq.pluck(@finished_tag, INFINITE_FUTURE) - begin - assert_event_type(ev, FINISHED) - ensure - ev.close + if is_client + @call.writes_done(write_tag) + ev = @cq.pluck(write_tag, INFINITE_FUTURE) + begin + assert_event_type(ev, FINISH_ACCEPTED) + ensure + ev.close + end + logger.debug("bidi-client: sent #{count} reqs, waiting to finish") + ev = @cq.pluck(@finished_tag, INFINITE_FUTURE) + begin + assert_event_type(ev, FINISHED) + ensure + ev.close + end + logger.debug('bidi-client: finished received') end - logger.debug('bidi-client: finished received') + rescue StandardError => e + logger.warn('bidi: write_loop failed') + logger.warn(e) end - rescue StandardError => e - logger.warn('bidi: write_loop failed') - logger.warn(e) end end - end - - # starts the read loop - def start_read_loop() - t = Thread.new do - begin - read_tag = Object.new - count = 0 - # queue the initial read before beginning the loop - loop do - logger.debug("waiting for read #{count}") - count += 1 - @call.start_read(read_tag) - ev = @cq.pluck(read_tag, INFINITE_FUTURE) - begin - assert_event_type(ev, READ) - - # handle the next event. - if ev.result.nil? - @readq.push(END_OF_READS) - logger.debug('done reading!') - break + # starts the read loop + def start_read_loop + Thread.new do + begin + read_tag = Object.new + count = 0 + + # queue the initial read before beginning the loop + loop do + logger.debug("waiting for read #{count}") + count += 1 + @call.start_read(read_tag) + ev = @cq.pluck(read_tag, INFINITE_FUTURE) + begin + assert_event_type(ev, READ) + + # handle the next event. + if ev.result.nil? + @readq.push(END_OF_READS) + logger.debug('done reading!') + break + end + + # push the latest read onto the queue and continue reading + logger.debug("received req: #{ev.result}") + res = @unmarshal.call(ev.result.to_s) + @readq.push(res) + ensure + ev.close end - - # push the latest read onto the queue and continue reading - logger.debug("received req.to_s: #{ev.result.to_s}") - res = @unmarshal.call(ev.result.to_s) - @readq.push(res) - ensure - ev.close end - end - rescue StandardError => e - logger.warn('bidi: read_loop failed') - logger.warn(e) - @readq.push(e) # let each_queued_msg terminate with this error + rescue StandardError => e + logger.warn('bidi: read_loop failed') + logger.warn(e) + @readq.push(e) # let each_queued_msg terminate with this error + end end end end - end - end diff --git a/src/ruby/lib/grpc/generic/client_stub.rb b/src/ruby/lib/grpc/generic/client_stub.rb index 62628cb1f0..7e13de19ca 100644 --- a/src/ruby/lib/grpc/generic/client_stub.rb +++ b/src/ruby/lib/grpc/generic/client_stub.rb @@ -30,377 +30,381 @@ require 'grpc/generic/active_call' require 'xray/thread_dump_signal_handler' -module Google::RPC +module Google + # Google::RPC contains the General RPC module. + module RPC + # ClientStub represents an endpoint used to send requests to GRPC servers. + class ClientStub + include Core::StatusCodes - # ClientStub represents an endpoint used to send requests to GRPC servers. - class ClientStub - include Core::StatusCodes + # Default deadline is 5 seconds. + DEFAULT_DEADLINE = 5 - # Default deadline is 5 seconds. - DEFAULT_DEADLINE = 5 - - # Creates a new ClientStub. - # - # Minimally, a stub is created with the just the host of the gRPC service - # it wishes to access, e.g., - # - # my_stub = ClientStub.new(example.host.com:50505) - # - # Any arbitrary keyword arguments are treated as channel arguments used to - # configure the RPC connection to the host. - # - # There are some specific keyword args that are not used to configure the - # channel: - # - # - :channel_override - # when present, this must be a pre-created GRPC::Channel. If it's present - # the host and arbitrary keyword arg areignored, and the RPC connection uses - # this channel. - # - # - :deadline - # when present, this is the default deadline used for calls - # - # - :update_metadata - # when present, this a func that takes a hash and returns a hash - # it can be used to update metadata, i.e, remove, change or update - # amend metadata values. - # - # @param host [String] the host the stub connects to - # @param q [Core::CompletionQueue] used to wait for events - # @param channel_override [Core::Channel] a pre-created channel - # @param deadline [Number] the default deadline to use in requests - # @param creds [Core::Credentials] secures and/or authenticates the channel - # @param update_metadata a func that updates metadata as described above - # @param kw [KeywordArgs]the channel arguments - def initialize(host, q, - channel_override:nil, - deadline: DEFAULT_DEADLINE, - creds: nil, - update_metadata: nil, - **kw) - if !q.is_a?Core::CompletionQueue - raise ArgumentError.new('not a CompletionQueue') - end - @queue = q + # Creates a new ClientStub. + # + # Minimally, a stub is created with the just the host of the gRPC service + # it wishes to access, e.g., + # + # my_stub = ClientStub.new(example.host.com:50505) + # + # Any arbitrary keyword arguments are treated as channel arguments used to + # configure the RPC connection to the host. + # + # There are some specific keyword args that are not used to configure the + # channel: + # + # - :channel_override + # when present, this must be a pre-created GRPC::Channel. If it's + # present the host and arbitrary keyword arg areignored, and the RPC + # connection uses this channel. + # + # - :deadline + # when present, this is the default deadline used for calls + # + # - :update_metadata + # when present, this a func that takes a hash and returns a hash + # it can be used to update metadata, i.e, remove, change or update + # amend metadata values. + # + # @param host [String] the host the stub connects to + # @param q [Core::CompletionQueue] used to wait for events + # @param channel_override [Core::Channel] a pre-created channel + # @param deadline [Number] the default deadline to use in requests + # @param creds [Core::Credentials] the channel + # @param update_metadata a func that updates metadata as described above + # @param kw [KeywordArgs]the channel arguments + def initialize(host, q, + channel_override:nil, + deadline: DEFAULT_DEADLINE, + creds: nil, + update_metadata: nil, + **kw) + unless q.is_a? Core::CompletionQueue + fail(ArgumentError, 'not a CompletionQueue') + end + @queue = q - # set the channel instance - if !channel_override.nil? - ch = channel_override - raise ArgumentError.new('not a Channel') unless ch.is_a?(Core::Channel) - elsif creds.nil? - ch = Core::Channel.new(host, kw) - elsif !creds.is_a?(Core::Credentials) - raise ArgumentError.new('not a Credentials') - else - ch = Core::Channel.new(host, kw, creds) - end - @ch = ch + # set the channel instance + if !channel_override.nil? + ch = channel_override + fail(ArgumentError, 'not a Channel') unless ch.is_a? Core::Channel + else + if creds.nil? + ch = Core::Channel.new(host, kw) + elsif !creds.is_a?(Core::Credentials) + fail(ArgumentError, 'not a Credentials') + else + ch = Core::Channel.new(host, kw, creds) + end + end + @ch = ch - @update_metadata = nil - if !update_metadata.nil? - if !update_metadata.is_a?(Proc) - raise ArgumentError.new('update_metadata is not a Proc') + @update_metadata = nil + unless update_metadata.nil? + unless update_metadata.is_a? Proc + fail(ArgumentError, 'update_metadata is not a Proc') + end + @update_metadata = update_metadata end - @update_metadata = update_metadata + + @host = host + @deadline = deadline end + # request_response sends a request to a GRPC server, and returns the + # response. + # + # == Flow Control == + # This is a blocking call. + # + # * it does not return until a response is received. + # + # * the requests is sent only when GRPC core's flow control allows it to + # be sent. + # + # == Errors == + # An RuntimeError is raised if + # + # * the server responds with a non-OK status + # + # * the deadline is exceeded + # + # == Return Value == + # + # If return_op is false, the call returns the response + # + # If return_op is true, the call returns an Operation, calling execute + # on the Operation returns the response. + # + # == Keyword Args == + # + # Unspecified keyword arguments are treated as metadata to be sent to the + # server. + # + # @param method [String] the RPC method to call on the GRPC server + # @param req [Object] the request sent to the server + # @param marshal [Function] f(obj)->string that marshals requests + # @param unmarshal [Function] f(string)->obj that unmarshals responses + # @param deadline [Numeric] (optional) the max completion time in seconds + # @param return_op [true|false] return an Operation if true + # @return [Object] the response received from the server + def request_response(method, req, marshal, unmarshal, deadline = nil, + return_op: false, **kw) + c = new_active_call(method, marshal, unmarshal, deadline || @deadline) + md = @update_metadata.nil? ? kw : @update_metadata.call(kw.clone) + return c.request_response(req, **md) unless return_op - @host = host - @deadline = deadline - end + # return the operation view of the active_call; define #execute as a + # new method for this instance that invokes #request_response. + op = c.operation + op.define_singleton_method(:execute) do + c.request_response(req, **md) + end + op + end - # request_response sends a request to a GRPC server, and returns the - # response. - # - # == Flow Control == - # This is a blocking call. - # - # * it does not return until a response is received. - # - # * the requests is sent only when GRPC core's flow control allows it to - # be sent. - # - # == Errors == - # An RuntimeError is raised if - # - # * the server responds with a non-OK status - # - # * the deadline is exceeded - # - # == Return Value == - # - # If return_op is false, the call returns the response - # - # If return_op is true, the call returns an Operation, calling execute - # on the Operation returns the response. - # - # == Keyword Args == - # - # Unspecified keyword arguments are treated as metadata to be sent to the - # server. - # - # @param method [String] the RPC method to call on the GRPC server - # @param req [Object] the request sent to the server - # @param marshal [Function] f(obj)->string that marshals requests - # @param unmarshal [Function] f(string)->obj that unmarshals responses - # @param deadline [Numeric] (optional) the max completion time in seconds - # @param return_op [true|false] (default false) return an Operation if true - # @return [Object] the response received from the server - def request_response(method, req, marshal, unmarshal, deadline=nil, - return_op:false, **kw) - c = new_active_call(method, marshal, unmarshal, deadline || @deadline) - md = @update_metadata.nil? ? kw : @update_metadata.call(kw.clone) - return c.request_response(req, **md) unless return_op + # client_streamer sends a stream of requests to a GRPC server, and + # returns a single response. + # + # requests provides an 'iterable' of Requests. I.e. it follows Ruby's + # #each enumeration protocol. In the simplest case, requests will be an + # array of marshallable objects; in typical case it will be an Enumerable + # that allows dynamic construction of the marshallable objects. + # + # == Flow Control == + # This is a blocking call. + # + # * it does not return until a response is received. + # + # * each requests is sent only when GRPC core's flow control allows it to + # be sent. + # + # == Errors == + # An RuntimeError is raised if + # + # * the server responds with a non-OK status + # + # * the deadline is exceeded + # + # == Return Value == + # + # If return_op is false, the call consumes the requests and returns + # the response. + # + # If return_op is true, the call returns the response. + # + # == Keyword Args == + # + # Unspecified keyword arguments are treated as metadata to be sent to the + # server. + # + # @param method [String] the RPC method to call on the GRPC server + # @param requests [Object] an Enumerable of requests to send + # @param marshal [Function] f(obj)->string that marshals requests + # @param unmarshal [Function] f(string)->obj that unmarshals responses + # @param deadline [Numeric] the max completion time in seconds + # @param return_op [true|false] return an Operation if true + # @return [Object|Operation] the response received from the server + def client_streamer(method, requests, marshal, unmarshal, deadline = nil, + return_op: false, **kw) + c = new_active_call(method, marshal, unmarshal, deadline || @deadline) + md = @update_metadata.nil? ? kw : @update_metadata.call(kw.clone) + return c.client_streamer(requests, **md) unless return_op - # return the operation view of the active_call; define #execute as a - # new method for this instance that invokes #request_response. - op = c.operation - op.define_singleton_method(:execute) do - c.request_response(req, **md) + # return the operation view of the active_call; define #execute as a + # new method for this instance that invokes #client_streamer. + op = c.operation + op.define_singleton_method(:execute) do + c.client_streamer(requests, **md) + end + op end - op - end - # client_streamer sends a stream of requests to a GRPC server, and - # returns a single response. - # - # requests provides an 'iterable' of Requests. I.e. it follows Ruby's - # #each enumeration protocol. In the simplest case, requests will be an - # array of marshallable objects; in typical case it will be an Enumerable - # that allows dynamic construction of the marshallable objects. - # - # == Flow Control == - # This is a blocking call. - # - # * it does not return until a response is received. - # - # * each requests is sent only when GRPC core's flow control allows it to - # be sent. - # - # == Errors == - # An RuntimeError is raised if - # - # * the server responds with a non-OK status - # - # * the deadline is exceeded - # - # == Return Value == - # - # If return_op is false, the call consumes the requests and returns - # the response. - # - # If return_op is true, the call returns the response. - # - # == Keyword Args == - # - # Unspecified keyword arguments are treated as metadata to be sent to the - # server. - # - # @param method [String] the RPC method to call on the GRPC server - # @param requests [Object] an Enumerable of requests to send - # @param marshal [Function] f(obj)->string that marshals requests - # @param unmarshal [Function] f(string)->obj that unmarshals responses - # @param deadline [Numeric] the max completion time in seconds - # @param return_op [true|false] (default false) return an Operation if true - # @return [Object|Operation] the response received from the server - def client_streamer(method, requests, marshal, unmarshal, deadline=nil, - return_op:false, **kw) - c = new_active_call(method, marshal, unmarshal, deadline || @deadline) - md = @update_metadata.nil? ? kw : @update_metadata.call(kw.clone) - return c.client_streamer(requests, **md) unless return_op + # server_streamer sends one request to the GRPC server, which yields a + # stream of responses. + # + # responses provides an enumerator over the streamed responses, i.e. it + # follows Ruby's #each iteration protocol. The enumerator blocks while + # waiting for each response, stops when the server signals that no + # further responses will be supplied. If the implicit block is provided, + # it is executed with each response as the argument and no result is + # returned. + # + # == Flow Control == + # This is a blocking call. + # + # * the request is sent only when GRPC core's flow control allows it to + # be sent. + # + # * the request will not complete until the server sends the final + # response followed by a status message. + # + # == Errors == + # An RuntimeError is raised if + # + # * the server responds with a non-OK status when any response is + # * retrieved + # + # * the deadline is exceeded + # + # == Return Value == + # + # if the return_op is false, the return value is an Enumerator of the + # results, unless a block is provided, in which case the block is + # executed with each response. + # + # if return_op is true, the function returns an Operation whose #execute + # method runs server streamer call. Again, Operation#execute either + # calls the given block with each response or returns an Enumerator of the + # responses. + # + # == Keyword Args == + # + # Unspecified keyword arguments are treated as metadata to be sent to the + # server. + # + # @param method [String] the RPC method to call on the GRPC server + # @param req [Object] the request sent to the server + # @param marshal [Function] f(obj)->string that marshals requests + # @param unmarshal [Function] f(string)->obj that unmarshals responses + # @param deadline [Numeric] the max completion time in seconds + # @param return_op [true|false]return an Operation if true + # @param blk [Block] when provided, is executed for each response + # @return [Enumerator|Operation|nil] as discussed above + def server_streamer(method, req, marshal, unmarshal, deadline = nil, + return_op: false, **kw, &blk) + c = new_active_call(method, marshal, unmarshal, deadline || @deadline) + md = @update_metadata.nil? ? kw : @update_metadata.call(kw.clone) + return c.server_streamer(req, **md, &blk) unless return_op - # return the operation view of the active_call; define #execute as a - # new method for this instance that invokes #client_streamer. - op = c.operation - op.define_singleton_method(:execute) do - c.client_streamer(requests, **md) + # return the operation view of the active_call; define #execute + # as a new method for this instance that invokes #server_streamer + op = c.operation + op.define_singleton_method(:execute) do + c.server_streamer(req, **md, &blk) + end + op end - op - end - # server_streamer sends one request to the GRPC server, which yields a - # stream of responses. - # - # responses provides an enumerator over the streamed responses, i.e. it - # follows Ruby's #each iteration protocol. The enumerator blocks while - # waiting for each response, stops when the server signals that no - # further responses will be supplied. If the implicit block is provided, - # it is executed with each response as the argument and no result is - # returned. - # - # == Flow Control == - # This is a blocking call. - # - # * the request is sent only when GRPC core's flow control allows it to - # be sent. - # - # * the request will not complete until the server sends the final response - # followed by a status message. - # - # == Errors == - # An RuntimeError is raised if - # - # * the server responds with a non-OK status when any response is - # * retrieved - # - # * the deadline is exceeded - # - # == Return Value == - # - # if the return_op is false, the return value is an Enumerator of the - # results, unless a block is provided, in which case the block is - # executed with each response. - # - # if return_op is true, the function returns an Operation whose #execute - # method runs server streamer call. Again, Operation#execute either - # calls the given block with each response or returns an Enumerator of the - # responses. - # - # == Keyword Args == - # - # Unspecified keyword arguments are treated as metadata to be sent to the - # server. - # - # @param method [String] the RPC method to call on the GRPC server - # @param req [Object] the request sent to the server - # @param marshal [Function] f(obj)->string that marshals requests - # @param unmarshal [Function] f(string)->obj that unmarshals responses - # @param deadline [Numeric] the max completion time in seconds - # @param return_op [true|false] (default false) return an Operation if true - # @param blk [Block] when provided, is executed for each response - # @return [Enumerator|Operation|nil] as discussed above - def server_streamer(method, req, marshal, unmarshal, deadline=nil, - return_op:false, **kw, &blk) - c = new_active_call(method, marshal, unmarshal, deadline || @deadline) - md = @update_metadata.nil? ? kw : @update_metadata.call(kw.clone) - return c.server_streamer(req, **md, &blk) unless return_op + # bidi_streamer sends a stream of requests to the GRPC server, and yields + # a stream of responses. + # + # This method takes an Enumerable of requests, and returns and enumerable + # of responses. + # + # == requests == + # + # requests provides an 'iterable' of Requests. I.e. it follows Ruby's + # #each enumeration protocol. In the simplest case, requests will be an + # array of marshallable objects; in typical case it will be an + # Enumerable that allows dynamic construction of the marshallable + # objects. + # + # == responses == + # + # This is an enumerator of responses. I.e, its #next method blocks + # waiting for the next response. Also, if at any point the block needs + # to consume all the remaining responses, this can be done using #each or + # #collect. Calling #each or #collect should only be done if + # the_call#writes_done has been called, otherwise the block will loop + # forever. + # + # == Flow Control == + # This is a blocking call. + # + # * the call completes when the next call to provided block returns + # * [False] + # + # * the execution block parameters are two objects for sending and + # receiving responses, each of which blocks waiting for flow control. + # E.g, calles to bidi_call#remote_send will wait until flow control + # allows another write before returning; and obviously calls to + # responses#next block until the next response is available. + # + # == Termination == + # + # As well as sending and receiving messages, the block passed to the + # function is also responsible for: + # + # * calling bidi_call#writes_done to indicate no further reqs will be + # sent. + # + # * returning false if once the bidi stream is functionally completed. + # + # Note that response#next will indicate that there are no further + # responses by throwing StopIteration, but can only happen either + # if bidi_call#writes_done is called. + # + # To terminate the RPC correctly the block: + # + # * must call bidi#writes_done and then + # + # * either return false as soon as there is no need for other responses + # + # * loop on responses#next until no further responses are available + # + # == Errors == + # An RuntimeError is raised if + # + # * the server responds with a non-OK status when any response is + # * retrieved + # + # * the deadline is exceeded + # + # + # == Keyword Args == + # + # Unspecified keyword arguments are treated as metadata to be sent to the + # server. + # + # == Return Value == + # + # if the return_op is false, the return value is an Enumerator of the + # results, unless a block is provided, in which case the block is + # executed with each response. + # + # if return_op is true, the function returns an Operation whose #execute + # method runs the Bidi call. Again, Operation#execute either calls a + # given block with each response or returns an Enumerator of the + # responses. + # + # @param method [String] the RPC method to call on the GRPC server + # @param requests [Object] an Enumerable of requests to send + # @param marshal [Function] f(obj)->string that marshals requests + # @param unmarshal [Function] f(string)->obj that unmarshals responses + # @param deadline [Numeric] (optional) the max completion time in seconds + # @param blk [Block] when provided, is executed for each response + # @param return_op [true|false] return an Operation if true + # @return [Enumerator|nil|Operation] as discussed above + def bidi_streamer(method, requests, marshal, unmarshal, deadline = nil, + return_op: false, **kw, &blk) + c = new_active_call(method, marshal, unmarshal, deadline || @deadline) + md = @update_metadata.nil? ? kw : @update_metadata.call(kw.clone) + return c.bidi_streamer(requests, **md, &blk) unless return_op - # return the operation view of the active_call; define #execute - # as a new method for this instance that invokes #server_streamer - op = c.operation - op.define_singleton_method(:execute) do - c.server_streamer(req, **md, &blk) + # return the operation view of the active_call; define #execute + # as a new method for this instance that invokes #bidi_streamer + op = c.operation + op.define_singleton_method(:execute) do + c.bidi_streamer(requests, **md, &blk) + end + op end - op - end - # bidi_streamer sends a stream of requests to the GRPC server, and yields - # a stream of responses. - # - # This method takes an Enumerable of requests, and returns and enumerable - # of responses. - # - # == requests == - # - # requests provides an 'iterable' of Requests. I.e. it follows Ruby's #each - # enumeration protocol. In the simplest case, requests will be an array of - # marshallable objects; in typical case it will be an Enumerable that - # allows dynamic construction of the marshallable objects. - # - # == responses == - # - # This is an enumerator of responses. I.e, its #next method blocks - # waiting for the next response. Also, if at any point the block needs - # to consume all the remaining responses, this can be done using #each or - # #collect. Calling #each or #collect should only be done if - # the_call#writes_done has been called, otherwise the block will loop - # forever. - # - # == Flow Control == - # This is a blocking call. - # - # * the call completes when the next call to provided block returns - # * [False] - # - # * the execution block parameters are two objects for sending and - # receiving responses, each of which blocks waiting for flow control. - # E.g, calles to bidi_call#remote_send will wait until flow control - # allows another write before returning; and obviously calls to - # responses#next block until the next response is available. - # - # == Termination == - # - # As well as sending and receiving messages, the block passed to the - # function is also responsible for: - # - # * calling bidi_call#writes_done to indicate no further reqs will be - # sent. - # - # * returning false if once the bidi stream is functionally completed. - # - # Note that response#next will indicate that there are no further - # responses by throwing StopIteration, but can only happen either - # if bidi_call#writes_done is called. - # - # To terminate the RPC correctly the block: - # - # * must call bidi#writes_done and then - # - # * either return false as soon as there is no need for other responses - # - # * loop on responses#next until no further responses are available - # - # == Errors == - # An RuntimeError is raised if - # - # * the server responds with a non-OK status when any response is - # * retrieved - # - # * the deadline is exceeded - # - # - # == Keyword Args == - # - # Unspecified keyword arguments are treated as metadata to be sent to the - # server. - # - # == Return Value == - # - # if the return_op is false, the return value is an Enumerator of the - # results, unless a block is provided, in which case the block is - # executed with each response. - # - # if return_op is true, the function returns an Operation whose #execute - # method runs the Bidi call. Again, Operation#execute either calls a - # given block with each response or returns an Enumerator of the responses. - # - # @param method [String] the RPC method to call on the GRPC server - # @param requests [Object] an Enumerable of requests to send - # @param marshal [Function] f(obj)->string that marshals requests - # @param unmarshal [Function] f(string)->obj that unmarshals responses - # @param deadline [Numeric] (optional) the max completion time in seconds - # @param blk [Block] when provided, is executed for each response - # @param return_op [true|false] (default false) return an Operation if true - # @return [Enumerator|nil|Operation] as discussed above - def bidi_streamer(method, requests, marshal, unmarshal, deadline=nil, - return_op:false, **kw, &blk) - c = new_active_call(method, marshal, unmarshal, deadline || @deadline) - md = @update_metadata.nil? ? kw : @update_metadata.call(kw.clone) - return c.bidi_streamer(requests, **md, &blk) unless return_op + private - # return the operation view of the active_call; define #execute - # as a new method for this instance that invokes #bidi_streamer - op = c.operation - op.define_singleton_method(:execute) do - c.bidi_streamer(requests, **md, &blk) + # Creates a new active stub + # + # @param ch [GRPC::Channel] the channel used to create the stub. + # @param marshal [Function] f(obj)->string that marshals requests + # @param unmarshal [Function] f(string)->obj that unmarshals responses + # @param deadline [TimeConst] + def new_active_call(ch, marshal, unmarshal, deadline = nil) + absolute_deadline = Core::TimeConsts.from_relative_time(deadline) + call = @ch.create_call(ch, @host, absolute_deadline) + ActiveCall.new(call, @queue, marshal, unmarshal, absolute_deadline, + started: false) end - op end - - private - # Creates a new active stub - # - # @param ch [GRPC::Channel] the channel used to create the stub. - # @param marshal [Function] f(obj)->string that marshals requests - # @param unmarshal [Function] f(string)->obj that unmarshals responses - # @param deadline [TimeConst] - def new_active_call(ch, marshal, unmarshal, deadline=nil) - absolute_deadline = Core::TimeConsts.from_relative_time(deadline) - call = @ch.create_call(ch, @host, absolute_deadline) - ActiveCall.new(call, @queue, marshal, unmarshal, absolute_deadline, - started:false) - end - end - end diff --git a/src/ruby/lib/grpc/generic/rpc_desc.rb b/src/ruby/lib/grpc/generic/rpc_desc.rb index a915708f92..e1aa33e318 100644 --- a/src/ruby/lib/grpc/generic/rpc_desc.rb +++ b/src/ruby/lib/grpc/generic/rpc_desc.rb @@ -29,54 +29,51 @@ require 'grpc/grpc' -module Google::RPC - - # RpcDesc is a Descriptor of an RPC method. - class RpcDesc < Struct.new(:name, :input, :output, :marshal_method, - :unmarshal_method) - include Core::StatusCodes - - # Used to wrap a message class to indicate that it needs to be streamed. - class Stream - attr_accessor :type - - def initialize(type) - @type = type +module Google + module RPC + # RpcDesc is a Descriptor of an RPC method. + class RpcDesc < Struct.new(:name, :input, :output, :marshal_method, + :unmarshal_method) + include Core::StatusCodes + + # Used to wrap a message class to indicate that it needs to be streamed. + class Stream + attr_accessor :type + + def initialize(type) + @type = type + end end - end - # @return [Proc] { |instance| marshalled(instance) } - def marshal_proc - Proc.new { |o| o.class.method(marshal_method).call(o).to_s } - end + # @return [Proc] { |instance| marshalled(instance) } + def marshal_proc + proc { |o| o.class.method(marshal_method).call(o).to_s } + end - # @param [:input, :output] target determines whether to produce the an - # unmarshal Proc for the rpc input parameter or - # its output parameter - # - # @return [Proc] An unmarshal proc { |marshalled(instance)| instance } - def unmarshal_proc(target) - raise ArgumentError if not [:input, :output].include?(target) - unmarshal_class = method(target).call - if unmarshal_class.is_a?Stream - unmarshal_class = unmarshal_class.type + # @param [:input, :output] target determines whether to produce the an + # unmarshal Proc for the rpc input parameter or + # its output parameter + # + # @return [Proc] An unmarshal proc { |marshalled(instance)| instance } + def unmarshal_proc(target) + fail ArgumentError unless [:input, :output].include?(target) + unmarshal_class = method(target).call + unmarshal_class = unmarshal_class.type if unmarshal_class.is_a? Stream + proc { |o| unmarshal_class.method(unmarshal_method).call(o) } end - Proc.new { |o| unmarshal_class.method(unmarshal_method).call(o) } - end - def run_server_method(active_call, mth) - # While a server method is running, it might be cancelled, its deadline - # might be reached, the handler could throw an unknown error, or a - # well-behaved handler could throw a StatusError. - begin - if is_request_response? + def run_server_method(active_call, mth) + # While a server method is running, it might be cancelled, its deadline + # might be reached, the handler could throw an unknown error, or a + # well-behaved handler could throw a StatusError. + if request_response? req = active_call.remote_read resp = mth.call(req, active_call.single_req_view) active_call.remote_send(resp) - elsif is_client_streamer? + elsif client_streamer? resp = mth.call(active_call.multi_req_view) active_call.remote_send(resp) - elsif is_server_streamer? + elsif server_streamer? req = active_call.remote_read replys = mth.call(req, active_call.single_req_view) replys.each { |r| active_call.remote_send(r) } @@ -88,7 +85,7 @@ module Google::RPC rescue BadStatus => e # this is raised by handlers that want GRPC to send an application # error code and detail message. - logger.debug("app error: #{active_call}, status:#{e.code}:#{e.details}") + logger.debug("app err: #{active_call}, status:#{e.code}:#{e.details}") send_status(active_call, e.code, e.details) rescue Core::CallError => e # This is raised by GRPC internals but should rarely, if ever happen. @@ -110,50 +107,46 @@ module Google::RPC logger.warn(e) send_status(active_call, UNKNOWN, 'no reason given') end - end - def assert_arity_matches(mth) - if (is_request_response? || is_server_streamer?) - if mth.arity != 2 - raise arity_error(mth, 2, "should be #{mth.name}(req, call)") - end - else - if mth.arity != 1 - raise arity_error(mth, 1, "should be #{mth.name}(call)") + def assert_arity_matches(mth) + if request_response? || server_streamer? + if mth.arity != 2 + fail arity_error(mth, 2, "should be #{mth.name}(req, call)") + end + else + if mth.arity != 1 + fail arity_error(mth, 1, "should be #{mth.name}(call)") + end end end - end - def is_request_response? - !input.is_a?(Stream) && !output.is_a?(Stream) - end + def request_response? + !input.is_a?(Stream) && !output.is_a?(Stream) + end - def is_client_streamer? - input.is_a?(Stream) && !output.is_a?(Stream) - end + def client_streamer? + input.is_a?(Stream) && !output.is_a?(Stream) + end - def is_server_streamer? - !input.is_a?(Stream) && output.is_a?(Stream) - end + def server_streamer? + !input.is_a?(Stream) && output.is_a?(Stream) + end - def is_bidi_streamer? - input.is_a?(Stream) && output.is_a?(Stream) - end + def bidi_streamer? + input.is_a?(Stream) && output.is_a?(Stream) + end - def arity_error(mth, want, msg) - "##{mth.name}: bad arg count; got:#{mth.arity}, want:#{want}, #{msg}" - end + def arity_error(mth, want, msg) + "##{mth.name}: bad arg count; got:#{mth.arity}, want:#{want}, #{msg}" + end - def send_status(active_client, code, details) - begin + def send_status(active_client, code, details) details = 'Not sure why' if details.nil? active_client.send_status(code, details) rescue StandardError => e - logger.warn('Could not send status %d:%s' % [code, details]) + logger.warn("Could not send status #{code}:#{details}") logger.warn(e) end end - end - end diff --git a/src/ruby/lib/grpc/generic/rpc_server.rb b/src/ruby/lib/grpc/generic/rpc_server.rb index 81db68804e..5ea3cc94d6 100644 --- a/src/ruby/lib/grpc/generic/rpc_server.rb +++ b/src/ruby/lib/grpc/generic/rpc_server.rb @@ -33,382 +33,378 @@ require 'grpc/generic/service' require 'thread' require 'xray/thread_dump_signal_handler' -module Google::RPC - - # RpcServer hosts a number of services and makes them available on the - # network. - class RpcServer - include Core::CompletionType - include Core::TimeConsts - extend ::Forwardable - - def_delegators :@server, :add_http2_port - - # Default thread pool size is 3 - DEFAULT_POOL_SIZE = 3 - - # Default max_waiting_requests size is 20 - DEFAULT_MAX_WAITING_REQUESTS = 20 - - # Creates a new RpcServer. - # - # The RPC server is configured using keyword arguments. - # - # There are some specific keyword args used to configure the RpcServer - # instance, however other arbitrary are allowed and when present are used - # to configure the listeninng connection set up by the RpcServer. - # - # * server_override: which if passed must be a [GRPC::Core::Server]. When - # present. - # - # * poll_period: when present, the server polls for new events with this - # period - # - # * pool_size: the size of the thread pool the server uses to run its - # threads - # - # * completion_queue_override: when supplied, this will be used as the - # completion_queue that the server uses to receive network events, - # otherwise its creates a new instance itself - # - # * creds: [GRPC::Core::ServerCredentials] - # the credentials used to secure the server - # - # * max_waiting_requests: the maximum number of requests that are not - # being handled to allow. When this limit is exceeded, the server responds - # with not available to new requests - def initialize(pool_size:DEFAULT_POOL_SIZE, - max_waiting_requests:DEFAULT_MAX_WAITING_REQUESTS, - poll_period:INFINITE_FUTURE, - completion_queue_override:nil, - creds:nil, - server_override:nil, - **kw) - if !completion_queue_override.nil? - cq = completion_queue_override - if !cq.is_a?(Core::CompletionQueue) - raise ArgumentError.new('not a CompletionQueue') +module Google + # Google::RPC contains the General RPC module. + module RPC + # RpcServer hosts a number of services and makes them available on the + # network. + class RpcServer + include Core::CompletionType + include Core::TimeConsts + extend ::Forwardable + + def_delegators :@server, :add_http2_port + + # Default thread pool size is 3 + DEFAULT_POOL_SIZE = 3 + + # Default max_waiting_requests size is 20 + DEFAULT_MAX_WAITING_REQUESTS = 20 + + # Creates a new RpcServer. + # + # The RPC server is configured using keyword arguments. + # + # There are some specific keyword args used to configure the RpcServer + # instance, however other arbitrary are allowed and when present are used + # to configure the listeninng connection set up by the RpcServer. + # + # * server_override: which if passed must be a [GRPC::Core::Server]. When + # present. + # + # * poll_period: when present, the server polls for new events with this + # period + # + # * pool_size: the size of the thread pool the server uses to run its + # threads + # + # * completion_queue_override: when supplied, this will be used as the + # completion_queue that the server uses to receive network events, + # otherwise its creates a new instance itself + # + # * creds: [GRPC::Core::ServerCredentials] + # the credentials used to secure the server + # + # * max_waiting_requests: the maximum number of requests that are not + # being handled to allow. When this limit is exceeded, the server responds + # with not available to new requests + def initialize(pool_size:DEFAULT_POOL_SIZE, + max_waiting_requests:DEFAULT_MAX_WAITING_REQUESTS, + poll_period:INFINITE_FUTURE, + completion_queue_override:nil, + creds:nil, + server_override:nil, + **kw) + if completion_queue_override.nil? + cq = Core::CompletionQueue.new + else + cq = completion_queue_override + unless cq.is_a? Core::CompletionQueue + fail(ArgumentError, 'not a CompletionQueue') + end end - else - cq = Core::CompletionQueue.new - end - @cq = cq - - if !server_override.nil? - srv = server_override - raise ArgumentError.new('not a Server') unless srv.is_a?(Core::Server) - elsif creds.nil? - srv = Core::Server.new(@cq, kw) - elsif !creds.is_a?(Core::ServerCredentials) - raise ArgumentError.new('not a ServerCredentials') - else - srv = Core::Server.new(@cq, kw, creds) + @cq = cq + + if server_override.nil? + if creds.nil? + srv = Core::Server.new(@cq, kw) + elsif !creds.is_a? Core::ServerCredentials + fail(ArgumentError, 'not a ServerCredentials') + else + srv = Core::Server.new(@cq, kw, creds) + end + else + srv = server_override + fail(ArgumentError, 'not a Server') unless srv.is_a? Core::Server + end + @server = srv + + @pool_size = pool_size + @max_waiting_requests = max_waiting_requests + @poll_period = poll_period + @run_mutex = Mutex.new + @run_cond = ConditionVariable.new + @pool = Pool.new(@pool_size) end - @server = srv - - @pool_size = pool_size - @max_waiting_requests = max_waiting_requests - @poll_period = poll_period - @run_mutex = Mutex.new - @run_cond = ConditionVariable.new - @pool = Pool.new(@pool_size) - end - # stops a running server - # - # the call has no impact if the server is already stopped, otherwise - # server's current call loop is it's last. - def stop - if @running + # stops a running server + # + # the call has no impact if the server is already stopped, otherwise + # server's current call loop is it's last. + def stop + return unless @running @stopped = true @pool.stop end - end - # determines if the server is currently running - def running? - @running ||= false - end + # determines if the server is currently running + def running? + @running ||= false + end - # Is called from other threads to wait for #run to start up the server. - # - # If run has not been called, this returns immediately. - # - # @param timeout [Numeric] number of seconds to wait - # @result [true, false] true if the server is running, false otherwise - def wait_till_running(timeout=0.1) - end_time, sleep_period = Time.now + timeout, (1.0 * timeout)/100 - while Time.now < end_time - if !running? - @run_mutex.synchronize { @run_cond.wait(@run_mutex) } + # Is called from other threads to wait for #run to start up the server. + # + # If run has not been called, this returns immediately. + # + # @param timeout [Numeric] number of seconds to wait + # @result [true, false] true if the server is running, false otherwise + def wait_till_running(timeout = 0.1) + end_time, sleep_period = Time.now + timeout, (1.0 * timeout) / 100 + while Time.now < end_time + @run_mutex.synchronize { @run_cond.wait(@run_mutex) } unless running? + sleep(sleep_period) end - sleep(sleep_period) + running? end - return running? - end - - # determines if the server is currently stopped - def stopped? - @stopped ||= false - end - - # handle registration of classes - # - # service is either a class that includes GRPC::GenericService and whose - # #new function can be called without argument or any instance of such a - # class. - # - # E.g, after - # - # class Divider - # include GRPC::GenericService - # rpc :div DivArgs, DivReply # single request, single response - # def initialize(optional_arg='default option') # no args - # ... - # end - # - # srv = GRPC::RpcServer.new(...) - # - # # Either of these works - # - # srv.handle(Divider) - # - # # or - # - # srv.handle(Divider.new('replace optional arg')) - # - # It raises RuntimeError: - # - if service is not valid service class or object - # - if it is a valid service, but the handler methods are already registered - # - if the server is already running - # - # @param service [Object|Class] a service class or object as described - # above - def handle(service) - raise 'cannot add services if the server is running' if running? - raise 'cannot add services if the server is stopped' if stopped? - cls = service.is_a?(Class) ? service : service.class - assert_valid_service_class(cls) - add_rpc_descs_for(service) - end - # runs the server - # - # - if no rpc_descs are registered, this exits immediately, otherwise it - # continues running permanently and does not return until program exit. - # - # - #running? returns true after this is called, until #stop cause the - # the server to stop. - def run - if rpc_descs.size == 0 - logger.warn('did not run as no services were present') - return + # determines if the server is currently stopped + def stopped? + @stopped ||= false end - @run_mutex.synchronize do - @running = true - @run_cond.signal + + # handle registration of classes + # + # service is either a class that includes GRPC::GenericService and whose + # #new function can be called without argument or any instance of such a + # class. + # + # E.g, after + # + # class Divider + # include GRPC::GenericService + # rpc :div DivArgs, DivReply # single request, single response + # def initialize(optional_arg='default option') # no args + # ... + # end + # + # srv = GRPC::RpcServer.new(...) + # + # # Either of these works + # + # srv.handle(Divider) + # + # # or + # + # srv.handle(Divider.new('replace optional arg')) + # + # It raises RuntimeError: + # - if service is not valid service class or object + # - its handler methods are already registered + # - if the server is already running + # + # @param service [Object|Class] a service class or object as described + # above + def handle(service) + fail 'cannot add services if the server is running' if running? + fail 'cannot add services if the server is stopped' if stopped? + cls = service.is_a?(Class) ? service : service.class + assert_valid_service_class(cls) + add_rpc_descs_for(service) end - @pool.start - @server.start - server_tag = Object.new - while !stopped? - @server.request_call(server_tag) - ev = @cq.pluck(server_tag, @poll_period) - next if ev.nil? - if ev.type != SERVER_RPC_NEW - logger.warn("bad evt: got:#{ev.type}, want:#{SERVER_RPC_NEW}") - ev.close - next + + # runs the server + # + # - if no rpc_descs are registered, this exits immediately, otherwise it + # continues running permanently and does not return until program exit. + # + # - #running? returns true after this is called, until #stop cause the + # the server to stop. + def run + if rpc_descs.size == 0 + logger.warn('did not run as no services were present') + return end - c = new_active_server_call(ev.call, ev.result) - if !c.nil? - mth = ev.result.method.to_sym - ev.close - @pool.schedule(c) do |call| - rpc_descs[mth].run_server_method(call, rpc_handlers[mth]) + @run_mutex.synchronize do + @running = true + @run_cond.signal + end + @pool.start + @server.start + server_tag = Object.new + until stopped? + @server.request_call(server_tag) + ev = @cq.pluck(server_tag, @poll_period) + next if ev.nil? + if ev.type != SERVER_RPC_NEW + logger.warn("bad evt: got:#{ev.type}, want:#{SERVER_RPC_NEW}") + ev.close + next + end + c = new_active_server_call(ev.call, ev.result) + unless c.nil? + mth = ev.result.method.to_sym + ev.close + @pool.schedule(c) do |call| + rpc_descs[mth].run_server_method(call, rpc_handlers[mth]) + end end end - end - @running = false - end - - def new_active_server_call(call, new_server_rpc) - # TODO(temiola): perhaps reuse the main server completion queue here, but - # for now, create a new completion queue per call, pending best practice - # usage advice from the c core. - - # Accept the call. This is necessary even if a status is to be sent back - # immediately - finished_tag = Object.new - call_queue = Core::CompletionQueue.new - call.metadata = new_server_rpc.metadata # store the metadata on the call - call.server_accept(call_queue, finished_tag) - call.server_end_initial_metadata() - - # Send UNAVAILABLE if there are too many unprocessed jobs - jobs_count, max = @pool.jobs_waiting, @max_waiting_requests - logger.info("waiting: #{jobs_count}, max: #{max}") - if @pool.jobs_waiting > @max_waiting_requests - logger.warn("NOT AVAILABLE: too many jobs_waiting: #{new_server_rpc}") - noop = Proc.new { |x| x } - c = ActiveCall.new(call, call_queue, noop, noop, - new_server_rpc.deadline, finished_tag: finished_tag) - c.send_status(StatusCodes::UNAVAILABLE, '') - return nil + @running = false end - # Send NOT_FOUND if the method does not exist - mth = new_server_rpc.method.to_sym - if !rpc_descs.has_key?(mth) - logger.warn("NOT_FOUND: #{new_server_rpc}") - noop = Proc.new { |x| x } - c = ActiveCall.new(call, call_queue, noop, noop, - new_server_rpc.deadline, finished_tag: finished_tag) - c.send_status(StatusCodes::NOT_FOUND, '') - return nil - end + def new_active_server_call(call, new_server_rpc) + # TODO(temiola): perhaps reuse the main server completion queue here, + # but for now, create a new completion queue per call, pending best + # practice usage advice from the c core. + + # Accept the call. This is necessary even if a status is to be sent + # back immediately + finished_tag = Object.new + call_queue = Core::CompletionQueue.new + call.metadata = new_server_rpc.metadata # store the metadata + call.server_accept(call_queue, finished_tag) + call.server_end_initial_metadata + + # Send UNAVAILABLE if there are too many unprocessed jobs + jobs_count, max = @pool.jobs_waiting, @max_waiting_requests + logger.info("waiting: #{jobs_count}, max: #{max}") + if @pool.jobs_waiting > @max_waiting_requests + logger.warn("NOT AVAILABLE: too many jobs_waiting: #{new_server_rpc}") + noop = proc { |x| x } + c = ActiveCall.new(call, call_queue, noop, noop, + new_server_rpc.deadline, + finished_tag: finished_tag) + c.send_status(StatusCodes::UNAVAILABLE, '') + return nil + end - # Create the ActiveCall - rpc_desc = rpc_descs[mth] - logger.info("deadline is #{new_server_rpc.deadline}; (now=#{Time.now})") - ActiveCall.new(call, call_queue, - rpc_desc.marshal_proc, rpc_desc.unmarshal_proc(:input), - new_server_rpc.deadline, finished_tag: finished_tag) - end + # Send NOT_FOUND if the method does not exist + mth = new_server_rpc.method.to_sym + unless rpc_descs.key?(mth) + logger.warn("NOT_FOUND: #{new_server_rpc}") + noop = proc { |x| x } + c = ActiveCall.new(call, call_queue, noop, noop, + new_server_rpc.deadline, + finished_tag: finished_tag) + c.send_status(StatusCodes::NOT_FOUND, '') + return nil + end - # Pool is a simple thread pool for running server requests. - class Pool - - def initialize(size) - raise 'pool size must be positive' unless size > 0 - @jobs = Queue.new - @size = size - @stopped = false - @stop_mutex = Mutex.new - @stop_cond = ConditionVariable.new - @workers = [] + # Create the ActiveCall + rpc_desc = rpc_descs[mth] + logger.info("deadline is #{new_server_rpc.deadline}; (now=#{Time.now})") + ActiveCall.new(call, call_queue, + rpc_desc.marshal_proc, rpc_desc.unmarshal_proc(:input), + new_server_rpc.deadline, finished_tag: finished_tag) end - # Returns the number of jobs waiting - def jobs_waiting - @jobs.size - end + # Pool is a simple thread pool for running server requests. + class Pool + def initialize(size) + fail 'pool size must be positive' unless size > 0 + @jobs = Queue.new + @size = size + @stopped = false + @stop_mutex = Mutex.new + @stop_cond = ConditionVariable.new + @workers = [] + end - # Runs the given block on the queue with the provided args. - # - # @param args the args passed blk when it is called - # @param blk the block to call - def schedule(*args, &blk) - raise 'already stopped' if @stopped - return if blk.nil? - logger.info('schedule another job') - @jobs << [blk, args] - end + # Returns the number of jobs waiting + def jobs_waiting + @jobs.size + end + + # Runs the given block on the queue with the provided args. + # + # @param args the args passed blk when it is called + # @param blk the block to call + def schedule(*args, &blk) + fail 'already stopped' if @stopped + return if blk.nil? + logger.info('schedule another job') + @jobs << [blk, args] + end - # Starts running the jobs in the thread pool. - def start - raise 'already stopped' if @stopped - until @workers.size == @size.to_i - next_thread = Thread.new do - catch(:exit) do # allows { throw :exit } to kill a thread - loop do - begin - blk, args = @jobs.pop - blk.call(*args) - rescue StandardError => e - logger.warn('Error in worker thread') - logger.warn(e) + # Starts running the jobs in the thread pool. + def start + fail 'already stopped' if @stopped + until @workers.size == @size.to_i + next_thread = Thread.new do + catch(:exit) do # allows { throw :exit } to kill a thread + loop do + begin + blk, args = @jobs.pop + blk.call(*args) + rescue StandardError => e + logger.warn('Error in worker thread') + logger.warn(e) + end end end - end - # removes the threads from workers, and signal when all the threads - # are complete. - @stop_mutex.synchronize do - @workers.delete(Thread.current) - if @workers.size == 0 - @stop_cond.signal + # removes the threads from workers, and signal when all the + # threads are complete. + @stop_mutex.synchronize do + @workers.delete(Thread.current) + @stop_cond.signal if @workers.size == 0 end end + @workers << next_thread end - @workers << next_thread end - end - # Stops the jobs in the pool - def stop - logger.info('stopping, will wait for all the workers to exit') - @workers.size.times { schedule { throw :exit } } - @stopped = true + # Stops the jobs in the pool + def stop + logger.info('stopping, will wait for all the workers to exit') + @workers.size.times { schedule { throw :exit } } + @stopped = true - # TODO(temiola): allow configuration of the keepalive period - keep_alive = 5 - @stop_mutex.synchronize do - if @workers.size > 0 - @stop_cond.wait(@stop_mutex, keep_alive) + # TODO(temiola): allow configuration of the keepalive period + keep_alive = 5 + @stop_mutex.synchronize do + @stop_cond.wait(@stop_mutex, keep_alive) if @workers.size > 0 end - end - # Forcibly shutdown any threads that are still alive. - if @workers.size > 0 - logger.warn("forcibly terminating #{@workers.size} worker(s)") - @workers.each do |t| - next unless t.alive? - begin - t.exit - rescue StandardError => e - logger.warn('error while terminating a worker') - logger.warn(e) + # Forcibly shutdown any threads that are still alive. + if @workers.size > 0 + logger.warn("forcibly terminating #{@workers.size} worker(s)") + @workers.each do |t| + next unless t.alive? + begin + t.exit + rescue StandardError => e + logger.warn('error while terminating a worker') + logger.warn(e) + end end end - end - logger.info('stopped, all workers are shutdown') + logger.info('stopped, all workers are shutdown') + end end - end + protected - protected - - def rpc_descs - @rpc_descs ||= {} - end + def rpc_descs + @rpc_descs ||= {} + end - def rpc_handlers - @rpc_handlers ||= {} - end + def rpc_handlers + @rpc_handlers ||= {} + end - private + private - def assert_valid_service_class(cls) - if !cls.include?(GenericService) - raise "#{cls} should 'include GenericService'" - end - if cls.rpc_descs.size == 0 - raise "#{cls} should specify some rpc descriptions" + def assert_valid_service_class(cls) + unless cls.include?(GenericService) + fail "#{cls} should 'include GenericService'" + end + if cls.rpc_descs.size == 0 + fail "#{cls} should specify some rpc descriptions" + end + cls.assert_rpc_descs_have_methods end - cls.assert_rpc_descs_have_methods - end - def add_rpc_descs_for(service) - cls = service.is_a?(Class) ? service : service.class - specs = rpc_descs - handlers = rpc_handlers - cls.rpc_descs.each_pair do |name,spec| - route = "/#{cls.service_name}/#{name}".to_sym - if specs.has_key?(route) - raise "Cannot add rpc #{route} from #{spec}, already registered" - else - specs[route] = spec - if service.is_a?(Class) - handlers[route] = cls.new.method(name.to_s.underscore.to_sym) + def add_rpc_descs_for(service) + cls = service.is_a?(Class) ? service : service.class + specs = rpc_descs + handlers = rpc_handlers + cls.rpc_descs.each_pair do |name, spec| + route = "/#{cls.service_name}/#{name}".to_sym + if specs.key? route + fail "Cannot add rpc #{route} from #{spec}, already registered" else - handlers[route] = service.method(name.to_s.underscore.to_sym) + specs[route] = spec + if service.is_a?(Class) + handlers[route] = cls.new.method(name.to_s.underscore.to_sym) + else + handlers[route] = service.method(name.to_s.underscore.to_sym) + end + logger.info("handling #{route} with #{handlers[route]}") end - logger.info("handling #{route} with #{handlers[route]}") end end end end - end diff --git a/src/ruby/lib/grpc/generic/service.rb b/src/ruby/lib/grpc/generic/service.rb index f3fe638fce..ff37617ccf 100644 --- a/src/ruby/lib/grpc/generic/service.rb +++ b/src/ruby/lib/grpc/generic/service.rb @@ -32,7 +32,6 @@ require 'grpc/generic/rpc_desc' # Extend String to add a method underscore class String - # creates a new string that is the underscore separate version of this one. # # E.g, @@ -40,210 +39,199 @@ class String # AMethod -> a_method # AnRpc -> an_rpc def underscore - word = self.dup + word = dup word.gsub!(/([A-Z]+)([A-Z][a-z])/, '\1_\2') word.gsub!(/([a-z\d])([A-Z])/, '\1_\2') word.tr!('-', '_') word.downcase! word end - end -module Google::RPC - - # Provides behaviour used to implement schema-derived service classes. - # - # Is intended to be used to support both client and server IDL-schema-derived - # servers. - module GenericService - - # Used to indicate that a name has already been specified - class DuplicateRpcName < StandardError - def initialize(name) - super("rpc (#{name}) is already defined") - end - end - - # Provides a simple DSL to describe RPC services. - # - # E.g, a Maths service that uses the serializable messages DivArgs, - # DivReply and Num might define its endpoint uses the following way: - # - # rpc :div DivArgs, DivReply # single request, single response - # rpc :sum stream(Num), Num # streamed input, single response - # rpc :fib FibArgs, stream(Num) # single request, streamed response - # rpc :div_many stream(DivArgs), stream(DivReply) - # # streamed req and resp +module Google + # Google::RPC contains the General RPC module. + module RPC + # Provides behaviour used to implement schema-derived service classes. # - # Each 'rpc' adds an RpcDesc to classes including this module, and - # #assert_rpc_descs_have_methods is used to ensure the including class - # provides methods with signatures that support all the descriptors. - module Dsl - - # This configures the method names that the serializable message - # implementation uses to marshal and unmarshal messages. - # - # - unmarshal_class method must be a class method on the serializable - # message type that takes a string (byte stream) and produces and object - # - # - marshal_class_method is called on a serializable message instance - # and produces a serialized string. - # - # The Dsl verifies that the types in the descriptor have both the - # unmarshal and marshal methods. - attr_writer(:marshal_class_method, :unmarshal_class_method) - - # This allows configuration of the service name. - attr_accessor(:service_name) + # Is intended to be used to support both client and server + # IDL-schema-derived servers. + module GenericService + # Used to indicate that a name has already been specified + class DuplicateRpcName < StandardError + def initialize(name) + super("rpc (#{name}) is already defined") + end + end - # Adds an RPC spec. + # Provides a simple DSL to describe RPC services. # - # Takes the RPC name and the classes representing the types to be - # serialized, and adds them to the including classes rpc_desc hash. + # E.g, a Maths service that uses the serializable messages DivArgs, + # DivReply and Num might define its endpoint uses the following way: # - # input and output should both have the methods #marshal and #unmarshal - # that are responsible for writing and reading an object instance from a - # byte buffer respectively. + # rpc :div DivArgs, DivReply # single request, single response + # rpc :sum stream(Num), Num # streamed input, single response + # rpc :fib FibArgs, stream(Num) # single request, streamed response + # rpc :div_many stream(DivArgs), stream(DivReply) + # # streamed req and resp # - # @param name [String] the name of the rpc - # @param input [Object] the input parameter's class - # @param output [Object] the output parameter's class - def rpc(name, input, output) - raise DuplicateRpcName, name if rpc_descs.has_key?(name) - assert_can_marshal(input) - assert_can_marshal(output) - rpc_descs[name] = RpcDesc.new(name, input, output, - marshal_class_method, - unmarshal_class_method) - end - - def inherited(subclass) - # Each subclass should have a distinct class variable with its own - # rpc_descs - subclass.rpc_descs.merge!(rpc_descs) - subclass.service_name = service_name - end - - # the name of the instance method used to marshal events to a byte stream. - def marshal_class_method - @marshal_class_method ||= :marshal - end + # Each 'rpc' adds an RpcDesc to classes including this module, and + # #assert_rpc_descs_have_methods is used to ensure the including class + # provides methods with signatures that support all the descriptors. + module Dsl + # This configures the method names that the serializable message + # implementation uses to marshal and unmarshal messages. + # + # - unmarshal_class method must be a class method on the serializable + # message type that takes a string (byte stream) and produces and object + # + # - marshal_class_method is called on a serializable message instance + # and produces a serialized string. + # + # The Dsl verifies that the types in the descriptor have both the + # unmarshal and marshal methods. + attr_writer(:marshal_class_method, :unmarshal_class_method) + + # This allows configuration of the service name. + attr_accessor(:service_name) + + # Adds an RPC spec. + # + # Takes the RPC name and the classes representing the types to be + # serialized, and adds them to the including classes rpc_desc hash. + # + # input and output should both have the methods #marshal and #unmarshal + # that are responsible for writing and reading an object instance from a + # byte buffer respectively. + # + # @param name [String] the name of the rpc + # @param input [Object] the input parameter's class + # @param output [Object] the output parameter's class + def rpc(name, input, output) + fail(DuplicateRpcName, name) if rpc_descs.key? name + assert_can_marshal(input) + assert_can_marshal(output) + rpc_descs[name] = RpcDesc.new(name, input, output, + marshal_class_method, + unmarshal_class_method) + end - # the name of the class method used to unmarshal from a byte stream. - def unmarshal_class_method - @unmarshal_class_method ||= :unmarshal - end + def inherited(subclass) + # Each subclass should have a distinct class variable with its own + # rpc_descs + subclass.rpc_descs.merge!(rpc_descs) + subclass.service_name = service_name + end - def assert_can_marshal(cls) - if cls.is_a?RpcDesc::Stream - cls = cls.type + # the name of the instance method used to marshal events to a byte + # stream. + def marshal_class_method + @marshal_class_method ||= :marshal end - mth = unmarshal_class_method - if !cls.methods.include?(mth) - raise ArgumentError, "#{cls} needs #{cls}.#{mth}" + # the name of the class method used to unmarshal from a byte stream. + def unmarshal_class_method + @unmarshal_class_method ||= :unmarshal end - mth = marshal_class_method - if !cls.methods.include?(mth) - raise ArgumentError, "#{cls} needs #{cls}.#{mth}" + def assert_can_marshal(cls) + cls = cls.type if cls.is_a? RpcDesc::Stream + mth = unmarshal_class_method + unless cls.methods.include? mth + fail(ArgumentError, "#{cls} needs #{cls}.#{mth}") + end + mth = marshal_class_method + return if cls.methods.include? mth + fail(ArgumentError, "#{cls} needs #{cls}.#{mth}") end - end - # @param cls [Class] the class of a serializable type - # @return cls wrapped in a RpcDesc::Stream - def stream(cls) - assert_can_marshal(cls) - RpcDesc::Stream.new(cls) - end + # @param cls [Class] the class of a serializable type + # @return cls wrapped in a RpcDesc::Stream + def stream(cls) + assert_can_marshal(cls) + RpcDesc::Stream.new(cls) + end - # the RpcDescs defined for this GenericService, keyed by name. - def rpc_descs - @rpc_descs ||= {} - end + # the RpcDescs defined for this GenericService, keyed by name. + def rpc_descs + @rpc_descs ||= {} + end - # Creates a rpc client class with methods for accessing the methods - # currently in rpc_descs. - def rpc_stub_class - descs = rpc_descs - route_prefix = service_name - Class.new(ClientStub) do - - # @param host [String] the host the stub connects to - # @param kw [KeywordArgs] the channel arguments, plus any optional - # args for configuring the client's channel - def initialize(host, **kw) - super(host, Core::CompletionQueue.new, **kw) - end + # Creates a rpc client class with methods for accessing the methods + # currently in rpc_descs. + def rpc_stub_class + descs = rpc_descs + route_prefix = service_name + Class.new(ClientStub) do + # @param host [String] the host the stub connects to + # @param kw [KeywordArgs] the channel arguments, plus any optional + # args for configuring the client's channel + def initialize(host, **kw) + super(host, Core::CompletionQueue.new, **kw) + end - # Used define_method to add a method for each rpc_desc. Each method - # calls the base class method for the given descriptor. - descs.each_pair do |name,desc| - mth_name = name.to_s.underscore.to_sym - marshal = desc.marshal_proc - unmarshal = desc.unmarshal_proc(:output) - route = "/#{route_prefix}/#{name}" - if desc.is_request_response? - define_method(mth_name) do |req,deadline=nil| - logger.debug("calling #{@host}:#{route}") - request_response(route, req, marshal, unmarshal, deadline) - end - elsif desc.is_client_streamer? - define_method(mth_name) do |reqs,deadline=nil| - logger.debug("calling #{@host}:#{route}") - client_streamer(route, reqs, marshal, unmarshal, deadline) - end - elsif desc.is_server_streamer? - define_method(mth_name) do |req,deadline=nil,&blk| - logger.debug("calling #{@host}:#{route}") - server_streamer(route, req, marshal, unmarshal, deadline, &blk) - end - else # is a bidi_stream - define_method(mth_name) do |reqs, deadline=nil,&blk| - logger.debug("calling #{@host}:#{route}") - bidi_streamer(route, reqs, marshal, unmarshal, deadline, &blk) + # Used define_method to add a method for each rpc_desc. Each method + # calls the base class method for the given descriptor. + descs.each_pair do |name, desc| + mth_name = name.to_s.underscore.to_sym + marshal = desc.marshal_proc + unmarshal = desc.unmarshal_proc(:output) + route = "/#{route_prefix}/#{name}" + if desc.request_response? + define_method(mth_name) do |req, deadline = nil| + logger.debug("calling #{@host}:#{route}") + request_response(route, req, marshal, unmarshal, deadline) + end + elsif desc.client_streamer? + define_method(mth_name) do |reqs, deadline = nil| + logger.debug("calling #{@host}:#{route}") + client_streamer(route, reqs, marshal, unmarshal, deadline) + end + elsif desc.server_streamer? + define_method(mth_name) do |req, deadline = nil, &blk| + logger.debug("calling #{@host}:#{route}") + server_streamer(route, req, marshal, unmarshal, deadline, + &blk) + end + else # is a bidi_stream + define_method(mth_name) do |reqs, deadline = nil, &blk| + logger.debug("calling #{@host}:#{route}") + bidi_streamer(route, reqs, marshal, unmarshal, deadline, &blk) + end end end end - end - end - - # Asserts that the appropriate methods are defined for each added rpc - # spec. Is intended to aid verifying that server classes are correctly - # implemented. - def assert_rpc_descs_have_methods - rpc_descs.each_pair do |m,spec| - mth_name = m.to_s.underscore.to_sym - if !self.instance_methods.include?(mth_name) - raise "#{self} does not provide instance method '#{mth_name}'" + # Asserts that the appropriate methods are defined for each added rpc + # spec. Is intended to aid verifying that server classes are correctly + # implemented. + def assert_rpc_descs_have_methods + rpc_descs.each_pair do |m, spec| + mth_name = m.to_s.underscore.to_sym + unless instance_methods.include?(mth_name) + fail "#{self} does not provide instance method '#{mth_name}'" + end + spec.assert_arity_matches(instance_method(mth_name)) end - spec.assert_arity_matches(self.instance_method(mth_name)) end end - end - - def self.included(o) - o.extend(Dsl) - - # Update to the use the service name including module. Proivde a default - # that can be nil e,g. when modules are declared dynamically. - return unless o.service_name.nil? - if o.name.nil? - o.service_name = 'GenericService' - else - modules = o.name.split('::') - if modules.length > 2 - o.service_name = modules[modules.length - 2] + def self.included(o) + o.extend(Dsl) + # Update to the use the service name including module. Proivde a default + # that can be nil e,g. when modules are declared dynamically. + return unless o.service_name.nil? + if o.name.nil? + o.service_name = 'GenericService' else - o.service_name = modules.first + modules = o.name.split('::') + if modules.length > 2 + o.service_name = modules[modules.length - 2] + else + o.service_name = modules.first + end end end end - end - end diff --git a/src/ruby/lib/grpc/version.rb b/src/ruby/lib/grpc/version.rb index 0a84f4c3a7..dd526e583a 100644 --- a/src/ruby/lib/grpc/version.rb +++ b/src/ruby/lib/grpc/version.rb @@ -28,6 +28,7 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. module Google + # Google::RPC contains the General RPC module. module RPC VERSION = '0.0.1' end diff --git a/src/ruby/spec/alloc_spec.rb b/src/ruby/spec/alloc_spec.rb index 305405e9bd..6dd59ab9fc 100644 --- a/src/ruby/spec/alloc_spec.rb +++ b/src/ruby/spec/alloc_spec.rb @@ -30,7 +30,6 @@ require 'grpc' describe 'Wrapped classes where .new cannot create an instance' do - describe GRPC::Core::Event do it 'should fail .new fail with a runtime error' do expect { GRPC::Core::Event.new }.to raise_error(TypeError) @@ -42,5 +41,4 @@ describe 'Wrapped classes where .new cannot create an instance' do expect { GRPC::Core::Event.new }.to raise_error(TypeError) end end - end diff --git a/src/ruby/spec/byte_buffer_spec.rb b/src/ruby/spec/byte_buffer_spec.rb index b89d7f3640..3a65f45c7e 100644 --- a/src/ruby/spec/byte_buffer_spec.rb +++ b/src/ruby/spec/byte_buffer_spec.rb @@ -30,9 +30,7 @@ require 'grpc' describe GRPC::Core::ByteBuffer do - describe '#new' do - it 'is constructed from a string' do expect { GRPC::Core::ByteBuffer.new('#new') }.not_to raise_error end @@ -50,7 +48,6 @@ describe GRPC::Core::ByteBuffer do expect { GRPC::Core::ByteBuffer.new(x) }.to raise_error TypeError end end - end describe '#to_s' do @@ -67,5 +64,4 @@ describe GRPC::Core::ByteBuffer do expect(a_copy.dup.to_s).to eq('#dup') end end - end diff --git a/src/ruby/spec/call_spec.rb b/src/ruby/spec/call_spec.rb index 8e8e3d3ae2..b8ecd64f39 100644 --- a/src/ruby/spec/call_spec.rb +++ b/src/ruby/spec/call_spec.rb @@ -33,30 +33,29 @@ require 'port_picker' include GRPC::Core::StatusCodes describe GRPC::Core::RpcErrors do - before(:each) do @known_types = { - :OK => 0, - :ERROR => 1, - :NOT_ON_SERVER => 2, - :NOT_ON_CLIENT => 3, - :ALREADY_ACCEPTED => 4, - :ALREADY_INVOKED => 5, - :NOT_INVOKED => 6, - :ALREADY_FINISHED => 7, - :TOO_MANY_OPERATIONS => 8, - :INVALID_FLAGS => 9, - :ErrorMessages => { - 0=>'ok', - 1=>'unknown error', - 2=>'not available on a server', - 3=>'not available on a client', - 4=>'call is already accepted', - 5=>'call is already invoked', - 6=>'call is not yet invoked', - 7=>'call is already finished', - 8=>'outstanding read or write present', - 9=>'a bad flag was given', + OK: 0, + ERROR: 1, + NOT_ON_SERVER: 2, + NOT_ON_CLIENT: 3, + ALREADY_ACCEPTED: 4, + ALREADY_INVOKED: 5, + NOT_INVOKED: 6, + ALREADY_FINISHED: 7, + TOO_MANY_OPERATIONS: 8, + INVALID_FLAGS: 9, + ErrorMessages: { + 0 => 'ok', + 1 => 'unknown error', + 2 => 'not available on a server', + 3 => 'not available on a client', + 4 => 'call is already accepted', + 5 => 'call is already invoked', + 6 => 'call is not yet invoked', + 7 => 'call is already finished', + 8 => 'outstanding read or write present', + 9 => 'a bad flag was given' } } end @@ -66,11 +65,9 @@ describe GRPC::Core::RpcErrors do syms_and_codes = m.constants.collect { |c| [c, m.const_get(c)] } expect(Hash[syms_and_codes]).to eq(@known_types) end - end describe GRPC::Core::Call do - before(:each) do @tag = Object.new @client_queue = GRPC::Core::CompletionQueue.new @@ -88,7 +85,7 @@ describe GRPC::Core::Call do describe '#start_read' do it 'should fail if called immediately' do - blk = Proc.new { make_test_call.start_read(@tag) } + blk = proc { make_test_call.start_read(@tag) } expect(&blk).to raise_error GRPC::Core::CallError end end @@ -96,21 +93,21 @@ describe GRPC::Core::Call do describe '#start_write' do it 'should fail if called immediately' do bytes = GRPC::Core::ByteBuffer.new('test string') - blk = Proc.new { make_test_call.start_write(bytes, @tag) } + blk = proc { make_test_call.start_write(bytes, @tag) } expect(&blk).to raise_error GRPC::Core::CallError end end describe '#start_write_status' do it 'should fail if called immediately' do - blk = Proc.new { make_test_call.start_write_status(153, 'x', @tag) } + blk = proc { make_test_call.start_write_status(153, 'x', @tag) } expect(&blk).to raise_error GRPC::Core::CallError end end describe '#writes_done' do it 'should fail if called immediately' do - blk = Proc.new { make_test_call.writes_done(Object.new) } + blk = proc { make_test_call.writes_done(Object.new) } expect(&blk).to raise_error GRPC::Core::CallError end end @@ -119,7 +116,8 @@ describe GRPC::Core::Call do it 'adds metadata to a call without fail' do call = make_test_call n = 37 - metadata = Hash[n.times.collect { |i| ["key%d" % i, "value%d" %i] } ] + one_md = proc { |x| [sprintf('key%d', x), sprintf('value%d', x)] } + metadata = Hash[n.times.collect { |i| one_md.call i }] expect { call.add_metadata(metadata) }.to_not raise_error end end @@ -174,7 +172,7 @@ describe GRPC::Core::Call do describe '#metadata' do it 'can save the metadata hash and read it back' do call = make_test_call - md = {'k1' => 'v1', 'k2' => 'v2'} + md = { 'k1' => 'v1', 'k2' => 'v2' } expect { call.metadata = md }.not_to raise_error expect(call.metadata).to be(md) end @@ -191,7 +189,6 @@ describe GRPC::Core::Call do end end - def make_test_call @ch.create_call('dummy_method', 'dummy_host', deadline) end @@ -199,5 +196,4 @@ describe GRPC::Core::Call do def deadline Time.now + 2 # in 2 seconds; arbitrary end - end diff --git a/src/ruby/spec/channel_spec.rb b/src/ruby/spec/channel_spec.rb index d2686127bb..820dbd39e9 100644 --- a/src/ruby/spec/channel_spec.rb +++ b/src/ruby/spec/channel_spec.rb @@ -37,8 +37,6 @@ def load_test_certs end describe GRPC::Core::Channel do - - def create_test_cert GRPC::Core::Credentials.new(load_test_certs[0]) end @@ -48,7 +46,6 @@ describe GRPC::Core::Channel do end shared_examples '#new' do - it 'take a host name without channel args' do expect { GRPC::Core::Channel.new('dummy_host', nil) }.not_to raise_error end @@ -61,14 +58,14 @@ describe GRPC::Core::Channel do end it 'does not take a hash with bad values as channel args' do - blk = construct_with_args(:symbol => Object.new) + blk = construct_with_args(symbol: Object.new) expect(&blk).to raise_error TypeError blk = construct_with_args('1' => Hash.new) expect(&blk).to raise_error TypeError end it 'can take a hash with a symbol key as channel args' do - blk = construct_with_args(:a_symbol => 1) + blk = construct_with_args(a_symbol: 1) expect(&blk).to_not raise_error end @@ -78,32 +75,30 @@ describe GRPC::Core::Channel do end it 'can take a hash with a string value as channel args' do - blk = construct_with_args(:a_symbol => '1') + blk = construct_with_args(a_symbol: '1') expect(&blk).to_not raise_error end it 'can take a hash with a symbol value as channel args' do - blk = construct_with_args(:a_symbol => :another_symbol) + blk = construct_with_args(a_symbol: :another_symbol) expect(&blk).to_not raise_error end it 'can take a hash with a numeric value as channel args' do - blk = construct_with_args(:a_symbol => 1) + blk = construct_with_args(a_symbol: 1) expect(&blk).to_not raise_error end it 'can take a hash with many args as channel args' do - args = Hash[127.times.collect { |x| [x.to_s, x] } ] + args = Hash[127.times.collect { |x| [x.to_s, x] }] blk = construct_with_args(args) expect(&blk).to_not raise_error end - end describe '#new for secure channels' do - def construct_with_args(a) - Proc.new { GRPC::Core::Channel.new('dummy_host', a, create_test_cert) } + proc { GRPC::Core::Channel.new('dummy_host', a, create_test_cert) } end it_behaves_like '#new' @@ -113,7 +108,7 @@ describe GRPC::Core::Channel do it_behaves_like '#new' def construct_with_args(a) - Proc.new { GRPC::Core::Channel.new('dummy_host', a) } + proc { GRPC::Core::Channel.new('dummy_host', a) } end end @@ -125,7 +120,7 @@ describe GRPC::Core::Channel do deadline = Time.now + 5 - blk = Proc.new do + blk = proc do ch.create_call('dummy_method', 'dummy_host', deadline) end expect(&blk).to_not raise_error @@ -138,12 +133,11 @@ describe GRPC::Core::Channel do ch.close deadline = Time.now + 5 - blk = Proc.new do + blk = proc do ch.create_call('dummy_method', 'dummy_host', deadline) end expect(&blk).to raise_error(RuntimeError) end - end describe '#destroy' do @@ -151,7 +145,7 @@ describe GRPC::Core::Channel do port = find_unused_tcp_port host = "localhost:#{port}" ch = GRPC::Core::Channel.new(host, nil) - blk = Proc.new { ch.destroy } + blk = proc { ch.destroy } expect(&blk).to_not raise_error end @@ -159,18 +153,16 @@ describe GRPC::Core::Channel do port = find_unused_tcp_port host = "localhost:#{port}" ch = GRPC::Core::Channel.new(host, nil) - blk = Proc.new { ch.destroy } + blk = proc { ch.destroy } blk.call expect(&blk).to_not raise_error end end describe '::SSL_TARGET' do - it 'is a symbol' do expect(GRPC::Core::Channel::SSL_TARGET).to be_a(Symbol) end - end describe '#close' do @@ -178,7 +170,7 @@ describe GRPC::Core::Channel do port = find_unused_tcp_port host = "localhost:#{port}" ch = GRPC::Core::Channel.new(host, nil) - blk = Proc.new { ch.close } + blk = proc { ch.close } expect(&blk).to_not raise_error end @@ -186,10 +178,9 @@ describe GRPC::Core::Channel do port = find_unused_tcp_port host = "localhost:#{port}" ch = GRPC::Core::Channel.new(host, nil) - blk = Proc.new { ch.close } + blk = proc { ch.close } blk.call expect(&blk).to_not raise_error end end - end diff --git a/src/ruby/spec/client_server_spec.rb b/src/ruby/spec/client_server_spec.rb index 5e68f524d6..1bcbc66446 100644 --- a/src/ruby/spec/client_server_spec.rb +++ b/src/ruby/spec/client_server_spec.rb @@ -41,7 +41,6 @@ def load_test_certs end shared_context 'setup: tags' do - before(:example) do @server_finished_tag = Object.new @client_finished_tag = Object.new @@ -71,7 +70,7 @@ shared_context 'setup: tags' do expect(ev).not_to be_nil expect(ev.type).to be(SERVER_RPC_NEW) ev.call.server_accept(@server_queue, @server_finished_tag) - ev.call.server_end_initial_metadata() + ev.call.server_end_initial_metadata ev.call.start_read(@server_tag) ev = @server_queue.pluck(@server_tag, TimeConsts::INFINITE_FUTURE) expect(ev.type).to be(READ) @@ -79,10 +78,10 @@ shared_context 'setup: tags' do ev = @server_queue.pluck(@server_tag, TimeConsts::INFINITE_FUTURE) expect(ev).not_to be_nil expect(ev.type).to be(WRITE_ACCEPTED) - return ev.call + ev.call end - def client_sends(call, sent='a message') + def client_sends(call, sent = 'a message') req = ByteBuffer.new(sent) call.start_invoke(@client_queue, @tag, @tag, @client_finished_tag) ev = @client_queue.pluck(@tag, TimeConsts::INFINITE_FUTURE) @@ -92,17 +91,15 @@ shared_context 'setup: tags' do ev = @client_queue.pluck(@tag, TimeConsts::INFINITE_FUTURE) expect(ev).not_to be_nil expect(ev.type).to be(WRITE_ACCEPTED) - return sent + sent end def new_client_call @ch.create_call('/method', 'localhost', deadline) end - end shared_examples 'basic GRPC message delivery is OK' do - include_context 'setup: tags' it 'servers receive requests from clients and start responding' do @@ -126,7 +123,7 @@ shared_examples 'basic GRPC message delivery is OK' do # the server response server_call.start_write(reply, @server_tag) - ev = expect_next_event_on(@server_queue, WRITE_ACCEPTED, @server_tag) + expect_next_event_on(@server_queue, WRITE_ACCEPTED, @server_tag) end it 'responses written by servers are received by the client' do @@ -135,15 +132,14 @@ shared_examples 'basic GRPC message delivery is OK' do server_receives_and_responds_with('server_response') call.start_read(@tag) - ev = expect_next_event_on(@client_queue, CLIENT_METADATA_READ, @tag) + expect_next_event_on(@client_queue, CLIENT_METADATA_READ, @tag) ev = expect_next_event_on(@client_queue, READ, @tag) expect(ev.result.to_s).to eq('server_response') end it 'servers can ignore a client write and send a status' do - reply = ByteBuffer.new('the server payload') call = new_client_call - msg = client_sends(call) + client_sends(call) # check the server rpc new was received @server.request_call(@server_tag) @@ -153,20 +149,20 @@ shared_examples 'basic GRPC message delivery is OK' do # accept the call - need to do this to sent status. server_call = ev.call server_call.server_accept(@server_queue, @server_finished_tag) - server_call.server_end_initial_metadata() + server_call.server_end_initial_metadata server_call.start_write_status(StatusCodes::NOT_FOUND, 'not found', @server_tag) # client gets an empty response for the read, preceeded by some metadata. call.start_read(@tag) - ev = expect_next_event_on(@client_queue, CLIENT_METADATA_READ, @tag) + expect_next_event_on(@client_queue, CLIENT_METADATA_READ, @tag) ev = expect_next_event_on(@client_queue, READ, @tag) expect(ev.tag).to be(@tag) expect(ev.result.to_s).to eq('') # finally, after client sends writes_done, they get the finished. call.writes_done(@tag) - ev = expect_next_event_on(@client_queue, FINISH_ACCEPTED, @tag) + expect_next_event_on(@client_queue, FINISH_ACCEPTED, @tag) ev = expect_next_event_on(@client_queue, FINISHED, @client_finished_tag) expect(ev.result.code).to eq(StatusCodes::NOT_FOUND) end @@ -175,12 +171,12 @@ shared_examples 'basic GRPC message delivery is OK' do call = new_client_call client_sends(call) server_call = server_receives_and_responds_with('server_response') - server_call.start_write_status(10101, 'status code is 10101', @server_tag) + server_call.start_write_status(10_101, 'status code is 10101', @server_tag) # first the client says writes are done call.start_read(@tag) - ev = expect_next_event_on(@client_queue, CLIENT_METADATA_READ, @tag) - ev = expect_next_event_on(@client_queue, READ, @tag) + expect_next_event_on(@client_queue, CLIENT_METADATA_READ, @tag) + expect_next_event_on(@client_queue, READ, @tag) call.writes_done(@tag) # but nothing happens until the server sends a status @@ -192,24 +188,23 @@ shared_examples 'basic GRPC message delivery is OK' do expect_next_event_on(@client_queue, FINISH_ACCEPTED, @tag) ev = expect_next_event_on(@client_queue, FINISHED, @client_finished_tag) expect(ev.result.details).to eq('status code is 10101') - expect(ev.result.code).to eq(10101) + expect(ev.result.code).to eq(10_101) end - end - shared_examples 'GRPC metadata delivery works OK' do - include_context 'setup: tags' describe 'from client => server' do - before(:example) do n = 7 # arbitrary number of metadata - diff_keys = Hash[n.times.collect { |i| ['k%d' % i, 'v%d' % i] }] - null_vals = Hash[n.times.collect { |i| ['k%d' % i, 'v\0%d' % i] }] - same_keys = Hash[n.times.collect { |i| ['k%d' % i, ['v%d' % i] * n] }] - symbol_key = {:a_key => 'a val'} + diff_keys_fn = proc { |i| [sprintf('k%d', i), sprintf('v%d', i)] } + diff_keys = Hash[n.times.collect { |x| diff_keys_fn.call x }] + null_vals_fn = proc { |i| [sprintf('k%d', i), sprintf('v\0%d', i)] } + null_vals = Hash[n.times.collect { |x| null_vals_fn.call x }] + same_keys_fn = proc { |i| [sprintf('k%d', i), [sprintf('v%d', i)] * n] } + same_keys = Hash[n.times.collect { |x| same_keys_fn.call x }] + symbol_key = { a_key: 'a val' } @valid_metadata = [diff_keys, same_keys, null_vals, symbol_key] @bad_keys = [] @bad_keys << { Object.new => 'a value' } @@ -239,28 +234,29 @@ shared_examples 'GRPC metadata delivery works OK' do # Client begins a call OK call.start_invoke(@client_queue, @tag, @tag, @client_finished_tag) - ev = expect_next_event_on(@client_queue, INVOKE_ACCEPTED, @tag) + expect_next_event_on(@client_queue, INVOKE_ACCEPTED, @tag) # ... server has all metadata available even though the client did not # send a write @server.request_call(@server_tag) ev = expect_next_event_on(@server_queue, SERVER_RPC_NEW, @server_tag) - replace_symbols = Hash[md.each_pair.collect { |x,y| [x.to_s, y] }] + replace_symbols = Hash[md.each_pair.collect { |x, y| [x.to_s, y] }] result = ev.result.metadata expect(result.merge(replace_symbols)).to eq(result) end end - end describe 'from server => client' do - before(:example) do n = 7 # arbitrary number of metadata - diff_keys = Hash[n.times.collect { |i| ['k%d' % i, 'v%d' % i] }] - null_vals = Hash[n.times.collect { |i| ['k%d' % i, 'v\0%d' % i] }] - same_keys = Hash[n.times.collect { |i| ['k%d' % i, ['v%d' % i] * n] }] - symbol_key = {:a_key => 'a val'} + diff_keys_fn = proc { |i| [sprintf('k%d', i), sprintf('v%d', i)] } + diff_keys = Hash[n.times.collect { |x| diff_keys_fn.call x }] + null_vals_fn = proc { |i| [sprintf('k%d', i), sprintf('v\0%d', i)] } + null_vals = Hash[n.times.collect { |x| null_vals_fn.call x }] + same_keys_fn = proc { |i| [sprintf('k%d', i), [sprintf('v%d', i)] * n] } + same_keys = Hash[n.times.collect { |x| same_keys_fn.call x }] + symbol_key = { a_key: 'a val' } @valid_metadata = [diff_keys, same_keys, null_vals, symbol_key] @bad_keys = [] @bad_keys << { Object.new => 'a value' } @@ -290,7 +286,7 @@ shared_examples 'GRPC metadata delivery works OK' do # ... server accepts the call without adding metadata server_call.server_accept(@server_queue, @server_finished_tag) - server_call.server_end_initial_metadata() + server_call.server_end_initial_metadata # ... these server sends some data, allowing the metadata read server_call.start_write(ByteBuffer.new('reply with metadata'), @@ -300,7 +296,7 @@ shared_examples 'GRPC metadata delivery works OK' do # there is the HTTP status metadata, though there should not be any # TODO(temiola): update this with the bug number to be resolved ev = expect_next_event_on(@client_queue, CLIENT_METADATA_READ, @tag) - expect(ev.result).to eq({':status' => '200'}) + expect(ev.result).to eq(':status' => '200') end it 'sends all the pairs and status:200 when keys and values are valid' do @@ -316,24 +312,19 @@ shared_examples 'GRPC metadata delivery works OK' do # ... server adds metadata and accepts the call server_call.add_metadata(md) server_call.server_accept(@server_queue, @server_finished_tag) - server_call.server_end_initial_metadata() + server_call.server_end_initial_metadata # Now the client can read the metadata ev = expect_next_event_on(@client_queue, CLIENT_METADATA_READ, @tag) - replace_symbols = Hash[md.each_pair.collect { |x,y| [x.to_s, y] }] + replace_symbols = Hash[md.each_pair.collect { |x, y| [x.to_s, y] }] replace_symbols[':status'] = '200' expect(ev.result).to eq(replace_symbols) end - end - end - end - describe 'the http client/server' do - before(:example) do port = find_unused_tcp_port host = "localhost:#{port}" @@ -354,11 +345,9 @@ describe 'the http client/server' do it_behaves_like 'GRPC metadata delivery works OK' do end - end describe 'the secure http client/server' do - before(:example) do certs = load_test_certs port = find_unused_tcp_port @@ -369,7 +358,7 @@ describe 'the secure http client/server' do @server = GRPC::Core::Server.new(@server_queue, nil, server_creds) @server.add_http2_port(host, true) @server.start - args = {Channel::SSL_TARGET => 'foo.test.google.com'} + args = { Channel::SSL_TARGET => 'foo.test.google.com' } @ch = Channel.new(host, args, GRPC::Core::Credentials.new(certs[0], nil, nil)) end @@ -383,5 +372,4 @@ describe 'the secure http client/server' do it_behaves_like 'GRPC metadata delivery works OK' do end - end diff --git a/src/ruby/spec/completion_queue_spec.rb b/src/ruby/spec/completion_queue_spec.rb index 50f74b5826..022a066e8e 100644 --- a/src/ruby/spec/completion_queue_spec.rb +++ b/src/ruby/spec/completion_queue_spec.rb @@ -30,7 +30,6 @@ require 'grpc' describe GRPC::Core::CompletionQueue do - describe '#new' do it 'is constructed successufully' do expect { GRPC::Core::CompletionQueue.new }.not_to raise_error @@ -53,7 +52,6 @@ describe GRPC::Core::CompletionQueue do expect { ch.next(a_time) }.not_to raise_error end end - end describe '#pluck' do @@ -74,8 +72,5 @@ describe GRPC::Core::CompletionQueue do expect { ch.pluck(tag, a_time) }.not_to raise_error end end - end - - end diff --git a/src/ruby/spec/credentials_spec.rb b/src/ruby/spec/credentials_spec.rb index 4d932db937..47b42aed29 100644 --- a/src/ruby/spec/credentials_spec.rb +++ b/src/ruby/spec/credentials_spec.rb @@ -29,7 +29,6 @@ require 'grpc' - def load_test_certs test_root = File.join(File.dirname(__FILE__), 'testdata') files = ['ca.pem', 'server1.pem', 'server1.key'] @@ -39,9 +38,7 @@ end Credentials = GRPC::Core::Credentials describe Credentials do - describe '#new' do - it 'can be constructed with fake inputs' do expect { Credentials.new('root_certs', 'key', 'cert') }.not_to raise_error end @@ -58,30 +55,23 @@ describe Credentials do it 'cannot be constructed with a nil server roots' do _, client_key, client_chain = load_test_certs - blk = Proc.new { Credentials.new(nil, client_key, client_chain) } + blk = proc { Credentials.new(nil, client_key, client_chain) } expect(&blk).to raise_error end - end describe '#compose' do - it 'can be completed OK' do certs = load_test_certs cred1 = Credentials.new(*certs) cred2 = Credentials.new(*certs) expect { cred1.compose(cred2) }.to_not raise_error end - end describe 'Credentials#default' do - it 'is not implemented yet' do - expect { Credentials.default() }.to raise_error RuntimeError + expect { Credentials.default }.to raise_error RuntimeError end - end - - end diff --git a/src/ruby/spec/event_spec.rb b/src/ruby/spec/event_spec.rb index a61b926dea..5dec07e1ed 100644 --- a/src/ruby/spec/event_spec.rb +++ b/src/ruby/spec/event_spec.rb @@ -30,25 +30,23 @@ require 'grpc' describe GRPC::Core::CompletionType do - before(:each) do @known_types = { - :QUEUE_SHUTDOWN => 0, - :READ => 1, - :INVOKE_ACCEPTED => 2, - :WRITE_ACCEPTED => 3, - :FINISH_ACCEPTED => 4, - :CLIENT_METADATA_READ => 5, - :FINISHED => 6, - :SERVER_RPC_NEW => 7, - :RESERVED => 8 + QUEUE_SHUTDOWN: 0, + READ: 1, + INVOKE_ACCEPTED: 2, + WRITE_ACCEPTED: 3, + FINISH_ACCEPTED: 4, + CLIENT_METADATA_READ: 5, + FINISHED: 6, + SERVER_RPC_NEW: 7, + RESERVED: 8 } end it 'should have all the known types' do mod = GRPC::Core::CompletionType - blk = Proc.new { Hash[mod.constants.collect { |c| [c, mod.const_get(c)] }] } + blk = proc { Hash[mod.constants.collect { |c| [c, mod.const_get(c)] }] } expect(blk.call).to eq(@known_types) end - end diff --git a/src/ruby/spec/generic/active_call_spec.rb b/src/ruby/spec/generic/active_call_spec.rb index bb73eef47c..898022f185 100644 --- a/src/ruby/spec/generic/active_call_spec.rb +++ b/src/ruby/spec/generic/active_call_spec.rb @@ -38,9 +38,9 @@ describe GRPC::ActiveCall do CompletionType = GRPC::Core::CompletionType before(:each) do - @pass_through = Proc.new { |x| x } + @pass_through = proc { |x| x } @server_tag = Object.new - @server_done_tag, meta_tag = Object.new + @server_done_tag = Object.new @tag = Object.new @client_queue = GRPC::Core::CompletionQueue.new @@ -70,7 +70,7 @@ describe GRPC::ActiveCall do describe '#multi_req_view' do it 'exposes a fixed subset of the ActiveCall methods' do - want = ['cancelled', 'deadline', 'each_remote_read', 'shutdown'] + want = %w(cancelled, deadline, each_remote_read, shutdown) v = @client_call.multi_req_view want.each do |w| expect(v.methods.include?(w)) @@ -80,7 +80,7 @@ describe GRPC::ActiveCall do describe '#single_req_view' do it 'exposes a fixed subset of the ActiveCall methods' do - want = ['cancelled', 'deadline', 'shutdown'] + want = %w(cancelled, deadline, shutdown) v = @client_call.single_req_view want.each do |w| expect(v.methods.include?(w)) @@ -110,7 +110,7 @@ describe GRPC::ActiveCall do # Accept the call, and verify that the server reads the response ok. ev.call.server_accept(@client_queue, @server_tag) - ev.call.server_end_initial_metadata() + ev.call.server_end_initial_metadata server_call = ActiveCall.new(ev.call, @client_queue, @pass_through, @pass_through, deadline) expect(server_call.remote_read).to eq(msg) @@ -120,7 +120,7 @@ describe GRPC::ActiveCall do call = make_test_call done_tag, meta_tag = ActiveCall.client_start_invoke(call, @client_queue, deadline) - marshal = Proc.new { |x| 'marshalled:' + x } + marshal = proc { |x| 'marshalled:' + x } client_call = ActiveCall.new(call, @client_queue, marshal, @pass_through, deadline, finished_tag: done_tag, @@ -132,33 +132,29 @@ describe GRPC::ActiveCall do @server.request_call(@server_tag) ev = @server_queue.next(deadline) ev.call.server_accept(@client_queue, @server_tag) - ev.call.server_end_initial_metadata() + ev.call.server_end_initial_metadata server_call = ActiveCall.new(ev.call, @client_queue, @pass_through, @pass_through, deadline) expect(server_call.remote_read).to eq('marshalled:' + msg) end - end describe '#client_start_invoke' do - it 'sends keywords as metadata to the server when the are present' do - call, pass_through = make_test_call, Proc.new { |x| x } - done_tag, meta_tag = ActiveCall.client_start_invoke(call, @client_queue, - deadline, k1: 'v1', - k2: 'v2') + call = make_test_call + ActiveCall.client_start_invoke(call, @client_queue, deadline, + k1: 'v1', k2: 'v2') @server.request_call(@server_tag) ev = @server_queue.next(deadline) expect(ev).to_not be_nil expect(ev.result.metadata['k1']).to eq('v1') expect(ev.result.metadata['k2']).to eq('v2') end - end describe '#remote_read' do it 'reads the response sent by a server' do - call, pass_through = make_test_call, Proc.new { |x| x } + call = make_test_call done_tag, meta_tag = ActiveCall.client_start_invoke(call, @client_queue, deadline) client_call = ActiveCall.new(call, @client_queue, @pass_through, @@ -173,7 +169,7 @@ describe GRPC::ActiveCall do end it 'saves metadata { status=200 } when the server adds no metadata' do - call, pass_through = make_test_call, Proc.new { |x| x } + call = make_test_call done_tag, meta_tag = ActiveCall.client_start_invoke(call, @client_queue, deadline) client_call = ActiveCall.new(call, @client_queue, @pass_through, @@ -186,11 +182,11 @@ describe GRPC::ActiveCall do server_call.remote_send('ignore me') expect(client_call.metadata).to be_nil client_call.remote_read - expect(client_call.metadata).to eq({':status' => '200'}) + expect(client_call.metadata).to eq(':status' => '200') end it 'saves metadata add by the server' do - call, pass_through = make_test_call, Proc.new { |x| x } + call = make_test_call done_tag, meta_tag = ActiveCall.client_start_invoke(call, @client_queue, deadline) client_call = ActiveCall.new(call, @client_queue, @pass_through, @@ -203,13 +199,12 @@ describe GRPC::ActiveCall do server_call.remote_send('ignore me') expect(client_call.metadata).to be_nil client_call.remote_read - expect(client_call.metadata).to eq({':status' => '200', 'k1' => 'v1', - 'k2' => 'v2'}) + expected = { ':status' => '200', 'k1' => 'v1', 'k2' => 'v2' } + expect(client_call.metadata).to eq(expected) end - it 'get a nil msg before a status when an OK status is sent' do - call, pass_through = make_test_call, Proc.new { |x| x } + call = make_test_call done_tag, meta_tag = ActiveCall.client_start_invoke(call, @client_queue, deadline) client_call = ActiveCall.new(call, @client_queue, @pass_through, @@ -227,12 +222,11 @@ describe GRPC::ActiveCall do expect(res).to be_nil end - it 'unmarshals the response using the unmarshal func' do call = make_test_call done_tag, meta_tag = ActiveCall.client_start_invoke(call, @client_queue, deadline) - unmarshal = Proc.new { |x| 'unmarshalled:' + x } + unmarshal = proc { |x| 'unmarshalled:' + x } client_call = ActiveCall.new(call, @client_queue, @pass_through, unmarshal, deadline, finished_tag: done_tag, @@ -245,7 +239,6 @@ describe GRPC::ActiveCall do server_call.remote_send('server_response') expect(client_call.remote_read).to eq('unmarshalled:server_response') end - end describe '#each_remote_read' do @@ -298,7 +291,6 @@ describe GRPC::ActiveCall do server_call.send_status(OK, 'OK') expect { e.next }.to raise_error(StopIteration) end - end describe '#writes_done' do @@ -357,7 +349,6 @@ describe GRPC::ActiveCall do expect { client_call.writes_done(true) }.to_not raise_error expect { server_call.finished }.to_not raise_error end - end def expect_server_to_receive(sent_text, **kw) @@ -371,7 +362,7 @@ describe GRPC::ActiveCall do ev = @server_queue.next(deadline) ev.call.add_metadata(kw) ev.call.server_accept(@client_queue, @server_done_tag) - ev.call.server_end_initial_metadata() + ev.call.server_end_initial_metadata ActiveCall.new(ev.call, @client_queue, @pass_through, @pass_through, deadline, finished_tag: @server_done_tag) @@ -384,5 +375,4 @@ describe GRPC::ActiveCall do def deadline Time.now + 0.25 # in 0.25 seconds; arbitrary end - end diff --git a/src/ruby/spec/generic/client_stub_spec.rb b/src/ruby/spec/generic/client_stub_spec.rb index 2db8718d1a..8ebe48bc4c 100644 --- a/src/ruby/spec/generic/client_stub_spec.rb +++ b/src/ruby/spec/generic/client_stub_spec.rb @@ -31,7 +31,7 @@ require 'grpc' require 'xray/thread_dump_signal_handler' require_relative '../port_picker' -NOOP = Proc.new { |x| x } +NOOP = proc { |x| x } def wakey_thread(&blk) awake_mutex, awake_cond = Mutex.new, ConditionVariable.new @@ -52,7 +52,6 @@ include GRPC::Core::StatusCodes include GRPC::Core::TimeConsts describe 'ClientStub' do - before(:each) do Thread.abort_on_exception = true @server = nil @@ -67,11 +66,10 @@ describe 'ClientStub' do end describe '#new' do - it 'can be created from a host and args' do host = new_test_host - opts = {:a_channel_arg => 'an_arg'} - blk = Proc.new do + opts = { a_channel_arg: 'an_arg' } + blk = proc do GRPC::ClientStub.new(host, @cq, **opts) end expect(&blk).not_to raise_error @@ -79,8 +77,8 @@ describe 'ClientStub' do it 'can be created with a default deadline' do host = new_test_host - opts = {:a_channel_arg => 'an_arg', :deadline => 5} - blk = Proc.new do + opts = { a_channel_arg: 'an_arg', deadline: 5 } + blk = proc do GRPC::ClientStub.new(host, @cq, **opts) end expect(&blk).not_to raise_error @@ -88,8 +86,8 @@ describe 'ClientStub' do it 'can be created with an channel override' do host = new_test_host - opts = {:a_channel_arg => 'an_arg', :channel_override => @ch} - blk = Proc.new do + opts = { a_channel_arg: 'an_arg', channel_override: @ch } + blk = proc do GRPC::ClientStub.new(host, @cq, **opts) end expect(&blk).not_to raise_error @@ -97,8 +95,8 @@ describe 'ClientStub' do it 'cannot be created with a bad channel override' do host = new_test_host - blk = Proc.new do - opts = {:a_channel_arg => 'an_arg', :channel_override => Object.new} + blk = proc do + opts = { a_channel_arg: 'an_arg', channel_override: Object.new } GRPC::ClientStub.new(host, @cq, **opts) end expect(&blk).to raise_error @@ -106,8 +104,8 @@ describe 'ClientStub' do it 'cannot be created with bad credentials' do host = new_test_host - blk = Proc.new do - opts = {:a_channel_arg => 'an_arg', :creds => Object.new} + blk = proc do + opts = { a_channel_arg: 'an_arg', creds: Object.new } GRPC::ClientStub.new(host, @cq, **opts) end expect(&blk).to raise_error @@ -116,17 +114,16 @@ describe 'ClientStub' do it 'can be created with test test credentials' do certs = load_test_certs host = new_test_host - blk = Proc.new do + blk = proc do opts = { GRPC::Core::Channel::SSL_TARGET => 'foo.test.google.com', - :a_channel_arg => 'an_arg', - :creds => GRPC::Core::Credentials.new(certs[0], nil, nil) + a_channel_arg: 'an_arg', + creds: GRPC::Core::Credentials.new(certs[0], nil, nil) } GRPC::ClientStub.new(host, @cq, **opts) end expect(&blk).to_not raise_error end - end describe '#request_response' do @@ -135,7 +132,6 @@ describe 'ClientStub' do end shared_examples 'request response' do - it 'should send a request to/receive a reply from a server' do host = new_test_host th = run_request_response(host, @sent_msg, @resp, @pass) @@ -146,8 +142,8 @@ describe 'ClientStub' do it 'should send metadata to the server ok' do host = new_test_host - th = run_request_response(host, @sent_msg, @resp, @pass, k1: 'v1', - k2: 'v2') + th = run_request_response(host, @sent_msg, @resp, @pass, + k1: 'v1', k2: 'v2') stub = GRPC::ClientStub.new(host, @cq) expect(get_response(stub)).to eq(@resp) th.join @@ -157,7 +153,10 @@ describe 'ClientStub' do host = new_test_host th = run_request_response(host, @sent_msg, @resp, @pass, k1: 'updated-v1', k2: 'v2') - update_md = Proc.new { |md| md[:k1] = 'updated-v1'; md } + update_md = proc do |md| + md[:k1] = 'updated-v1' + md + end stub = GRPC::ClientStub.new(host, @cq, update_metadata: update_md) expect(get_response(stub)).to eq(@resp) th.join @@ -167,7 +166,7 @@ describe 'ClientStub' do alt_host = new_test_host th = run_request_response(alt_host, @sent_msg, @resp, @pass) ch = GRPC::Core::Channel.new(alt_host, nil) - stub = GRPC::ClientStub.new('ignored-host', @cq, channel_override:ch) + stub = GRPC::ClientStub.new('ignored-host', @cq, channel_override: ch) expect(get_response(stub)).to eq(@resp) th.join end @@ -176,45 +175,37 @@ describe 'ClientStub' do host = new_test_host th = run_request_response(host, @sent_msg, @resp, @fail) stub = GRPC::ClientStub.new(host, @cq) - blk = Proc.new { get_response(stub) } + blk = proc { get_response(stub) } expect(&blk).to raise_error(GRPC::BadStatus) th.join end - end describe 'without a call operation' do - def get_response(stub) - stub.request_response(@method, @sent_msg, NOOP, NOOP, k1: 'v1', - k2: 'v2') + stub.request_response(@method, @sent_msg, NOOP, NOOP, + k1: 'v1', k2: 'v2') end it_behaves_like 'request response' - end describe 'via a call operation' do - def get_response(stub) op = stub.request_response(@method, @sent_msg, NOOP, NOOP, - return_op:true, k1: 'v1', k2: 'v2') + return_op: true, k1: 'v1', k2: 'v2') expect(op).to be_a(GRPC::ActiveCall::Operation) - op.execute() + op.execute end it_behaves_like 'request response' - end - end describe '#client_streamer' do - shared_examples 'client streaming' do - before(:each) do - @sent_msgs = Array.new(3) { |i| 'msg_' + (i+1).to_s } + @sent_msgs = Array.new(3) { |i| 'msg_' + (i + 1).to_s } @resp = 'a_reply' end @@ -228,19 +219,21 @@ describe 'ClientStub' do it 'should send metadata to the server ok' do host = new_test_host - th = run_client_streamer(host, @sent_msgs, @resp, @pass, k1: 'v1', - k2: 'v2') + th = run_client_streamer(host, @sent_msgs, @resp, @pass, + k1: 'v1', k2: 'v2') stub = GRPC::ClientStub.new(host, @cq) expect(get_response(stub)).to eq(@resp) th.join end - it 'should update the sent metadata with a provided metadata updater' do host = new_test_host th = run_client_streamer(host, @sent_msgs, @resp, @pass, k1: 'updated-v1', k2: 'v2') - update_md = Proc.new { |md| md[:k1] = 'updated-v1'; md } + update_md = proc do |md| + md[:k1] = 'updated-v1' + md + end stub = GRPC::ClientStub.new(host, @cq, update_metadata: update_md) expect(get_response(stub)).to eq(@resp) th.join @@ -250,46 +243,38 @@ describe 'ClientStub' do host = new_test_host th = run_client_streamer(host, @sent_msgs, @resp, @fail) stub = GRPC::ClientStub.new(host, @cq) - blk = Proc.new { get_response(stub) } + blk = proc { get_response(stub) } expect(&blk).to raise_error(GRPC::BadStatus) th.join end - end describe 'without a call operation' do - def get_response(stub) - stub.client_streamer(@method, @sent_msgs, NOOP, NOOP, k1: 'v1', - k2: 'v2') + stub.client_streamer(@method, @sent_msgs, NOOP, NOOP, + k1: 'v1', k2: 'v2') end it_behaves_like 'client streaming' - end describe 'via a call operation' do - def get_response(stub) op = stub.client_streamer(@method, @sent_msgs, NOOP, NOOP, - return_op:true, k1: 'v1', k2: 'v2') + return_op: true, k1: 'v1', k2: 'v2') expect(op).to be_a(GRPC::ActiveCall::Operation) - resp = op.execute() + op.execute end it_behaves_like 'client streaming' - end - end describe '#server_streamer' do - shared_examples 'server streaming' do - before(:each) do @sent_msg = 'a_msg' - @replys = Array.new(3) { |i| 'reply_' + (i+1).to_s } + @replys = Array.new(3) { |i| 'reply_' + (i + 1).to_s } end it 'should send a request to/receive replies from a server' do @@ -311,8 +296,8 @@ describe 'ClientStub' do it 'should send metadata to the server ok' do host = new_test_host - th = run_server_streamer(host, @sent_msg, @replys, @fail, k1: 'v1', - k2: 'v2') + th = run_server_streamer(host, @sent_msg, @replys, @fail, + k1: 'v1', k2: 'v2') stub = GRPC::ClientStub.new(host, @cq) e = get_responses(stub) expect { e.collect { |r| r } }.to raise_error(GRPC::BadStatus) @@ -323,55 +308,50 @@ describe 'ClientStub' do host = new_test_host th = run_server_streamer(host, @sent_msg, @replys, @pass, k1: 'updated-v1', k2: 'v2') - update_md = Proc.new { |md| md[:k1] = 'updated-v1'; md } + update_md = proc do |md| + md[:k1] = 'updated-v1' + md + end stub = GRPC::ClientStub.new(host, @cq, update_metadata: update_md) e = get_responses(stub) expect(e.collect { |r| r }).to eq(@replys) th.join end - end describe 'without a call operation' do - def get_responses(stub) - e = stub.server_streamer(@method, @sent_msg, NOOP, NOOP, k1: 'v1', - k2: 'v2') + e = stub.server_streamer(@method, @sent_msg, NOOP, NOOP, + k1: 'v1', k2: 'v2') expect(e).to be_a(Enumerator) e end it_behaves_like 'server streaming' - end describe 'via a call operation' do - def get_responses(stub) op = stub.server_streamer(@method, @sent_msg, NOOP, NOOP, - return_op:true, k1: 'v1', k2: 'v2') + return_op: true, k1: 'v1', k2: 'v2') expect(op).to be_a(GRPC::ActiveCall::Operation) - e = op.execute() + e = op.execute expect(e).to be_a(Enumerator) e end it_behaves_like 'server streaming' - end - end describe '#bidi_streamer' do - shared_examples 'bidi streaming' do - before(:each) do - @sent_msgs = Array.new(3) { |i| 'msg_' + (i+1).to_s } - @replys = Array.new(3) { |i| 'reply_' + (i+1).to_s } + @sent_msgs = Array.new(3) { |i| 'msg_' + (i + 1).to_s } + @replys = Array.new(3) { |i| 'reply_' + (i + 1).to_s } end - it 'supports sending all the requests first', :bidi => true do + it 'supports sending all the requests first', bidi: true do host = new_test_host th = run_bidi_streamer_handle_inputs_first(host, @sent_msgs, @replys, @pass) @@ -381,7 +361,7 @@ describe 'ClientStub' do th.join end - it 'supports client-initiated ping pong', :bidi => true do + it 'supports client-initiated ping pong', bidi: true do host = new_test_host th = run_bidi_streamer_echo_ping_pong(host, @sent_msgs, @pass, true) stub = GRPC::ClientStub.new(host, @cq) @@ -396,7 +376,7 @@ describe 'ClientStub' do # servers don't know if all the client metadata has been sent until # they receive a message from the client. Without receiving all the # metadata, the server does not accept the call, so this test hangs. - xit 'supports a server-initiated ping pong', :bidi => true do + xit 'supports a server-initiated ping pong', bidi: true do host = new_test_host th = run_bidi_streamer_echo_ping_pong(host, @sent_msgs, @pass, false) stub = GRPC::ClientStub.new(host, @cq) @@ -404,11 +384,9 @@ describe 'ClientStub' do expect(e.collect { |r| r }).to eq(@sent_msgs) th.join end - end describe 'without a call operation' do - def get_responses(stub) e = stub.bidi_streamer(@method, @sent_msgs, NOOP, NOOP) expect(e).to be_a(Enumerator) @@ -416,13 +394,12 @@ describe 'ClientStub' do end it_behaves_like 'bidi streaming' - end describe 'via a call operation' do - def get_responses(stub) - op = stub.bidi_streamer(@method, @sent_msgs, NOOP, NOOP, return_op:true) + op = stub.bidi_streamer(@method, @sent_msgs, NOOP, NOOP, + return_op: true) expect(op).to be_a(GRPC::ActiveCall::Operation) e = op.execute expect(e).to be_a(Enumerator) @@ -430,9 +407,7 @@ describe 'ClientStub' do end it_behaves_like 'bidi streaming' - end - end def run_server_streamer(hostname, expected_input, replys, status, **kw) @@ -514,14 +489,13 @@ describe 'ClientStub' do def expect_server_to_be_invoked(hostname, awake_mutex, awake_cond) server_queue = start_test_server(hostname, awake_mutex, awake_cond) - test_deadline = Time.now + 10 # fail tests after 10 seconds ev = server_queue.pluck(@server_tag, INFINITE_FUTURE) - raise OutOfTime if ev.nil? + fail OutOfTime if ev.nil? server_call = ev.call server_call.metadata = ev.result.metadata finished_tag = Object.new server_call.server_accept(server_queue, finished_tag) - server_call.server_end_initial_metadata() + server_call.server_end_initial_metadata GRPC::ActiveCall.new(server_call, server_queue, NOOP, NOOP, INFINITE_FUTURE, finished_tag: finished_tag) end @@ -530,5 +504,4 @@ describe 'ClientStub' do port = find_unused_tcp_port "localhost:#{port}" end - end diff --git a/src/ruby/spec/generic/rpc_desc_spec.rb b/src/ruby/spec/generic/rpc_desc_spec.rb index efef7e4686..ac0b5c51f4 100644 --- a/src/ruby/spec/generic/rpc_desc_spec.rb +++ b/src/ruby/spec/generic/rpc_desc_spec.rb @@ -30,9 +30,7 @@ require 'grpc' require 'grpc/generic/rpc_desc' - describe GRPC::RpcDesc do - RpcDesc = GRPC::RpcDesc Stream = RpcDesc::Stream OK = GRPC::Core::StatusCodes::OK @@ -56,7 +54,6 @@ describe GRPC::RpcDesc do end describe '#run_server_method' do - describe 'for request responses' do before(:each) do @call = double('active_call') @@ -78,7 +75,7 @@ describe GRPC::RpcDesc do it 'absorbs EventError with no further action' do expect(@call).to receive(:remote_read).once.and_raise(EventError) - blk = Proc.new do + blk = proc do @request_response.run_server_method(@call, method(:fake_reqresp)) end expect(&blk).to_not raise_error @@ -86,7 +83,7 @@ describe GRPC::RpcDesc do it 'absorbs CallError with no further action' do expect(@call).to receive(:remote_read).once.and_raise(CallError) - blk = Proc.new do + blk = proc do @request_response.run_server_method(@call, method(:fake_reqresp)) end expect(&blk).to_not raise_error @@ -100,7 +97,6 @@ describe GRPC::RpcDesc do expect(@call).to receive(:finished).once @request_response.run_server_method(@call, method(:fake_reqresp)) end - end describe 'for client streamers' do @@ -122,7 +118,7 @@ describe GRPC::RpcDesc do it 'absorbs EventError with no further action' do expect(@call).to receive(:remote_send).once.and_raise(EventError) - blk = Proc.new do + blk = proc do @client_streamer.run_server_method(@call, method(:fake_clstream)) end expect(&blk).to_not raise_error @@ -130,20 +126,18 @@ describe GRPC::RpcDesc do it 'absorbs CallError with no further action' do expect(@call).to receive(:remote_send).once.and_raise(CallError) - blk = Proc.new do + blk = proc do @client_streamer.run_server_method(@call, method(:fake_clstream)) end expect(&blk).to_not raise_error end it 'sends a response and closes the stream if there no errors' do - req = Object.new expect(@call).to receive(:remote_send).once.with(@ok_response) expect(@call).to receive(:send_status).once.with(OK, 'OK') expect(@call).to receive(:finished).once @client_streamer.run_server_method(@call, method(:fake_clstream)) end - end describe 'for server streaming' do @@ -167,7 +161,7 @@ describe GRPC::RpcDesc do it 'absorbs EventError with no further action' do expect(@call).to receive(:remote_read).once.and_raise(EventError) - blk = Proc.new do + blk = proc do @server_streamer.run_server_method(@call, method(:fake_svstream)) end expect(&blk).to_not raise_error @@ -175,7 +169,7 @@ describe GRPC::RpcDesc do it 'absorbs CallError with no further action' do expect(@call).to receive(:remote_read).once.and_raise(CallError) - blk = Proc.new do + blk = proc do @server_streamer.run_server_method(@call, method(:fake_svstream)) end expect(&blk).to_not raise_error @@ -189,7 +183,6 @@ describe GRPC::RpcDesc do expect(@call).to receive(:finished).once @server_streamer.run_server_method(@call, method(:fake_svstream)) end - end describe 'for bidi streamers' do @@ -215,30 +208,27 @@ describe GRPC::RpcDesc do end it 'closes the stream if there no errors' do - req = Object.new expect(@call).to receive(:run_server_bidi) expect(@call).to receive(:send_status).once.with(OK, 'OK') expect(@call).to receive(:finished).once @bidi_streamer.run_server_method(@call, method(:fake_bidistream)) end - end - end describe '#assert_arity_matches' do def no_arg end - def fake_clstream(arg) + def fake_clstream(_arg) end - def fake_svstream(arg1, arg2) + def fake_svstream(_arg1, _arg2) end it 'raises when a request_response does not have 2 args' do [:fake_clstream, :no_arg].each do |mth| - blk = Proc.new do + blk = proc do @request_response.assert_arity_matches(method(mth)) end expect(&blk).to raise_error @@ -246,7 +236,7 @@ describe GRPC::RpcDesc do end it 'passes when a request_response has 2 args' do - blk = Proc.new do + blk = proc do @request_response.assert_arity_matches(method(:fake_svstream)) end expect(&blk).to_not raise_error @@ -254,7 +244,7 @@ describe GRPC::RpcDesc do it 'raises when a server_streamer does not have 2 args' do [:fake_clstream, :no_arg].each do |mth| - blk = Proc.new do + blk = proc do @server_streamer.assert_arity_matches(method(mth)) end expect(&blk).to raise_error @@ -262,7 +252,7 @@ describe GRPC::RpcDesc do end it 'passes when a server_streamer has 2 args' do - blk = Proc.new do + blk = proc do @server_streamer.assert_arity_matches(method(:fake_svstream)) end expect(&blk).to_not raise_error @@ -270,7 +260,7 @@ describe GRPC::RpcDesc do it 'raises when a client streamer does not have 1 arg' do [:fake_svstream, :no_arg].each do |mth| - blk = Proc.new do + blk = proc do @client_streamer.assert_arity_matches(method(mth)) end expect(&blk).to raise_error @@ -278,16 +268,15 @@ describe GRPC::RpcDesc do end it 'passes when a client_streamer has 1 arg' do - blk = Proc.new do + blk = proc do @client_streamer.assert_arity_matches(method(:fake_clstream)) end expect(&blk).to_not raise_error end - it 'raises when a bidi streamer does not have 1 arg' do [:fake_svstream, :no_arg].each do |mth| - blk = Proc.new do + blk = proc do @bidi_streamer.assert_arity_matches(method(mth)) end expect(&blk).to raise_error @@ -295,88 +284,78 @@ describe GRPC::RpcDesc do end it 'passes when a bidi streamer has 1 arg' do - blk = Proc.new do + blk = proc do @bidi_streamer.assert_arity_matches(method(:fake_clstream)) end expect(&blk).to_not raise_error end - end - describe '#is_request_response?' do - + describe '#request_response?' do it 'is true only input and output are both not Streams' do - expect(@request_response.is_request_response?).to be(true) - expect(@client_streamer.is_request_response?).to be(false) - expect(@bidi_streamer.is_request_response?).to be(false) - expect(@server_streamer.is_request_response?).to be(false) + expect(@request_response.request_response?).to be(true) + expect(@client_streamer.request_response?).to be(false) + expect(@bidi_streamer.request_response?).to be(false) + expect(@server_streamer.request_response?).to be(false) end - end - describe '#is_client_streamer?' do - + describe '#client_streamer?' do it 'is true only when input is a Stream and output is not a Stream' do - expect(@client_streamer.is_client_streamer?).to be(true) - expect(@request_response.is_client_streamer?).to be(false) - expect(@server_streamer.is_client_streamer?).to be(false) - expect(@bidi_streamer.is_client_streamer?).to be(false) + expect(@client_streamer.client_streamer?).to be(true) + expect(@request_response.client_streamer?).to be(false) + expect(@server_streamer.client_streamer?).to be(false) + expect(@bidi_streamer.client_streamer?).to be(false) end - end - describe '#is_server_streamer?' do - + describe '#server_streamer?' do it 'is true only when output is a Stream and input is not a Stream' do - expect(@server_streamer.is_server_streamer?).to be(true) - expect(@client_streamer.is_server_streamer?).to be(false) - expect(@request_response.is_server_streamer?).to be(false) - expect(@bidi_streamer.is_server_streamer?).to be(false) + expect(@server_streamer.server_streamer?).to be(true) + expect(@client_streamer.server_streamer?).to be(false) + expect(@request_response.server_streamer?).to be(false) + expect(@bidi_streamer.server_streamer?).to be(false) end - end - describe '#is_bidi_streamer?' do - + describe '#bidi_streamer?' do it 'is true only when output is a Stream and input is a Stream' do - expect(@bidi_streamer.is_bidi_streamer?).to be(true) - expect(@server_streamer.is_bidi_streamer?).to be(false) - expect(@client_streamer.is_bidi_streamer?).to be(false) - expect(@request_response.is_bidi_streamer?).to be(false) + expect(@bidi_streamer.bidi_streamer?).to be(true) + expect(@server_streamer.bidi_streamer?).to be(false) + expect(@client_streamer.bidi_streamer?).to be(false) + expect(@request_response.bidi_streamer?).to be(false) end - end - def fake_reqresp(req, call) + def fake_reqresp(_req, _call) @ok_response end - def fake_clstream(call) + def fake_clstream(_call) @ok_response end - def fake_svstream(req, call) + def fake_svstream(_req, _call) [@ok_response, @ok_response] end def fake_bidistream(an_array) - return an_array + an_array end - def bad_status(req, call) - raise GRPC::BadStatus.new(@bs_code, 'NOK') + def bad_status(_req, _call) + fail GRPC::BadStatus.new(@bs_code, 'NOK') end - def other_error(req, call) - raise ArgumentError.new('other error') + def other_error(_req, _call) + fail(ArgumentError, 'other error') end - def bad_status_alt(call) - raise GRPC::BadStatus.new(@bs_code, 'NOK') + def bad_status_alt(_call) + fail GRPC::BadStatus.new(@bs_code, 'NOK') end - def other_error_alt(call) - raise ArgumentError.new('other error') + def other_error_alt(_call) + fail(ArgumentError, 'other error') end - end diff --git a/src/ruby/spec/generic/rpc_server_pool_spec.rb b/src/ruby/spec/generic/rpc_server_pool_spec.rb index 83979ec164..27fabd9c31 100644 --- a/src/ruby/spec/generic/rpc_server_pool_spec.rb +++ b/src/ruby/spec/generic/rpc_server_pool_spec.rb @@ -33,9 +33,7 @@ require 'xray/thread_dump_signal_handler' Pool = GRPC::RpcServer::Pool describe Pool do - describe '#new' do - it 'raises if a non-positive size is used' do expect { Pool.new(0) }.to raise_error expect { Pool.new(-1) }.to raise_error @@ -45,11 +43,9 @@ describe Pool do it 'is constructed OK with a positive size' do expect { Pool.new(1) }.not_to raise_error end - end describe '#jobs_waiting' do - it 'at start, it is zero' do p = Pool.new(1) expect(p.jobs_waiting).to be(0) @@ -57,74 +53,67 @@ describe Pool do it 'it increases, with each scheduled job if the pool is not running' do p = Pool.new(1) - job = Proc.new { } + job = proc {} expect(p.jobs_waiting).to be(0) 5.times do |i| p.schedule(&job) expect(p.jobs_waiting).to be(i + 1) end - end it 'it decreases as jobs are run' do p = Pool.new(1) - job = Proc.new { } + job = proc {} expect(p.jobs_waiting).to be(0) - 3.times do |i| + 3.times do p.schedule(&job) end p.start sleep 2 expect(p.jobs_waiting).to be(0) end - end describe '#schedule' do - it 'throws if the pool is already stopped' do p = Pool.new(1) - p.stop() - job = Proc.new { } + p.stop + job = proc {} expect { p.schedule(&job) }.to raise_error end it 'adds jobs that get run by the pool' do p = Pool.new(1) - p.start() + p.start o, q = Object.new, Queue.new - job = Proc.new { q.push(o) } + job = proc { q.push(o) } p.schedule(&job) expect(q.pop).to be(o) p.stop end - end describe '#stop' do - it 'works when there are no scheduled tasks' do p = Pool.new(1) - expect { p.stop() }.not_to raise_error + expect { p.stop }.not_to raise_error end it 'stops jobs when there are long running jobs' do p = Pool.new(1) - p.start() + p.start o, q = Object.new, Queue.new - job = Proc.new do + job = proc do sleep(5) # long running q.push(o) end p.schedule(&job) sleep(1) # should ensure the long job gets scheduled - expect { p.stop() }.not_to raise_error + expect { p.stop }.not_to raise_error end - end describe '#start' do - it 'runs pre-scheduled jobs' do p = Pool.new(2) o, q = Object.new, Queue.new @@ -146,7 +135,5 @@ describe Pool do end p.stop end - end - end diff --git a/src/ruby/spec/generic/rpc_server_spec.rb b/src/ruby/spec/generic/rpc_server_spec.rb index 5997fdb363..cd4888a3b4 100644 --- a/src/ruby/spec/generic/rpc_server_spec.rb +++ b/src/ruby/spec/generic/rpc_server_spec.rb @@ -37,33 +37,37 @@ def load_test_certs files.map { |f| File.open(File.join(test_root, f)).read } end +# A test message class EchoMsg - def self.marshal(o) + def self.marshal(_o) '' end - def self.unmarshal(o) + def self.unmarshal(_o) EchoMsg.new end end +# A test service with no methods. class EmptyService include GRPC::GenericService end +# A test service without an implementation. class NoRpcImplementation include GRPC::GenericService rpc :an_rpc, EchoMsg, EchoMsg end +# A test service with an implementation. class EchoService include GRPC::GenericService rpc :an_rpc, EchoMsg, EchoMsg - def initialize(default_var='ignored') + def initialize(_default_var = 'ignored') end - def an_rpc(req, call) + def an_rpc(req, _call) logger.info('echo service received a request') req end @@ -71,14 +75,15 @@ end EchoStub = EchoService.rpc_stub_class +# A slow test service. class SlowService include GRPC::GenericService rpc :an_rpc, EchoMsg, EchoMsg - def initialize(default_var='ignored') + def initialize(_default_var = 'ignored') end - def an_rpc(req, call) + def an_rpc(req, _call) delay = 0.25 logger.info("starting a slow #{delay} rpc") sleep delay @@ -89,7 +94,6 @@ end SlowStub = SlowService.rpc_stub_class describe GRPC::RpcServer do - RpcServer = GRPC::RpcServer StatusCodes = GRPC::Core::StatusCodes @@ -97,7 +101,7 @@ describe GRPC::RpcServer do @method = 'an_rpc_method' @pass = 0 @fail = 1 - @noop = Proc.new { |x| x } + @noop = proc { |x| x } @server_queue = GRPC::Core::CompletionQueue.new port = find_unused_tcp_port @@ -112,18 +116,17 @@ describe GRPC::RpcServer do end describe '#new' do - it 'can be created with just some args' do - opts = {:a_channel_arg => 'an_arg'} - blk = Proc.new do + opts = { a_channel_arg: 'an_arg' } + blk = proc do RpcServer.new(**opts) end expect(&blk).not_to raise_error end it 'can be created with a default deadline' do - opts = {:a_channel_arg => 'an_arg', :deadline => 5} - blk = Proc.new do + opts = { a_channel_arg: 'an_arg', deadline: 5 } + blk = proc do RpcServer.new(**opts) end expect(&blk).not_to raise_error @@ -131,20 +134,20 @@ describe GRPC::RpcServer do it 'can be created with a completion queue override' do opts = { - :a_channel_arg => 'an_arg', - :completion_queue_override => @server_queue + a_channel_arg: 'an_arg', + completion_queue_override: @server_queue } - blk = Proc.new do + blk = proc do RpcServer.new(**opts) end expect(&blk).not_to raise_error end it 'cannot be created with a bad completion queue override' do - blk = Proc.new do + blk = proc do opts = { - :a_channel_arg => 'an_arg', - :completion_queue_override => Object.new + a_channel_arg: 'an_arg', + completion_queue_override: Object.new } RpcServer.new(**opts) end @@ -152,10 +155,10 @@ describe GRPC::RpcServer do end it 'cannot be created with invalid ServerCredentials' do - blk = Proc.new do + blk = proc do opts = { - :a_channel_arg => 'an_arg', - :creds => Object.new + a_channel_arg: 'an_arg', + creds: Object.new } RpcServer.new(**opts) end @@ -165,10 +168,10 @@ describe GRPC::RpcServer do it 'can be created with the creds as valid ServerCedentials' do certs = load_test_certs server_creds = GRPC::Core::ServerCredentials.new(nil, certs[1], certs[2]) - blk = Proc.new do + blk = proc do opts = { - :a_channel_arg => 'an_arg', - :creds => server_creds + a_channel_arg: 'an_arg', + creds: server_creds } RpcServer.new(**opts) end @@ -176,30 +179,28 @@ describe GRPC::RpcServer do end it 'can be created with a server override' do - opts = {:a_channel_arg => 'an_arg', :server_override => @server} - blk = Proc.new do + opts = { a_channel_arg: 'an_arg', server_override: @server } + blk = proc do RpcServer.new(**opts) end expect(&blk).not_to raise_error end it 'cannot be created with a bad server override' do - blk = Proc.new do + blk = proc do opts = { - :a_channel_arg => 'an_arg', - :server_override => Object.new + a_channel_arg: 'an_arg', + server_override: Object.new } RpcServer.new(**opts) end expect(&blk).to raise_error end - end describe '#stopped?' do - before(:each) do - opts = {:a_channel_arg => 'an_arg', :poll_period => 1} + opts = { a_channel_arg: 'an_arg', poll_period: 1 } @srv = RpcServer.new(**opts) end @@ -229,33 +230,31 @@ describe GRPC::RpcServer do expect(@srv.stopped?).to be(true) t.join end - end describe '#running?' do - it 'starts out false' do - opts = {:a_channel_arg => 'an_arg', :server_override => @server} + opts = { a_channel_arg: 'an_arg', server_override: @server } r = RpcServer.new(**opts) expect(r.running?).to be(false) end it 'is false after run is called with no services registered' do opts = { - :a_channel_arg => 'an_arg', - :poll_period => 1, - :server_override => @server + a_channel_arg: 'an_arg', + poll_period: 1, + server_override: @server } r = RpcServer.new(**opts) - r.run() + r.run expect(r.running?).to be(false) end it 'is true after run is called with a registered service' do opts = { - :a_channel_arg => 'an_arg', - :poll_period => 1, - :server_override => @server + a_channel_arg: 'an_arg', + poll_period: 1, + server_override: @server } r = RpcServer.new(**opts) r.handle(EchoService) @@ -265,13 +264,11 @@ describe GRPC::RpcServer do r.stop t.join end - end describe '#handle' do - before(:each) do - @opts = {:a_channel_arg => 'an_arg', :poll_period => 1} + @opts = { a_channel_arg: 'an_arg', poll_period: 1 } @srv = RpcServer.new(**@opts) end @@ -309,33 +306,30 @@ describe GRPC::RpcServer do @srv.handle(EchoService) expect { r.handle(EchoService) }.to raise_error end - end describe '#run' do - before(:each) do @client_opts = { - :channel_override => @ch + channel_override: @ch } @marshal = EchoService.rpc_descs[:an_rpc].marshal_proc @unmarshal = EchoService.rpc_descs[:an_rpc].unmarshal_proc(:output) server_opts = { - :server_override => @server, - :completion_queue_override => @server_queue, - :poll_period => 1 + server_override: @server, + completion_queue_override: @server_queue, + poll_period: 1 } @srv = RpcServer.new(**server_opts) end describe 'when running' do - it 'should return NOT_FOUND status for requests on unknown methods' do @srv.handle(EchoService) t = Thread.new { @srv.run } @srv.wait_till_running req = EchoMsg.new - blk = Proc.new do + blk = proc do cq = GRPC::Core::CompletionQueue.new stub = GRPC::ClientStub.new(@host, cq, **@client_opts) stub.request_response('/unknown', req, @marshal, @unmarshal) @@ -352,20 +346,19 @@ describe GRPC::RpcServer do req = EchoMsg.new n = 5 # arbitrary stub = EchoStub.new(@host, **@client_opts) - n.times { |x| expect(stub.an_rpc(req)).to be_a(EchoMsg) } + n.times { expect(stub.an_rpc(req)).to be_a(EchoMsg) } @srv.stop t.join end it 'should obtain responses for multiple parallel requests' do @srv.handle(EchoService) - t = Thread.new { @srv.run } + Thread.new { @srv.run } @srv.wait_till_running req, q = EchoMsg.new, Queue.new n = 5 # arbitrary threads = [] - n.times do |x| - cq = GRPC::Core::CompletionQueue.new + n.times do threads << Thread.new do stub = EchoStub.new(@host, **@client_opts) q << stub.an_rpc(req) @@ -373,44 +366,40 @@ describe GRPC::RpcServer do end n.times { expect(q.pop).to be_a(EchoMsg) } @srv.stop - threads.each { |t| t.join } + threads.each(&:join) end it 'should return UNAVAILABLE status if there too many jobs' do opts = { - :a_channel_arg => 'an_arg', - :server_override => @server, - :completion_queue_override => @server_queue, - :pool_size => 1, - :poll_period => 1, - :max_waiting_requests => 0 + a_channel_arg: 'an_arg', + server_override: @server, + completion_queue_override: @server_queue, + pool_size: 1, + poll_period: 1, + max_waiting_requests: 0 } alt_srv = RpcServer.new(**opts) alt_srv.handle(SlowService) - t = Thread.new { alt_srv.run } + Thread.new { alt_srv.run } alt_srv.wait_till_running req = EchoMsg.new n = 5 # arbitrary, use as many to ensure the server pool is exceeded threads = [] - _1_failed_as_unavailable = false - n.times do |x| + one_failed_as_unavailable = false + n.times do threads << Thread.new do - cq = GRPC::Core::CompletionQueue.new stub = SlowStub.new(@host, **@client_opts) begin stub.an_rpc(req) rescue GRPC::BadStatus => e - _1_failed_as_unavailable = e.code == StatusCodes::UNAVAILABLE + one_failed_as_unavailable = e.code == StatusCodes::UNAVAILABLE end end end - threads.each { |t| t.join } + threads.each(&:join) alt_srv.stop - expect(_1_failed_as_unavailable).to be(true) + expect(one_failed_as_unavailable).to be(true) end - end - end - end diff --git a/src/ruby/spec/generic/service_spec.rb b/src/ruby/spec/generic/service_spec.rb index a8e0c6f52f..29f2412631 100644 --- a/src/ruby/spec/generic/service_spec.rb +++ b/src/ruby/spec/generic/service_spec.rb @@ -31,23 +31,24 @@ require 'grpc' require 'grpc/generic/rpc_desc' require 'grpc/generic/service' - +# A test message that encodes/decodes using marshal/marshal. class GoodMsg - def self.marshal(o) + def self.marshal(_o) '' end - def self.unmarshal(o) + def self.unmarshal(_o) GoodMsg.new end end +# A test message that encodes/decodes using encode/decode. class EncodeDecodeMsg - def self.encode(o) + def self.encode(_o) '' end - def self.decode(o) + def self.decode(_o) GoodMsg.new end end @@ -55,7 +56,6 @@ end GenericService = GRPC::GenericService Dsl = GenericService::Dsl - describe 'String#underscore' do it 'should convert CamelCase to underscore separated' do expect('AnRPC'.underscore).to eq('an_rpc') @@ -66,20 +66,14 @@ describe 'String#underscore' do end describe Dsl do - it 'can be included in new classes' do - blk = Proc.new do - c = Class.new { include Dsl } - end + blk = proc { Class.new { include Dsl } } expect(&blk).to_not raise_error end - end describe GenericService do - describe 'including it' do - it 'adds a class method, rpc' do c = Class.new do include GenericService @@ -144,9 +138,8 @@ describe GenericService do end describe '#include' do - it 'raises if #rpc is missing an arg' do - blk = Proc.new do + blk = proc do Class.new do include GenericService rpc :AnRpc, GoodMsg @@ -154,7 +147,7 @@ describe GenericService do end expect(&blk).to raise_error ArgumentError - blk = Proc.new do + blk = proc do Class.new do include GenericService rpc :AnRpc @@ -164,9 +157,8 @@ describe GenericService do end describe 'when #rpc args are incorrect' do - it 'raises if an arg does not have the marshal or unmarshal methods' do - blk = Proc.new do + blk = proc do Class.new do include GenericService rpc :AnRpc, GoodMsg, Object @@ -176,13 +168,14 @@ describe GenericService do end it 'raises if a type arg only has the marshal method' do + # a bad message type with only a marshal method class OnlyMarshal def marshal(o) o end end - blk = Proc.new do + blk = proc do Class.new do include GenericService rpc :AnRpc, OnlyMarshal, GoodMsg @@ -192,12 +185,13 @@ describe GenericService do end it 'raises if a type arg only has the unmarshal method' do + # a bad message type with only an unmarshal method class OnlyUnmarshal def self.ummarshal(o) o end end - blk = Proc.new do + blk = proc do Class.new do include GenericService rpc :AnRpc, GoodMsg, OnlyUnmarshal @@ -208,7 +202,7 @@ describe GenericService do end it 'is ok for services that expect the default {un,}marshal methods' do - blk = Proc.new do + blk = proc do Class.new do include GenericService rpc :AnRpc, GoodMsg, GoodMsg @@ -218,7 +212,7 @@ describe GenericService do end it 'is ok for services that override the default {un,}marshal methods' do - blk = Proc.new do + blk = proc do Class.new do include GenericService self.marshal_class_method = :encode @@ -228,11 +222,9 @@ describe GenericService do end expect(&blk).not_to raise_error end - end describe '#rpc_stub_class' do - it 'generates a client class that defines any of the rpc methods' do s = Class.new do include GenericService @@ -249,7 +241,6 @@ describe GenericService do end describe 'the generated instances' do - it 'can be instanciated with just a hostname' do s = Class.new do include GenericService @@ -277,13 +268,10 @@ describe GenericService do expect(o.methods).to include(:a_client_streamer) expect(o.methods).to include(:a_bidi_streamer) end - end - end describe '#assert_rpc_descs_have_methods' do - it 'fails if there is no instance method for an rpc descriptor' do c1 = Class.new do include GenericService @@ -310,16 +298,16 @@ describe GenericService do rpc :AClientStreamer, stream(GoodMsg), GoodMsg rpc :ABidiStreamer, stream(GoodMsg), stream(GoodMsg) - def an_rpc(req, call) + def an_rpc(_req, _call) end - def a_server_streamer(req, call) + def a_server_streamer(_req, _call) end - def a_client_streamer(call) + def a_client_streamer(_call) end - def a_bidi_streamer(call) + def a_bidi_streamer(_call) end end expect { c.assert_rpc_descs_have_methods }.to_not raise_error @@ -330,7 +318,7 @@ describe GenericService do include GenericService rpc :AnRpc, GoodMsg, GoodMsg - def an_rpc(req, call) + def an_rpc(_req, _call) end end c = Class.new(base) @@ -344,13 +332,11 @@ describe GenericService do rpc :AnRpc, GoodMsg, GoodMsg end c = Class.new(base) do - def an_rpc(req, call) + def an_rpc(_req, _call) end end expect { c.assert_rpc_descs_have_methods }.to_not raise_error expect(c.include?(GenericService)).to be(true) end - end - end diff --git a/src/ruby/spec/metadata_spec.rb b/src/ruby/spec/metadata_spec.rb index d5dc8b2338..9cdce6b40d 100644 --- a/src/ruby/spec/metadata_spec.rb +++ b/src/ruby/spec/metadata_spec.rb @@ -30,7 +30,6 @@ require 'grpc' describe GRPC::Core::Metadata do - describe '#new' do it 'should create instances' do expect { GRPC::Core::Metadata.new('a key', 'a value') }.to_not raise_error @@ -62,5 +61,4 @@ describe GRPC::Core::Metadata do expect(md.dup.value).to eq('a value') end end - end diff --git a/src/ruby/spec/port_picker.rb b/src/ruby/spec/port_picker.rb index 1b52113e10..1891874505 100644 --- a/src/ruby/spec/port_picker.rb +++ b/src/ruby/spec/port_picker.rb @@ -32,14 +32,14 @@ require 'socket' # @param [Fixnum] the minimum port number to accept # @param [Fixnum] the maximum port number to accept # @return [Fixnum ]a free tcp port -def find_unused_tcp_port(min=32768, max=60000) - # Allow the system to assign a port, by specifying 0. +def find_unused_tcp_port(min = 32_768, max = 60_000) + # Allow the system to assign a port, by sp[ecifying 0. # Loop until a port is assigned in the required range loop do socket = Socket.new(:INET, :STREAM, 0) socket.bind(Addrinfo.tcp('127.0.0.1', 0)) p = socket.local_address.ip_port socket.close - return p if p > min and p < 60000 + return p if p > min && p < max end end diff --git a/src/ruby/spec/server_credentials_spec.rb b/src/ruby/spec/server_credentials_spec.rb index bcc2cae4dd..faa713d562 100644 --- a/src/ruby/spec/server_credentials_spec.rb +++ b/src/ruby/spec/server_credentials_spec.rb @@ -35,13 +35,10 @@ def load_test_certs files.map { |f| File.open(File.join(test_root, f)).read } end - describe GRPC::Core::ServerCredentials do - Creds = GRPC::Core::ServerCredentials describe '#new' do - it 'can be constructed from a fake CA PEM, server PEM and a server key' do expect { Creds.new('a', 'b', 'c') }.not_to raise_error end @@ -53,22 +50,20 @@ describe GRPC::Core::ServerCredentials do it 'cannot be constructed without a server cert chain' do root_cert, server_key, _ = load_test_certs - blk = Proc.new { Creds.new(root_cert, server_key, nil) } + blk = proc { Creds.new(root_cert, server_key, nil) } expect(&blk).to raise_error end it 'cannot be constructed without a server key' do - root_cert, server_key, _ = load_test_certs - blk = Proc.new { Creds.new(root_cert, _, cert_chain) } + root_cert, _, _ = load_test_certs + blk = proc { Creds.new(root_cert, nil, cert_chain) } expect(&blk).to raise_error end it 'can be constructed without a root_cret' do _, server_key, cert_chain = load_test_certs - blk = Proc.new { Creds.new(_, server_key, cert_chain) } + blk = proc { Creds.new(nil, server_key, cert_chain) } expect(&blk).to_not raise_error end - end - end diff --git a/src/ruby/spec/server_spec.rb b/src/ruby/spec/server_spec.rb index 28f520a2f6..6e5bb523de 100644 --- a/src/ruby/spec/server_spec.rb +++ b/src/ruby/spec/server_spec.rb @@ -39,7 +39,6 @@ end Server = GRPC::Core::Server describe Server do - def create_test_cert GRPC::Core::ServerCredentials.new(*load_test_certs) end @@ -49,11 +48,8 @@ describe Server do end describe '#start' do - it 'runs without failing' do - blk = Proc.new do - s = Server.new(@cq, nil).start - end + blk = proc { Server.new(@cq, nil).start } expect(&blk).to_not raise_error end @@ -62,20 +58,19 @@ describe Server do s.close expect { s.start }.to raise_error(RuntimeError) end - end describe '#destroy' do it 'destroys a server ok' do s = start_a_server - blk = Proc.new { s.destroy } + blk = proc { s.destroy } expect(&blk).to_not raise_error end it 'can be called more than once without error' do s = start_a_server begin - blk = Proc.new { s.destroy } + blk = proc { s.destroy } expect(&blk).to_not raise_error blk.call expect(&blk).to_not raise_error @@ -89,7 +84,7 @@ describe Server do it 'closes a server ok' do s = start_a_server begin - blk = Proc.new { s.close } + blk = proc { s.close } expect(&blk).to_not raise_error ensure s.close @@ -98,7 +93,7 @@ describe Server do it 'can be called more than once without error' do s = start_a_server - blk = Proc.new { s.close } + blk = proc { s.close } expect(&blk).to_not raise_error blk.call expect(&blk).to_not raise_error @@ -106,11 +101,9 @@ describe Server do end describe '#add_http_port' do - describe 'for insecure servers' do - it 'runs without failing' do - blk = Proc.new do + blk = proc do s = Server.new(@cq, nil) s.add_http2_port('localhost:0') s.close @@ -123,13 +116,11 @@ describe Server do s.close expect { s.add_http2_port('localhost:0') }.to raise_error(RuntimeError) end - end describe 'for secure servers' do - it 'runs without failing' do - blk = Proc.new do + blk = proc do s = Server.new(@cq, nil) s.add_http2_port('localhost:0', true) s.close @@ -140,16 +131,13 @@ describe Server do it 'fails if the server is closed' do s = Server.new(@cq, nil) s.close - blk = Proc.new { s.add_http2_port('localhost:0', true) } + blk = proc { s.add_http2_port('localhost:0', true) } expect(&blk).to raise_error(RuntimeError) end - end - end shared_examples '#new' do - it 'takes a completion queue with nil channel args' do expect { Server.new(@cq, nil, create_test_cert) }.to_not raise_error end @@ -162,14 +150,14 @@ describe Server do end it 'does not take a hash with bad values as channel args' do - blk = construct_with_args(:symbol => Object.new) + blk = construct_with_args(symbol: Object.new) expect(&blk).to raise_error TypeError blk = construct_with_args('1' => Hash.new) expect(&blk).to raise_error TypeError end it 'can take a hash with a symbol key as channel args' do - blk = construct_with_args(:a_symbol => 1) + blk = construct_with_args(a_symbol: 1) expect(&blk).to_not raise_error end @@ -179,46 +167,41 @@ describe Server do end it 'can take a hash with a string value as channel args' do - blk = construct_with_args(:a_symbol => '1') + blk = construct_with_args(a_symbol: '1') expect(&blk).to_not raise_error end it 'can take a hash with a symbol value as channel args' do - blk = construct_with_args(:a_symbol => :another_symbol) + blk = construct_with_args(a_symbol: :another_symbol) expect(&blk).to_not raise_error end it 'can take a hash with a numeric value as channel args' do - blk = construct_with_args(:a_symbol => 1) + blk = construct_with_args(a_symbol: 1) expect(&blk).to_not raise_error end it 'can take a hash with many args as channel args' do - args = Hash[127.times.collect { |x| [x.to_s, x] } ] + args = Hash[127.times.collect { |x| [x.to_s, x] }] blk = construct_with_args(args) expect(&blk).to_not raise_error end - end describe '#new with an insecure channel' do - def construct_with_args(a) - Proc.new { Server.new(@cq, a) } + proc { Server.new(@cq, a) } end it_behaves_like '#new' - end describe '#new with a secure channel' do - def construct_with_args(a) - Proc.new { Server.new(@cq, a, create_test_cert) } + proc { Server.new(@cq, a, create_test_cert) } end it_behaves_like '#new' - end def start_a_server @@ -229,5 +212,4 @@ describe Server do s.start s end - end diff --git a/src/ruby/spec/time_consts_spec.rb b/src/ruby/spec/time_consts_spec.rb index 27755075a9..b01027ce26 100644 --- a/src/ruby/spec/time_consts_spec.rb +++ b/src/ruby/spec/time_consts_spec.rb @@ -32,7 +32,6 @@ require 'grpc' TimeConsts = GRPC::Core::TimeConsts describe TimeConsts do - before(:each) do @known_consts = [:ZERO, :INFINITE_FUTURE, :INFINITE_PAST].sort end @@ -49,11 +48,9 @@ describe TimeConsts do end end end - end describe '#from_relative_time' do - it 'cannot handle arbitrary objects' do expect { TimeConsts.from_relative_time(Object.new) }.to raise_error end @@ -89,5 +86,4 @@ describe '#from_relative_time' do expect(abs.to_f).to be_within(epsilon).of(want.to_f) end end - end -- cgit v1.2.3 From 1fdb1e61d2a89075ecaaa592a3b2f4a7bff60784 Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Fri, 16 Jan 2015 03:06:39 -0800 Subject: Fix a typo --- src/ruby/spec/port_picker.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/ruby/spec/port_picker.rb b/src/ruby/spec/port_picker.rb index 1891874505..98ffbacc1b 100644 --- a/src/ruby/spec/port_picker.rb +++ b/src/ruby/spec/port_picker.rb @@ -33,7 +33,7 @@ require 'socket' # @param [Fixnum] the maximum port number to accept # @return [Fixnum ]a free tcp port def find_unused_tcp_port(min = 32_768, max = 60_000) - # Allow the system to assign a port, by sp[ecifying 0. + # Allow the system to assign a port, by specifying 0. # Loop until a port is assigned in the required range loop do socket = Socket.new(:INET, :STREAM, 0) -- cgit v1.2.3 From 4ffdcd56ce472093ff58d53142230542653616f2 Mon Sep 17 00:00:00 2001 From: Craig Tiller Date: Fri, 16 Jan 2015 11:34:55 -0800 Subject: Add an optional server shutdown event. Allows servers to expedite shutdown once all in-progress calls are completed. We may want to eventually remove grpc_server_shutdown in preference to this. --- Makefile | 206 ++++++++++++++++++++- include/grpc/grpc.h | 5 + src/core/surface/completion_queue.c | 7 + src/core/surface/completion_queue.h | 2 + src/core/surface/event_string.c | 3 + src/core/surface/server.c | 25 ++- test/core/end2end/cq_verifier.c | 8 + test/core/end2end/cq_verifier.h | 1 + test/core/end2end/gen_build_json.py | 1 + test/core/end2end/tests/graceful_server_shutdown.c | 160 ++++++++++++++++ 10 files changed, 415 insertions(+), 3 deletions(-) create mode 100644 test/core/end2end/tests/graceful_server_shutdown.c (limited to 'src') diff --git a/Makefile b/Makefile index 87f6719bd7..9eeae975f1 100644 --- a/Makefile +++ b/Makefile @@ -372,6 +372,7 @@ chttp2_fake_security_census_simple_request_test: bins/$(CONFIG)/chttp2_fake_secu chttp2_fake_security_disappearing_server_test: bins/$(CONFIG)/chttp2_fake_security_disappearing_server_test chttp2_fake_security_early_server_shutdown_finishes_inflight_calls_test: bins/$(CONFIG)/chttp2_fake_security_early_server_shutdown_finishes_inflight_calls_test chttp2_fake_security_early_server_shutdown_finishes_tags_test: bins/$(CONFIG)/chttp2_fake_security_early_server_shutdown_finishes_tags_test +chttp2_fake_security_graceful_server_shutdown_test: bins/$(CONFIG)/chttp2_fake_security_graceful_server_shutdown_test chttp2_fake_security_invoke_large_request_test: bins/$(CONFIG)/chttp2_fake_security_invoke_large_request_test chttp2_fake_security_max_concurrent_streams_test: bins/$(CONFIG)/chttp2_fake_security_max_concurrent_streams_test chttp2_fake_security_no_op_test: bins/$(CONFIG)/chttp2_fake_security_no_op_test @@ -393,6 +394,7 @@ chttp2_fullstack_census_simple_request_test: bins/$(CONFIG)/chttp2_fullstack_cen chttp2_fullstack_disappearing_server_test: bins/$(CONFIG)/chttp2_fullstack_disappearing_server_test chttp2_fullstack_early_server_shutdown_finishes_inflight_calls_test: bins/$(CONFIG)/chttp2_fullstack_early_server_shutdown_finishes_inflight_calls_test chttp2_fullstack_early_server_shutdown_finishes_tags_test: bins/$(CONFIG)/chttp2_fullstack_early_server_shutdown_finishes_tags_test +chttp2_fullstack_graceful_server_shutdown_test: bins/$(CONFIG)/chttp2_fullstack_graceful_server_shutdown_test chttp2_fullstack_invoke_large_request_test: bins/$(CONFIG)/chttp2_fullstack_invoke_large_request_test chttp2_fullstack_max_concurrent_streams_test: bins/$(CONFIG)/chttp2_fullstack_max_concurrent_streams_test chttp2_fullstack_no_op_test: bins/$(CONFIG)/chttp2_fullstack_no_op_test @@ -414,6 +416,7 @@ chttp2_simple_ssl_fullstack_census_simple_request_test: bins/$(CONFIG)/chttp2_si chttp2_simple_ssl_fullstack_disappearing_server_test: bins/$(CONFIG)/chttp2_simple_ssl_fullstack_disappearing_server_test chttp2_simple_ssl_fullstack_early_server_shutdown_finishes_inflight_calls_test: bins/$(CONFIG)/chttp2_simple_ssl_fullstack_early_server_shutdown_finishes_inflight_calls_test chttp2_simple_ssl_fullstack_early_server_shutdown_finishes_tags_test: bins/$(CONFIG)/chttp2_simple_ssl_fullstack_early_server_shutdown_finishes_tags_test +chttp2_simple_ssl_fullstack_graceful_server_shutdown_test: bins/$(CONFIG)/chttp2_simple_ssl_fullstack_graceful_server_shutdown_test chttp2_simple_ssl_fullstack_invoke_large_request_test: bins/$(CONFIG)/chttp2_simple_ssl_fullstack_invoke_large_request_test chttp2_simple_ssl_fullstack_max_concurrent_streams_test: bins/$(CONFIG)/chttp2_simple_ssl_fullstack_max_concurrent_streams_test chttp2_simple_ssl_fullstack_no_op_test: bins/$(CONFIG)/chttp2_simple_ssl_fullstack_no_op_test @@ -435,6 +438,7 @@ chttp2_simple_ssl_with_oauth2_fullstack_census_simple_request_test: bins/$(CONFI chttp2_simple_ssl_with_oauth2_fullstack_disappearing_server_test: bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_disappearing_server_test chttp2_simple_ssl_with_oauth2_fullstack_early_server_shutdown_finishes_inflight_calls_test: bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_early_server_shutdown_finishes_inflight_calls_test chttp2_simple_ssl_with_oauth2_fullstack_early_server_shutdown_finishes_tags_test: bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_early_server_shutdown_finishes_tags_test +chttp2_simple_ssl_with_oauth2_fullstack_graceful_server_shutdown_test: bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_graceful_server_shutdown_test chttp2_simple_ssl_with_oauth2_fullstack_invoke_large_request_test: bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_invoke_large_request_test chttp2_simple_ssl_with_oauth2_fullstack_max_concurrent_streams_test: bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_max_concurrent_streams_test chttp2_simple_ssl_with_oauth2_fullstack_no_op_test: bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_no_op_test @@ -456,6 +460,7 @@ chttp2_socket_pair_census_simple_request_test: bins/$(CONFIG)/chttp2_socket_pair chttp2_socket_pair_disappearing_server_test: bins/$(CONFIG)/chttp2_socket_pair_disappearing_server_test chttp2_socket_pair_early_server_shutdown_finishes_inflight_calls_test: bins/$(CONFIG)/chttp2_socket_pair_early_server_shutdown_finishes_inflight_calls_test chttp2_socket_pair_early_server_shutdown_finishes_tags_test: bins/$(CONFIG)/chttp2_socket_pair_early_server_shutdown_finishes_tags_test +chttp2_socket_pair_graceful_server_shutdown_test: bins/$(CONFIG)/chttp2_socket_pair_graceful_server_shutdown_test chttp2_socket_pair_invoke_large_request_test: bins/$(CONFIG)/chttp2_socket_pair_invoke_large_request_test chttp2_socket_pair_max_concurrent_streams_test: bins/$(CONFIG)/chttp2_socket_pair_max_concurrent_streams_test chttp2_socket_pair_no_op_test: bins/$(CONFIG)/chttp2_socket_pair_no_op_test @@ -477,6 +482,7 @@ chttp2_socket_pair_one_byte_at_a_time_census_simple_request_test: bins/$(CONFIG) chttp2_socket_pair_one_byte_at_a_time_disappearing_server_test: bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_disappearing_server_test chttp2_socket_pair_one_byte_at_a_time_early_server_shutdown_finishes_inflight_calls_test: bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_early_server_shutdown_finishes_inflight_calls_test chttp2_socket_pair_one_byte_at_a_time_early_server_shutdown_finishes_tags_test: bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_early_server_shutdown_finishes_tags_test +chttp2_socket_pair_one_byte_at_a_time_graceful_server_shutdown_test: bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_graceful_server_shutdown_test chttp2_socket_pair_one_byte_at_a_time_invoke_large_request_test: bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_invoke_large_request_test chttp2_socket_pair_one_byte_at_a_time_max_concurrent_streams_test: bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_max_concurrent_streams_test chttp2_socket_pair_one_byte_at_a_time_no_op_test: bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_no_op_test @@ -524,13 +530,13 @@ shared_cxx: libs/$(CONFIG)/libgrpc++.$(SHARED_EXT) privatelibs: privatelibs_c privatelibs_cxx -privatelibs_c: libs/$(CONFIG)/libgpr_test_util.a libs/$(CONFIG)/libgrpc_test_util.a libs/$(CONFIG)/libend2end_fixture_chttp2_fake_security.a libs/$(CONFIG)/libend2end_fixture_chttp2_fullstack.a libs/$(CONFIG)/libend2end_fixture_chttp2_simple_ssl_fullstack.a libs/$(CONFIG)/libend2end_fixture_chttp2_simple_ssl_with_oauth2_fullstack.a libs/$(CONFIG)/libend2end_fixture_chttp2_socket_pair.a libs/$(CONFIG)/libend2end_fixture_chttp2_socket_pair_one_byte_at_a_time.a libs/$(CONFIG)/libend2end_test_cancel_after_accept.a libs/$(CONFIG)/libend2end_test_cancel_after_accept_and_writes_closed.a libs/$(CONFIG)/libend2end_test_cancel_after_invoke.a libs/$(CONFIG)/libend2end_test_cancel_before_invoke.a libs/$(CONFIG)/libend2end_test_cancel_in_a_vacuum.a libs/$(CONFIG)/libend2end_test_census_simple_request.a libs/$(CONFIG)/libend2end_test_disappearing_server.a libs/$(CONFIG)/libend2end_test_early_server_shutdown_finishes_inflight_calls.a libs/$(CONFIG)/libend2end_test_early_server_shutdown_finishes_tags.a libs/$(CONFIG)/libend2end_test_invoke_large_request.a libs/$(CONFIG)/libend2end_test_max_concurrent_streams.a libs/$(CONFIG)/libend2end_test_no_op.a libs/$(CONFIG)/libend2end_test_ping_pong_streaming.a libs/$(CONFIG)/libend2end_test_request_response_with_binary_metadata_and_payload.a libs/$(CONFIG)/libend2end_test_request_response_with_metadata_and_payload.a libs/$(CONFIG)/libend2end_test_request_response_with_payload.a libs/$(CONFIG)/libend2end_test_request_response_with_trailing_metadata_and_payload.a libs/$(CONFIG)/libend2end_test_simple_delayed_request.a libs/$(CONFIG)/libend2end_test_simple_request.a libs/$(CONFIG)/libend2end_test_thread_stress.a libs/$(CONFIG)/libend2end_test_writes_done_hangs_with_pending_read.a libs/$(CONFIG)/libend2end_certs.a +privatelibs_c: libs/$(CONFIG)/libgpr_test_util.a libs/$(CONFIG)/libgrpc_test_util.a libs/$(CONFIG)/libend2end_fixture_chttp2_fake_security.a libs/$(CONFIG)/libend2end_fixture_chttp2_fullstack.a libs/$(CONFIG)/libend2end_fixture_chttp2_simple_ssl_fullstack.a libs/$(CONFIG)/libend2end_fixture_chttp2_simple_ssl_with_oauth2_fullstack.a libs/$(CONFIG)/libend2end_fixture_chttp2_socket_pair.a libs/$(CONFIG)/libend2end_fixture_chttp2_socket_pair_one_byte_at_a_time.a libs/$(CONFIG)/libend2end_test_cancel_after_accept.a libs/$(CONFIG)/libend2end_test_cancel_after_accept_and_writes_closed.a libs/$(CONFIG)/libend2end_test_cancel_after_invoke.a libs/$(CONFIG)/libend2end_test_cancel_before_invoke.a libs/$(CONFIG)/libend2end_test_cancel_in_a_vacuum.a libs/$(CONFIG)/libend2end_test_census_simple_request.a libs/$(CONFIG)/libend2end_test_disappearing_server.a libs/$(CONFIG)/libend2end_test_early_server_shutdown_finishes_inflight_calls.a libs/$(CONFIG)/libend2end_test_early_server_shutdown_finishes_tags.a libs/$(CONFIG)/libend2end_test_graceful_server_shutdown.a libs/$(CONFIG)/libend2end_test_invoke_large_request.a libs/$(CONFIG)/libend2end_test_max_concurrent_streams.a libs/$(CONFIG)/libend2end_test_no_op.a libs/$(CONFIG)/libend2end_test_ping_pong_streaming.a libs/$(CONFIG)/libend2end_test_request_response_with_binary_metadata_and_payload.a libs/$(CONFIG)/libend2end_test_request_response_with_metadata_and_payload.a libs/$(CONFIG)/libend2end_test_request_response_with_payload.a libs/$(CONFIG)/libend2end_test_request_response_with_trailing_metadata_and_payload.a libs/$(CONFIG)/libend2end_test_simple_delayed_request.a libs/$(CONFIG)/libend2end_test_simple_request.a libs/$(CONFIG)/libend2end_test_thread_stress.a libs/$(CONFIG)/libend2end_test_writes_done_hangs_with_pending_read.a libs/$(CONFIG)/libend2end_certs.a privatelibs_cxx: libs/$(CONFIG)/libgrpc++_test_util.a buildtests: buildtests_c buildtests_cxx -buildtests_c: privatelibs_c bins/$(CONFIG)/grpc_byte_buffer_reader_test bins/$(CONFIG)/gpr_cancellable_test bins/$(CONFIG)/gpr_log_test bins/$(CONFIG)/gpr_useful_test bins/$(CONFIG)/gpr_cmdline_test bins/$(CONFIG)/gpr_histogram_test bins/$(CONFIG)/gpr_host_port_test bins/$(CONFIG)/gpr_slice_buffer_test bins/$(CONFIG)/gpr_slice_test bins/$(CONFIG)/gpr_string_test bins/$(CONFIG)/gpr_sync_test bins/$(CONFIG)/gpr_thd_test bins/$(CONFIG)/gpr_time_test bins/$(CONFIG)/murmur_hash_test bins/$(CONFIG)/grpc_stream_op_test bins/$(CONFIG)/alpn_test bins/$(CONFIG)/time_averaged_stats_test bins/$(CONFIG)/chttp2_stream_encoder_test bins/$(CONFIG)/hpack_table_test bins/$(CONFIG)/chttp2_stream_map_test bins/$(CONFIG)/hpack_parser_test bins/$(CONFIG)/transport_metadata_test bins/$(CONFIG)/chttp2_status_conversion_test bins/$(CONFIG)/chttp2_transport_end2end_test bins/$(CONFIG)/tcp_posix_test bins/$(CONFIG)/dualstack_socket_test bins/$(CONFIG)/no_server_test bins/$(CONFIG)/resolve_address_test bins/$(CONFIG)/sockaddr_utils_test bins/$(CONFIG)/tcp_server_posix_test bins/$(CONFIG)/tcp_client_posix_test bins/$(CONFIG)/grpc_channel_stack_test bins/$(CONFIG)/metadata_buffer_test bins/$(CONFIG)/grpc_completion_queue_test bins/$(CONFIG)/census_window_stats_test bins/$(CONFIG)/census_statistics_quick_test bins/$(CONFIG)/census_statistics_small_log_test bins/$(CONFIG)/census_statistics_performance_test bins/$(CONFIG)/census_statistics_multiple_writers_test bins/$(CONFIG)/census_statistics_multiple_writers_circular_buffer_test bins/$(CONFIG)/census_stub_test bins/$(CONFIG)/census_hash_table_test bins/$(CONFIG)/fling_server bins/$(CONFIG)/fling_client bins/$(CONFIG)/fling_test bins/$(CONFIG)/echo_server bins/$(CONFIG)/echo_client bins/$(CONFIG)/echo_test bins/$(CONFIG)/message_compress_test bins/$(CONFIG)/bin_encoder_test bins/$(CONFIG)/secure_endpoint_test bins/$(CONFIG)/httpcli_format_request_test bins/$(CONFIG)/httpcli_parser_test bins/$(CONFIG)/httpcli_test bins/$(CONFIG)/grpc_credentials_test bins/$(CONFIG)/grpc_base64_test bins/$(CONFIG)/grpc_json_token_test bins/$(CONFIG)/timeout_encoding_test bins/$(CONFIG)/fd_posix_test bins/$(CONFIG)/fling_stream_test bins/$(CONFIG)/lame_client_test bins/$(CONFIG)/alarm_test bins/$(CONFIG)/alarm_list_test bins/$(CONFIG)/alarm_heap_test bins/$(CONFIG)/time_test bins/$(CONFIG)/chttp2_fake_security_cancel_after_accept_test bins/$(CONFIG)/chttp2_fake_security_cancel_after_accept_and_writes_closed_test bins/$(CONFIG)/chttp2_fake_security_cancel_after_invoke_test bins/$(CONFIG)/chttp2_fake_security_cancel_before_invoke_test bins/$(CONFIG)/chttp2_fake_security_cancel_in_a_vacuum_test bins/$(CONFIG)/chttp2_fake_security_census_simple_request_test bins/$(CONFIG)/chttp2_fake_security_disappearing_server_test bins/$(CONFIG)/chttp2_fake_security_early_server_shutdown_finishes_inflight_calls_test bins/$(CONFIG)/chttp2_fake_security_early_server_shutdown_finishes_tags_test bins/$(CONFIG)/chttp2_fake_security_invoke_large_request_test bins/$(CONFIG)/chttp2_fake_security_max_concurrent_streams_test bins/$(CONFIG)/chttp2_fake_security_no_op_test bins/$(CONFIG)/chttp2_fake_security_ping_pong_streaming_test bins/$(CONFIG)/chttp2_fake_security_request_response_with_binary_metadata_and_payload_test bins/$(CONFIG)/chttp2_fake_security_request_response_with_metadata_and_payload_test bins/$(CONFIG)/chttp2_fake_security_request_response_with_payload_test bins/$(CONFIG)/chttp2_fake_security_request_response_with_trailing_metadata_and_payload_test bins/$(CONFIG)/chttp2_fake_security_simple_delayed_request_test bins/$(CONFIG)/chttp2_fake_security_simple_request_test bins/$(CONFIG)/chttp2_fake_security_thread_stress_test bins/$(CONFIG)/chttp2_fake_security_writes_done_hangs_with_pending_read_test bins/$(CONFIG)/chttp2_fullstack_cancel_after_accept_test bins/$(CONFIG)/chttp2_fullstack_cancel_after_accept_and_writes_closed_test bins/$(CONFIG)/chttp2_fullstack_cancel_after_invoke_test bins/$(CONFIG)/chttp2_fullstack_cancel_before_invoke_test bins/$(CONFIG)/chttp2_fullstack_cancel_in_a_vacuum_test bins/$(CONFIG)/chttp2_fullstack_census_simple_request_test bins/$(CONFIG)/chttp2_fullstack_disappearing_server_test bins/$(CONFIG)/chttp2_fullstack_early_server_shutdown_finishes_inflight_calls_test bins/$(CONFIG)/chttp2_fullstack_early_server_shutdown_finishes_tags_test bins/$(CONFIG)/chttp2_fullstack_invoke_large_request_test bins/$(CONFIG)/chttp2_fullstack_max_concurrent_streams_test bins/$(CONFIG)/chttp2_fullstack_no_op_test bins/$(CONFIG)/chttp2_fullstack_ping_pong_streaming_test bins/$(CONFIG)/chttp2_fullstack_request_response_with_binary_metadata_and_payload_test bins/$(CONFIG)/chttp2_fullstack_request_response_with_metadata_and_payload_test bins/$(CONFIG)/chttp2_fullstack_request_response_with_payload_test bins/$(CONFIG)/chttp2_fullstack_request_response_with_trailing_metadata_and_payload_test bins/$(CONFIG)/chttp2_fullstack_simple_delayed_request_test bins/$(CONFIG)/chttp2_fullstack_simple_request_test bins/$(CONFIG)/chttp2_fullstack_thread_stress_test bins/$(CONFIG)/chttp2_fullstack_writes_done_hangs_with_pending_read_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_cancel_after_accept_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_cancel_after_accept_and_writes_closed_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_cancel_after_invoke_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_cancel_before_invoke_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_cancel_in_a_vacuum_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_census_simple_request_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_disappearing_server_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_early_server_shutdown_finishes_inflight_calls_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_early_server_shutdown_finishes_tags_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_invoke_large_request_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_max_concurrent_streams_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_no_op_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_ping_pong_streaming_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_request_response_with_binary_metadata_and_payload_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_request_response_with_metadata_and_payload_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_request_response_with_payload_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_request_response_with_trailing_metadata_and_payload_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_simple_delayed_request_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_simple_request_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_thread_stress_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_writes_done_hangs_with_pending_read_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_cancel_after_accept_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_cancel_after_accept_and_writes_closed_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_cancel_after_invoke_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_cancel_before_invoke_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_cancel_in_a_vacuum_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_census_simple_request_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_disappearing_server_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_early_server_shutdown_finishes_inflight_calls_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_early_server_shutdown_finishes_tags_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_invoke_large_request_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_max_concurrent_streams_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_no_op_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_ping_pong_streaming_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_request_response_with_binary_metadata_and_payload_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_request_response_with_metadata_and_payload_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_request_response_with_payload_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_request_response_with_trailing_metadata_and_payload_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_simple_delayed_request_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_simple_request_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_thread_stress_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_writes_done_hangs_with_pending_read_test bins/$(CONFIG)/chttp2_socket_pair_cancel_after_accept_test bins/$(CONFIG)/chttp2_socket_pair_cancel_after_accept_and_writes_closed_test bins/$(CONFIG)/chttp2_socket_pair_cancel_after_invoke_test bins/$(CONFIG)/chttp2_socket_pair_cancel_before_invoke_test bins/$(CONFIG)/chttp2_socket_pair_cancel_in_a_vacuum_test bins/$(CONFIG)/chttp2_socket_pair_census_simple_request_test bins/$(CONFIG)/chttp2_socket_pair_disappearing_server_test bins/$(CONFIG)/chttp2_socket_pair_early_server_shutdown_finishes_inflight_calls_test bins/$(CONFIG)/chttp2_socket_pair_early_server_shutdown_finishes_tags_test bins/$(CONFIG)/chttp2_socket_pair_invoke_large_request_test bins/$(CONFIG)/chttp2_socket_pair_max_concurrent_streams_test bins/$(CONFIG)/chttp2_socket_pair_no_op_test bins/$(CONFIG)/chttp2_socket_pair_ping_pong_streaming_test bins/$(CONFIG)/chttp2_socket_pair_request_response_with_binary_metadata_and_payload_test bins/$(CONFIG)/chttp2_socket_pair_request_response_with_metadata_and_payload_test bins/$(CONFIG)/chttp2_socket_pair_request_response_with_payload_test bins/$(CONFIG)/chttp2_socket_pair_request_response_with_trailing_metadata_and_payload_test bins/$(CONFIG)/chttp2_socket_pair_simple_delayed_request_test bins/$(CONFIG)/chttp2_socket_pair_simple_request_test bins/$(CONFIG)/chttp2_socket_pair_thread_stress_test bins/$(CONFIG)/chttp2_socket_pair_writes_done_hangs_with_pending_read_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_cancel_after_accept_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_cancel_after_accept_and_writes_closed_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_cancel_after_invoke_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_cancel_before_invoke_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_cancel_in_a_vacuum_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_census_simple_request_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_disappearing_server_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_early_server_shutdown_finishes_inflight_calls_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_early_server_shutdown_finishes_tags_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_invoke_large_request_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_max_concurrent_streams_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_no_op_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_ping_pong_streaming_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_request_response_with_binary_metadata_and_payload_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_request_response_with_metadata_and_payload_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_request_response_with_payload_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_request_response_with_trailing_metadata_and_payload_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_simple_delayed_request_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_simple_request_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_thread_stress_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_writes_done_hangs_with_pending_read_test +buildtests_c: privatelibs_c bins/$(CONFIG)/grpc_byte_buffer_reader_test bins/$(CONFIG)/gpr_cancellable_test bins/$(CONFIG)/gpr_log_test bins/$(CONFIG)/gpr_useful_test bins/$(CONFIG)/gpr_cmdline_test bins/$(CONFIG)/gpr_histogram_test bins/$(CONFIG)/gpr_host_port_test bins/$(CONFIG)/gpr_slice_buffer_test bins/$(CONFIG)/gpr_slice_test bins/$(CONFIG)/gpr_string_test bins/$(CONFIG)/gpr_sync_test bins/$(CONFIG)/gpr_thd_test bins/$(CONFIG)/gpr_time_test bins/$(CONFIG)/murmur_hash_test bins/$(CONFIG)/grpc_stream_op_test bins/$(CONFIG)/alpn_test bins/$(CONFIG)/time_averaged_stats_test bins/$(CONFIG)/chttp2_stream_encoder_test bins/$(CONFIG)/hpack_table_test bins/$(CONFIG)/chttp2_stream_map_test bins/$(CONFIG)/hpack_parser_test bins/$(CONFIG)/transport_metadata_test bins/$(CONFIG)/chttp2_status_conversion_test bins/$(CONFIG)/chttp2_transport_end2end_test bins/$(CONFIG)/tcp_posix_test bins/$(CONFIG)/dualstack_socket_test bins/$(CONFIG)/no_server_test bins/$(CONFIG)/resolve_address_test bins/$(CONFIG)/sockaddr_utils_test bins/$(CONFIG)/tcp_server_posix_test bins/$(CONFIG)/tcp_client_posix_test bins/$(CONFIG)/grpc_channel_stack_test bins/$(CONFIG)/metadata_buffer_test bins/$(CONFIG)/grpc_completion_queue_test bins/$(CONFIG)/census_window_stats_test bins/$(CONFIG)/census_statistics_quick_test bins/$(CONFIG)/census_statistics_small_log_test bins/$(CONFIG)/census_statistics_performance_test bins/$(CONFIG)/census_statistics_multiple_writers_test bins/$(CONFIG)/census_statistics_multiple_writers_circular_buffer_test bins/$(CONFIG)/census_stub_test bins/$(CONFIG)/census_hash_table_test bins/$(CONFIG)/fling_server bins/$(CONFIG)/fling_client bins/$(CONFIG)/fling_test bins/$(CONFIG)/echo_server bins/$(CONFIG)/echo_client bins/$(CONFIG)/echo_test bins/$(CONFIG)/message_compress_test bins/$(CONFIG)/bin_encoder_test bins/$(CONFIG)/secure_endpoint_test bins/$(CONFIG)/httpcli_format_request_test bins/$(CONFIG)/httpcli_parser_test bins/$(CONFIG)/httpcli_test bins/$(CONFIG)/grpc_credentials_test bins/$(CONFIG)/grpc_base64_test bins/$(CONFIG)/grpc_json_token_test bins/$(CONFIG)/timeout_encoding_test bins/$(CONFIG)/fd_posix_test bins/$(CONFIG)/fling_stream_test bins/$(CONFIG)/lame_client_test bins/$(CONFIG)/alarm_test bins/$(CONFIG)/alarm_list_test bins/$(CONFIG)/alarm_heap_test bins/$(CONFIG)/time_test bins/$(CONFIG)/chttp2_fake_security_cancel_after_accept_test bins/$(CONFIG)/chttp2_fake_security_cancel_after_accept_and_writes_closed_test bins/$(CONFIG)/chttp2_fake_security_cancel_after_invoke_test bins/$(CONFIG)/chttp2_fake_security_cancel_before_invoke_test bins/$(CONFIG)/chttp2_fake_security_cancel_in_a_vacuum_test bins/$(CONFIG)/chttp2_fake_security_census_simple_request_test bins/$(CONFIG)/chttp2_fake_security_disappearing_server_test bins/$(CONFIG)/chttp2_fake_security_early_server_shutdown_finishes_inflight_calls_test bins/$(CONFIG)/chttp2_fake_security_early_server_shutdown_finishes_tags_test bins/$(CONFIG)/chttp2_fake_security_graceful_server_shutdown_test bins/$(CONFIG)/chttp2_fake_security_invoke_large_request_test bins/$(CONFIG)/chttp2_fake_security_max_concurrent_streams_test bins/$(CONFIG)/chttp2_fake_security_no_op_test bins/$(CONFIG)/chttp2_fake_security_ping_pong_streaming_test bins/$(CONFIG)/chttp2_fake_security_request_response_with_binary_metadata_and_payload_test bins/$(CONFIG)/chttp2_fake_security_request_response_with_metadata_and_payload_test bins/$(CONFIG)/chttp2_fake_security_request_response_with_payload_test bins/$(CONFIG)/chttp2_fake_security_request_response_with_trailing_metadata_and_payload_test bins/$(CONFIG)/chttp2_fake_security_simple_delayed_request_test bins/$(CONFIG)/chttp2_fake_security_simple_request_test bins/$(CONFIG)/chttp2_fake_security_thread_stress_test bins/$(CONFIG)/chttp2_fake_security_writes_done_hangs_with_pending_read_test bins/$(CONFIG)/chttp2_fullstack_cancel_after_accept_test bins/$(CONFIG)/chttp2_fullstack_cancel_after_accept_and_writes_closed_test bins/$(CONFIG)/chttp2_fullstack_cancel_after_invoke_test bins/$(CONFIG)/chttp2_fullstack_cancel_before_invoke_test bins/$(CONFIG)/chttp2_fullstack_cancel_in_a_vacuum_test bins/$(CONFIG)/chttp2_fullstack_census_simple_request_test bins/$(CONFIG)/chttp2_fullstack_disappearing_server_test bins/$(CONFIG)/chttp2_fullstack_early_server_shutdown_finishes_inflight_calls_test bins/$(CONFIG)/chttp2_fullstack_early_server_shutdown_finishes_tags_test bins/$(CONFIG)/chttp2_fullstack_graceful_server_shutdown_test bins/$(CONFIG)/chttp2_fullstack_invoke_large_request_test bins/$(CONFIG)/chttp2_fullstack_max_concurrent_streams_test bins/$(CONFIG)/chttp2_fullstack_no_op_test bins/$(CONFIG)/chttp2_fullstack_ping_pong_streaming_test bins/$(CONFIG)/chttp2_fullstack_request_response_with_binary_metadata_and_payload_test bins/$(CONFIG)/chttp2_fullstack_request_response_with_metadata_and_payload_test bins/$(CONFIG)/chttp2_fullstack_request_response_with_payload_test bins/$(CONFIG)/chttp2_fullstack_request_response_with_trailing_metadata_and_payload_test bins/$(CONFIG)/chttp2_fullstack_simple_delayed_request_test bins/$(CONFIG)/chttp2_fullstack_simple_request_test bins/$(CONFIG)/chttp2_fullstack_thread_stress_test bins/$(CONFIG)/chttp2_fullstack_writes_done_hangs_with_pending_read_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_cancel_after_accept_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_cancel_after_accept_and_writes_closed_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_cancel_after_invoke_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_cancel_before_invoke_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_cancel_in_a_vacuum_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_census_simple_request_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_disappearing_server_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_early_server_shutdown_finishes_inflight_calls_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_early_server_shutdown_finishes_tags_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_graceful_server_shutdown_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_invoke_large_request_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_max_concurrent_streams_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_no_op_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_ping_pong_streaming_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_request_response_with_binary_metadata_and_payload_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_request_response_with_metadata_and_payload_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_request_response_with_payload_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_request_response_with_trailing_metadata_and_payload_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_simple_delayed_request_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_simple_request_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_thread_stress_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_writes_done_hangs_with_pending_read_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_cancel_after_accept_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_cancel_after_accept_and_writes_closed_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_cancel_after_invoke_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_cancel_before_invoke_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_cancel_in_a_vacuum_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_census_simple_request_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_disappearing_server_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_early_server_shutdown_finishes_inflight_calls_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_early_server_shutdown_finishes_tags_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_graceful_server_shutdown_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_invoke_large_request_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_max_concurrent_streams_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_no_op_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_ping_pong_streaming_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_request_response_with_binary_metadata_and_payload_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_request_response_with_metadata_and_payload_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_request_response_with_payload_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_request_response_with_trailing_metadata_and_payload_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_simple_delayed_request_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_simple_request_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_thread_stress_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_writes_done_hangs_with_pending_read_test bins/$(CONFIG)/chttp2_socket_pair_cancel_after_accept_test bins/$(CONFIG)/chttp2_socket_pair_cancel_after_accept_and_writes_closed_test bins/$(CONFIG)/chttp2_socket_pair_cancel_after_invoke_test bins/$(CONFIG)/chttp2_socket_pair_cancel_before_invoke_test bins/$(CONFIG)/chttp2_socket_pair_cancel_in_a_vacuum_test bins/$(CONFIG)/chttp2_socket_pair_census_simple_request_test bins/$(CONFIG)/chttp2_socket_pair_disappearing_server_test bins/$(CONFIG)/chttp2_socket_pair_early_server_shutdown_finishes_inflight_calls_test bins/$(CONFIG)/chttp2_socket_pair_early_server_shutdown_finishes_tags_test bins/$(CONFIG)/chttp2_socket_pair_graceful_server_shutdown_test bins/$(CONFIG)/chttp2_socket_pair_invoke_large_request_test bins/$(CONFIG)/chttp2_socket_pair_max_concurrent_streams_test bins/$(CONFIG)/chttp2_socket_pair_no_op_test bins/$(CONFIG)/chttp2_socket_pair_ping_pong_streaming_test bins/$(CONFIG)/chttp2_socket_pair_request_response_with_binary_metadata_and_payload_test bins/$(CONFIG)/chttp2_socket_pair_request_response_with_metadata_and_payload_test bins/$(CONFIG)/chttp2_socket_pair_request_response_with_payload_test bins/$(CONFIG)/chttp2_socket_pair_request_response_with_trailing_metadata_and_payload_test bins/$(CONFIG)/chttp2_socket_pair_simple_delayed_request_test bins/$(CONFIG)/chttp2_socket_pair_simple_request_test bins/$(CONFIG)/chttp2_socket_pair_thread_stress_test bins/$(CONFIG)/chttp2_socket_pair_writes_done_hangs_with_pending_read_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_cancel_after_accept_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_cancel_after_accept_and_writes_closed_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_cancel_after_invoke_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_cancel_before_invoke_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_cancel_in_a_vacuum_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_census_simple_request_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_disappearing_server_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_early_server_shutdown_finishes_inflight_calls_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_early_server_shutdown_finishes_tags_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_graceful_server_shutdown_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_invoke_large_request_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_max_concurrent_streams_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_no_op_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_ping_pong_streaming_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_request_response_with_binary_metadata_and_payload_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_request_response_with_metadata_and_payload_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_request_response_with_payload_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_request_response_with_trailing_metadata_and_payload_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_simple_delayed_request_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_simple_request_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_thread_stress_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_writes_done_hangs_with_pending_read_test buildtests_cxx: privatelibs_cxx bins/$(CONFIG)/thread_pool_test bins/$(CONFIG)/status_test bins/$(CONFIG)/sync_client_async_server_test bins/$(CONFIG)/qps_client bins/$(CONFIG)/qps_server bins/$(CONFIG)/interop_server bins/$(CONFIG)/interop_client bins/$(CONFIG)/end2end_test bins/$(CONFIG)/channel_arguments_test bins/$(CONFIG)/credentials_test @@ -677,6 +683,8 @@ test_c: buildtests_c $(Q) ./bins/$(CONFIG)/chttp2_fake_security_early_server_shutdown_finishes_inflight_calls_test || ( echo test chttp2_fake_security_early_server_shutdown_finishes_inflight_calls_test failed ; exit 1 ) $(E) "[RUN] Testing chttp2_fake_security_early_server_shutdown_finishes_tags_test" $(Q) ./bins/$(CONFIG)/chttp2_fake_security_early_server_shutdown_finishes_tags_test || ( echo test chttp2_fake_security_early_server_shutdown_finishes_tags_test failed ; exit 1 ) + $(E) "[RUN] Testing chttp2_fake_security_graceful_server_shutdown_test" + $(Q) ./bins/$(CONFIG)/chttp2_fake_security_graceful_server_shutdown_test || ( echo test chttp2_fake_security_graceful_server_shutdown_test failed ; exit 1 ) $(E) "[RUN] Testing chttp2_fake_security_invoke_large_request_test" $(Q) ./bins/$(CONFIG)/chttp2_fake_security_invoke_large_request_test || ( echo test chttp2_fake_security_invoke_large_request_test failed ; exit 1 ) $(E) "[RUN] Testing chttp2_fake_security_max_concurrent_streams_test" @@ -719,6 +727,8 @@ test_c: buildtests_c $(Q) ./bins/$(CONFIG)/chttp2_fullstack_early_server_shutdown_finishes_inflight_calls_test || ( echo test chttp2_fullstack_early_server_shutdown_finishes_inflight_calls_test failed ; exit 1 ) $(E) "[RUN] Testing chttp2_fullstack_early_server_shutdown_finishes_tags_test" $(Q) ./bins/$(CONFIG)/chttp2_fullstack_early_server_shutdown_finishes_tags_test || ( echo test chttp2_fullstack_early_server_shutdown_finishes_tags_test failed ; exit 1 ) + $(E) "[RUN] Testing chttp2_fullstack_graceful_server_shutdown_test" + $(Q) ./bins/$(CONFIG)/chttp2_fullstack_graceful_server_shutdown_test || ( echo test chttp2_fullstack_graceful_server_shutdown_test failed ; exit 1 ) $(E) "[RUN] Testing chttp2_fullstack_invoke_large_request_test" $(Q) ./bins/$(CONFIG)/chttp2_fullstack_invoke_large_request_test || ( echo test chttp2_fullstack_invoke_large_request_test failed ; exit 1 ) $(E) "[RUN] Testing chttp2_fullstack_max_concurrent_streams_test" @@ -761,6 +771,8 @@ test_c: buildtests_c $(Q) ./bins/$(CONFIG)/chttp2_simple_ssl_fullstack_early_server_shutdown_finishes_inflight_calls_test || ( echo test chttp2_simple_ssl_fullstack_early_server_shutdown_finishes_inflight_calls_test failed ; exit 1 ) $(E) "[RUN] Testing chttp2_simple_ssl_fullstack_early_server_shutdown_finishes_tags_test" $(Q) ./bins/$(CONFIG)/chttp2_simple_ssl_fullstack_early_server_shutdown_finishes_tags_test || ( echo test chttp2_simple_ssl_fullstack_early_server_shutdown_finishes_tags_test failed ; exit 1 ) + $(E) "[RUN] Testing chttp2_simple_ssl_fullstack_graceful_server_shutdown_test" + $(Q) ./bins/$(CONFIG)/chttp2_simple_ssl_fullstack_graceful_server_shutdown_test || ( echo test chttp2_simple_ssl_fullstack_graceful_server_shutdown_test failed ; exit 1 ) $(E) "[RUN] Testing chttp2_simple_ssl_fullstack_invoke_large_request_test" $(Q) ./bins/$(CONFIG)/chttp2_simple_ssl_fullstack_invoke_large_request_test || ( echo test chttp2_simple_ssl_fullstack_invoke_large_request_test failed ; exit 1 ) $(E) "[RUN] Testing chttp2_simple_ssl_fullstack_max_concurrent_streams_test" @@ -803,6 +815,8 @@ test_c: buildtests_c $(Q) ./bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_early_server_shutdown_finishes_inflight_calls_test || ( echo test chttp2_simple_ssl_with_oauth2_fullstack_early_server_shutdown_finishes_inflight_calls_test failed ; exit 1 ) $(E) "[RUN] Testing chttp2_simple_ssl_with_oauth2_fullstack_early_server_shutdown_finishes_tags_test" $(Q) ./bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_early_server_shutdown_finishes_tags_test || ( echo test chttp2_simple_ssl_with_oauth2_fullstack_early_server_shutdown_finishes_tags_test failed ; exit 1 ) + $(E) "[RUN] Testing chttp2_simple_ssl_with_oauth2_fullstack_graceful_server_shutdown_test" + $(Q) ./bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_graceful_server_shutdown_test || ( echo test chttp2_simple_ssl_with_oauth2_fullstack_graceful_server_shutdown_test failed ; exit 1 ) $(E) "[RUN] Testing chttp2_simple_ssl_with_oauth2_fullstack_invoke_large_request_test" $(Q) ./bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_invoke_large_request_test || ( echo test chttp2_simple_ssl_with_oauth2_fullstack_invoke_large_request_test failed ; exit 1 ) $(E) "[RUN] Testing chttp2_simple_ssl_with_oauth2_fullstack_max_concurrent_streams_test" @@ -845,6 +859,8 @@ test_c: buildtests_c $(Q) ./bins/$(CONFIG)/chttp2_socket_pair_early_server_shutdown_finishes_inflight_calls_test || ( echo test chttp2_socket_pair_early_server_shutdown_finishes_inflight_calls_test failed ; exit 1 ) $(E) "[RUN] Testing chttp2_socket_pair_early_server_shutdown_finishes_tags_test" $(Q) ./bins/$(CONFIG)/chttp2_socket_pair_early_server_shutdown_finishes_tags_test || ( echo test chttp2_socket_pair_early_server_shutdown_finishes_tags_test failed ; exit 1 ) + $(E) "[RUN] Testing chttp2_socket_pair_graceful_server_shutdown_test" + $(Q) ./bins/$(CONFIG)/chttp2_socket_pair_graceful_server_shutdown_test || ( echo test chttp2_socket_pair_graceful_server_shutdown_test failed ; exit 1 ) $(E) "[RUN] Testing chttp2_socket_pair_invoke_large_request_test" $(Q) ./bins/$(CONFIG)/chttp2_socket_pair_invoke_large_request_test || ( echo test chttp2_socket_pair_invoke_large_request_test failed ; exit 1 ) $(E) "[RUN] Testing chttp2_socket_pair_max_concurrent_streams_test" @@ -887,6 +903,8 @@ test_c: buildtests_c $(Q) ./bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_early_server_shutdown_finishes_inflight_calls_test || ( echo test chttp2_socket_pair_one_byte_at_a_time_early_server_shutdown_finishes_inflight_calls_test failed ; exit 1 ) $(E) "[RUN] Testing chttp2_socket_pair_one_byte_at_a_time_early_server_shutdown_finishes_tags_test" $(Q) ./bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_early_server_shutdown_finishes_tags_test || ( echo test chttp2_socket_pair_one_byte_at_a_time_early_server_shutdown_finishes_tags_test failed ; exit 1 ) + $(E) "[RUN] Testing chttp2_socket_pair_one_byte_at_a_time_graceful_server_shutdown_test" + $(Q) ./bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_graceful_server_shutdown_test || ( echo test chttp2_socket_pair_one_byte_at_a_time_graceful_server_shutdown_test failed ; exit 1 ) $(E) "[RUN] Testing chttp2_socket_pair_one_byte_at_a_time_invoke_large_request_test" $(Q) ./bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_invoke_large_request_test || ( echo test chttp2_socket_pair_one_byte_at_a_time_invoke_large_request_test failed ; exit 1 ) $(E) "[RUN] Testing chttp2_socket_pair_one_byte_at_a_time_max_concurrent_streams_test" @@ -2488,6 +2506,28 @@ endif objs/$(CONFIG)/test/core/end2end/tests/early_server_shutdown_finishes_tags.o: +LIBEND2END_TEST_GRACEFUL_SERVER_SHUTDOWN_SRC = \ + test/core/end2end/tests/graceful_server_shutdown.c \ + + +LIBEND2END_TEST_GRACEFUL_SERVER_SHUTDOWN_OBJS = $(addprefix objs/$(CONFIG)/, $(addsuffix .o, $(basename $(LIBEND2END_TEST_GRACEFUL_SERVER_SHUTDOWN_SRC)))) + +libs/$(CONFIG)/libend2end_test_graceful_server_shutdown.a: $(ZLIB_DEP) $(LIBEND2END_TEST_GRACEFUL_SERVER_SHUTDOWN_OBJS) + $(E) "[AR] Creating $@" + $(Q) mkdir -p `dirname $@` + $(Q) $(AR) rcs libs/$(CONFIG)/libend2end_test_graceful_server_shutdown.a $(LIBEND2END_TEST_GRACEFUL_SERVER_SHUTDOWN_OBJS) + + + + + +ifneq ($(NO_DEPS),true) +-include $(LIBEND2END_TEST_GRACEFUL_SERVER_SHUTDOWN_OBJS:.o=.dep) +endif + +objs/$(CONFIG)/test/core/end2end/tests/graceful_server_shutdown.o: + + LIBEND2END_TEST_INVOKE_LARGE_REQUEST_SRC = \ test/core/end2end/tests/invoke_large_request.c \ @@ -5452,6 +5492,33 @@ endif endif +CHTTP2_FAKE_SECURITY_GRACEFUL_SERVER_SHUTDOWN_TEST_SRC = \ + +CHTTP2_FAKE_SECURITY_GRACEFUL_SERVER_SHUTDOWN_TEST_OBJS = $(addprefix objs/$(CONFIG)/, $(addsuffix .o, $(basename $(CHTTP2_FAKE_SECURITY_GRACEFUL_SERVER_SHUTDOWN_TEST_SRC)))) + +ifeq ($(NO_SECURE),true) + +bins/$(CONFIG)/chttp2_fake_security_graceful_server_shutdown_test: openssl_dep_error + +else + +bins/$(CONFIG)/chttp2_fake_security_graceful_server_shutdown_test: $(CHTTP2_FAKE_SECURITY_GRACEFUL_SERVER_SHUTDOWN_TEST_OBJS) libs/$(CONFIG)/libend2end_fixture_chttp2_fake_security.a libs/$(CONFIG)/libend2end_test_graceful_server_shutdown.a libs/$(CONFIG)/libend2end_certs.a libs/$(CONFIG)/libgrpc_test_util.a libs/$(CONFIG)/libgrpc.a libs/$(CONFIG)/libgpr_test_util.a libs/$(CONFIG)/libgpr.a + $(E) "[LD] Linking $@" + $(Q) mkdir -p `dirname $@` + $(Q) $(LD) $(LDFLAGS) $(CHTTP2_FAKE_SECURITY_GRACEFUL_SERVER_SHUTDOWN_TEST_OBJS) libs/$(CONFIG)/libend2end_fixture_chttp2_fake_security.a libs/$(CONFIG)/libend2end_test_graceful_server_shutdown.a libs/$(CONFIG)/libend2end_certs.a libs/$(CONFIG)/libgrpc_test_util.a libs/$(CONFIG)/libgrpc.a libs/$(CONFIG)/libgpr_test_util.a libs/$(CONFIG)/libgpr.a $(LDLIBS) $(LDLIBS_SECURE) -o bins/$(CONFIG)/chttp2_fake_security_graceful_server_shutdown_test + +endif + + +deps_chttp2_fake_security_graceful_server_shutdown_test: $(CHTTP2_FAKE_SECURITY_GRACEFUL_SERVER_SHUTDOWN_TEST_OBJS:.o=.dep) + +ifneq ($(NO_SECURE),true) +ifneq ($(NO_DEPS),true) +-include $(CHTTP2_FAKE_SECURITY_GRACEFUL_SERVER_SHUTDOWN_TEST_OBJS:.o=.dep) +endif +endif + + CHTTP2_FAKE_SECURITY_INVOKE_LARGE_REQUEST_TEST_SRC = \ CHTTP2_FAKE_SECURITY_INVOKE_LARGE_REQUEST_TEST_OBJS = $(addprefix objs/$(CONFIG)/, $(addsuffix .o, $(basename $(CHTTP2_FAKE_SECURITY_INVOKE_LARGE_REQUEST_TEST_SRC)))) @@ -6019,6 +6086,33 @@ endif endif +CHTTP2_FULLSTACK_GRACEFUL_SERVER_SHUTDOWN_TEST_SRC = \ + +CHTTP2_FULLSTACK_GRACEFUL_SERVER_SHUTDOWN_TEST_OBJS = $(addprefix objs/$(CONFIG)/, $(addsuffix .o, $(basename $(CHTTP2_FULLSTACK_GRACEFUL_SERVER_SHUTDOWN_TEST_SRC)))) + +ifeq ($(NO_SECURE),true) + +bins/$(CONFIG)/chttp2_fullstack_graceful_server_shutdown_test: openssl_dep_error + +else + +bins/$(CONFIG)/chttp2_fullstack_graceful_server_shutdown_test: $(CHTTP2_FULLSTACK_GRACEFUL_SERVER_SHUTDOWN_TEST_OBJS) libs/$(CONFIG)/libend2end_fixture_chttp2_fullstack.a libs/$(CONFIG)/libend2end_test_graceful_server_shutdown.a libs/$(CONFIG)/libend2end_certs.a libs/$(CONFIG)/libgrpc_test_util.a libs/$(CONFIG)/libgrpc.a libs/$(CONFIG)/libgpr_test_util.a libs/$(CONFIG)/libgpr.a + $(E) "[LD] Linking $@" + $(Q) mkdir -p `dirname $@` + $(Q) $(LD) $(LDFLAGS) $(CHTTP2_FULLSTACK_GRACEFUL_SERVER_SHUTDOWN_TEST_OBJS) libs/$(CONFIG)/libend2end_fixture_chttp2_fullstack.a libs/$(CONFIG)/libend2end_test_graceful_server_shutdown.a libs/$(CONFIG)/libend2end_certs.a libs/$(CONFIG)/libgrpc_test_util.a libs/$(CONFIG)/libgrpc.a libs/$(CONFIG)/libgpr_test_util.a libs/$(CONFIG)/libgpr.a $(LDLIBS) $(LDLIBS_SECURE) -o bins/$(CONFIG)/chttp2_fullstack_graceful_server_shutdown_test + +endif + + +deps_chttp2_fullstack_graceful_server_shutdown_test: $(CHTTP2_FULLSTACK_GRACEFUL_SERVER_SHUTDOWN_TEST_OBJS:.o=.dep) + +ifneq ($(NO_SECURE),true) +ifneq ($(NO_DEPS),true) +-include $(CHTTP2_FULLSTACK_GRACEFUL_SERVER_SHUTDOWN_TEST_OBJS:.o=.dep) +endif +endif + + CHTTP2_FULLSTACK_INVOKE_LARGE_REQUEST_TEST_SRC = \ CHTTP2_FULLSTACK_INVOKE_LARGE_REQUEST_TEST_OBJS = $(addprefix objs/$(CONFIG)/, $(addsuffix .o, $(basename $(CHTTP2_FULLSTACK_INVOKE_LARGE_REQUEST_TEST_SRC)))) @@ -6586,6 +6680,33 @@ endif endif +CHTTP2_SIMPLE_SSL_FULLSTACK_GRACEFUL_SERVER_SHUTDOWN_TEST_SRC = \ + +CHTTP2_SIMPLE_SSL_FULLSTACK_GRACEFUL_SERVER_SHUTDOWN_TEST_OBJS = $(addprefix objs/$(CONFIG)/, $(addsuffix .o, $(basename $(CHTTP2_SIMPLE_SSL_FULLSTACK_GRACEFUL_SERVER_SHUTDOWN_TEST_SRC)))) + +ifeq ($(NO_SECURE),true) + +bins/$(CONFIG)/chttp2_simple_ssl_fullstack_graceful_server_shutdown_test: openssl_dep_error + +else + +bins/$(CONFIG)/chttp2_simple_ssl_fullstack_graceful_server_shutdown_test: $(CHTTP2_SIMPLE_SSL_FULLSTACK_GRACEFUL_SERVER_SHUTDOWN_TEST_OBJS) libs/$(CONFIG)/libend2end_fixture_chttp2_simple_ssl_fullstack.a libs/$(CONFIG)/libend2end_test_graceful_server_shutdown.a libs/$(CONFIG)/libend2end_certs.a libs/$(CONFIG)/libgrpc_test_util.a libs/$(CONFIG)/libgrpc.a libs/$(CONFIG)/libgpr_test_util.a libs/$(CONFIG)/libgpr.a + $(E) "[LD] Linking $@" + $(Q) mkdir -p `dirname $@` + $(Q) $(LD) $(LDFLAGS) $(CHTTP2_SIMPLE_SSL_FULLSTACK_GRACEFUL_SERVER_SHUTDOWN_TEST_OBJS) libs/$(CONFIG)/libend2end_fixture_chttp2_simple_ssl_fullstack.a libs/$(CONFIG)/libend2end_test_graceful_server_shutdown.a libs/$(CONFIG)/libend2end_certs.a libs/$(CONFIG)/libgrpc_test_util.a libs/$(CONFIG)/libgrpc.a libs/$(CONFIG)/libgpr_test_util.a libs/$(CONFIG)/libgpr.a $(LDLIBS) $(LDLIBS_SECURE) -o bins/$(CONFIG)/chttp2_simple_ssl_fullstack_graceful_server_shutdown_test + +endif + + +deps_chttp2_simple_ssl_fullstack_graceful_server_shutdown_test: $(CHTTP2_SIMPLE_SSL_FULLSTACK_GRACEFUL_SERVER_SHUTDOWN_TEST_OBJS:.o=.dep) + +ifneq ($(NO_SECURE),true) +ifneq ($(NO_DEPS),true) +-include $(CHTTP2_SIMPLE_SSL_FULLSTACK_GRACEFUL_SERVER_SHUTDOWN_TEST_OBJS:.o=.dep) +endif +endif + + CHTTP2_SIMPLE_SSL_FULLSTACK_INVOKE_LARGE_REQUEST_TEST_SRC = \ CHTTP2_SIMPLE_SSL_FULLSTACK_INVOKE_LARGE_REQUEST_TEST_OBJS = $(addprefix objs/$(CONFIG)/, $(addsuffix .o, $(basename $(CHTTP2_SIMPLE_SSL_FULLSTACK_INVOKE_LARGE_REQUEST_TEST_SRC)))) @@ -7153,6 +7274,33 @@ endif endif +CHTTP2_SIMPLE_SSL_WITH_OAUTH2_FULLSTACK_GRACEFUL_SERVER_SHUTDOWN_TEST_SRC = \ + +CHTTP2_SIMPLE_SSL_WITH_OAUTH2_FULLSTACK_GRACEFUL_SERVER_SHUTDOWN_TEST_OBJS = $(addprefix objs/$(CONFIG)/, $(addsuffix .o, $(basename $(CHTTP2_SIMPLE_SSL_WITH_OAUTH2_FULLSTACK_GRACEFUL_SERVER_SHUTDOWN_TEST_SRC)))) + +ifeq ($(NO_SECURE),true) + +bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_graceful_server_shutdown_test: openssl_dep_error + +else + +bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_graceful_server_shutdown_test: $(CHTTP2_SIMPLE_SSL_WITH_OAUTH2_FULLSTACK_GRACEFUL_SERVER_SHUTDOWN_TEST_OBJS) libs/$(CONFIG)/libend2end_fixture_chttp2_simple_ssl_with_oauth2_fullstack.a libs/$(CONFIG)/libend2end_test_graceful_server_shutdown.a libs/$(CONFIG)/libend2end_certs.a libs/$(CONFIG)/libgrpc_test_util.a libs/$(CONFIG)/libgrpc.a libs/$(CONFIG)/libgpr_test_util.a libs/$(CONFIG)/libgpr.a + $(E) "[LD] Linking $@" + $(Q) mkdir -p `dirname $@` + $(Q) $(LD) $(LDFLAGS) $(CHTTP2_SIMPLE_SSL_WITH_OAUTH2_FULLSTACK_GRACEFUL_SERVER_SHUTDOWN_TEST_OBJS) libs/$(CONFIG)/libend2end_fixture_chttp2_simple_ssl_with_oauth2_fullstack.a libs/$(CONFIG)/libend2end_test_graceful_server_shutdown.a libs/$(CONFIG)/libend2end_certs.a libs/$(CONFIG)/libgrpc_test_util.a libs/$(CONFIG)/libgrpc.a libs/$(CONFIG)/libgpr_test_util.a libs/$(CONFIG)/libgpr.a $(LDLIBS) $(LDLIBS_SECURE) -o bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_graceful_server_shutdown_test + +endif + + +deps_chttp2_simple_ssl_with_oauth2_fullstack_graceful_server_shutdown_test: $(CHTTP2_SIMPLE_SSL_WITH_OAUTH2_FULLSTACK_GRACEFUL_SERVER_SHUTDOWN_TEST_OBJS:.o=.dep) + +ifneq ($(NO_SECURE),true) +ifneq ($(NO_DEPS),true) +-include $(CHTTP2_SIMPLE_SSL_WITH_OAUTH2_FULLSTACK_GRACEFUL_SERVER_SHUTDOWN_TEST_OBJS:.o=.dep) +endif +endif + + CHTTP2_SIMPLE_SSL_WITH_OAUTH2_FULLSTACK_INVOKE_LARGE_REQUEST_TEST_SRC = \ CHTTP2_SIMPLE_SSL_WITH_OAUTH2_FULLSTACK_INVOKE_LARGE_REQUEST_TEST_OBJS = $(addprefix objs/$(CONFIG)/, $(addsuffix .o, $(basename $(CHTTP2_SIMPLE_SSL_WITH_OAUTH2_FULLSTACK_INVOKE_LARGE_REQUEST_TEST_SRC)))) @@ -7720,6 +7868,33 @@ endif endif +CHTTP2_SOCKET_PAIR_GRACEFUL_SERVER_SHUTDOWN_TEST_SRC = \ + +CHTTP2_SOCKET_PAIR_GRACEFUL_SERVER_SHUTDOWN_TEST_OBJS = $(addprefix objs/$(CONFIG)/, $(addsuffix .o, $(basename $(CHTTP2_SOCKET_PAIR_GRACEFUL_SERVER_SHUTDOWN_TEST_SRC)))) + +ifeq ($(NO_SECURE),true) + +bins/$(CONFIG)/chttp2_socket_pair_graceful_server_shutdown_test: openssl_dep_error + +else + +bins/$(CONFIG)/chttp2_socket_pair_graceful_server_shutdown_test: $(CHTTP2_SOCKET_PAIR_GRACEFUL_SERVER_SHUTDOWN_TEST_OBJS) libs/$(CONFIG)/libend2end_fixture_chttp2_socket_pair.a libs/$(CONFIG)/libend2end_test_graceful_server_shutdown.a libs/$(CONFIG)/libend2end_certs.a libs/$(CONFIG)/libgrpc_test_util.a libs/$(CONFIG)/libgrpc.a libs/$(CONFIG)/libgpr_test_util.a libs/$(CONFIG)/libgpr.a + $(E) "[LD] Linking $@" + $(Q) mkdir -p `dirname $@` + $(Q) $(LD) $(LDFLAGS) $(CHTTP2_SOCKET_PAIR_GRACEFUL_SERVER_SHUTDOWN_TEST_OBJS) libs/$(CONFIG)/libend2end_fixture_chttp2_socket_pair.a libs/$(CONFIG)/libend2end_test_graceful_server_shutdown.a libs/$(CONFIG)/libend2end_certs.a libs/$(CONFIG)/libgrpc_test_util.a libs/$(CONFIG)/libgrpc.a libs/$(CONFIG)/libgpr_test_util.a libs/$(CONFIG)/libgpr.a $(LDLIBS) $(LDLIBS_SECURE) -o bins/$(CONFIG)/chttp2_socket_pair_graceful_server_shutdown_test + +endif + + +deps_chttp2_socket_pair_graceful_server_shutdown_test: $(CHTTP2_SOCKET_PAIR_GRACEFUL_SERVER_SHUTDOWN_TEST_OBJS:.o=.dep) + +ifneq ($(NO_SECURE),true) +ifneq ($(NO_DEPS),true) +-include $(CHTTP2_SOCKET_PAIR_GRACEFUL_SERVER_SHUTDOWN_TEST_OBJS:.o=.dep) +endif +endif + + CHTTP2_SOCKET_PAIR_INVOKE_LARGE_REQUEST_TEST_SRC = \ CHTTP2_SOCKET_PAIR_INVOKE_LARGE_REQUEST_TEST_OBJS = $(addprefix objs/$(CONFIG)/, $(addsuffix .o, $(basename $(CHTTP2_SOCKET_PAIR_INVOKE_LARGE_REQUEST_TEST_SRC)))) @@ -8287,6 +8462,33 @@ endif endif +CHTTP2_SOCKET_PAIR_ONE_BYTE_AT_A_TIME_GRACEFUL_SERVER_SHUTDOWN_TEST_SRC = \ + +CHTTP2_SOCKET_PAIR_ONE_BYTE_AT_A_TIME_GRACEFUL_SERVER_SHUTDOWN_TEST_OBJS = $(addprefix objs/$(CONFIG)/, $(addsuffix .o, $(basename $(CHTTP2_SOCKET_PAIR_ONE_BYTE_AT_A_TIME_GRACEFUL_SERVER_SHUTDOWN_TEST_SRC)))) + +ifeq ($(NO_SECURE),true) + +bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_graceful_server_shutdown_test: openssl_dep_error + +else + +bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_graceful_server_shutdown_test: $(CHTTP2_SOCKET_PAIR_ONE_BYTE_AT_A_TIME_GRACEFUL_SERVER_SHUTDOWN_TEST_OBJS) libs/$(CONFIG)/libend2end_fixture_chttp2_socket_pair_one_byte_at_a_time.a libs/$(CONFIG)/libend2end_test_graceful_server_shutdown.a libs/$(CONFIG)/libend2end_certs.a libs/$(CONFIG)/libgrpc_test_util.a libs/$(CONFIG)/libgrpc.a libs/$(CONFIG)/libgpr_test_util.a libs/$(CONFIG)/libgpr.a + $(E) "[LD] Linking $@" + $(Q) mkdir -p `dirname $@` + $(Q) $(LD) $(LDFLAGS) $(CHTTP2_SOCKET_PAIR_ONE_BYTE_AT_A_TIME_GRACEFUL_SERVER_SHUTDOWN_TEST_OBJS) libs/$(CONFIG)/libend2end_fixture_chttp2_socket_pair_one_byte_at_a_time.a libs/$(CONFIG)/libend2end_test_graceful_server_shutdown.a libs/$(CONFIG)/libend2end_certs.a libs/$(CONFIG)/libgrpc_test_util.a libs/$(CONFIG)/libgrpc.a libs/$(CONFIG)/libgpr_test_util.a libs/$(CONFIG)/libgpr.a $(LDLIBS) $(LDLIBS_SECURE) -o bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_graceful_server_shutdown_test + +endif + + +deps_chttp2_socket_pair_one_byte_at_a_time_graceful_server_shutdown_test: $(CHTTP2_SOCKET_PAIR_ONE_BYTE_AT_A_TIME_GRACEFUL_SERVER_SHUTDOWN_TEST_OBJS:.o=.dep) + +ifneq ($(NO_SECURE),true) +ifneq ($(NO_DEPS),true) +-include $(CHTTP2_SOCKET_PAIR_ONE_BYTE_AT_A_TIME_GRACEFUL_SERVER_SHUTDOWN_TEST_OBJS:.o=.dep) +endif +endif + + CHTTP2_SOCKET_PAIR_ONE_BYTE_AT_A_TIME_INVOKE_LARGE_REQUEST_TEST_SRC = \ CHTTP2_SOCKET_PAIR_ONE_BYTE_AT_A_TIME_INVOKE_LARGE_REQUEST_TEST_OBJS = $(addprefix objs/$(CONFIG)/, $(addsuffix .o, $(basename $(CHTTP2_SOCKET_PAIR_ONE_BYTE_AT_A_TIME_INVOKE_LARGE_REQUEST_TEST_SRC)))) diff --git a/include/grpc/grpc.h b/include/grpc/grpc.h index 40a3d2acb5..3c5b0de195 100644 --- a/include/grpc/grpc.h +++ b/include/grpc/grpc.h @@ -194,6 +194,7 @@ typedef enum grpc_completion_type { GRPC_FINISHED, /* An RPC has finished. The event contains status. On the server this will be OK or Cancelled. */ GRPC_SERVER_RPC_NEW, /* A new RPC has arrived at the server */ + GRPC_SERVER_SHUTDOWN, /* The server has finished shutting down */ GRPC_COMPLETION_DO_NOT_USE /* must be last, forces users to include a default: case */ } grpc_completion_type; @@ -439,6 +440,10 @@ void grpc_server_start(grpc_server *server); Existing calls will be allowed to complete. */ void grpc_server_shutdown(grpc_server *server); +/* As per grpc_server_shutdown, but send a GRPC_SERVER_SHUTDOWN event when + there are no more calls being serviced. */ +void grpc_server_shutdown_and_notify(grpc_server *server, void *tag); + /* Destroy a server. Forcefully cancels all existing calls. */ void grpc_server_destroy(grpc_server *server); diff --git a/src/core/surface/completion_queue.c b/src/core/surface/completion_queue.c index 0f09933fc0..652f23e888 100644 --- a/src/core/surface/completion_queue.c +++ b/src/core/surface/completion_queue.c @@ -155,6 +155,13 @@ static void end_op_locked(grpc_completion_queue *cc, } } +void grpc_cq_end_server_shutdown(grpc_completion_queue *cc, void *tag) { + gpr_mu_lock(GRPC_POLLSET_MU(&cc->pollset)); + add_locked(cc, GRPC_SERVER_SHUTDOWN, tag, NULL, NULL, NULL); + end_op_locked(cc, GRPC_SERVER_SHUTDOWN); + gpr_mu_unlock(GRPC_POLLSET_MU(&cc->pollset)); +} + void grpc_cq_end_read(grpc_completion_queue *cc, void *tag, grpc_call *call, grpc_event_finish_func on_finish, void *user_data, grpc_byte_buffer *read) { diff --git a/src/core/surface/completion_queue.h b/src/core/surface/completion_queue.h index 5e45749396..85984075f7 100644 --- a/src/core/surface/completion_queue.h +++ b/src/core/surface/completion_queue.h @@ -97,6 +97,8 @@ void grpc_cq_end_new_rpc(grpc_completion_queue *cc, void *tag, grpc_call *call, gpr_timespec deadline, size_t metadata_count, grpc_metadata *metadata_elements); +void grpc_cq_end_server_shutdown(grpc_completion_queue *cc, void *tag); + /* disable polling for some tests */ void grpc_completion_queue_dont_poll_test_only(grpc_completion_queue *cc); diff --git a/src/core/surface/event_string.c b/src/core/surface/event_string.c index 8bd8049520..8ae2af7472 100644 --- a/src/core/surface/event_string.c +++ b/src/core/surface/event_string.c @@ -63,6 +63,9 @@ char *grpc_event_string(grpc_event *ev) { if (ev == NULL) return gpr_strdup("null"); switch (ev->type) { + case GRPC_SERVER_SHUTDOWN: + p += sprintf(p, "SERVER_SHUTDOWN"); + break; case GRPC_QUEUE_SHUTDOWN: p += sprintf(p, "QUEUE_SHUTDOWN"); break; diff --git a/src/core/surface/server.c b/src/core/surface/server.c index 167bfe97d1..846a00c94f 100644 --- a/src/core/surface/server.c +++ b/src/core/surface/server.c @@ -81,6 +81,8 @@ struct grpc_server { size_t tag_cap; gpr_uint8 shutdown; + gpr_uint8 have_shutdown_tag; + void *shutdown_tag; call_data *lists[CALL_LIST_COUNT]; channel_data root_channel_data; @@ -375,6 +377,10 @@ static void destroy_call_elem(grpc_call_element *elem) { for (i = 0; i < CALL_LIST_COUNT; i++) { call_list_remove(chand->server, elem->call_data, i); } + if (chand->server->shutdown && chand->server->have_shutdown_tag && + chand->server->lists[ALL_CALLS] == NULL) { + grpc_cq_end_server_shutdown(chand->server->cq, chand->server->shutdown_tag); + } gpr_mu_unlock(&chand->server->mu); server_unref(chand->server); @@ -513,7 +519,8 @@ grpc_transport_setup_result grpc_server_setup_transport( grpc_channel_get_channel_stack(channel), transport); } -void grpc_server_shutdown(grpc_server *server) { +void shutdown_internal(grpc_server *server, gpr_uint8 have_shutdown_tag, + void *shutdown_tag) { listener *l; void **tags; size_t ntags; @@ -551,6 +558,14 @@ void grpc_server_shutdown(grpc_server *server) { server->ntags = 0; server->shutdown = 1; + server->have_shutdown_tag = have_shutdown_tag; + server->shutdown_tag = shutdown_tag; + if (have_shutdown_tag) { + grpc_cq_begin_op(server->cq, NULL, GRPC_SERVER_SHUTDOWN); + if (server->lists[ALL_CALLS] == NULL) { + grpc_cq_end_server_shutdown(server->cq, shutdown_tag); + } + } gpr_mu_unlock(&server->mu); for (i = 0; i < nchannels; i++) { @@ -583,6 +598,14 @@ void grpc_server_shutdown(grpc_server *server) { } } +void grpc_server_shutdown(grpc_server *server) { + shutdown_internal(server, 0, NULL); +} + +void grpc_server_shutdown_and_notify(grpc_server *server, void *tag) { + shutdown_internal(server, 1, tag); +} + void grpc_server_destroy(grpc_server *server) { channel_data *c; gpr_mu_lock(&server->mu); diff --git a/test/core/end2end/cq_verifier.c b/test/core/end2end/cq_verifier.c index e5b7304743..cfb3bbad7e 100644 --- a/test/core/end2end/cq_verifier.c +++ b/test/core/end2end/cq_verifier.c @@ -223,6 +223,8 @@ static void verify_matches(expectation *e, grpc_event *ev) { GPR_ASSERT(ev->data.read == NULL); } break; + case GRPC_SERVER_SHUTDOWN: + break; case GRPC_COMPLETION_DO_NOT_USE: gpr_log(GPR_ERROR, "not implemented"); abort(); @@ -295,6 +297,8 @@ static size_t expectation_to_string(char *out, expectation *e) { len = sprintf(out, "GRPC_READ data=%s", str); gpr_free(str); return len; + case GRPC_SERVER_SHUTDOWN: + return sprintf(out, "GRPC_SERVER_SHUTDOWN"); case GRPC_COMPLETION_DO_NOT_USE: case GRPC_QUEUE_SHUTDOWN: gpr_log(GPR_ERROR, "not implemented"); @@ -487,3 +491,7 @@ void cq_expect_finished(cq_verifier *v, void *tag, ...) { finished_internal(v, tag, GRPC_STATUS__DO_NOT_USE, NULL, args); va_end(args); } + +void cq_expect_server_shutdown(cq_verifier *v, void *tag) { + add(v, GRPC_SERVER_SHUTDOWN, tag); +} \ No newline at end of file diff --git a/test/core/end2end/cq_verifier.h b/test/core/end2end/cq_verifier.h index 034aefdd5c..a1966c14c5 100644 --- a/test/core/end2end/cq_verifier.h +++ b/test/core/end2end/cq_verifier.h @@ -70,5 +70,6 @@ void cq_expect_finished_with_status(cq_verifier *v, void *tag, grpc_status_code status_code, const char *details, ...); void cq_expect_finished(cq_verifier *v, void *tag, ...); +void cq_expect_server_shutdown(cq_verifier *v, void *tag); #endif /* __GRPC_TEST_END2END_CQ_VERIFIER_H__ */ diff --git a/test/core/end2end/gen_build_json.py b/test/core/end2end/gen_build_json.py index b91995bc76..e8ae5056c3 100755 --- a/test/core/end2end/gen_build_json.py +++ b/test/core/end2end/gen_build_json.py @@ -25,6 +25,7 @@ END2END_TESTS = [ 'disappearing_server', 'early_server_shutdown_finishes_inflight_calls', 'early_server_shutdown_finishes_tags', + 'graceful_server_shutdown', 'invoke_large_request', 'max_concurrent_streams', 'no_op', diff --git a/test/core/end2end/tests/graceful_server_shutdown.c b/test/core/end2end/tests/graceful_server_shutdown.c new file mode 100644 index 0000000000..0815306963 --- /dev/null +++ b/test/core/end2end/tests/graceful_server_shutdown.c @@ -0,0 +1,160 @@ +/* + * + * Copyright 2014, 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. + * + */ + +#include "test/core/end2end/end2end_tests.h" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include "test/core/end2end/cq_verifier.h" + +enum { TIMEOUT = 200000 }; + +static void *tag(gpr_intptr t) { return (void *)t; } + +static grpc_end2end_test_fixture begin_test(grpc_end2end_test_config config, + const char *test_name, + grpc_channel_args *client_args, + grpc_channel_args *server_args) { + grpc_end2end_test_fixture f; + gpr_log(GPR_INFO, "%s/%s", test_name, config.name); + f = config.create_fixture(client_args, server_args); + config.init_client(&f, client_args); + config.init_server(&f, server_args); + return f; +} + +static gpr_timespec n_seconds_time(int n) { + return gpr_time_add(gpr_now(), gpr_time_from_micros(GPR_US_PER_SEC * n)); +} + +static gpr_timespec five_seconds_time(void) { return n_seconds_time(5); } + +static void drain_cq(grpc_completion_queue *cq) { + grpc_event *ev; + grpc_completion_type type; + do { + ev = grpc_completion_queue_next(cq, five_seconds_time()); + GPR_ASSERT(ev); + type = ev->type; + grpc_event_finish(ev); + } while (type != GRPC_QUEUE_SHUTDOWN); +} + +static void shutdown_server(grpc_end2end_test_fixture *f) { + if (!f->server) return; + grpc_server_destroy(f->server); + f->server = NULL; +} + +static void shutdown_client(grpc_end2end_test_fixture *f) { + if (!f->client) return; + grpc_channel_destroy(f->client); + f->client = NULL; +} + +static void end_test(grpc_end2end_test_fixture *f) { + shutdown_server(f); + shutdown_client(f); + + grpc_completion_queue_shutdown(f->server_cq); + drain_cq(f->server_cq); + grpc_completion_queue_destroy(f->server_cq); + grpc_completion_queue_shutdown(f->client_cq); + drain_cq(f->client_cq); + grpc_completion_queue_destroy(f->client_cq); +} + +static void test_early_server_shutdown_finishes_inflight_calls( + grpc_end2end_test_config config) { + grpc_end2end_test_fixture f = begin_test(config, __FUNCTION__, NULL, NULL); + grpc_call *c; + grpc_call *s; + gpr_timespec deadline = five_seconds_time(); + cq_verifier *v_client = cq_verifier_create(f.client_cq); + cq_verifier *v_server = cq_verifier_create(f.server_cq); + + c = grpc_channel_create_call(f.client, "/foo", "test.google.com", deadline); + GPR_ASSERT(c); + + GPR_ASSERT(GRPC_CALL_OK == + grpc_call_start_invoke(c, f.client_cq, tag(1), tag(2), tag(3), 0)); + cq_expect_invoke_accepted(v_client, tag(1), GRPC_OP_OK); + cq_verify(v_client); + + GPR_ASSERT(GRPC_CALL_OK == grpc_call_writes_done(c, tag(4))); + cq_expect_finish_accepted(v_client, tag(4), GRPC_OP_OK); + cq_verify(v_client); + + GPR_ASSERT(GRPC_CALL_OK == grpc_server_request_call(f.server, tag(100))); + cq_expect_server_rpc_new(v_server, &s, tag(100), "/foo", "test.google.com", + deadline, NULL); + cq_verify(v_server); + + GPR_ASSERT(GRPC_CALL_OK == grpc_call_server_accept(s, f.server_cq, tag(102))); + GPR_ASSERT(GRPC_CALL_OK == grpc_call_server_end_initial_metadata(s, 0)); + cq_expect_client_metadata_read(v_client, tag(2), NULL); + cq_verify(v_client); + + /* shutdown the server */ + grpc_server_shutdown_and_notify(f.server, tag(0xdead)); + cq_verify_empty(v_server); + + grpc_call_start_write_status(s, GRPC_STATUS_OK, NULL, tag(103)); + grpc_call_destroy(s); + cq_expect_finish_accepted(v_server, tag(103), GRPC_OP_OK); + cq_expect_finished(v_server, tag(102), NULL); + cq_expect_server_shutdown(v_server, tag(0xdead)); + cq_verify(v_server); + + cq_expect_finished_with_status(v_client, tag(3), GRPC_OP_OK, NULL, NULL); + cq_verify(v_client); + + grpc_call_destroy(c); + + cq_verifier_destroy(v_client); + cq_verifier_destroy(v_server); + + end_test(&f); + config.tear_down_data(&f); +} + +void grpc_end2end_tests(grpc_end2end_test_config config) { + test_early_server_shutdown_finishes_inflight_calls(config); +} -- cgit v1.2.3 From aac57fde95e19fc1c0062747aca748cc8e5e9980 Mon Sep 17 00:00:00 2001 From: Craig Tiller Date: Fri, 16 Jan 2015 12:54:26 -0800 Subject: Build php modules from run_tests.py --- src/php/ext/grpc/config.m4 | 12 +++++++++--- tools/run_tests/build_php.sh | 21 +++++++++++++++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/php/ext/grpc/config.m4 b/src/php/ext/grpc/config.m4 index d7d13f413e..f8f15ce968 100755 --- a/src/php/ext/grpc/config.m4 +++ b/src/php/ext/grpc/config.m4 @@ -38,7 +38,13 @@ if test "$PHP_GRPC" != "no"; then PHP_ADD_LIBRARY(rt,,GRPC_SHARED_LIBADD) PHP_ADD_LIBRARY(rt) - PHP_ADD_LIBPATH($GRPC_DIR/lib) + if test -e $GRPC_DIR/libs/opt; then + GRPC_LIBDIR=$GRPC_DIR/libs/opt + else + GRPC_LIBDIR=$GRPC_DIR/lib + fi + + PHP_ADD_LIBPATH($GRPC_LIBDIR) PHP_CHECK_LIBRARY(gpr,gpr_now, [ @@ -48,7 +54,7 @@ if test "$PHP_GRPC" != "no"; then ],[ AC_MSG_ERROR([wrong gpr lib version or lib not found]) ],[ - -L$GRPC_DIR/lib + -L$GRPC_LIBDIR ]) PHP_ADD_LIBRARY(event,,GRPC_SHARED_LIBADD) @@ -68,7 +74,7 @@ if test "$PHP_GRPC" != "no"; then ],[ AC_MSG_ERROR([wrong grpc lib version or lib not found]) ],[ - -L$GRPC_DIR/lib + -L$GRPC_LIBDIR ]) PHP_SUBST(GRPC_SHARED_LIBADD) diff --git a/tools/run_tests/build_php.sh b/tools/run_tests/build_php.sh index a9bf588e2f..996ddce29b 100755 --- a/tools/run_tests/build_php.sh +++ b/tools/run_tests/build_php.sh @@ -1 +1,22 @@ #!/bin/bash + +set -ex + +# change to grpc repo root +cd $(dirname $0)/../.. + +export GRPC_DIR=`pwd` + +# make the libraries +make -j shared_c + +# build php +cd src/php + +cd ext/grpc +phpize +cd ../.. +ext/grpc/configure +#cd ext/grpc +make + -- cgit v1.2.3 From e94373360f3f0d5167b0c893385335736cb84a3f Mon Sep 17 00:00:00 2001 From: Craig Tiller Date: Fri, 16 Jan 2015 12:59:26 -0800 Subject: Add shebang --- src/php/bin/run_tests.sh | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/php/bin/run_tests.sh b/src/php/bin/run_tests.sh index cf4cc78a52..d221e66642 100755 --- a/src/php/bin/run_tests.sh +++ b/src/php/bin/run_tests.sh @@ -1,3 +1,4 @@ +#!/bin/sh # Loads the local shared library, and runs all of the test cases in tests/ # against it cd $(dirname $0) -- cgit v1.2.3 From 1b3a881f8fbf00a7b278cf60cc37b892c751c10a Mon Sep 17 00:00:00 2001 From: Craig Tiller Date: Fri, 16 Jan 2015 13:02:33 -0800 Subject: Dont hardcode phpunit director --- src/php/bin/run_tests.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/php/bin/run_tests.sh b/src/php/bin/run_tests.sh index d221e66642..50175e5b06 100755 --- a/src/php/bin/run_tests.sh +++ b/src/php/bin/run_tests.sh @@ -3,4 +3,4 @@ # against it cd $(dirname $0) php -d extension_dir=../ext/grpc/modules/ -d extension=grpc.so \ - /usr/local/bin/phpunit -v --debug --strict ../tests/unit_tests + phpunit -v --debug --strict ../tests/unit_tests -- cgit v1.2.3 From ff7cdd3badc3517773b8dc13468982ee370d3db7 Mon Sep 17 00:00:00 2001 From: Craig Tiller Date: Fri, 16 Jan 2015 13:04:08 -0800 Subject: Use local .gitignore --- .gitignore | 3 --- src/php/.gitignore | 5 ++++- 2 files changed, 4 insertions(+), 4 deletions(-) mode change 100755 => 100644 src/php/.gitignore (limited to 'src') diff --git a/.gitignore b/.gitignore index 914cb45d65..954b3cfcc1 100644 --- a/.gitignore +++ b/.gitignore @@ -10,6 +10,3 @@ objs # cache for run_tests.py .run_tests_cache -# phpize output -src/php/ext/grpc/ltmain.sh - diff --git a/src/php/.gitignore b/src/php/.gitignore old mode 100755 new mode 100644 index 00fbd965dc..0bb5f8e956 --- a/src/php/.gitignore +++ b/src/php/.gitignore @@ -15,4 +15,7 @@ run-tests.php install-sh libtool missing -mkinstalldirs \ No newline at end of file +mkinstalldirs + +ext/grpc/ltmain.sh + -- cgit v1.2.3 From 62b03e2d9f9930217a289392c2af84dccaf46927 Mon Sep 17 00:00:00 2001 From: Craig Tiller Date: Fri, 16 Jan 2015 13:19:16 -0800 Subject: Sym-link in system extensions --- src/php/bin/run_tests.sh | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/php/bin/run_tests.sh b/src/php/bin/run_tests.sh index 50175e5b06..c334ad9091 100755 --- a/src/php/bin/run_tests.sh +++ b/src/php/bin/run_tests.sh @@ -1,6 +1,17 @@ #!/bin/sh # Loads the local shared library, and runs all of the test cases in tests/ # against it +set -ex cd $(dirname $0) -php -d extension_dir=../ext/grpc/modules/ -d extension=grpc.so \ +default_extension_dir=`php -i | grep extension_dir | sed 's/.*=> //g'` + +# sym-link in system supplied extensions +for f in $default_extension_dir/*.so +do + ln -s $f ../ext/grpc/modules/$(basename $f) || true +done + +php \ + -d extension_dir=../ext/grpc/modules/ \ + -d extension=grpc.so \ phpunit -v --debug --strict ../tests/unit_tests -- cgit v1.2.3 From eb65ac997413eab7edc3281a1b92034629bfb4ea Mon Sep 17 00:00:00 2001 From: Craig Tiller Date: Fri, 16 Jan 2015 13:23:07 -0800 Subject: Remove libevent references --- src/php/ext/grpc/config.m4 | 9 --------- 1 file changed, 9 deletions(-) (limited to 'src') diff --git a/src/php/ext/grpc/config.m4 b/src/php/ext/grpc/config.m4 index f8f15ce968..7652ca74aa 100755 --- a/src/php/ext/grpc/config.m4 +++ b/src/php/ext/grpc/config.m4 @@ -57,15 +57,6 @@ if test "$PHP_GRPC" != "no"; then -L$GRPC_LIBDIR ]) - PHP_ADD_LIBRARY(event,,GRPC_SHARED_LIBADD) - PHP_ADD_LIBRARY(event) - - PHP_ADD_LIBRARY(event_pthreads,,GRPC_SHARED_LIBADD) - PHP_ADD_LIBRARY(event_pthreads) - - PHP_ADD_LIBRARY(event_core,,GRPC_SHARED_LIBADD) - PHP_ADD_LIBRARY(event_core) - PHP_CHECK_LIBRARY(grpc,grpc_channel_destroy, [ PHP_ADD_LIBRARY(grpc,,GRPC_SHARED_LIBADD) -- cgit v1.2.3 From 6c57f6b1cfc10d9ba9ba15bb3e8099a240a5dbfa Mon Sep 17 00:00:00 2001 From: Tim Emiola Date: Fri, 16 Jan 2015 13:49:40 -0800 Subject: Fixes a regression in the style pull request --- src/ruby/grpc.gemspec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/ruby/grpc.gemspec b/src/ruby/grpc.gemspec index ad4e274b7e..8d7f44f30e 100755 --- a/src/ruby/grpc.gemspec +++ b/src/ruby/grpc.gemspec @@ -21,7 +21,7 @@ Gem::Specification.new do |s| s.add_dependency 'xray' s.add_dependency 'logging', '~> 1.8' - s.add_dependency 'google-protobuf', '~> 3.0.0alpha' + s.add_dependency 'google-protobuf', '~> 3.0.0alpha.1.1' s.add_dependency 'minitest', '~> 5.4' # reqd for interop tests s.add_development_dependency 'bundler', '~> 1.7' -- cgit v1.2.3 From c2e80bfbd0ee80772a4b36e482761e97292e82a4 Mon Sep 17 00:00:00 2001 From: Craig Tiller Date: Fri, 16 Jan 2015 14:04:29 -0800 Subject: Pickup wherever phpunit is installed --- src/php/bin/run_tests.sh | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/php/bin/run_tests.sh b/src/php/bin/run_tests.sh index c334ad9091..28282c3e37 100755 --- a/src/php/bin/run_tests.sh +++ b/src/php/bin/run_tests.sh @@ -1,17 +1,17 @@ #!/bin/sh # Loads the local shared library, and runs all of the test cases in tests/ # against it -set -ex +set -e cd $(dirname $0) default_extension_dir=`php -i | grep extension_dir | sed 's/.*=> //g'` # sym-link in system supplied extensions for f in $default_extension_dir/*.so do - ln -s $f ../ext/grpc/modules/$(basename $f) || true + ln -s $f ../ext/grpc/modules/$(basename $f) &> /dev/null || true done php \ -d extension_dir=../ext/grpc/modules/ \ -d extension=grpc.so \ - phpunit -v --debug --strict ../tests/unit_tests + `which phpunit` -v --debug --strict ../tests/unit_tests -- cgit v1.2.3 From bc29d801594989b6cb6093ecff9ad78f31223e63 Mon Sep 17 00:00:00 2001 From: Craig Tiller Date: Fri, 16 Jan 2015 14:55:49 -0800 Subject: Better GRPC_LIBDIR config --- src/php/ext/grpc/config.m4 | 6 +----- tools/run_tests/build_php.sh | 1 + 2 files changed, 2 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/php/ext/grpc/config.m4 b/src/php/ext/grpc/config.m4 index 7652ca74aa..27c67781e7 100755 --- a/src/php/ext/grpc/config.m4 +++ b/src/php/ext/grpc/config.m4 @@ -38,11 +38,7 @@ if test "$PHP_GRPC" != "no"; then PHP_ADD_LIBRARY(rt,,GRPC_SHARED_LIBADD) PHP_ADD_LIBRARY(rt) - if test -e $GRPC_DIR/libs/opt; then - GRPC_LIBDIR=$GRPC_DIR/libs/opt - else - GRPC_LIBDIR=$GRPC_DIR/lib - fi + GRPC_LIBDIR=$GRPC_DIR/${GRPC_LIB_SUBDIR-lib} PHP_ADD_LIBPATH($GRPC_LIBDIR) diff --git a/tools/run_tests/build_php.sh b/tools/run_tests/build_php.sh index de899742da..6841656bdb 100755 --- a/tools/run_tests/build_php.sh +++ b/tools/run_tests/build_php.sh @@ -6,6 +6,7 @@ set -ex cd $(dirname $0)/../.. root=`pwd` +export GRPC_LIB_SUBDIR=libs/opt # make the libraries make -j static_c -- cgit v1.2.3 From 7f3ed1eda19eaf846df93b7c4d1ab1069ab0c130 Mon Sep 17 00:00:00 2001 From: David Klempner Date: Fri, 16 Jan 2015 15:35:56 -0800 Subject: Factor out the pollset kicking mechanism and eliminate sharding This change pulls out a separate pollset_kick module, which currently uses a freelist of pipes dynamically assigned to pollsets when they enter polling rather than the previous racy sharding mechanism. We ultimately may wish to eliminate the dynamic assignment for multipoll sets, but this should be sufficient for the moment. --- Makefile | 53 ++++++- build.json | 16 ++ src/core/iomgr/pollset_kick.h | 68 +++++++++ src/core/iomgr/pollset_kick_posix.c | 161 +++++++++++++++++++++ src/core/iomgr/pollset_kick_posix.h | 47 ++++++ .../iomgr/pollset_multipoller_with_poll_posix.c | 9 +- src/core/iomgr/pollset_posix.c | 84 ++--------- src/core/iomgr/pollset_posix.h | 3 + test/core/iomgr/poll_kick_test.c | 101 +++++++++++++ vsprojects/vs2013/grpc.vcxproj | 4 + vsprojects/vs2013/grpc_unsecure.vcxproj | 4 + 11 files changed, 479 insertions(+), 71 deletions(-) create mode 100644 src/core/iomgr/pollset_kick.h create mode 100644 src/core/iomgr/pollset_kick_posix.c create mode 100644 src/core/iomgr/pollset_kick_posix.h create mode 100644 test/core/iomgr/poll_kick_test.c (limited to 'src') diff --git a/Makefile b/Makefile index 7668ca8b74..4335a528a2 100644 --- a/Makefile +++ b/Makefile @@ -370,6 +370,7 @@ alarm_test: bins/$(CONFIG)/alarm_test alarm_list_test: bins/$(CONFIG)/alarm_list_test alarm_heap_test: bins/$(CONFIG)/alarm_heap_test time_test: bins/$(CONFIG)/time_test +poll_kick_test: bins/$(CONFIG)/poll_kick_test chttp2_fake_security_cancel_after_accept_test: bins/$(CONFIG)/chttp2_fake_security_cancel_after_accept_test chttp2_fake_security_cancel_after_accept_and_writes_closed_test: bins/$(CONFIG)/chttp2_fake_security_cancel_after_accept_and_writes_closed_test chttp2_fake_security_cancel_after_invoke_test: bins/$(CONFIG)/chttp2_fake_security_cancel_after_invoke_test @@ -543,7 +544,7 @@ privatelibs_cxx: libs/$(CONFIG)/libgrpc++_test_util.a buildtests: buildtests_c buildtests_cxx -buildtests_c: privatelibs_c bins/$(CONFIG)/grpc_byte_buffer_reader_test bins/$(CONFIG)/gpr_cancellable_test bins/$(CONFIG)/gpr_log_test bins/$(CONFIG)/gpr_useful_test bins/$(CONFIG)/gpr_cmdline_test bins/$(CONFIG)/gpr_histogram_test bins/$(CONFIG)/gpr_host_port_test bins/$(CONFIG)/gpr_slice_buffer_test bins/$(CONFIG)/gpr_slice_test bins/$(CONFIG)/gpr_string_test bins/$(CONFIG)/gpr_sync_test bins/$(CONFIG)/gpr_thd_test bins/$(CONFIG)/gpr_time_test bins/$(CONFIG)/murmur_hash_test bins/$(CONFIG)/grpc_stream_op_test bins/$(CONFIG)/alpn_test bins/$(CONFIG)/time_averaged_stats_test bins/$(CONFIG)/chttp2_stream_encoder_test bins/$(CONFIG)/hpack_table_test bins/$(CONFIG)/chttp2_stream_map_test bins/$(CONFIG)/hpack_parser_test bins/$(CONFIG)/transport_metadata_test bins/$(CONFIG)/chttp2_status_conversion_test bins/$(CONFIG)/chttp2_transport_end2end_test bins/$(CONFIG)/tcp_posix_test bins/$(CONFIG)/dualstack_socket_test bins/$(CONFIG)/no_server_test bins/$(CONFIG)/resolve_address_test bins/$(CONFIG)/sockaddr_utils_test bins/$(CONFIG)/tcp_server_posix_test bins/$(CONFIG)/tcp_client_posix_test bins/$(CONFIG)/grpc_channel_stack_test bins/$(CONFIG)/metadata_buffer_test bins/$(CONFIG)/grpc_completion_queue_test bins/$(CONFIG)/census_window_stats_test bins/$(CONFIG)/census_statistics_quick_test bins/$(CONFIG)/census_statistics_small_log_test bins/$(CONFIG)/census_statistics_performance_test bins/$(CONFIG)/census_statistics_multiple_writers_test bins/$(CONFIG)/census_statistics_multiple_writers_circular_buffer_test bins/$(CONFIG)/census_stub_test bins/$(CONFIG)/census_hash_table_test bins/$(CONFIG)/fling_server bins/$(CONFIG)/fling_client bins/$(CONFIG)/fling_test bins/$(CONFIG)/echo_server bins/$(CONFIG)/echo_client bins/$(CONFIG)/echo_test bins/$(CONFIG)/message_compress_test bins/$(CONFIG)/bin_encoder_test bins/$(CONFIG)/secure_endpoint_test bins/$(CONFIG)/httpcli_format_request_test bins/$(CONFIG)/httpcli_parser_test bins/$(CONFIG)/httpcli_test bins/$(CONFIG)/grpc_credentials_test bins/$(CONFIG)/grpc_base64_test bins/$(CONFIG)/grpc_json_token_test bins/$(CONFIG)/timeout_encoding_test bins/$(CONFIG)/fd_posix_test bins/$(CONFIG)/fling_stream_test bins/$(CONFIG)/lame_client_test bins/$(CONFIG)/alarm_test bins/$(CONFIG)/alarm_list_test bins/$(CONFIG)/alarm_heap_test bins/$(CONFIG)/time_test bins/$(CONFIG)/chttp2_fake_security_cancel_after_accept_test bins/$(CONFIG)/chttp2_fake_security_cancel_after_accept_and_writes_closed_test bins/$(CONFIG)/chttp2_fake_security_cancel_after_invoke_test bins/$(CONFIG)/chttp2_fake_security_cancel_before_invoke_test bins/$(CONFIG)/chttp2_fake_security_cancel_in_a_vacuum_test bins/$(CONFIG)/chttp2_fake_security_census_simple_request_test bins/$(CONFIG)/chttp2_fake_security_disappearing_server_test bins/$(CONFIG)/chttp2_fake_security_early_server_shutdown_finishes_inflight_calls_test bins/$(CONFIG)/chttp2_fake_security_early_server_shutdown_finishes_tags_test bins/$(CONFIG)/chttp2_fake_security_graceful_server_shutdown_test bins/$(CONFIG)/chttp2_fake_security_invoke_large_request_test bins/$(CONFIG)/chttp2_fake_security_max_concurrent_streams_test bins/$(CONFIG)/chttp2_fake_security_no_op_test bins/$(CONFIG)/chttp2_fake_security_ping_pong_streaming_test bins/$(CONFIG)/chttp2_fake_security_request_response_with_binary_metadata_and_payload_test bins/$(CONFIG)/chttp2_fake_security_request_response_with_metadata_and_payload_test bins/$(CONFIG)/chttp2_fake_security_request_response_with_payload_test bins/$(CONFIG)/chttp2_fake_security_request_response_with_trailing_metadata_and_payload_test bins/$(CONFIG)/chttp2_fake_security_simple_delayed_request_test bins/$(CONFIG)/chttp2_fake_security_simple_request_test bins/$(CONFIG)/chttp2_fake_security_thread_stress_test bins/$(CONFIG)/chttp2_fake_security_writes_done_hangs_with_pending_read_test bins/$(CONFIG)/chttp2_fullstack_cancel_after_accept_test bins/$(CONFIG)/chttp2_fullstack_cancel_after_accept_and_writes_closed_test bins/$(CONFIG)/chttp2_fullstack_cancel_after_invoke_test bins/$(CONFIG)/chttp2_fullstack_cancel_before_invoke_test bins/$(CONFIG)/chttp2_fullstack_cancel_in_a_vacuum_test bins/$(CONFIG)/chttp2_fullstack_census_simple_request_test bins/$(CONFIG)/chttp2_fullstack_disappearing_server_test bins/$(CONFIG)/chttp2_fullstack_early_server_shutdown_finishes_inflight_calls_test bins/$(CONFIG)/chttp2_fullstack_early_server_shutdown_finishes_tags_test bins/$(CONFIG)/chttp2_fullstack_graceful_server_shutdown_test bins/$(CONFIG)/chttp2_fullstack_invoke_large_request_test bins/$(CONFIG)/chttp2_fullstack_max_concurrent_streams_test bins/$(CONFIG)/chttp2_fullstack_no_op_test bins/$(CONFIG)/chttp2_fullstack_ping_pong_streaming_test bins/$(CONFIG)/chttp2_fullstack_request_response_with_binary_metadata_and_payload_test bins/$(CONFIG)/chttp2_fullstack_request_response_with_metadata_and_payload_test bins/$(CONFIG)/chttp2_fullstack_request_response_with_payload_test bins/$(CONFIG)/chttp2_fullstack_request_response_with_trailing_metadata_and_payload_test bins/$(CONFIG)/chttp2_fullstack_simple_delayed_request_test bins/$(CONFIG)/chttp2_fullstack_simple_request_test bins/$(CONFIG)/chttp2_fullstack_thread_stress_test bins/$(CONFIG)/chttp2_fullstack_writes_done_hangs_with_pending_read_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_cancel_after_accept_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_cancel_after_accept_and_writes_closed_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_cancel_after_invoke_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_cancel_before_invoke_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_cancel_in_a_vacuum_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_census_simple_request_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_disappearing_server_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_early_server_shutdown_finishes_inflight_calls_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_early_server_shutdown_finishes_tags_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_graceful_server_shutdown_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_invoke_large_request_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_max_concurrent_streams_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_no_op_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_ping_pong_streaming_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_request_response_with_binary_metadata_and_payload_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_request_response_with_metadata_and_payload_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_request_response_with_payload_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_request_response_with_trailing_metadata_and_payload_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_simple_delayed_request_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_simple_request_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_thread_stress_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_writes_done_hangs_with_pending_read_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_cancel_after_accept_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_cancel_after_accept_and_writes_closed_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_cancel_after_invoke_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_cancel_before_invoke_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_cancel_in_a_vacuum_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_census_simple_request_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_disappearing_server_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_early_server_shutdown_finishes_inflight_calls_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_early_server_shutdown_finishes_tags_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_graceful_server_shutdown_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_invoke_large_request_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_max_concurrent_streams_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_no_op_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_ping_pong_streaming_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_request_response_with_binary_metadata_and_payload_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_request_response_with_metadata_and_payload_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_request_response_with_payload_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_request_response_with_trailing_metadata_and_payload_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_simple_delayed_request_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_simple_request_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_thread_stress_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_writes_done_hangs_with_pending_read_test bins/$(CONFIG)/chttp2_socket_pair_cancel_after_accept_test bins/$(CONFIG)/chttp2_socket_pair_cancel_after_accept_and_writes_closed_test bins/$(CONFIG)/chttp2_socket_pair_cancel_after_invoke_test bins/$(CONFIG)/chttp2_socket_pair_cancel_before_invoke_test bins/$(CONFIG)/chttp2_socket_pair_cancel_in_a_vacuum_test bins/$(CONFIG)/chttp2_socket_pair_census_simple_request_test bins/$(CONFIG)/chttp2_socket_pair_disappearing_server_test bins/$(CONFIG)/chttp2_socket_pair_early_server_shutdown_finishes_inflight_calls_test bins/$(CONFIG)/chttp2_socket_pair_early_server_shutdown_finishes_tags_test bins/$(CONFIG)/chttp2_socket_pair_graceful_server_shutdown_test bins/$(CONFIG)/chttp2_socket_pair_invoke_large_request_test bins/$(CONFIG)/chttp2_socket_pair_max_concurrent_streams_test bins/$(CONFIG)/chttp2_socket_pair_no_op_test bins/$(CONFIG)/chttp2_socket_pair_ping_pong_streaming_test bins/$(CONFIG)/chttp2_socket_pair_request_response_with_binary_metadata_and_payload_test bins/$(CONFIG)/chttp2_socket_pair_request_response_with_metadata_and_payload_test bins/$(CONFIG)/chttp2_socket_pair_request_response_with_payload_test bins/$(CONFIG)/chttp2_socket_pair_request_response_with_trailing_metadata_and_payload_test bins/$(CONFIG)/chttp2_socket_pair_simple_delayed_request_test bins/$(CONFIG)/chttp2_socket_pair_simple_request_test bins/$(CONFIG)/chttp2_socket_pair_thread_stress_test bins/$(CONFIG)/chttp2_socket_pair_writes_done_hangs_with_pending_read_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_cancel_after_accept_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_cancel_after_accept_and_writes_closed_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_cancel_after_invoke_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_cancel_before_invoke_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_cancel_in_a_vacuum_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_census_simple_request_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_disappearing_server_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_early_server_shutdown_finishes_inflight_calls_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_early_server_shutdown_finishes_tags_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_graceful_server_shutdown_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_invoke_large_request_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_max_concurrent_streams_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_no_op_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_ping_pong_streaming_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_request_response_with_binary_metadata_and_payload_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_request_response_with_metadata_and_payload_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_request_response_with_payload_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_request_response_with_trailing_metadata_and_payload_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_simple_delayed_request_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_simple_request_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_thread_stress_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_writes_done_hangs_with_pending_read_test +buildtests_c: privatelibs_c bins/$(CONFIG)/grpc_byte_buffer_reader_test bins/$(CONFIG)/gpr_cancellable_test bins/$(CONFIG)/gpr_log_test bins/$(CONFIG)/gpr_useful_test bins/$(CONFIG)/gpr_cmdline_test bins/$(CONFIG)/gpr_histogram_test bins/$(CONFIG)/gpr_host_port_test bins/$(CONFIG)/gpr_slice_buffer_test bins/$(CONFIG)/gpr_slice_test bins/$(CONFIG)/gpr_string_test bins/$(CONFIG)/gpr_sync_test bins/$(CONFIG)/gpr_thd_test bins/$(CONFIG)/gpr_time_test bins/$(CONFIG)/murmur_hash_test bins/$(CONFIG)/grpc_stream_op_test bins/$(CONFIG)/alpn_test bins/$(CONFIG)/time_averaged_stats_test bins/$(CONFIG)/chttp2_stream_encoder_test bins/$(CONFIG)/hpack_table_test bins/$(CONFIG)/chttp2_stream_map_test bins/$(CONFIG)/hpack_parser_test bins/$(CONFIG)/transport_metadata_test bins/$(CONFIG)/chttp2_status_conversion_test bins/$(CONFIG)/chttp2_transport_end2end_test bins/$(CONFIG)/tcp_posix_test bins/$(CONFIG)/dualstack_socket_test bins/$(CONFIG)/no_server_test bins/$(CONFIG)/resolve_address_test bins/$(CONFIG)/sockaddr_utils_test bins/$(CONFIG)/tcp_server_posix_test bins/$(CONFIG)/tcp_client_posix_test bins/$(CONFIG)/grpc_channel_stack_test bins/$(CONFIG)/metadata_buffer_test bins/$(CONFIG)/grpc_completion_queue_test bins/$(CONFIG)/census_window_stats_test bins/$(CONFIG)/census_statistics_quick_test bins/$(CONFIG)/census_statistics_small_log_test bins/$(CONFIG)/census_statistics_performance_test bins/$(CONFIG)/census_statistics_multiple_writers_test bins/$(CONFIG)/census_statistics_multiple_writers_circular_buffer_test bins/$(CONFIG)/census_stub_test bins/$(CONFIG)/census_hash_table_test bins/$(CONFIG)/fling_server bins/$(CONFIG)/fling_client bins/$(CONFIG)/fling_test bins/$(CONFIG)/echo_server bins/$(CONFIG)/echo_client bins/$(CONFIG)/echo_test bins/$(CONFIG)/message_compress_test bins/$(CONFIG)/bin_encoder_test bins/$(CONFIG)/secure_endpoint_test bins/$(CONFIG)/httpcli_format_request_test bins/$(CONFIG)/httpcli_parser_test bins/$(CONFIG)/httpcli_test bins/$(CONFIG)/grpc_credentials_test bins/$(CONFIG)/grpc_base64_test bins/$(CONFIG)/grpc_json_token_test bins/$(CONFIG)/timeout_encoding_test bins/$(CONFIG)/fd_posix_test bins/$(CONFIG)/fling_stream_test bins/$(CONFIG)/lame_client_test bins/$(CONFIG)/alarm_test bins/$(CONFIG)/alarm_list_test bins/$(CONFIG)/alarm_heap_test bins/$(CONFIG)/time_test bins/$(CONFIG)/poll_kick_test bins/$(CONFIG)/chttp2_fake_security_cancel_after_accept_test bins/$(CONFIG)/chttp2_fake_security_cancel_after_accept_and_writes_closed_test bins/$(CONFIG)/chttp2_fake_security_cancel_after_invoke_test bins/$(CONFIG)/chttp2_fake_security_cancel_before_invoke_test bins/$(CONFIG)/chttp2_fake_security_cancel_in_a_vacuum_test bins/$(CONFIG)/chttp2_fake_security_census_simple_request_test bins/$(CONFIG)/chttp2_fake_security_disappearing_server_test bins/$(CONFIG)/chttp2_fake_security_early_server_shutdown_finishes_inflight_calls_test bins/$(CONFIG)/chttp2_fake_security_early_server_shutdown_finishes_tags_test bins/$(CONFIG)/chttp2_fake_security_graceful_server_shutdown_test bins/$(CONFIG)/chttp2_fake_security_invoke_large_request_test bins/$(CONFIG)/chttp2_fake_security_max_concurrent_streams_test bins/$(CONFIG)/chttp2_fake_security_no_op_test bins/$(CONFIG)/chttp2_fake_security_ping_pong_streaming_test bins/$(CONFIG)/chttp2_fake_security_request_response_with_binary_metadata_and_payload_test bins/$(CONFIG)/chttp2_fake_security_request_response_with_metadata_and_payload_test bins/$(CONFIG)/chttp2_fake_security_request_response_with_payload_test bins/$(CONFIG)/chttp2_fake_security_request_response_with_trailing_metadata_and_payload_test bins/$(CONFIG)/chttp2_fake_security_simple_delayed_request_test bins/$(CONFIG)/chttp2_fake_security_simple_request_test bins/$(CONFIG)/chttp2_fake_security_thread_stress_test bins/$(CONFIG)/chttp2_fake_security_writes_done_hangs_with_pending_read_test bins/$(CONFIG)/chttp2_fullstack_cancel_after_accept_test bins/$(CONFIG)/chttp2_fullstack_cancel_after_accept_and_writes_closed_test bins/$(CONFIG)/chttp2_fullstack_cancel_after_invoke_test bins/$(CONFIG)/chttp2_fullstack_cancel_before_invoke_test bins/$(CONFIG)/chttp2_fullstack_cancel_in_a_vacuum_test bins/$(CONFIG)/chttp2_fullstack_census_simple_request_test bins/$(CONFIG)/chttp2_fullstack_disappearing_server_test bins/$(CONFIG)/chttp2_fullstack_early_server_shutdown_finishes_inflight_calls_test bins/$(CONFIG)/chttp2_fullstack_early_server_shutdown_finishes_tags_test bins/$(CONFIG)/chttp2_fullstack_graceful_server_shutdown_test bins/$(CONFIG)/chttp2_fullstack_invoke_large_request_test bins/$(CONFIG)/chttp2_fullstack_max_concurrent_streams_test bins/$(CONFIG)/chttp2_fullstack_no_op_test bins/$(CONFIG)/chttp2_fullstack_ping_pong_streaming_test bins/$(CONFIG)/chttp2_fullstack_request_response_with_binary_metadata_and_payload_test bins/$(CONFIG)/chttp2_fullstack_request_response_with_metadata_and_payload_test bins/$(CONFIG)/chttp2_fullstack_request_response_with_payload_test bins/$(CONFIG)/chttp2_fullstack_request_response_with_trailing_metadata_and_payload_test bins/$(CONFIG)/chttp2_fullstack_simple_delayed_request_test bins/$(CONFIG)/chttp2_fullstack_simple_request_test bins/$(CONFIG)/chttp2_fullstack_thread_stress_test bins/$(CONFIG)/chttp2_fullstack_writes_done_hangs_with_pending_read_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_cancel_after_accept_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_cancel_after_accept_and_writes_closed_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_cancel_after_invoke_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_cancel_before_invoke_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_cancel_in_a_vacuum_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_census_simple_request_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_disappearing_server_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_early_server_shutdown_finishes_inflight_calls_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_early_server_shutdown_finishes_tags_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_graceful_server_shutdown_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_invoke_large_request_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_max_concurrent_streams_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_no_op_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_ping_pong_streaming_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_request_response_with_binary_metadata_and_payload_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_request_response_with_metadata_and_payload_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_request_response_with_payload_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_request_response_with_trailing_metadata_and_payload_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_simple_delayed_request_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_simple_request_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_thread_stress_test bins/$(CONFIG)/chttp2_simple_ssl_fullstack_writes_done_hangs_with_pending_read_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_cancel_after_accept_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_cancel_after_accept_and_writes_closed_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_cancel_after_invoke_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_cancel_before_invoke_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_cancel_in_a_vacuum_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_census_simple_request_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_disappearing_server_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_early_server_shutdown_finishes_inflight_calls_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_early_server_shutdown_finishes_tags_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_graceful_server_shutdown_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_invoke_large_request_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_max_concurrent_streams_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_no_op_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_ping_pong_streaming_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_request_response_with_binary_metadata_and_payload_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_request_response_with_metadata_and_payload_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_request_response_with_payload_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_request_response_with_trailing_metadata_and_payload_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_simple_delayed_request_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_simple_request_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_thread_stress_test bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_writes_done_hangs_with_pending_read_test bins/$(CONFIG)/chttp2_socket_pair_cancel_after_accept_test bins/$(CONFIG)/chttp2_socket_pair_cancel_after_accept_and_writes_closed_test bins/$(CONFIG)/chttp2_socket_pair_cancel_after_invoke_test bins/$(CONFIG)/chttp2_socket_pair_cancel_before_invoke_test bins/$(CONFIG)/chttp2_socket_pair_cancel_in_a_vacuum_test bins/$(CONFIG)/chttp2_socket_pair_census_simple_request_test bins/$(CONFIG)/chttp2_socket_pair_disappearing_server_test bins/$(CONFIG)/chttp2_socket_pair_early_server_shutdown_finishes_inflight_calls_test bins/$(CONFIG)/chttp2_socket_pair_early_server_shutdown_finishes_tags_test bins/$(CONFIG)/chttp2_socket_pair_graceful_server_shutdown_test bins/$(CONFIG)/chttp2_socket_pair_invoke_large_request_test bins/$(CONFIG)/chttp2_socket_pair_max_concurrent_streams_test bins/$(CONFIG)/chttp2_socket_pair_no_op_test bins/$(CONFIG)/chttp2_socket_pair_ping_pong_streaming_test bins/$(CONFIG)/chttp2_socket_pair_request_response_with_binary_metadata_and_payload_test bins/$(CONFIG)/chttp2_socket_pair_request_response_with_metadata_and_payload_test bins/$(CONFIG)/chttp2_socket_pair_request_response_with_payload_test bins/$(CONFIG)/chttp2_socket_pair_request_response_with_trailing_metadata_and_payload_test bins/$(CONFIG)/chttp2_socket_pair_simple_delayed_request_test bins/$(CONFIG)/chttp2_socket_pair_simple_request_test bins/$(CONFIG)/chttp2_socket_pair_thread_stress_test bins/$(CONFIG)/chttp2_socket_pair_writes_done_hangs_with_pending_read_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_cancel_after_accept_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_cancel_after_accept_and_writes_closed_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_cancel_after_invoke_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_cancel_before_invoke_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_cancel_in_a_vacuum_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_census_simple_request_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_disappearing_server_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_early_server_shutdown_finishes_inflight_calls_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_early_server_shutdown_finishes_tags_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_graceful_server_shutdown_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_invoke_large_request_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_max_concurrent_streams_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_no_op_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_ping_pong_streaming_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_request_response_with_binary_metadata_and_payload_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_request_response_with_metadata_and_payload_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_request_response_with_payload_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_request_response_with_trailing_metadata_and_payload_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_simple_delayed_request_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_simple_request_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_thread_stress_test bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_writes_done_hangs_with_pending_read_test buildtests_cxx: privatelibs_cxx bins/$(CONFIG)/thread_pool_test bins/$(CONFIG)/status_test bins/$(CONFIG)/sync_client_async_server_test bins/$(CONFIG)/qps_client bins/$(CONFIG)/qps_server bins/$(CONFIG)/interop_server bins/$(CONFIG)/interop_client bins/$(CONFIG)/end2end_test bins/$(CONFIG)/channel_arguments_test bins/$(CONFIG)/credentials_test @@ -672,6 +673,8 @@ test_c: buildtests_c $(Q) ./bins/$(CONFIG)/alarm_heap_test || ( echo test alarm_heap_test failed ; exit 1 ) $(E) "[RUN] Testing time_test" $(Q) ./bins/$(CONFIG)/time_test || ( echo test time_test failed ; exit 1 ) + $(E) "[RUN] Testing poll_kick_test" + $(Q) ./bins/$(CONFIG)/poll_kick_test || ( echo test poll_kick_test failed ; exit 1 ) $(E) "[RUN] Testing chttp2_fake_security_cancel_after_accept_test" $(Q) ./bins/$(CONFIG)/chttp2_fake_security_cancel_after_accept_test || ( echo test chttp2_fake_security_cancel_after_accept_test failed ; exit 1 ) $(E) "[RUN] Testing chttp2_fake_security_cancel_after_accept_and_writes_closed_test" @@ -1304,6 +1307,7 @@ LIBGRPC_SRC = \ src/core/iomgr/fd_posix.c \ src/core/iomgr/iomgr.c \ src/core/iomgr/iomgr_posix.c \ + src/core/iomgr/pollset_kick_posix.c \ src/core/iomgr/pollset_multipoller_with_poll_posix.c \ src/core/iomgr/pollset_posix.c \ src/core/iomgr/resolve_address_posix.c \ @@ -1421,6 +1425,7 @@ src/core/iomgr/endpoint_pair_posix.c: $(OPENSSL_DEP) src/core/iomgr/fd_posix.c: $(OPENSSL_DEP) src/core/iomgr/iomgr.c: $(OPENSSL_DEP) src/core/iomgr/iomgr_posix.c: $(OPENSSL_DEP) +src/core/iomgr/pollset_kick_posix.c: $(OPENSSL_DEP) src/core/iomgr/pollset_multipoller_with_poll_posix.c: $(OPENSSL_DEP) src/core/iomgr/pollset_posix.c: $(OPENSSL_DEP) src/core/iomgr/resolve_address_posix.c: $(OPENSSL_DEP) @@ -1555,6 +1560,7 @@ objs/$(CONFIG)/src/core/iomgr/endpoint_pair_posix.o: objs/$(CONFIG)/src/core/iomgr/fd_posix.o: objs/$(CONFIG)/src/core/iomgr/iomgr.o: objs/$(CONFIG)/src/core/iomgr/iomgr_posix.o: +objs/$(CONFIG)/src/core/iomgr/pollset_kick_posix.o: objs/$(CONFIG)/src/core/iomgr/pollset_multipoller_with_poll_posix.o: objs/$(CONFIG)/src/core/iomgr/pollset_posix.o: objs/$(CONFIG)/src/core/iomgr/resolve_address_posix.o: @@ -1637,6 +1643,7 @@ LIBGRPC_UNSECURE_SRC = \ src/core/iomgr/fd_posix.c \ src/core/iomgr/iomgr.c \ src/core/iomgr/iomgr_posix.c \ + src/core/iomgr/pollset_kick_posix.c \ src/core/iomgr/pollset_multipoller_with_poll_posix.c \ src/core/iomgr/pollset_posix.c \ src/core/iomgr/resolve_address_posix.c \ @@ -1754,6 +1761,7 @@ objs/$(CONFIG)/src/core/iomgr/endpoint_pair_posix.o: objs/$(CONFIG)/src/core/iomgr/fd_posix.o: objs/$(CONFIG)/src/core/iomgr/iomgr.o: objs/$(CONFIG)/src/core/iomgr/iomgr_posix.o: +objs/$(CONFIG)/src/core/iomgr/pollset_kick_posix.o: objs/$(CONFIG)/src/core/iomgr/pollset_multipoller_with_poll_posix.o: objs/$(CONFIG)/src/core/iomgr/pollset_posix.o: objs/$(CONFIG)/src/core/iomgr/resolve_address_posix.o: @@ -5447,6 +5455,37 @@ endif endif +POLL_KICK_TEST_SRC = \ + test/core/iomgr/poll_kick_test.c \ + +POLL_KICK_TEST_OBJS = $(addprefix objs/$(CONFIG)/, $(addsuffix .o, $(basename $(POLL_KICK_TEST_SRC)))) + +ifeq ($(NO_SECURE),true) + +# You can't build secure targets if you don't have OpenSSL with ALPN. + +bins/$(CONFIG)/poll_kick_test: openssl_dep_error + +else + +bins/$(CONFIG)/poll_kick_test: $(POLL_KICK_TEST_OBJS) libs/$(CONFIG)/libgrpc_test_util.a libs/$(CONFIG)/libgrpc.a libs/$(CONFIG)/libgpr_test_util.a libs/$(CONFIG)/libgpr.a + $(E) "[LD] Linking $@" + $(Q) mkdir -p `dirname $@` + $(Q) $(LD) $(LDFLAGS) $(POLL_KICK_TEST_OBJS) libs/$(CONFIG)/libgrpc_test_util.a libs/$(CONFIG)/libgrpc.a libs/$(CONFIG)/libgpr_test_util.a libs/$(CONFIG)/libgpr.a $(LDLIBS) $(LDLIBS_SECURE) -o bins/$(CONFIG)/poll_kick_test + +endif + +objs/$(CONFIG)/test/core/iomgr/poll_kick_test.o: libs/$(CONFIG)/libgrpc_test_util.a libs/$(CONFIG)/libgrpc.a libs/$(CONFIG)/libgpr_test_util.a libs/$(CONFIG)/libgpr.a + +deps_poll_kick_test: $(POLL_KICK_TEST_OBJS:.o=.dep) + +ifneq ($(NO_SECURE),true) +ifneq ($(NO_DEPS),true) +-include $(POLL_KICK_TEST_OBJS:.o=.dep) +endif +endif + + CHTTP2_FAKE_SECURITY_CANCEL_AFTER_ACCEPT_TEST_SRC = \ CHTTP2_FAKE_SECURITY_CANCEL_AFTER_ACCEPT_TEST_OBJS = $(addprefix objs/$(CONFIG)/, $(addsuffix .o, $(basename $(CHTTP2_FAKE_SECURITY_CANCEL_AFTER_ACCEPT_TEST_SRC)))) @@ -5714,6 +5753,8 @@ CHTTP2_FAKE_SECURITY_GRACEFUL_SERVER_SHUTDOWN_TEST_OBJS = $(addprefix objs/$(CON ifeq ($(NO_SECURE),true) +# You can't build secure targets if you don't have OpenSSL with ALPN. + bins/$(CONFIG)/chttp2_fake_security_graceful_server_shutdown_test: openssl_dep_error else @@ -6350,6 +6391,8 @@ CHTTP2_FULLSTACK_GRACEFUL_SERVER_SHUTDOWN_TEST_OBJS = $(addprefix objs/$(CONFIG) ifeq ($(NO_SECURE),true) +# You can't build secure targets if you don't have OpenSSL with ALPN. + bins/$(CONFIG)/chttp2_fullstack_graceful_server_shutdown_test: openssl_dep_error else @@ -6986,6 +7029,8 @@ CHTTP2_SIMPLE_SSL_FULLSTACK_GRACEFUL_SERVER_SHUTDOWN_TEST_OBJS = $(addprefix obj ifeq ($(NO_SECURE),true) +# You can't build secure targets if you don't have OpenSSL with ALPN. + bins/$(CONFIG)/chttp2_simple_ssl_fullstack_graceful_server_shutdown_test: openssl_dep_error else @@ -7622,6 +7667,8 @@ CHTTP2_SIMPLE_SSL_WITH_OAUTH2_FULLSTACK_GRACEFUL_SERVER_SHUTDOWN_TEST_OBJS = $(a ifeq ($(NO_SECURE),true) +# You can't build secure targets if you don't have OpenSSL with ALPN. + bins/$(CONFIG)/chttp2_simple_ssl_with_oauth2_fullstack_graceful_server_shutdown_test: openssl_dep_error else @@ -8258,6 +8305,8 @@ CHTTP2_SOCKET_PAIR_GRACEFUL_SERVER_SHUTDOWN_TEST_OBJS = $(addprefix objs/$(CONFI ifeq ($(NO_SECURE),true) +# You can't build secure targets if you don't have OpenSSL with ALPN. + bins/$(CONFIG)/chttp2_socket_pair_graceful_server_shutdown_test: openssl_dep_error else @@ -8894,6 +8943,8 @@ CHTTP2_SOCKET_PAIR_ONE_BYTE_AT_A_TIME_GRACEFUL_SERVER_SHUTDOWN_TEST_OBJS = $(add ifeq ($(NO_SECURE),true) +# You can't build secure targets if you don't have OpenSSL with ALPN. + bins/$(CONFIG)/chttp2_socket_pair_one_byte_at_a_time_graceful_server_shutdown_test: openssl_dep_error else diff --git a/build.json b/build.json index 1e465404a5..d1b3c92680 100644 --- a/build.json +++ b/build.json @@ -38,6 +38,7 @@ "src/core/iomgr/fd_posix.c", "src/core/iomgr/iomgr.c", "src/core/iomgr/iomgr_posix.c", + "src/core/iomgr/pollset_kick_posix.c", "src/core/iomgr/pollset_multipoller_with_poll_posix.c", "src/core/iomgr/pollset_posix.c", "src/core/iomgr/resolve_address_posix.c", @@ -126,6 +127,8 @@ "src/core/iomgr/iomgr.h", "src/core/iomgr/iomgr_internal.h", "src/core/iomgr/iomgr_posix.h", + "src/core/iomgr/pollset_kick.h", + "src/core/iomgr/pollset_kick_posix.h", "src/core/iomgr/pollset.h", "src/core/iomgr/pollset_posix.h", "src/core/iomgr/resolve_address.h", @@ -1497,6 +1500,19 @@ "gpr_test_util", "gpr" ] + }, + { + "name": "poll_kick_test", + "build": "test", + "src": [ + "test/core/iomgr/poll_kick_test.c" + ], + "deps": [ + "grpc_test_util", + "grpc", + "gpr_test_util", + "gpr" + ] } ] } diff --git a/src/core/iomgr/pollset_kick.h b/src/core/iomgr/pollset_kick.h new file mode 100644 index 0000000000..f088818b9a --- /dev/null +++ b/src/core/iomgr/pollset_kick.h @@ -0,0 +1,68 @@ +/* + * + * 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_IOMGR_POLLSET_KICK_H_ +#define __GRPC_INTERNAL_IOMGR_POLLSET_KICK_H_ + +#include + +/* This is an abstraction around the typical pipe mechanism for waking up a + thread sitting in a poll() style call. */ + +#ifdef GPR_POSIX_SOCKET +#include "src/core/iomgr/pollset_kick_posix.h" +#else +#error "No pollset kick support on platform" +#endif + +void grpc_pollset_kick_global_init(void); +void grpc_pollset_kick_global_destroy(void); + +void grpc_pollset_kick_init(grpc_pollset_kick_state *kick_state); +void grpc_pollset_kick_destroy(grpc_pollset_kick_state *kick_state); + +/* Must be called before entering poll(). If return value is -1, this consumed + an existing kick. Otherwise the return value is an FD to add to the poll set. + */ +int grpc_pollset_kick_pre_poll(grpc_pollset_kick_state *kick_state); + +/* Consume an existing kick. Must be called after poll returns that the fd was + readable, and before calling kick_post_poll. */ +void grpc_pollset_kick_consume(grpc_pollset_kick_state *kick_state); + +/* Must be called after pre_poll, and after consume if applicable */ +void grpc_pollset_kick_post_poll(grpc_pollset_kick_state *kick_state); + +void grpc_pollset_kick_kick(grpc_pollset_kick_state *kick_state); + +#endif /* __GRPC_INTERNAL_IOMGR_POLLSET_KICK_H_ */ diff --git a/src/core/iomgr/pollset_kick_posix.c b/src/core/iomgr/pollset_kick_posix.c new file mode 100644 index 0000000000..d16e49e459 --- /dev/null +++ b/src/core/iomgr/pollset_kick_posix.c @@ -0,0 +1,161 @@ +/* + * + * 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. + * + */ + +#include "src/core/iomgr/pollset_kick_posix.h" + +#include +#include +#include + +#include "src/core/iomgr/socket_utils_posix.h" +#include +#include + +/* This implementation is based on a freelist of pipes. */ + +typedef struct grpc_kick_pipe_info { + int pipe_read_fd; + int pipe_write_fd; + struct grpc_kick_pipe_info *next; +} grpc_kick_pipe_info; + +static grpc_kick_pipe_info *pipe_freelist = NULL; +static gpr_mu pipe_freelist_mu; + +static grpc_kick_pipe_info *allocate_pipe() { + grpc_kick_pipe_info *info; + gpr_mu_lock(&pipe_freelist_mu); + if (pipe_freelist != NULL) { + info = pipe_freelist; + pipe_freelist = pipe_freelist->next; + } else { + int pipefd[2]; + /* TODO(klempner): Make this nonfatal */ + GPR_ASSERT(0 == pipe(pipefd)); + GPR_ASSERT(grpc_set_socket_nonblocking(pipefd[0], 1)); + GPR_ASSERT(grpc_set_socket_nonblocking(pipefd[1], 1)); + info = gpr_malloc(sizeof(*info)); + info->pipe_read_fd = pipefd[0]; + info->pipe_write_fd = pipefd[1]; + info->next = NULL; + } + gpr_mu_unlock(&pipe_freelist_mu); + return info; +} + +static void free_pipe(grpc_kick_pipe_info *pipe_info) { + /* TODO(klempner): Start closing pipes if the free list gets too large */ + gpr_mu_lock(&pipe_freelist_mu); + pipe_info->next = pipe_freelist; + pipe_freelist = pipe_info; + gpr_mu_unlock(&pipe_freelist_mu); +} + +void grpc_pollset_kick_global_init() { + pipe_freelist = NULL; + gpr_mu_init(&pipe_freelist_mu); +} + +void grpc_pollset_kick_global_destroy() { + while (pipe_freelist != NULL) { + grpc_kick_pipe_info *current = pipe_freelist; + pipe_freelist = pipe_freelist->next; + close(current->pipe_read_fd); + close(current->pipe_write_fd); + gpr_free(current); + } + gpr_mu_destroy(&pipe_freelist_mu); +} + +void grpc_pollset_kick_init(grpc_pollset_kick_state *kick_state) { + gpr_mu_init(&kick_state->mu); + kick_state->kicked = 0; + kick_state->pipe_info = NULL; +} + +void grpc_pollset_kick_destroy(grpc_pollset_kick_state *kick_state) { + gpr_mu_destroy(&kick_state->mu); + GPR_ASSERT(kick_state->pipe_info == NULL); +} + +int grpc_pollset_kick_pre_poll(grpc_pollset_kick_state *kick_state) { + gpr_mu_lock(&kick_state->mu); + if (kick_state->kicked) { + kick_state->kicked = 0; + gpr_mu_unlock(&kick_state->mu); + return -1; + } + kick_state->pipe_info = allocate_pipe(); + gpr_mu_unlock(&kick_state->mu); + return kick_state->pipe_info->pipe_read_fd; +} + +void grpc_pollset_kick_consume(grpc_pollset_kick_state *kick_state) { + char buf[128]; + int r; + + for (;;) { + r = read(kick_state->pipe_info->pipe_read_fd, buf, sizeof(buf)); + if (r > 0) continue; + if (r == 0) return; + switch (errno) { + case EAGAIN: + return; + case EINTR: + continue; + default: + gpr_log(GPR_ERROR, "error reading pipe: %s", strerror(errno)); + return; + } + } +} + +void grpc_pollset_kick_post_poll(grpc_pollset_kick_state *kick_state) { + gpr_mu_lock(&kick_state->mu); + free_pipe(kick_state->pipe_info); + kick_state->pipe_info = NULL; + gpr_mu_unlock(&kick_state->mu); +} + +void grpc_pollset_kick_kick(grpc_pollset_kick_state *kick_state) { + gpr_mu_lock(&kick_state->mu); + if (kick_state->pipe_info != NULL) { + char c = 0; + while (write(kick_state->pipe_info->pipe_write_fd, &c, 1) != 1 && + errno == EINTR) + ; + } else { + kick_state->kicked = 1; + } + gpr_mu_unlock(&kick_state->mu); +} diff --git a/src/core/iomgr/pollset_kick_posix.h b/src/core/iomgr/pollset_kick_posix.h new file mode 100644 index 0000000000..bae3b5923a --- /dev/null +++ b/src/core/iomgr/pollset_kick_posix.h @@ -0,0 +1,47 @@ +/* + * + * 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_IOMGR_POLLSET_KICK_POSIX_H_ +#define __GRPC_INTERNAL_IOMGR_POLLSET_KICK_POSIX_H_ + +#include + +struct grpc_kick_pipe_info; + +typedef struct grpc_pollset_kick_state { + gpr_mu mu; + int kicked; + struct grpc_kick_pipe_info *pipe_info; +} grpc_pollset_kick_state; + +#endif /* __GRPC_INTERNAL_IOMGR_POLLSET_KICK_POSIX_H_ */ diff --git a/src/core/iomgr/pollset_multipoller_with_poll_posix.c b/src/core/iomgr/pollset_multipoller_with_poll_posix.c index e482da94f7..7c9a9491cb 100644 --- a/src/core/iomgr/pollset_multipoller_with_poll_posix.c +++ b/src/core/iomgr/pollset_multipoller_with_poll_posix.c @@ -131,7 +131,11 @@ static int multipoll_with_poll_pollset_maybe_work( } nf = 0; np = 1; - h->pfds[0].fd = grpc_kick_read_fd(pollset); + h->pfds[0].fd = grpc_pollset_kick_pre_poll(&pollset->kick_state); + if (h->pfds[0].fd < 0) { + /* Already kicked */ + return 1; + } h->pfds[0].events = POLLIN; h->pfds[0].revents = POLLOUT; for (i = 0; i < h->fd_count; i++) { @@ -173,7 +177,7 @@ static int multipoll_with_poll_pollset_maybe_work( /* do nothing */ } else { if (h->pfds[0].revents & POLLIN) { - grpc_kick_drain(pollset); + grpc_pollset_kick_consume(&pollset->kick_state); } for (i = 1; i < np; i++) { if (h->pfds[i].revents & POLLIN) { @@ -184,6 +188,7 @@ static int multipoll_with_poll_pollset_maybe_work( } } } + grpc_pollset_kick_post_poll(&pollset->kick_state); end_polling(pollset); gpr_mu_lock(&pollset->mu); diff --git a/src/core/iomgr/pollset_posix.c b/src/core/iomgr/pollset_posix.c index 6f1b3ced7d..2555322532 100644 --- a/src/core/iomgr/pollset_posix.c +++ b/src/core/iomgr/pollset_posix.c @@ -48,18 +48,6 @@ #include #include -/* kick pipes: we keep a sharded set of pipes to allow breaking from poll. - Ideally this would be 1:1 with pollsets, but we'd like to avoid associating - full kernel objects with each pollset to keep them lightweight, so instead - keep a sharded set and allow associating a pollset with one of the shards. - - TODO(ctiller): move this out from this file, and allow an eventfd - implementation on linux */ - -#define LOG2_KICK_SHARDS 6 -#define KICK_SHARDS (1 << LOG2_KICK_SHARDS) - -static int g_kick_pipes[KICK_SHARDS][2]; static grpc_pollset g_backup_pollset; static int g_shutdown_backup_poller; static gpr_event g_backup_poller_done; @@ -82,65 +70,22 @@ static void backup_poller(void *p) { gpr_event_set(&g_backup_poller_done, (void *)1); } -static size_t kick_shard(const grpc_pollset *info) { - size_t x = (size_t)info; - return ((x >> 4) ^ (x >> 9) ^ (x >> 14)) & (KICK_SHARDS - 1); -} - -int grpc_kick_read_fd(grpc_pollset *p) { - return g_kick_pipes[kick_shard(p)][0]; -} - -static int grpc_kick_write_fd(grpc_pollset *p) { - return g_kick_pipes[kick_shard(p)][1]; -} - -void grpc_pollset_force_kick(grpc_pollset *p) { - char c = 0; - while (write(grpc_kick_write_fd(p), &c, 1) != 1 && errno == EINTR) - ; -} - void grpc_pollset_kick(grpc_pollset *p) { if (!p->counter) return; - grpc_pollset_force_kick(p); + grpc_pollset_kick_kick(&p->kick_state); } -void grpc_kick_drain(grpc_pollset *p) { - int fd = grpc_kick_read_fd(p); - char buf[128]; - int r; - - for (;;) { - r = read(fd, buf, sizeof(buf)); - if (r > 0) continue; - if (r == 0) return; - switch (errno) { - case EAGAIN: - return; - case EINTR: - continue; - default: - gpr_log(GPR_ERROR, "error reading pipe: %s", strerror(errno)); - return; - } - } -} +void grpc_pollset_force_kick(grpc_pollset *p) { grpc_pollset_kick(p); } /* global state management */ grpc_pollset *grpc_backup_pollset(void) { return &g_backup_pollset; } void grpc_pollset_global_init(void) { - int i; gpr_thd_id id; - /* initialize the kick shards */ - for (i = 0; i < KICK_SHARDS; i++) { - GPR_ASSERT(0 == pipe(g_kick_pipes[i])); - GPR_ASSERT(grpc_set_socket_nonblocking(g_kick_pipes[i][0], 1)); - GPR_ASSERT(grpc_set_socket_nonblocking(g_kick_pipes[i][1], 1)); - } + /* Initialize kick fd state */ + grpc_pollset_kick_global_init(); /* initialize the backup pollset */ grpc_pollset_init(&g_backup_pollset); @@ -152,8 +97,6 @@ void grpc_pollset_global_init(void) { } void grpc_pollset_global_shutdown(void) { - int i; - /* terminate the backup poller thread */ gpr_mu_lock(&g_backup_pollset.mu); g_shutdown_backup_poller = 1; @@ -163,11 +106,8 @@ void grpc_pollset_global_shutdown(void) { /* destroy the backup pollset */ grpc_pollset_destroy(&g_backup_pollset); - /* destroy the kick shards */ - for (i = 0; i < KICK_SHARDS; i++) { - close(g_kick_pipes[i][0]); - close(g_kick_pipes[i][1]); - } + /* destroy the kick pipes */ + grpc_pollset_kick_global_destroy(); } /* main interface */ @@ -178,6 +118,7 @@ static void become_unary_pollset(grpc_pollset *pollset, grpc_fd *fd); void grpc_pollset_init(grpc_pollset *pollset) { gpr_mu_init(&pollset->mu); gpr_cv_init(&pollset->cv); + grpc_pollset_kick_init(&pollset->kick_state); become_empty_pollset(pollset); } @@ -213,6 +154,7 @@ int grpc_pollset_work(grpc_pollset *pollset, gpr_timespec deadline) { void grpc_pollset_destroy(grpc_pollset *pollset) { pollset->vtable->destroy(pollset); + grpc_pollset_kick_destroy(&pollset->kick_state); gpr_mu_destroy(&pollset->mu); gpr_cv_destroy(&pollset->cv); } @@ -290,7 +232,11 @@ static int unary_poll_pollset_maybe_work(grpc_pollset *pollset, return 1; } } - pfd[0].fd = grpc_kick_read_fd(pollset); + pfd[0].fd = grpc_pollset_kick_pre_poll(&pollset->kick_state); + if (pfd[0].fd < 0) { + /* Already kicked */ + return 1; + } pfd[0].events = POLLIN; pfd[0].revents = 0; pfd[1].fd = fd->fd; @@ -308,7 +254,7 @@ static int unary_poll_pollset_maybe_work(grpc_pollset *pollset, /* do nothing */ } else { if (pfd[0].revents & POLLIN) { - grpc_kick_drain(pollset); + grpc_pollset_kick_consume(&pollset->kick_state); } if (pfd[1].revents & POLLIN) { grpc_fd_become_readable(fd, allow_synchronous_callback); @@ -318,6 +264,8 @@ static int unary_poll_pollset_maybe_work(grpc_pollset *pollset, } } + grpc_pollset_kick_post_poll(&pollset->kick_state); + gpr_mu_lock(&pollset->mu); grpc_fd_end_poll(fd, pollset); pollset->counter = 0; diff --git a/src/core/iomgr/pollset_posix.h b/src/core/iomgr/pollset_posix.h index 32a8f533ae..f62433707e 100644 --- a/src/core/iomgr/pollset_posix.h +++ b/src/core/iomgr/pollset_posix.h @@ -36,6 +36,8 @@ #include +#include "src/core/iomgr/pollset_kick.h" + typedef struct grpc_pollset_vtable grpc_pollset_vtable; /* forward declare only in this file to avoid leaking impl details via @@ -51,6 +53,7 @@ typedef struct grpc_pollset { const grpc_pollset_vtable *vtable; gpr_mu mu; gpr_cv cv; + grpc_pollset_kick_state kick_state; int counter; union { int fd; diff --git a/test/core/iomgr/poll_kick_test.c b/test/core/iomgr/poll_kick_test.c new file mode 100644 index 0000000000..9f0d0f38b3 --- /dev/null +++ b/test/core/iomgr/poll_kick_test.c @@ -0,0 +1,101 @@ +/* + * + * 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. + * + */ + +#include "src/core/iomgr/pollset_kick.h" + +#include +#include "test/core/util/test_config.h" + +static void test_allocation() { + grpc_pollset_kick_state state; + grpc_pollset_kick_init(&state); + grpc_pollset_kick_destroy(&state); +} + +static void test_non_kick() { + grpc_pollset_kick_state state; + int fd; + + grpc_pollset_kick_init(&state); + fd = grpc_pollset_kick_pre_poll(&state); + GPR_ASSERT(fd >= 0); + + grpc_pollset_kick_post_poll(&state); + grpc_pollset_kick_destroy(&state); +} + +static void test_basic_kick() { + /* Kicked during poll */ + grpc_pollset_kick_state state; + int fd; + grpc_pollset_kick_init(&state); + + fd = grpc_pollset_kick_pre_poll(&state); + GPR_ASSERT(fd >= 0); + + grpc_pollset_kick_kick(&state); + + /* Now hypothetically we polled and found that we were kicked */ + grpc_pollset_kick_consume(&state); + + grpc_pollset_kick_post_poll(&state); + + grpc_pollset_kick_destroy(&state); +} + +static void test_non_poll_kick() { + /* Kick before entering poll */ + grpc_pollset_kick_state state; + int fd; + + grpc_pollset_kick_init(&state); + + grpc_pollset_kick_kick(&state); + fd = grpc_pollset_kick_pre_poll(&state); + GPR_ASSERT(fd < 0); + grpc_pollset_kick_destroy(&state); +} + +int main(int argc, char **argv) { + grpc_test_init(argc, argv); + + grpc_pollset_kick_global_init(); + + test_allocation(); + test_basic_kick(); + test_non_poll_kick(); + test_non_kick(); + + grpc_pollset_kick_global_destroy(); + return 0; +} diff --git a/vsprojects/vs2013/grpc.vcxproj b/vsprojects/vs2013/grpc.vcxproj index 9f3ec8c597..28cfe01b33 100644 --- a/vsprojects/vs2013/grpc.vcxproj +++ b/vsprojects/vs2013/grpc.vcxproj @@ -118,6 +118,8 @@ + + @@ -246,6 +248,8 @@ + + diff --git a/vsprojects/vs2013/grpc_unsecure.vcxproj b/vsprojects/vs2013/grpc_unsecure.vcxproj index 9f3ec8c597..28cfe01b33 100644 --- a/vsprojects/vs2013/grpc_unsecure.vcxproj +++ b/vsprojects/vs2013/grpc_unsecure.vcxproj @@ -118,6 +118,8 @@ + + @@ -246,6 +248,8 @@ + + -- cgit v1.2.3 From ecd49345b5c500b9ea1da70b15c90b87da3ff55a Mon Sep 17 00:00:00 2001 From: Craig Tiller Date: Sun, 18 Jan 2015 14:36:47 -0800 Subject: Use clang-format-3.5 --- .clang-format | 12 +-- src/compiler/cpp_generator.cc | 58 +++++------ src/compiler/cpp_generator.h | 6 +- src/compiler/cpp_generator_helpers.h | 16 +-- src/compiler/cpp_plugin.cc | 16 +-- src/compiler/ruby_generator.cc | 10 +- src/compiler/ruby_generator.h | 2 +- src/compiler/ruby_generator_helpers-inl.h | 6 +- src/compiler/ruby_generator_map-inl.h | 2 +- src/compiler/ruby_generator_string-inl.h | 22 ++-- src/compiler/ruby_plugin.cc | 10 +- src/core/channel/census_filter.c | 12 +-- src/core/channel/channel_stack.c | 11 +- src/core/channel/child_channel.c | 4 +- src/core/channel/client_channel.c | 4 +- src/core/channel/connected_channel.c | 6 +- src/core/channel/http_client_filter.c | 4 +- src/core/channel/http_filter.c | 4 +- src/core/channel/http_server_filter.c | 4 +- src/core/channel/metadata_buffer.c | 2 +- src/core/channel/noop_filter.c | 4 +- src/core/security/auth.c | 5 +- src/core/security/security_context.c | 8 +- src/core/statistics/census_rpc_stats.c | 5 +- src/core/statistics/census_tracing.c | 3 +- src/core/support/murmur_hash.c | 8 +- src/core/surface/call.c | 4 +- src/core/surface/channel.c | 2 +- src/core/surface/client.c | 4 +- src/core/surface/lame_client.c | 4 +- src/core/surface/server.c | 4 +- src/core/transport/chttp2/hpack_table.c | 124 +++++++++++------------ src/core/transport/chttp2/varint.h | 20 ++-- src/core/transport/chttp2_transport.c | 14 +-- src/core/tsi/fake_transport_security.c | 17 ++-- src/core/tsi/ssl_transport_security.c | 23 +++-- src/core/tsi/ssl_transport_security.h | 3 +- src/cpp/client/channel.cc | 56 +++++----- src/cpp/client/channel.h | 22 ++-- src/cpp/client/channel_arguments.cc | 18 ++-- src/cpp/client/client_context.cc | 8 +- src/cpp/client/create_channel.cc | 8 +- src/cpp/client/credentials.cc | 40 ++++---- src/cpp/proto/proto_utils.cc | 12 +-- src/cpp/proto/proto_utils.h | 6 +- src/cpp/server/async_server.cc | 4 +- src/cpp/server/async_server_context.cc | 16 +-- src/cpp/server/completion_queue.cc | 8 +- src/cpp/server/server.cc | 16 +-- src/cpp/server/server_builder.cc | 12 +-- src/cpp/server/server_credentials.cc | 20 ++-- src/cpp/server/server_rpc_handler.cc | 14 +-- src/cpp/server/server_rpc_handler.h | 8 +- src/cpp/server/thread_pool.cc | 4 +- src/cpp/server/thread_pool.h | 2 +- src/cpp/stream/stream_context.cc | 34 +++---- src/cpp/stream/stream_context.h | 50 ++++----- src/cpp/util/status.cc | 4 +- src/cpp/util/time.cc | 4 +- src/cpp/util/time.h | 4 +- src/php/ext/grpc/call.c | 19 ++-- src/php/ext/grpc/channel.c | 2 +- src/php/ext/grpc/completion_queue.c | 16 +-- src/php/ext/grpc/credentials.c | 13 ++- src/php/ext/grpc/php_grpc.c | 3 +- src/php/ext/grpc/server.c | 8 +- src/php/ext/grpc/server_credentials.c | 4 +- src/php/ext/grpc/timeval.c | 24 ++--- test/core/channel/channel_stack_test.c | 4 +- test/core/channel/metadata_buffer_test.c | 4 +- test/core/end2end/cq_verifier.c | 1 - test/core/end2end/tests/max_concurrent_streams.c | 2 +- test/core/end2end/tests/thread_stress.c | 4 +- test/core/iomgr/alarm_list_test.c | 14 +-- test/core/iomgr/endpoint_tests.c | 4 +- test/core/statistics/hash_table_test.c | 22 ++-- test/core/surface/completion_queue_benchmark.c | 14 +-- test/core/surface/completion_queue_test.c | 20 ++-- test/core/transport/chttp2/stream_map_test.c | 6 +- tools/clang-format/clang-format-all.sh | 5 +- tools/clang-format/config.sh | 1 + 81 files changed, 511 insertions(+), 512 deletions(-) create mode 100644 tools/clang-format/config.sh (limited to 'src') diff --git a/.clang-format b/.clang-format index 38804f78c4..651e1296ba 100644 --- a/.clang-format +++ b/.clang-format @@ -2,27 +2,22 @@ Language: Cpp # BasedOnStyle: Google AccessModifierOffset: -1 -AlignAfterOpenBracket: true +ConstructorInitializerIndentWidth: 4 AlignEscapedNewlinesLeft: true -AlignOperands: true AlignTrailingComments: true AllowAllParametersOfDeclarationOnNextLine: true AllowShortBlocksOnASingleLine: false -AllowShortCaseLabelsOnASingleLine: false AllowShortIfStatementsOnASingleLine: true AllowShortLoopsOnASingleLine: true AllowShortFunctionsOnASingleLine: All -AlwaysBreakAfterDefinitionReturnType: false AlwaysBreakTemplateDeclarations: true AlwaysBreakBeforeMultilineStrings: true -BreakBeforeBinaryOperators: None +BreakBeforeBinaryOperators: false BreakBeforeTernaryOperators: true BreakConstructorInitializersBeforeComma: false BinPackParameters: true -BinPackArguments: true ColumnLimit: 80 ConstructorInitializerAllOnOneLineOrOnePerLine: true -ConstructorInitializerIndentWidth: 4 DerivePointerAlignment: true ExperimentalAutoDetectBinPacking: false IndentCaseLabels: true @@ -31,7 +26,6 @@ IndentFunctionDeclarationAfterType: false MaxEmptyLinesToKeep: 1 KeepEmptyLinesAtTheStartOfBlocks: false NamespaceIndentation: None -ObjCBlockIndentWidth: 2 ObjCSpaceAfterProperty: false ObjCSpaceBeforeProtocolList: false PenaltyBreakBeforeFirstCallParameter: 1 @@ -49,11 +43,9 @@ TabWidth: 8 UseTab: Never BreakBeforeBraces: Attach SpacesInParentheses: false -SpacesInSquareBrackets: false SpacesInAngles: false SpaceInEmptyParentheses: false SpacesInCStyleCastParentheses: false -SpaceAfterCStyleCast: false SpacesInContainerLiterals: true SpaceBeforeAssignmentOperators: true ContinuationIndentWidth: 4 diff --git a/src/compiler/cpp_generator.cc b/src/compiler/cpp_generator.cc index 29bd3560f3..8724f97e8b 100644 --- a/src/compiler/cpp_generator.cc +++ b/src/compiler/cpp_generator.cc @@ -45,23 +45,23 @@ namespace grpc_cpp_generator { namespace { -bool NoStreaming(const google::protobuf::MethodDescriptor* method) { +bool NoStreaming(const google::protobuf::MethodDescriptor *method) { return !method->client_streaming() && !method->server_streaming(); } -bool ClientOnlyStreaming(const google::protobuf::MethodDescriptor* method) { +bool ClientOnlyStreaming(const google::protobuf::MethodDescriptor *method) { return method->client_streaming() && !method->server_streaming(); } -bool ServerOnlyStreaming(const google::protobuf::MethodDescriptor* method) { +bool ServerOnlyStreaming(const google::protobuf::MethodDescriptor *method) { return !method->client_streaming() && method->server_streaming(); } -bool BidiStreaming(const google::protobuf::MethodDescriptor* method) { +bool BidiStreaming(const google::protobuf::MethodDescriptor *method) { return method->client_streaming() && method->server_streaming(); } -bool HasClientOnlyStreaming(const google::protobuf::FileDescriptor* file) { +bool HasClientOnlyStreaming(const google::protobuf::FileDescriptor *file) { for (int i = 0; i < file->service_count(); i++) { for (int j = 0; j < file->service(i)->method_count(); j++) { if (ClientOnlyStreaming(file->service(i)->method(j))) { @@ -72,7 +72,7 @@ bool HasClientOnlyStreaming(const google::protobuf::FileDescriptor* file) { return false; } -bool HasServerOnlyStreaming(const google::protobuf::FileDescriptor* file) { +bool HasServerOnlyStreaming(const google::protobuf::FileDescriptor *file) { for (int i = 0; i < file->service_count(); i++) { for (int j = 0; j < file->service(i)->method_count(); j++) { if (ServerOnlyStreaming(file->service(i)->method(j))) { @@ -83,7 +83,7 @@ bool HasServerOnlyStreaming(const google::protobuf::FileDescriptor* file) { return false; } -bool HasBidiStreaming(const google::protobuf::FileDescriptor* file) { +bool HasBidiStreaming(const google::protobuf::FileDescriptor *file) { for (int i = 0; i < file->service_count(); i++) { for (int j = 0; j < file->service(i)->method_count(); j++) { if (BidiStreaming(file->service(i)->method(j))) { @@ -95,7 +95,7 @@ bool HasBidiStreaming(const google::protobuf::FileDescriptor* file) { } } // namespace -std::string GetHeaderIncludes(const google::protobuf::FileDescriptor* file) { +std::string GetHeaderIncludes(const google::protobuf::FileDescriptor *file) { std::string temp = "#include \"grpc++/impl/internal_stub.h\"\n" "#include \"grpc++/status.h\"\n" @@ -131,9 +131,9 @@ std::string GetSourceIncludes() { "#include \"grpc++/stream.h\"\n"; } -void PrintHeaderClientMethod(google::protobuf::io::Printer* printer, - const google::protobuf::MethodDescriptor* method, - std::map* vars) { +void PrintHeaderClientMethod(google::protobuf::io::Printer *printer, + const google::protobuf::MethodDescriptor *method, + std::map *vars) { (*vars)["Method"] = method->name(); (*vars)["Request"] = grpc_cpp_generator::ClassName(method->input_type(), true); @@ -160,9 +160,9 @@ void PrintHeaderClientMethod(google::protobuf::io::Printer* printer, } } -void PrintHeaderServerMethod(google::protobuf::io::Printer* printer, - const google::protobuf::MethodDescriptor* method, - std::map* vars) { +void PrintHeaderServerMethod(google::protobuf::io::Printer *printer, + const google::protobuf::MethodDescriptor *method, + std::map *vars) { (*vars)["Method"] = method->name(); (*vars)["Request"] = grpc_cpp_generator::ClassName(method->input_type(), true); @@ -194,9 +194,9 @@ void PrintHeaderServerMethod(google::protobuf::io::Printer* printer, } } -void PrintHeaderService(google::protobuf::io::Printer* printer, - const google::protobuf::ServiceDescriptor* service, - std::map* vars) { +void PrintHeaderService(google::protobuf::io::Printer *printer, + const google::protobuf::ServiceDescriptor *service, + std::map *vars) { (*vars)["Service"] = service->name(); printer->Print(*vars, @@ -241,7 +241,7 @@ void PrintHeaderService(google::protobuf::io::Printer* printer, printer->Print("};\n"); } -std::string GetHeaderServices(const google::protobuf::FileDescriptor* file) { +std::string GetHeaderServices(const google::protobuf::FileDescriptor *file) { std::string output; google::protobuf::io::StringOutputStream output_stream(&output); google::protobuf::io::Printer printer(&output_stream, '$'); @@ -254,9 +254,9 @@ std::string GetHeaderServices(const google::protobuf::FileDescriptor* file) { return output; } -void PrintSourceClientMethod(google::protobuf::io::Printer* printer, - const google::protobuf::MethodDescriptor* method, - std::map* vars) { +void PrintSourceClientMethod(google::protobuf::io::Printer *printer, + const google::protobuf::MethodDescriptor *method, + std::map *vars) { (*vars)["Method"] = method->name(); (*vars)["Request"] = grpc_cpp_generator::ClassName(method->input_type(), true); @@ -312,9 +312,9 @@ void PrintSourceClientMethod(google::protobuf::io::Printer* printer, } } -void PrintSourceServerMethod(google::protobuf::io::Printer* printer, - const google::protobuf::MethodDescriptor* method, - std::map* vars) { +void PrintSourceServerMethod(google::protobuf::io::Printer *printer, + const google::protobuf::MethodDescriptor *method, + std::map *vars) { (*vars)["Method"] = method->name(); (*vars)["Request"] = grpc_cpp_generator::ClassName(method->input_type(), true); @@ -362,9 +362,9 @@ void PrintSourceServerMethod(google::protobuf::io::Printer* printer, } } -void PrintSourceService(google::protobuf::io::Printer* printer, - const google::protobuf::ServiceDescriptor* service, - std::map* vars) { +void PrintSourceService(google::protobuf::io::Printer *printer, + const google::protobuf::ServiceDescriptor *service, + std::map *vars) { (*vars)["Service"] = service->name(); printer->Print( *vars, @@ -394,7 +394,7 @@ void PrintSourceService(google::protobuf::io::Printer* printer, "}\n"); printer->Print("service_ = new ::grpc::RpcService();\n"); for (int i = 0; i < service->method_count(); ++i) { - const google::protobuf::MethodDescriptor* method = service->method(i); + const google::protobuf::MethodDescriptor *method = service->method(i); (*vars)["Method"] = method->name(); (*vars)["Request"] = grpc_cpp_generator::ClassName(method->input_type(), true); @@ -458,7 +458,7 @@ void PrintSourceService(google::protobuf::io::Printer* printer, printer->Print("}\n\n"); } -std::string GetSourceServices(const google::protobuf::FileDescriptor* file) { +std::string GetSourceServices(const google::protobuf::FileDescriptor *file) { std::string output; google::protobuf::io::StringOutputStream output_stream(&output); google::protobuf::io::Printer printer(&output_stream, '$'); diff --git a/src/compiler/cpp_generator.h b/src/compiler/cpp_generator.h index 1a74211b71..fe84d08b4c 100644 --- a/src/compiler/cpp_generator.h +++ b/src/compiler/cpp_generator.h @@ -45,16 +45,16 @@ class FileDescriptor; namespace grpc_cpp_generator { // Return the includes needed for generated header file. -std::string GetHeaderIncludes(const google::protobuf::FileDescriptor* file); +std::string GetHeaderIncludes(const google::protobuf::FileDescriptor *file); // Return the includes needed for generated source file. std::string GetSourceIncludes(); // Return the services for generated header file. -std::string GetHeaderServices(const google::protobuf::FileDescriptor* file); +std::string GetHeaderServices(const google::protobuf::FileDescriptor *file); // Return the services for generated source file. -std::string GetSourceServices(const google::protobuf::FileDescriptor* file); +std::string GetSourceServices(const google::protobuf::FileDescriptor *file); } // namespace grpc_cpp_generator diff --git a/src/compiler/cpp_generator_helpers.h b/src/compiler/cpp_generator_helpers.h index 1ad3cb2db3..54c343866f 100644 --- a/src/compiler/cpp_generator_helpers.h +++ b/src/compiler/cpp_generator_helpers.h @@ -41,7 +41,7 @@ namespace grpc_cpp_generator { -inline bool StripSuffix(std::string* filename, const std::string& suffix) { +inline bool StripSuffix(std::string *filename, const std::string &suffix) { if (filename->length() >= suffix.length()) { size_t suffix_pos = filename->length() - suffix.length(); if (filename->compare(suffix_pos, std::string::npos, suffix) == 0) { @@ -60,8 +60,8 @@ inline std::string StripProto(std::string filename) { return filename; } -inline std::string StringReplace(std::string str, const std::string& from, - const std::string& to) { +inline std::string StringReplace(std::string str, const std::string &from, + const std::string &to) { size_t pos = 0; for (;;) { @@ -76,22 +76,22 @@ inline std::string StringReplace(std::string str, const std::string& from, return str; } -inline std::string DotsToColons(const std::string& name) { +inline std::string DotsToColons(const std::string &name) { return StringReplace(name, ".", "::"); } -inline std::string DotsToUnderscores(const std::string& name) { +inline std::string DotsToUnderscores(const std::string &name) { return StringReplace(name, ".", "_"); } -inline std::string ClassName(const google::protobuf::Descriptor* descriptor, +inline std::string ClassName(const google::protobuf::Descriptor *descriptor, bool qualified) { // Find "outer", the descriptor of the top-level message in which // "descriptor" is embedded. - const google::protobuf::Descriptor* outer = descriptor; + const google::protobuf::Descriptor *outer = descriptor; while (outer->containing_type() != NULL) outer = outer->containing_type(); - const std::string& outer_name = outer->full_name(); + const std::string &outer_name = outer->full_name(); std::string inner_name = descriptor->full_name().substr(outer_name.size()); if (qualified) { diff --git a/src/compiler/cpp_plugin.cc b/src/compiler/cpp_plugin.cc index e43278529d..a7fdb1f093 100644 --- a/src/compiler/cpp_plugin.cc +++ b/src/compiler/cpp_plugin.cc @@ -51,10 +51,10 @@ class CppGrpcGenerator : public google::protobuf::compiler::CodeGenerator { CppGrpcGenerator() {} virtual ~CppGrpcGenerator() {} - virtual bool Generate(const google::protobuf::FileDescriptor* file, - const std::string& parameter, - google::protobuf::compiler::GeneratorContext* context, - std::string* error) const { + virtual bool Generate(const google::protobuf::FileDescriptor *file, + const std::string ¶meter, + google::protobuf::compiler::GeneratorContext *context, + std::string *error) const { if (file->options().cc_generic_services()) { *error = "cpp grpc proto compiler plugin does not work with generic " @@ -81,9 +81,9 @@ class CppGrpcGenerator : public google::protobuf::compiler::CodeGenerator { private: // Insert the given code into the given file at the given insertion point. - void Insert(google::protobuf::compiler::GeneratorContext* context, - const std::string& filename, const std::string& insertion_point, - const std::string& code) const { + void Insert(google::protobuf::compiler::GeneratorContext *context, + const std::string &filename, const std::string &insertion_point, + const std::string &code) const { std::unique_ptr output( context->OpenForInsert(filename, insertion_point)); google::protobuf::io::CodedOutputStream coded_out(output.get()); @@ -91,7 +91,7 @@ class CppGrpcGenerator : public google::protobuf::compiler::CodeGenerator { } }; -int main(int argc, char* argv[]) { +int main(int argc, char *argv[]) { CppGrpcGenerator generator; return google::protobuf::compiler::PluginMain(argc, argv, &generator); } diff --git a/src/compiler/ruby_generator.cc b/src/compiler/ruby_generator.cc index 393f8f3b59..16632325dc 100644 --- a/src/compiler/ruby_generator.cc +++ b/src/compiler/ruby_generator.cc @@ -57,8 +57,8 @@ namespace grpc_ruby_generator { namespace { // Prints out the method using the ruby gRPC DSL. -void PrintMethod(const MethodDescriptor* method, const std::string& package, - Printer* out) { +void PrintMethod(const MethodDescriptor *method, const std::string &package, + Printer *out) { std::string input_type = RubyTypeOf(method->input_type()->name(), package); if (method->client_streaming()) { input_type = "stream(" + input_type + ")"; @@ -75,8 +75,8 @@ void PrintMethod(const MethodDescriptor* method, const std::string& package, } // Prints out the service using the ruby gRPC DSL. -void PrintService(const ServiceDescriptor* service, const std::string& package, - Printer* out) { +void PrintService(const ServiceDescriptor *service, const std::string &package, + Printer *out) { if (service->method_count() == 0) { return; } @@ -125,7 +125,7 @@ void PrintService(const ServiceDescriptor* service, const std::string& package, } // namespace -std::string GetServices(const FileDescriptor* file) { +std::string GetServices(const FileDescriptor *file) { std::string output; StringOutputStream output_stream(&output); Printer out(&output_stream, '$'); diff --git a/src/compiler/ruby_generator.h b/src/compiler/ruby_generator.h index 0306536d08..89d7a0b92a 100644 --- a/src/compiler/ruby_generator.h +++ b/src/compiler/ruby_generator.h @@ -44,7 +44,7 @@ class FileDescriptor; namespace grpc_ruby_generator { -std::string GetServices(const google::protobuf::FileDescriptor* file); +std::string GetServices(const google::protobuf::FileDescriptor *file); } // namespace grpc_ruby_generator diff --git a/src/compiler/ruby_generator_helpers-inl.h b/src/compiler/ruby_generator_helpers-inl.h index 7b973ed9eb..0034f5ef56 100644 --- a/src/compiler/ruby_generator_helpers-inl.h +++ b/src/compiler/ruby_generator_helpers-inl.h @@ -41,8 +41,8 @@ namespace grpc_ruby_generator { -inline bool ServicesFilename(const google::protobuf::FileDescriptor* file, - std::string* file_name_or_error) { +inline bool ServicesFilename(const google::protobuf::FileDescriptor *file, + std::string *file_name_or_error) { // Get output file name. static const unsigned proto_suffix_length = 6; // length of ".proto" if (file->name().size() > proto_suffix_length && @@ -58,7 +58,7 @@ inline bool ServicesFilename(const google::protobuf::FileDescriptor* file, } inline std::string MessagesRequireName( - const google::protobuf::FileDescriptor* file) { + const google::protobuf::FileDescriptor *file) { return Replace(file->name(), ".proto", ""); } diff --git a/src/compiler/ruby_generator_map-inl.h b/src/compiler/ruby_generator_map-inl.h index a49650a2f7..fea9c2e2fa 100644 --- a/src/compiler/ruby_generator_map-inl.h +++ b/src/compiler/ruby_generator_map-inl.h @@ -49,7 +49,7 @@ namespace grpc_ruby_generator { // Converts an initializer list of the form { key0, value0, key1, value1, ... } // into a map of key* to value*. Is merely a readability helper for later code. inline std::map ListToDict( - const initializer_list& values) { + const initializer_list &values) { if (values.size() % 2 != 0) { // MOE: insert std::cerr << "Not every 'key' has a value in `values`." // << std::endl; diff --git a/src/compiler/ruby_generator_string-inl.h b/src/compiler/ruby_generator_string-inl.h index a253f78d49..d24a61b9f5 100644 --- a/src/compiler/ruby_generator_string-inl.h +++ b/src/compiler/ruby_generator_string-inl.h @@ -45,8 +45,8 @@ using std::transform; namespace grpc_ruby_generator { // Split splits a string using char into elems. -inline std::vector& Split(const std::string& s, char delim, - std::vector* elems) { +inline std::vector &Split(const std::string &s, char delim, + std::vector *elems) { std::stringstream ss(s); std::string item; while (getline(ss, item, delim)) { @@ -56,15 +56,15 @@ inline std::vector& Split(const std::string& s, char delim, } // Split splits a string using char, returning the result in a vector. -inline std::vector Split(const std::string& s, char delim) { +inline std::vector Split(const std::string &s, char delim) { std::vector elems; Split(s, delim, &elems); return elems; } // Replace replaces from with to in s. -inline std::string Replace(std::string s, const std::string& from, - const std::string& to) { +inline std::string Replace(std::string s, const std::string &from, + const std::string &to) { size_t start_pos = s.find(from); if (start_pos == std::string::npos) { return s; @@ -74,8 +74,8 @@ inline std::string Replace(std::string s, const std::string& from, } // ReplaceAll replaces all instances of search with replace in s. -inline std::string ReplaceAll(std::string s, const std::string& search, - const std::string& replace) { +inline std::string ReplaceAll(std::string s, const std::string &search, + const std::string &replace) { size_t pos = 0; while ((pos = s.find(search, pos)) != std::string::npos) { s.replace(pos, search.length(), replace); @@ -85,8 +85,8 @@ inline std::string ReplaceAll(std::string s, const std::string& search, } // ReplacePrefix replaces from with to in s if search is a prefix of s. -inline bool ReplacePrefix(std::string* s, const std::string& from, - const std::string& to) { +inline bool ReplacePrefix(std::string *s, const std::string &from, + const std::string &to) { size_t start_pos = s->find(from); if (start_pos == std::string::npos || start_pos != 0) { return false; @@ -105,8 +105,8 @@ inline std::string CapitalizeFirst(std::string s) { } // RubyTypeOf updates a proto type to the required ruby equivalent. -inline std::string RubyTypeOf(const std::string& a_type, - const std::string& package) { +inline std::string RubyTypeOf(const std::string &a_type, + const std::string &package) { std::string res(a_type); ReplacePrefix(&res, package, ""); // remove the leading package if present ReplacePrefix(&res, ".", ""); // remove the leading . (no package) diff --git a/src/compiler/ruby_plugin.cc b/src/compiler/ruby_plugin.cc index 86c0e11e1c..9397452f55 100644 --- a/src/compiler/ruby_plugin.cc +++ b/src/compiler/ruby_plugin.cc @@ -52,10 +52,10 @@ class RubyGrpcGenerator : public google::protobuf::compiler::CodeGenerator { RubyGrpcGenerator() {} ~RubyGrpcGenerator() override {} - bool Generate(const google::protobuf::FileDescriptor* file, - const std::string& parameter, - google::protobuf::compiler::GeneratorContext* context, - std::string* error) const override { + bool Generate(const google::protobuf::FileDescriptor *file, + const std::string ¶meter, + google::protobuf::compiler::GeneratorContext *context, + std::string *error) const override { std::string code = grpc_ruby_generator::GetServices(file); if (code.size() == 0) { return true; // don't generate a file if there are no services @@ -74,7 +74,7 @@ class RubyGrpcGenerator : public google::protobuf::compiler::CodeGenerator { } }; -int main(int argc, char* argv[]) { +int main(int argc, char *argv[]) { RubyGrpcGenerator generator; return google::protobuf::compiler::PluginMain(argc, argv, &generator); } diff --git a/src/core/channel/census_filter.c b/src/core/channel/census_filter.c index 2799bded8a..ed60f0a5f6 100644 --- a/src/core/channel/census_filter.c +++ b/src/core/channel/census_filter.c @@ -178,19 +178,19 @@ static void destroy_channel_elem(grpc_channel_element* elem) { } const grpc_channel_filter grpc_client_census_filter = { - client_call_op, channel_op, + client_call_op, channel_op, - sizeof(call_data), client_init_call_elem, client_destroy_call_elem, + sizeof(call_data), client_init_call_elem, client_destroy_call_elem, - sizeof(channel_data), init_channel_elem, destroy_channel_elem, + sizeof(channel_data), init_channel_elem, destroy_channel_elem, "census-client"}; const grpc_channel_filter grpc_server_census_filter = { - server_call_op, channel_op, + server_call_op, channel_op, - sizeof(call_data), server_init_call_elem, server_destroy_call_elem, + sizeof(call_data), server_init_call_elem, server_destroy_call_elem, - sizeof(channel_data), init_channel_elem, destroy_channel_elem, + sizeof(channel_data), init_channel_elem, destroy_channel_elem, "census-server"}; diff --git a/src/core/channel/channel_stack.c b/src/core/channel/channel_stack.c index 14fc800778..5ee412bf7d 100644 --- a/src/core/channel/channel_stack.c +++ b/src/core/channel/channel_stack.c @@ -54,7 +54,7 @@ /* Given a size, round up to the next multiple of sizeof(void*) */ #define ROUND_UP_TO_ALIGNMENT_SIZE(x) \ - (((x) + GPR_MAX_ALIGNMENT - 1) & ~(GPR_MAX_ALIGNMENT - 1)) + (((x)+GPR_MAX_ALIGNMENT - 1) & ~(GPR_MAX_ALIGNMENT - 1)) size_t grpc_channel_stack_size(const grpc_channel_filter **filters, size_t filter_count) { @@ -190,13 +190,14 @@ void grpc_channel_next_op(grpc_channel_element *elem, grpc_channel_op *op) { grpc_channel_stack *grpc_channel_stack_from_top_element( grpc_channel_element *elem) { - return (grpc_channel_stack *)((char *)(elem)-ROUND_UP_TO_ALIGNMENT_SIZE( - sizeof(grpc_channel_stack))); + return (grpc_channel_stack *)((char *)(elem) - + ROUND_UP_TO_ALIGNMENT_SIZE( + sizeof(grpc_channel_stack))); } grpc_call_stack *grpc_call_stack_from_top_element(grpc_call_element *elem) { - return (grpc_call_stack *)((char *)(elem)-ROUND_UP_TO_ALIGNMENT_SIZE( - sizeof(grpc_call_stack))); + return (grpc_call_stack *)((char *)(elem) - ROUND_UP_TO_ALIGNMENT_SIZE( + sizeof(grpc_call_stack))); } static void do_nothing(void *user_data, grpc_op_error error) {} diff --git a/src/core/channel/child_channel.c b/src/core/channel/child_channel.c index 3778f4fb88..f400e9b670 100644 --- a/src/core/channel/child_channel.c +++ b/src/core/channel/child_channel.c @@ -165,9 +165,9 @@ static void lb_destroy_channel_elem(grpc_channel_element *elem) { } const grpc_channel_filter grpc_child_channel_top_filter = { - lb_call_op, lb_channel_op, + lb_call_op, lb_channel_op, - sizeof(lb_call_data), lb_init_call_elem, lb_destroy_call_elem, + sizeof(lb_call_data), lb_init_call_elem, lb_destroy_call_elem, sizeof(lb_channel_data), lb_init_channel_elem, lb_destroy_channel_elem, diff --git a/src/core/channel/client_channel.c b/src/core/channel/client_channel.c index 46283835a0..fa75561c78 100644 --- a/src/core/channel/client_channel.c +++ b/src/core/channel/client_channel.c @@ -450,9 +450,9 @@ static void destroy_channel_elem(grpc_channel_element *elem) { } const grpc_channel_filter grpc_client_channel_filter = { - call_op, channel_op, + call_op, channel_op, - sizeof(call_data), init_call_elem, destroy_call_elem, + sizeof(call_data), init_call_elem, destroy_call_elem, sizeof(channel_data), init_channel_elem, destroy_channel_elem, diff --git a/src/core/channel/connected_channel.c b/src/core/channel/connected_channel.c index 30de10905c..e01cb81a89 100644 --- a/src/core/channel/connected_channel.c +++ b/src/core/channel/connected_channel.c @@ -69,7 +69,7 @@ typedef struct { /* We perform a small hack to locate transport data alongside the connected channel data in call allocations, to allow everything to be pulled in minimal cache line requests */ -#define TRANSPORT_STREAM_FROM_CALL_DATA(calld) ((grpc_stream *)((calld) + 1)) +#define TRANSPORT_STREAM_FROM_CALL_DATA(calld) ((grpc_stream *)((calld)+1)) #define CALL_DATA_FROM_TRANSPORT_STREAM(transport_stream) \ (((call_data *)(transport_stream)) - 1) @@ -257,9 +257,9 @@ static void destroy_channel_elem(grpc_channel_element *elem) { } const grpc_channel_filter grpc_connected_channel_filter = { - call_op, channel_op, + call_op, channel_op, - sizeof(call_data), init_call_elem, destroy_call_elem, + sizeof(call_data), init_call_elem, destroy_call_elem, sizeof(channel_data), init_channel_elem, destroy_channel_elem, diff --git a/src/core/channel/http_client_filter.c b/src/core/channel/http_client_filter.c index ab9d3aff16..b139b72795 100644 --- a/src/core/channel/http_client_filter.c +++ b/src/core/channel/http_client_filter.c @@ -178,9 +178,9 @@ static void destroy_channel_elem(grpc_channel_element *elem) { } const grpc_channel_filter grpc_http_client_filter = { - call_op, channel_op, + call_op, channel_op, - sizeof(call_data), init_call_elem, destroy_call_elem, + sizeof(call_data), init_call_elem, destroy_call_elem, sizeof(channel_data), init_channel_elem, destroy_channel_elem, diff --git a/src/core/channel/http_filter.c b/src/core/channel/http_filter.c index 6cfe34695c..846f7b9713 100644 --- a/src/core/channel/http_filter.c +++ b/src/core/channel/http_filter.c @@ -132,9 +132,9 @@ static void destroy_channel_elem(grpc_channel_element *elem) { } const grpc_channel_filter grpc_http_filter = { - call_op, channel_op, + call_op, channel_op, - sizeof(call_data), init_call_elem, destroy_call_elem, + sizeof(call_data), init_call_elem, destroy_call_elem, sizeof(channel_data), init_channel_elem, destroy_channel_elem, diff --git a/src/core/channel/http_server_filter.c b/src/core/channel/http_server_filter.c index 44eab43f09..19b9606b43 100644 --- a/src/core/channel/http_server_filter.c +++ b/src/core/channel/http_server_filter.c @@ -244,9 +244,9 @@ static void destroy_channel_elem(grpc_channel_element *elem) { } const grpc_channel_filter grpc_http_server_filter = { - call_op, channel_op, + call_op, channel_op, - sizeof(call_data), init_call_elem, destroy_call_elem, + sizeof(call_data), init_call_elem, destroy_call_elem, sizeof(channel_data), init_channel_elem, destroy_channel_elem, diff --git a/src/core/channel/metadata_buffer.c b/src/core/channel/metadata_buffer.c index d4de4ba576..75fd90b707 100644 --- a/src/core/channel/metadata_buffer.c +++ b/src/core/channel/metadata_buffer.c @@ -61,7 +61,7 @@ struct grpc_metadata_buffer_impl { size_t elem_cap; }; -#define ELEMS(buffer) ((qelem *)((buffer) + 1)) +#define ELEMS(buffer) ((qelem *)((buffer)+1)) void grpc_metadata_buffer_init(grpc_metadata_buffer *buffer) { /* start buffer as NULL, indicating no elements */ diff --git a/src/core/channel/noop_filter.c b/src/core/channel/noop_filter.c index 6f854a2b87..b6b3f661f7 100644 --- a/src/core/channel/noop_filter.c +++ b/src/core/channel/noop_filter.c @@ -131,9 +131,9 @@ static void destroy_channel_elem(grpc_channel_element *elem) { } const grpc_channel_filter grpc_no_op_filter = { - call_op, channel_op, + call_op, channel_op, - sizeof(call_data), init_call_elem, destroy_call_elem, + sizeof(call_data), init_call_elem, destroy_call_elem, sizeof(channel_data), init_channel_elem, destroy_channel_elem, diff --git a/src/core/security/auth.c b/src/core/security/auth.c index e36bf2382f..f743b25838 100644 --- a/src/core/security/auth.c +++ b/src/core/security/auth.c @@ -157,5 +157,6 @@ static void destroy_channel_elem(grpc_channel_element *elem) { } const grpc_channel_filter grpc_client_auth_filter = { - call_op, channel_op, sizeof(call_data), init_call_elem, destroy_call_elem, - sizeof(channel_data), init_channel_elem, destroy_channel_elem, "auth"}; + call_op, channel_op, sizeof(call_data), + init_call_elem, destroy_call_elem, sizeof(channel_data), + init_channel_elem, destroy_channel_elem, "auth"}; diff --git a/src/core/security/security_context.c b/src/core/security/security_context.c index 421b81fd36..3a70f44a0a 100644 --- a/src/core/security/security_context.c +++ b/src/core/security/security_context.c @@ -413,10 +413,10 @@ grpc_security_status grpc_ssl_server_security_context_create( (const unsigned char **)&config->pem_private_key, &config->pem_private_key_size, (const unsigned char **)&config->pem_cert_chain, - &config->pem_cert_chain_size, 1, - config->pem_root_certs, config->pem_root_certs_size, - GRPC_SSL_CIPHER_SUITES, alpn_protocol_strings, - alpn_protocol_string_lengths, num_alpn_protocols, &c->handshaker_factory); + &config->pem_cert_chain_size, 1, config->pem_root_certs, + config->pem_root_certs_size, GRPC_SSL_CIPHER_SUITES, + alpn_protocol_strings, alpn_protocol_string_lengths, num_alpn_protocols, + &c->handshaker_factory); if (result != TSI_OK) { gpr_log(GPR_ERROR, "Handshaker factory creation failed with %s.", tsi_result_to_string(result)); diff --git a/src/core/statistics/census_rpc_stats.c b/src/core/statistics/census_rpc_stats.c index 2db3054a0d..39094b5f65 100644 --- a/src/core/statistics/census_rpc_stats.c +++ b/src/core/statistics/census_rpc_stats.c @@ -85,8 +85,9 @@ 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) { memset(stats, 0, sizeof(census_rpc_stats)); diff --git a/src/core/statistics/census_tracing.c b/src/core/statistics/census_tracing.c index 8c7cf11642..1e61602071 100644 --- a/src/core/statistics/census_tracing.c +++ b/src/core/statistics/census_tracing.c @@ -76,7 +76,8 @@ static void delete_trace_obj(void* obj) { trace_obj_destroy((trace_obj*)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 */, - NULL /* delete key */}; + NULL /* delete key */ +}; static gpr_once g_init_mutex_once = GPR_ONCE_INIT; static gpr_mu g_mu; /* Guards following two static variables. */ diff --git a/src/core/support/murmur_hash.c b/src/core/support/murmur_hash.c index 5d30263e52..08b1eb80d8 100644 --- a/src/core/support/murmur_hash.c +++ b/src/core/support/murmur_hash.c @@ -46,8 +46,8 @@ handle aligned reads, do the conversion here */ #define GETBLOCK32(p, i) (p)[(i)] -gpr_uint32 gpr_murmur_hash3(const void* key, size_t len, gpr_uint32 seed) { - const gpr_uint8* data = (const gpr_uint8*)key; +gpr_uint32 gpr_murmur_hash3(const void *key, size_t len, gpr_uint32 seed) { + const gpr_uint8 *data = (const gpr_uint8 *)key; const int nblocks = len / 4; int i; @@ -57,8 +57,8 @@ gpr_uint32 gpr_murmur_hash3(const void* key, size_t len, gpr_uint32 seed) { const gpr_uint32 c1 = 0xcc9e2d51; const gpr_uint32 c2 = 0x1b873593; - const gpr_uint32* blocks = (const uint32_t*)(data + nblocks * 4); - const uint8_t* tail = (const uint8_t*)(data + nblocks * 4); + const gpr_uint32 *blocks = (const uint32_t *)(data + nblocks * 4); + const uint8_t *tail = (const uint8_t *)(data + nblocks * 4); /* body */ for (i = -nblocks; i; i++) { diff --git a/src/core/surface/call.c b/src/core/surface/call.c index 26bfa02ad1..46502fb6b1 100644 --- a/src/core/surface/call.c +++ b/src/core/surface/call.c @@ -198,7 +198,7 @@ struct grpc_call { gpr_refcount internal_refcount; }; -#define CALL_STACK_FROM_CALL(call) ((grpc_call_stack *)((call) + 1)) +#define CALL_STACK_FROM_CALL(call) ((grpc_call_stack *)((call)+1)) #define CALL_FROM_CALL_STACK(call_stack) (((grpc_call *)(call_stack)) - 1) #define CALL_ELEM_FROM_CALL(call, idx) \ grpc_call_stack_element(CALL_STACK_FROM_CALL(call), idx) @@ -801,7 +801,7 @@ static gpr_uint32 decode_status(grpc_mdelem *md) { gpr_uint32 status; void *user_data = grpc_mdelem_get_user_data(md, destroy_status); if (user_data) { - status = ((gpr_uint32)(gpr_intptr)user_data) - STATUS_OFFSET; + status = ((gpr_uint32)(gpr_intptr) user_data) - STATUS_OFFSET; } else { if (!gpr_parse_bytes_to_uint32(grpc_mdstr_as_c_string(md->value), GPR_SLICE_LENGTH(md->value->slice), diff --git a/src/core/surface/channel.c b/src/core/surface/channel.c index a1bcea58dd..8ef13675fe 100644 --- a/src/core/surface/channel.c +++ b/src/core/surface/channel.c @@ -51,7 +51,7 @@ struct grpc_channel { grpc_mdstr *authority_string; }; -#define CHANNEL_STACK_FROM_CHANNEL(c) ((grpc_channel_stack *)((c) + 1)) +#define CHANNEL_STACK_FROM_CHANNEL(c) ((grpc_channel_stack *)((c)+1)) grpc_channel *grpc_channel_create_from_filters( const grpc_channel_filter **filters, size_t num_filters, diff --git a/src/core/surface/client.c b/src/core/surface/client.c index 524b0718a9..74c79bdf9b 100644 --- a/src/core/surface/client.c +++ b/src/core/surface/client.c @@ -109,9 +109,9 @@ static void init_channel_elem(grpc_channel_element *elem, static void destroy_channel_elem(grpc_channel_element *elem) {} const grpc_channel_filter grpc_client_surface_filter = { - call_op, channel_op, + call_op, channel_op, - sizeof(call_data), init_call_elem, destroy_call_elem, + sizeof(call_data), init_call_elem, destroy_call_elem, sizeof(channel_data), init_channel_elem, destroy_channel_elem, diff --git a/src/core/surface/lame_client.c b/src/core/surface/lame_client.c index 5fa3e42362..a5244dbe61 100644 --- a/src/core/surface/lame_client.c +++ b/src/core/surface/lame_client.c @@ -111,9 +111,9 @@ static void destroy_channel_elem(grpc_channel_element *elem) { } static const grpc_channel_filter lame_filter = { - call_op, channel_op, + call_op, channel_op, - sizeof(call_data), init_call_elem, destroy_call_elem, + sizeof(call_data), init_call_elem, destroy_call_elem, sizeof(channel_data), init_channel_elem, destroy_channel_elem, diff --git a/src/core/surface/server.c b/src/core/surface/server.c index 846a00c94f..cbdd3bfa30 100644 --- a/src/core/surface/server.c +++ b/src/core/surface/server.c @@ -411,9 +411,9 @@ static void destroy_channel_elem(grpc_channel_element *elem) { } static const grpc_channel_filter server_surface_filter = { - call_op, channel_op, + call_op, channel_op, - sizeof(call_data), init_call_elem, destroy_call_elem, + sizeof(call_data), init_call_elem, destroy_call_elem, sizeof(channel_data), init_channel_elem, destroy_channel_elem, diff --git a/src/core/transport/chttp2/hpack_table.c b/src/core/transport/chttp2/hpack_table.c index ae8bfa8009..8f2ebecfeb 100644 --- a/src/core/transport/chttp2/hpack_table.c +++ b/src/core/transport/chttp2/hpack_table.c @@ -43,68 +43,68 @@ static struct { const char *key; const char *value; } static_table[] = { - /* 0: */ {NULL, NULL}, - /* 1: */ {":authority", ""}, - /* 2: */ {":method", "GET"}, - /* 3: */ {":method", "POST"}, - /* 4: */ {":path", "/"}, - /* 5: */ {":path", "/index.html"}, - /* 6: */ {":scheme", "http"}, - /* 7: */ {":scheme", "https"}, - /* 8: */ {":status", "200"}, - /* 9: */ {":status", "204"}, - /* 10: */ {":status", "206"}, - /* 11: */ {":status", "304"}, - /* 12: */ {":status", "400"}, - /* 13: */ {":status", "404"}, - /* 14: */ {":status", "500"}, - /* 15: */ {"accept-charset", ""}, - /* 16: */ {"accept-encoding", "gzip, deflate"}, - /* 17: */ {"accept-language", ""}, - /* 18: */ {"accept-ranges", ""}, - /* 19: */ {"accept", ""}, - /* 20: */ {"access-control-allow-origin", ""}, - /* 21: */ {"age", ""}, - /* 22: */ {"allow", ""}, - /* 23: */ {"authorization", ""}, - /* 24: */ {"cache-control", ""}, - /* 25: */ {"content-disposition", ""}, - /* 26: */ {"content-encoding", ""}, - /* 27: */ {"content-language", ""}, - /* 28: */ {"content-length", ""}, - /* 29: */ {"content-location", ""}, - /* 30: */ {"content-range", ""}, - /* 31: */ {"content-type", ""}, - /* 32: */ {"cookie", ""}, - /* 33: */ {"date", ""}, - /* 34: */ {"etag", ""}, - /* 35: */ {"expect", ""}, - /* 36: */ {"expires", ""}, - /* 37: */ {"from", ""}, - /* 38: */ {"host", ""}, - /* 39: */ {"if-match", ""}, - /* 40: */ {"if-modified-since", ""}, - /* 41: */ {"if-none-match", ""}, - /* 42: */ {"if-range", ""}, - /* 43: */ {"if-unmodified-since", ""}, - /* 44: */ {"last-modified", ""}, - /* 45: */ {"link", ""}, - /* 46: */ {"location", ""}, - /* 47: */ {"max-forwards", ""}, - /* 48: */ {"proxy-authenticate", ""}, - /* 49: */ {"proxy-authorization", ""}, - /* 50: */ {"range", ""}, - /* 51: */ {"referer", ""}, - /* 52: */ {"refresh", ""}, - /* 53: */ {"retry-after", ""}, - /* 54: */ {"server", ""}, - /* 55: */ {"set-cookie", ""}, - /* 56: */ {"strict-transport-security", ""}, - /* 57: */ {"transfer-encoding", ""}, - /* 58: */ {"user-agent", ""}, - /* 59: */ {"vary", ""}, - /* 60: */ {"via", ""}, - /* 61: */ {"www-authenticate", ""}, + /* 0: */ {NULL, NULL}, + /* 1: */ {":authority", ""}, + /* 2: */ {":method", "GET"}, + /* 3: */ {":method", "POST"}, + /* 4: */ {":path", "/"}, + /* 5: */ {":path", "/index.html"}, + /* 6: */ {":scheme", "http"}, + /* 7: */ {":scheme", "https"}, + /* 8: */ {":status", "200"}, + /* 9: */ {":status", "204"}, + /* 10: */ {":status", "206"}, + /* 11: */ {":status", "304"}, + /* 12: */ {":status", "400"}, + /* 13: */ {":status", "404"}, + /* 14: */ {":status", "500"}, + /* 15: */ {"accept-charset", ""}, + /* 16: */ {"accept-encoding", "gzip, deflate"}, + /* 17: */ {"accept-language", ""}, + /* 18: */ {"accept-ranges", ""}, + /* 19: */ {"accept", ""}, + /* 20: */ {"access-control-allow-origin", ""}, + /* 21: */ {"age", ""}, + /* 22: */ {"allow", ""}, + /* 23: */ {"authorization", ""}, + /* 24: */ {"cache-control", ""}, + /* 25: */ {"content-disposition", ""}, + /* 26: */ {"content-encoding", ""}, + /* 27: */ {"content-language", ""}, + /* 28: */ {"content-length", ""}, + /* 29: */ {"content-location", ""}, + /* 30: */ {"content-range", ""}, + /* 31: */ {"content-type", ""}, + /* 32: */ {"cookie", ""}, + /* 33: */ {"date", ""}, + /* 34: */ {"etag", ""}, + /* 35: */ {"expect", ""}, + /* 36: */ {"expires", ""}, + /* 37: */ {"from", ""}, + /* 38: */ {"host", ""}, + /* 39: */ {"if-match", ""}, + /* 40: */ {"if-modified-since", ""}, + /* 41: */ {"if-none-match", ""}, + /* 42: */ {"if-range", ""}, + /* 43: */ {"if-unmodified-since", ""}, + /* 44: */ {"last-modified", ""}, + /* 45: */ {"link", ""}, + /* 46: */ {"location", ""}, + /* 47: */ {"max-forwards", ""}, + /* 48: */ {"proxy-authenticate", ""}, + /* 49: */ {"proxy-authorization", ""}, + /* 50: */ {"range", ""}, + /* 51: */ {"referer", ""}, + /* 52: */ {"refresh", ""}, + /* 53: */ {"retry-after", ""}, + /* 54: */ {"server", ""}, + /* 55: */ {"set-cookie", ""}, + /* 56: */ {"strict-transport-security", ""}, + /* 57: */ {"transfer-encoding", ""}, + /* 58: */ {"user-agent", ""}, + /* 59: */ {"vary", ""}, + /* 60: */ {"via", ""}, + /* 61: */ {"www-authenticate", ""}, }; void grpc_chttp2_hptbl_init(grpc_chttp2_hptbl *tbl, grpc_mdctx *mdctx) { diff --git a/src/core/transport/chttp2/varint.h b/src/core/transport/chttp2/varint.h index 940df00a99..55f92af3d6 100644 --- a/src/core/transport/chttp2/varint.h +++ b/src/core/transport/chttp2/varint.h @@ -58,16 +58,16 @@ void grpc_chttp2_hpack_write_varint_tail(gpr_uint32 tail_value, : grpc_chttp2_hpack_varint_length( \ (n)-GRPC_CHTTP2_MAX_IN_PREFIX(prefix_bits))) -#define GRPC_CHTTP2_WRITE_VARINT(n, prefix_bits, prefix_or, target, length) \ - do { \ - gpr_uint8* tgt = target; \ - if ((length) == 1) { \ - (tgt)[0] = (prefix_or) | (n); \ - } else { \ - (tgt)[0] = (prefix_or) | GRPC_CHTTP2_MAX_IN_PREFIX(prefix_bits); \ - grpc_chttp2_hpack_write_varint_tail( \ - (n)-GRPC_CHTTP2_MAX_IN_PREFIX(prefix_bits), (tgt) + 1, (length)-1); \ - } \ +#define GRPC_CHTTP2_WRITE_VARINT(n, prefix_bits, prefix_or, target, length) \ + do { \ + gpr_uint8* tgt = target; \ + if ((length) == 1) { \ + (tgt)[0] = (prefix_or) | (n); \ + } else { \ + (tgt)[0] = (prefix_or) | GRPC_CHTTP2_MAX_IN_PREFIX(prefix_bits); \ + grpc_chttp2_hpack_write_varint_tail( \ + (n)-GRPC_CHTTP2_MAX_IN_PREFIX(prefix_bits), (tgt)+1, (length)-1); \ + } \ } while (0) #endif /* __GRPC_INTERNAL_TRANSPORT_CHTTP2_VARINT_H__ */ diff --git a/src/core/transport/chttp2_transport.c b/src/core/transport/chttp2_transport.c index 1b90d4715b..6078e1b65b 100644 --- a/src/core/transport/chttp2_transport.c +++ b/src/core/transport/chttp2_transport.c @@ -525,7 +525,7 @@ static int init_stream(grpc_transport *gt, grpc_stream *gs, lock(t); s->id = 0; } else { - s->id = (gpr_uint32)(gpr_uintptr)server_data; + s->id = (gpr_uint32)(gpr_uintptr) server_data; t->incoming_stream = s; grpc_chttp2_stream_map_add(&t->stream_map, s->id, s); } @@ -1238,7 +1238,7 @@ static int init_header_frame_parser(transport *t, int is_continuation) { t->incoming_stream = NULL; /* if stream is accepted, we set incoming_stream in init_stream */ t->cb->accept_stream(t->cb_user_data, &t->base, - (void *)(gpr_uintptr)t->incoming_stream_id); + (void *)(gpr_uintptr) t->incoming_stream_id); s = t->incoming_stream; if (!s) { gpr_log(GPR_ERROR, "stream not accepted"); @@ -1503,8 +1503,8 @@ static int process_read(transport *t, gpr_slice slice) { "Connect string mismatch: expected '%c' (%d) got '%c' (%d) " "at byte %d", CLIENT_CONNECT_STRING[t->deframe_state], - (int)(gpr_uint8)CLIENT_CONNECT_STRING[t->deframe_state], *cur, - (int)*cur, t->deframe_state); + (int)(gpr_uint8) CLIENT_CONNECT_STRING[t->deframe_state], + *cur, (int)*cur, t->deframe_state); return 0; } ++cur; @@ -1737,9 +1737,9 @@ static void add_to_pollset(grpc_transport *gt, grpc_pollset *pollset) { */ static const grpc_transport_vtable vtable = { - sizeof(stream), init_stream, send_batch, set_allow_window_updates, - add_to_pollset, destroy_stream, abort_stream, goaway, close_transport, - send_ping, destroy_transport}; + sizeof(stream), init_stream, send_batch, set_allow_window_updates, + add_to_pollset, destroy_stream, abort_stream, goaway, + close_transport, send_ping, destroy_transport}; void grpc_create_chttp2_transport(grpc_transport_setup_callback setup, void *arg, diff --git a/src/core/tsi/fake_transport_security.c b/src/core/tsi/fake_transport_security.c index 446329215f..756b2173ec 100644 --- a/src/core/tsi/fake_transport_security.c +++ b/src/core/tsi/fake_transport_security.c @@ -120,7 +120,7 @@ static void store32_little_endian(gpr_uint32 value, unsigned char* buf) { buf[3] = (unsigned char)(value >> 24) & 0xFF; buf[2] = (unsigned char)(value >> 16) & 0xFF; buf[1] = (unsigned char)(value >> 8) & 0xFF; - buf[0] = (unsigned char)(value)&0xFF; + buf[0] = (unsigned char)(value) & 0xFF; } static void tsi_fake_frame_reset(tsi_fake_frame* frame, int needs_draining) { @@ -230,10 +230,11 @@ static void tsi_fake_frame_destruct(tsi_fake_frame* frame) { /* --- tsi_frame_protector methods implementation. ---*/ -static tsi_result fake_protector_protect( - tsi_frame_protector* self, const unsigned char* unprotected_bytes, - size_t* unprotected_bytes_size, unsigned char* protected_output_frames, - size_t* protected_output_frames_size) { +static tsi_result fake_protector_protect(tsi_frame_protector* self, + const unsigned char* unprotected_bytes, + size_t* unprotected_bytes_size, + unsigned char* protected_output_frames, + size_t* protected_output_frames_size) { tsi_result result = TSI_OK; tsi_fake_frame_protector* impl = (tsi_fake_frame_protector*)self; unsigned char frame_header[TSI_FAKE_FRAME_HEADER_SIZE]; @@ -480,8 +481,10 @@ static void fake_handshaker_destroy(tsi_handshaker* self) { static const tsi_handshaker_vtable handshaker_vtable = { fake_handshaker_get_bytes_to_send_to_peer, - fake_handshaker_process_bytes_from_peer, fake_handshaker_get_result, - fake_handshaker_extract_peer, fake_handshaker_create_frame_protector, + fake_handshaker_process_bytes_from_peer, + fake_handshaker_get_result, + fake_handshaker_extract_peer, + fake_handshaker_create_frame_protector, fake_handshaker_destroy, }; diff --git a/src/core/tsi/ssl_transport_security.c b/src/core/tsi/ssl_transport_security.c index 02af080a31..1159254a8c 100644 --- a/src/core/tsi/ssl_transport_security.c +++ b/src/core/tsi/ssl_transport_security.c @@ -573,10 +573,11 @@ static tsi_result build_alpn_protocol_name_list( /* --- tsi_frame_protector methods implementation. ---*/ -static tsi_result ssl_protector_protect( - tsi_frame_protector* self, const unsigned char* unprotected_bytes, - size_t* unprotected_bytes_size, unsigned char* protected_output_frames, - size_t* protected_output_frames_size) { +static tsi_result ssl_protector_protect(tsi_frame_protector* self, + const unsigned char* unprotected_bytes, + size_t* unprotected_bytes_size, + unsigned char* protected_output_frames, + size_t* protected_output_frames_size) { tsi_ssl_frame_protector* impl = (tsi_ssl_frame_protector*)self; int read_from_ssl; size_t available; @@ -707,8 +708,9 @@ static const tsi_frame_protector_vtable frame_protector_vtable = { /* --- tsi_handshaker methods implementation. ---*/ -static tsi_result ssl_handshaker_get_bytes_to_send_to_peer( - tsi_handshaker* self, unsigned char* bytes, size_t* bytes_size) { +static tsi_result ssl_handshaker_get_bytes_to_send_to_peer(tsi_handshaker* self, + unsigned char* bytes, + size_t* bytes_size) { tsi_ssl_handshaker* impl = (tsi_ssl_handshaker*)self; int bytes_read_from_ssl = 0; if (bytes == NULL || bytes_size == NULL || *bytes_size == 0 || @@ -871,8 +873,10 @@ static void ssl_handshaker_destroy(tsi_handshaker* self) { static const tsi_handshaker_vtable handshaker_vtable = { ssl_handshaker_get_bytes_to_send_to_peer, - ssl_handshaker_process_bytes_from_peer, ssl_handshaker_get_result, - ssl_handshaker_extract_peer, ssl_handshaker_create_frame_protector, + ssl_handshaker_process_bytes_from_peer, + ssl_handshaker_get_result, + ssl_handshaker_extract_peer, + ssl_handshaker_create_frame_protector, ssl_handshaker_destroy, }; @@ -1157,8 +1161,7 @@ tsi_result tsi_create_ssl_client_handshaker_factory( tsi_result tsi_create_ssl_server_handshaker_factory( const unsigned char** pem_private_keys, - const size_t* pem_private_keys_sizes, - const unsigned char** pem_cert_chains, + const size_t* pem_private_keys_sizes, const unsigned char** pem_cert_chains, const size_t* pem_cert_chains_sizes, size_t key_cert_pair_count, const unsigned char* pem_client_root_certs, size_t pem_client_root_certs_size, const char* cipher_list, diff --git a/src/core/tsi/ssl_transport_security.h b/src/core/tsi/ssl_transport_security.h index 9c839b9d3a..3a33deacac 100644 --- a/src/core/tsi/ssl_transport_security.h +++ b/src/core/tsi/ssl_transport_security.h @@ -132,8 +132,7 @@ tsi_result tsi_create_ssl_client_handshaker_factory( where a parameter is invalid. */ tsi_result tsi_create_ssl_server_handshaker_factory( const unsigned char** pem_private_keys, - const size_t* pem_private_keys_sizes, - const unsigned char** pem_cert_chains, + const size_t* pem_private_keys_sizes, const unsigned char** pem_cert_chains, const size_t* pem_cert_chains_sizes, size_t key_cert_pair_count, const unsigned char* pem_client_root_certs, size_t pem_client_root_certs_size, const char* cipher_suites, diff --git a/src/cpp/client/channel.cc b/src/cpp/client/channel.cc index ddda8c22d6..a8919a10d9 100644 --- a/src/cpp/client/channel.cc +++ b/src/cpp/client/channel.cc @@ -53,7 +53,7 @@ namespace grpc { -Channel::Channel(const grpc::string& target, const ChannelArguments& args) +Channel::Channel(const grpc::string &target, const ChannelArguments &args) : target_(target) { grpc_channel_args channel_args; args.SetChannelArgs(&channel_args); @@ -61,15 +61,15 @@ Channel::Channel(const grpc::string& target, const ChannelArguments& args) target_.c_str(), channel_args.num_args > 0 ? &channel_args : nullptr); } -Channel::Channel(const grpc::string& target, - const std::unique_ptr& creds, - const ChannelArguments& args) +Channel::Channel(const grpc::string &target, + const std::unique_ptr &creds, + const ChannelArguments &args) : target_(args.GetSslTargetNameOverride().empty() ? target : args.GetSslTargetNameOverride()) { grpc_channel_args channel_args; args.SetChannelArgs(&channel_args); - grpc_credentials* c_creds = creds ? creds->GetRawCreds() : nullptr; + grpc_credentials *c_creds = creds ? creds->GetRawCreds() : nullptr; c_channel_ = grpc_secure_channel_create( c_creds, target.c_str(), channel_args.num_args > 0 ? &channel_args : nullptr); @@ -79,9 +79,9 @@ Channel::~Channel() { grpc_channel_destroy(c_channel_); } namespace { // Pluck the finished event and set to status when it is not nullptr. -void GetFinalStatus(grpc_completion_queue* cq, void* finished_tag, - Status* status) { - grpc_event* ev = +void GetFinalStatus(grpc_completion_queue *cq, void *finished_tag, + Status *status) { + grpc_event *ev = grpc_completion_queue_pluck(cq, finished_tag, gpr_inf_future); if (status) { StatusCode error_code = static_cast(ev->data.finished.status); @@ -94,23 +94,23 @@ void GetFinalStatus(grpc_completion_queue* cq, void* finished_tag, } // namespace // TODO(yangg) more error handling -Status Channel::StartBlockingRpc(const RpcMethod& method, - ClientContext* context, - const google::protobuf::Message& request, - google::protobuf::Message* result) { +Status Channel::StartBlockingRpc(const RpcMethod &method, + ClientContext *context, + const google::protobuf::Message &request, + google::protobuf::Message *result) { Status status; - grpc_call* call = grpc_channel_create_call( + grpc_call *call = grpc_channel_create_call( c_channel_, method.name(), target_.c_str(), context->RawDeadline()); context->set_call(call); - grpc_event* ev; - void* finished_tag = reinterpret_cast(call); - void* invoke_tag = reinterpret_cast(call) + 1; - void* metadata_read_tag = reinterpret_cast(call) + 2; - void* write_tag = reinterpret_cast(call) + 3; - void* halfclose_tag = reinterpret_cast(call) + 4; - void* read_tag = reinterpret_cast(call) + 5; + grpc_event *ev; + void *finished_tag = reinterpret_cast(call); + void *invoke_tag = reinterpret_cast(call) + 1; + void *metadata_read_tag = reinterpret_cast(call) + 2; + void *write_tag = reinterpret_cast(call) + 3; + void *halfclose_tag = reinterpret_cast(call) + 4; + void *read_tag = reinterpret_cast(call) + 5; - grpc_completion_queue* cq = grpc_completion_queue_create(); + grpc_completion_queue *cq = grpc_completion_queue_create(); context->set_cq(cq); // add_metadata from context // @@ -126,7 +126,7 @@ Status Channel::StartBlockingRpc(const RpcMethod& method, return status; } // write request - grpc_byte_buffer* write_buffer = nullptr; + grpc_byte_buffer *write_buffer = nullptr; success = SerializeProto(request, &write_buffer); if (!success) { grpc_call_cancel(call); @@ -172,14 +172,14 @@ Status Channel::StartBlockingRpc(const RpcMethod& method, return status; } -StreamContextInterface* Channel::CreateStream( - const RpcMethod& method, ClientContext* context, - const google::protobuf::Message* request, - google::protobuf::Message* result) { - grpc_call* call = grpc_channel_create_call( +StreamContextInterface *Channel::CreateStream( + const RpcMethod &method, ClientContext *context, + const google::protobuf::Message *request, + google::protobuf::Message *result) { + grpc_call *call = grpc_channel_create_call( c_channel_, method.name(), target_.c_str(), context->RawDeadline()); context->set_call(call); - grpc_completion_queue* cq = grpc_completion_queue_create(); + grpc_completion_queue *cq = grpc_completion_queue_create(); context->set_cq(cq); return new StreamContext(method, context, request, result); } diff --git a/src/cpp/client/channel.h b/src/cpp/client/channel.h index 8de1180ac2..67d18bf4c8 100644 --- a/src/cpp/client/channel.h +++ b/src/cpp/client/channel.h @@ -48,24 +48,24 @@ class StreamContextInterface; class Channel : public ChannelInterface { public: - Channel(const grpc::string& target, const ChannelArguments& args); - Channel(const grpc::string& target, const std::unique_ptr& creds, - const ChannelArguments& args); + Channel(const grpc::string &target, const ChannelArguments &args); + Channel(const grpc::string &target, const std::unique_ptr &creds, + const ChannelArguments &args); ~Channel() override; - Status StartBlockingRpc(const RpcMethod& method, ClientContext* context, - const google::protobuf::Message& request, - google::protobuf::Message* result) override; + Status StartBlockingRpc(const RpcMethod &method, ClientContext *context, + const google::protobuf::Message &request, + google::protobuf::Message *result) override; - StreamContextInterface* CreateStream( - const RpcMethod& method, ClientContext* context, - const google::protobuf::Message* request, - google::protobuf::Message* result) override; + StreamContextInterface *CreateStream( + const RpcMethod &method, ClientContext *context, + const google::protobuf::Message *request, + google::protobuf::Message *result) override; private: const grpc::string target_; - grpc_channel* c_channel_; // owned + grpc_channel *c_channel_; // owned }; } // namespace grpc diff --git a/src/cpp/client/channel_arguments.cc b/src/cpp/client/channel_arguments.cc index eba9c1e76a..70713f015f 100644 --- a/src/cpp/client/channel_arguments.cc +++ b/src/cpp/client/channel_arguments.cc @@ -37,7 +37,7 @@ namespace grpc { -void ChannelArguments::SetSslTargetNameOverride(const grpc::string& name) { +void ChannelArguments::SetSslTargetNameOverride(const grpc::string &name) { SetString(GRPC_SSL_TARGET_NAME_OVERRIDE_ARG, name); } @@ -50,32 +50,32 @@ grpc::string ChannelArguments::GetSslTargetNameOverride() const { return ""; } -void ChannelArguments::SetInt(const grpc::string& key, int value) { +void ChannelArguments::SetInt(const grpc::string &key, int value) { grpc_arg arg; arg.type = GRPC_ARG_INTEGER; strings_.push_back(key); - arg.key = const_cast(strings_.back().c_str()); + arg.key = const_cast(strings_.back().c_str()); arg.value.integer = value; args_.push_back(arg); } -void ChannelArguments::SetString(const grpc::string& key, - const grpc::string& value) { +void ChannelArguments::SetString(const grpc::string &key, + const grpc::string &value) { grpc_arg arg; arg.type = GRPC_ARG_STRING; strings_.push_back(key); - arg.key = const_cast(strings_.back().c_str()); + arg.key = const_cast(strings_.back().c_str()); strings_.push_back(value); - arg.value.string = const_cast(strings_.back().c_str()); + arg.value.string = const_cast(strings_.back().c_str()); args_.push_back(arg); } -void ChannelArguments::SetChannelArgs(grpc_channel_args* channel_args) const { +void ChannelArguments::SetChannelArgs(grpc_channel_args *channel_args) const { channel_args->num_args = args_.size(); if (channel_args->num_args > 0) { - channel_args->args = const_cast(&args_[0]); + channel_args->args = const_cast(&args_[0]); } } diff --git a/src/cpp/client/client_context.cc b/src/cpp/client/client_context.cc index 505b7d89b4..7bda2d07c3 100644 --- a/src/cpp/client/client_context.cc +++ b/src/cpp/client/client_context.cc @@ -50,7 +50,7 @@ ClientContext::~ClientContext() { if (cq_) { grpc_completion_queue_shutdown(cq_); // Drain cq_. - grpc_event* ev; + grpc_event *ev; grpc_completion_type t; do { ev = grpc_completion_queue_next(cq_, gpr_inf_future); @@ -62,7 +62,7 @@ ClientContext::~ClientContext() { } void ClientContext::set_absolute_deadline( - const system_clock::time_point& deadline) { + const system_clock::time_point &deadline) { Timepoint2Timespec(deadline, &absolute_deadline_); } @@ -70,8 +70,8 @@ system_clock::time_point ClientContext::absolute_deadline() { return Timespec2Timepoint(absolute_deadline_); } -void ClientContext::AddMetadata(const grpc::string& meta_key, - const grpc::string& meta_value) { +void ClientContext::AddMetadata(const grpc::string &meta_key, + const grpc::string &meta_value) { return; } diff --git a/src/cpp/client/create_channel.cc b/src/cpp/client/create_channel.cc index 1a88d7f2f1..9cc5cff214 100644 --- a/src/cpp/client/create_channel.cc +++ b/src/cpp/client/create_channel.cc @@ -40,14 +40,14 @@ namespace grpc { class ChannelArguments; -std::shared_ptr CreateChannel(const grpc::string& target, - const ChannelArguments& args) { +std::shared_ptr CreateChannel(const grpc::string &target, + const ChannelArguments &args) { return std::shared_ptr(new Channel(target, args)); } std::shared_ptr CreateChannel( - const grpc::string& target, const std::unique_ptr& creds, - const ChannelArguments& args) { + const grpc::string &target, const std::unique_ptr &creds, + const ChannelArguments &args) { return std::shared_ptr(new Channel(target, creds, args)); } } // namespace grpc diff --git a/src/cpp/client/credentials.cc b/src/cpp/client/credentials.cc index d81cf9f4d0..0955fa28ae 100644 --- a/src/cpp/client/credentials.cc +++ b/src/cpp/client/credentials.cc @@ -40,37 +40,37 @@ namespace grpc { -Credentials::Credentials(grpc_credentials* c_creds) : creds_(c_creds) {} +Credentials::Credentials(grpc_credentials *c_creds) : creds_(c_creds) {} Credentials::~Credentials() { grpc_credentials_release(creds_); } -grpc_credentials* Credentials::GetRawCreds() { return creds_; } +grpc_credentials *Credentials::GetRawCreds() { return creds_; } std::unique_ptr CredentialsFactory::DefaultCredentials() { - grpc_credentials* c_creds = grpc_default_credentials_create(); + grpc_credentials *c_creds = grpc_default_credentials_create(); std::unique_ptr cpp_creds(new Credentials(c_creds)); return cpp_creds; } // Builds SSL Credentials given SSL specific options std::unique_ptr CredentialsFactory::SslCredentials( - const SslCredentialsOptions& options) { - const unsigned char* pem_root_certs = + const SslCredentialsOptions &options) { + const unsigned char *pem_root_certs = options.pem_root_certs.empty() ? nullptr - : reinterpret_cast( + : reinterpret_cast( options.pem_root_certs.c_str()); if (pem_root_certs == nullptr) { return std::unique_ptr(); } - const unsigned char* pem_private_key = + const unsigned char *pem_private_key = options.pem_private_key.empty() ? nullptr - : reinterpret_cast( + : reinterpret_cast( options.pem_private_key.c_str()); - const unsigned char* pem_cert_chain = + const unsigned char *pem_cert_chain = options.pem_cert_chain.empty() ? nullptr - : reinterpret_cast( + : reinterpret_cast( options.pem_cert_chain.c_str()); - grpc_credentials* c_creds = grpc_ssl_credentials_create( + grpc_credentials *c_creds = grpc_ssl_credentials_create( pem_root_certs, options.pem_root_certs.size(), pem_private_key, options.pem_private_key.size(), pem_cert_chain, options.pem_cert_chain.size()); @@ -81,7 +81,7 @@ std::unique_ptr CredentialsFactory::SslCredentials( // Builds credentials for use when running in GCE std::unique_ptr CredentialsFactory::ComputeEngineCredentials() { - grpc_credentials* c_creds = grpc_compute_engine_credentials_create(); + grpc_credentials *c_creds = grpc_compute_engine_credentials_create(); std::unique_ptr cpp_creds( c_creds == nullptr ? nullptr : new Credentials(c_creds)); return cpp_creds; @@ -89,11 +89,11 @@ std::unique_ptr CredentialsFactory::ComputeEngineCredentials() { // Builds service account credentials. std::unique_ptr CredentialsFactory::ServiceAccountCredentials( - const grpc::string& json_key, const grpc::string& scope, + const grpc::string &json_key, const grpc::string &scope, std::chrono::seconds token_lifetime) { gpr_timespec lifetime = gpr_time_from_seconds( token_lifetime.count() > 0 ? token_lifetime.count() : 0); - grpc_credentials* c_creds = grpc_service_account_credentials_create( + grpc_credentials *c_creds = grpc_service_account_credentials_create( json_key.c_str(), scope.c_str(), lifetime); std::unique_ptr cpp_creds( c_creds == nullptr ? nullptr : new Credentials(c_creds)); @@ -102,9 +102,9 @@ std::unique_ptr CredentialsFactory::ServiceAccountCredentials( // Builds IAM credentials. std::unique_ptr CredentialsFactory::IAMCredentials( - const grpc::string& authorization_token, - const grpc::string& authority_selector) { - grpc_credentials* c_creds = grpc_iam_credentials_create( + const grpc::string &authorization_token, + const grpc::string &authority_selector) { + grpc_credentials *c_creds = grpc_iam_credentials_create( authorization_token.c_str(), authority_selector.c_str()); std::unique_ptr cpp_creds( c_creds == nullptr ? nullptr : new Credentials(c_creds)); @@ -113,13 +113,13 @@ std::unique_ptr CredentialsFactory::IAMCredentials( // Combines two credentials objects into a composite credentials. std::unique_ptr CredentialsFactory::ComposeCredentials( - const std::unique_ptr& creds1, - const std::unique_ptr& creds2) { + const std::unique_ptr &creds1, + const std::unique_ptr &creds2) { // Note that we are not saving unique_ptrs to the two credentials // passed in here. This is OK because the underlying C objects (i.e., // creds1 and creds2) into grpc_composite_credentials_create will see their // refcounts incremented. - grpc_credentials* c_creds = grpc_composite_credentials_create( + grpc_credentials *c_creds = grpc_composite_credentials_create( creds1->GetRawCreds(), creds2->GetRawCreds()); std::unique_ptr cpp_creds( c_creds == nullptr ? nullptr : new Credentials(c_creds)); diff --git a/src/cpp/proto/proto_utils.cc b/src/cpp/proto/proto_utils.cc index 3b94dc3c07..85f859b9eb 100644 --- a/src/cpp/proto/proto_utils.cc +++ b/src/cpp/proto/proto_utils.cc @@ -40,8 +40,8 @@ namespace grpc { -bool SerializeProto(const google::protobuf::Message& msg, - grpc_byte_buffer** bp) { +bool SerializeProto(const google::protobuf::Message &msg, + grpc_byte_buffer **bp) { grpc::string msg_str; bool success = msg.SerializeToString(&msg_str); if (success) { @@ -53,13 +53,13 @@ bool SerializeProto(const google::protobuf::Message& msg, return success; } -bool DeserializeProto(grpc_byte_buffer* buffer, - google::protobuf::Message* msg) { +bool DeserializeProto(grpc_byte_buffer *buffer, + google::protobuf::Message *msg) { grpc::string msg_string; - grpc_byte_buffer_reader* reader = grpc_byte_buffer_reader_create(buffer); + grpc_byte_buffer_reader *reader = grpc_byte_buffer_reader_create(buffer); gpr_slice slice; while (grpc_byte_buffer_reader_next(reader, &slice)) { - const char* data = reinterpret_cast( + const char *data = reinterpret_cast( slice.refcount ? slice.data.refcounted.bytes : slice.data.inlined.bytes); msg_string.append(data, slice.refcount ? slice.data.refcounted.length diff --git a/src/cpp/proto/proto_utils.h b/src/cpp/proto/proto_utils.h index ea472f9c51..a611a227fa 100644 --- a/src/cpp/proto/proto_utils.h +++ b/src/cpp/proto/proto_utils.h @@ -46,11 +46,11 @@ namespace grpc { // Serialize the msg into a buffer created inside the function. The caller // should destroy the returned buffer when done with it. If serialization fails, // false is returned and buffer is left unchanged. -bool SerializeProto(const google::protobuf::Message& msg, - grpc_byte_buffer** buffer); +bool SerializeProto(const google::protobuf::Message &msg, + grpc_byte_buffer **buffer); // The caller keeps ownership of buffer and msg. -bool DeserializeProto(grpc_byte_buffer* buffer, google::protobuf::Message* msg); +bool DeserializeProto(grpc_byte_buffer *buffer, google::protobuf::Message *msg); } // namespace grpc diff --git a/src/cpp/server/async_server.cc b/src/cpp/server/async_server.cc index aae2c82050..d576201b11 100644 --- a/src/cpp/server/async_server.cc +++ b/src/cpp/server/async_server.cc @@ -39,7 +39,7 @@ namespace grpc { -AsyncServer::AsyncServer(CompletionQueue* cc) +AsyncServer::AsyncServer(CompletionQueue *cc) : started_(false), shutdown_(false) { server_ = grpc_server_create(cc->cq(), nullptr); } @@ -53,7 +53,7 @@ AsyncServer::~AsyncServer() { grpc_server_destroy(server_); } -void AsyncServer::AddPort(const grpc::string& addr) { +void AsyncServer::AddPort(const grpc::string &addr) { GPR_ASSERT(!started_); int success = grpc_server_add_http2_port(server_, addr.c_str()); GPR_ASSERT(success); diff --git a/src/cpp/server/async_server_context.cc b/src/cpp/server/async_server_context.cc index 298936dec9..92958111c0 100644 --- a/src/cpp/server/async_server_context.cc +++ b/src/cpp/server/async_server_context.cc @@ -42,7 +42,7 @@ namespace grpc { AsyncServerContext::AsyncServerContext( - grpc_call* call, const grpc::string& method, const grpc::string& host, + grpc_call *call, const grpc::string &method, const grpc::string &host, system_clock::time_point absolute_deadline) : method_(method), host_(host), @@ -52,21 +52,21 @@ AsyncServerContext::AsyncServerContext( AsyncServerContext::~AsyncServerContext() { grpc_call_destroy(call_); } -void AsyncServerContext::Accept(grpc_completion_queue* cq) { +void AsyncServerContext::Accept(grpc_completion_queue *cq) { GPR_ASSERT(grpc_call_server_accept(call_, cq, this) == GRPC_CALL_OK); GPR_ASSERT(grpc_call_server_end_initial_metadata(call_, 0) == GRPC_CALL_OK); } -bool AsyncServerContext::StartRead(google::protobuf::Message* request) { +bool AsyncServerContext::StartRead(google::protobuf::Message *request) { GPR_ASSERT(request); request_ = request; grpc_call_error err = grpc_call_start_read(call_, this); return err == GRPC_CALL_OK; } -bool AsyncServerContext::StartWrite(const google::protobuf::Message& response, +bool AsyncServerContext::StartWrite(const google::protobuf::Message &response, int flags) { - grpc_byte_buffer* buffer = nullptr; + grpc_byte_buffer *buffer = nullptr; if (!SerializeProto(response, &buffer)) { return false; } @@ -75,16 +75,16 @@ bool AsyncServerContext::StartWrite(const google::protobuf::Message& response, return err == GRPC_CALL_OK; } -bool AsyncServerContext::StartWriteStatus(const Status& status) { +bool AsyncServerContext::StartWriteStatus(const Status &status) { grpc_call_error err = grpc_call_start_write_status( call_, static_cast(status.code()), status.details().empty() ? nullptr - : const_cast(status.details().c_str()), + : const_cast(status.details().c_str()), this); return err == GRPC_CALL_OK; } -bool AsyncServerContext::ParseRead(grpc_byte_buffer* read_buffer) { +bool AsyncServerContext::ParseRead(grpc_byte_buffer *read_buffer) { GPR_ASSERT(request_); bool success = DeserializeProto(read_buffer, request_); request_ = nullptr; diff --git a/src/cpp/server/completion_queue.cc b/src/cpp/server/completion_queue.cc index 56d165c9a6..102a81bf0e 100644 --- a/src/cpp/server/completion_queue.cc +++ b/src/cpp/server/completion_queue.cc @@ -48,8 +48,8 @@ CompletionQueue::~CompletionQueue() { grpc_completion_queue_destroy(cq_); } void CompletionQueue::Shutdown() { grpc_completion_queue_shutdown(cq_); } -CompletionQueue::CompletionType CompletionQueue::Next(void** tag) { - grpc_event* ev; +CompletionQueue::CompletionType CompletionQueue::Next(void **tag) { + grpc_event *ev; CompletionType return_type; bool success; @@ -65,8 +65,8 @@ CompletionQueue::CompletionType CompletionQueue::Next(void** tag) { case GRPC_READ: *tag = ev->tag; if (ev->data.read) { - success = - static_cast(ev->tag)->ParseRead(ev->data.read); + success = static_cast(ev->tag) + ->ParseRead(ev->data.read); return_type = success ? SERVER_READ_OK : SERVER_READ_ERROR; } else { return_type = SERVER_READ_ERROR; diff --git a/src/cpp/server/server.cc b/src/cpp/server/server.cc index d85748eea4..193688e743 100644 --- a/src/cpp/server/server.cc +++ b/src/cpp/server/server.cc @@ -49,7 +49,7 @@ namespace grpc { // TODO(rocking): consider a better default value like num of cores. static const int kNumThreads = 4; -Server::Server(ThreadPoolInterface* thread_pool, ServerCredentials* creds) +Server::Server(ThreadPoolInterface *thread_pool, ServerCredentials *creds) : started_(false), shutdown_(false), num_running_cb_(0), @@ -82,14 +82,14 @@ Server::~Server() { } } -void Server::RegisterService(RpcService* service) { +void Server::RegisterService(RpcService *service) { for (int i = 0; i < service->GetMethodCount(); ++i) { - RpcServiceMethod* method = service->GetMethod(i); + RpcServiceMethod *method = service->GetMethod(i); method_map_.insert(std::make_pair(method->name(), method)); } } -void Server::AddPort(const grpc::string& addr) { +void Server::AddPort(const grpc::string &addr) { GPR_ASSERT(!started_); int success; if (secure_) { @@ -131,7 +131,7 @@ void Server::Shutdown() { // Shutdown the completion queue. cq_.Shutdown(); - void* tag = nullptr; + void *tag = nullptr; CompletionQueue::CompletionType t = cq_.Next(&tag); GPR_ASSERT(t == CompletionQueue::QUEUE_CLOSED); } @@ -147,18 +147,18 @@ void Server::ScheduleCallback() { void Server::RunRpc() { // Wait for one more incoming rpc. - void* tag = nullptr; + void *tag = nullptr; AllowOneRpc(); CompletionQueue::CompletionType t = cq_.Next(&tag); GPR_ASSERT(t == CompletionQueue::SERVER_RPC_NEW); - AsyncServerContext* server_context = static_cast(tag); + AsyncServerContext *server_context = static_cast(tag); // server_context could be nullptr during server shutdown. if (server_context != nullptr) { // Schedule a new callback to handle more rpcs. ScheduleCallback(); - RpcServiceMethod* method = nullptr; + RpcServiceMethod *method = nullptr; auto iter = method_map_.find(server_context->method()); if (iter != method_map_.end()) { method = iter->second; diff --git a/src/cpp/server/server_builder.cc b/src/cpp/server/server_builder.cc index d74d8cb65f..add22cc3d8 100644 --- a/src/cpp/server/server_builder.cc +++ b/src/cpp/server/server_builder.cc @@ -40,30 +40,30 @@ namespace grpc { ServerBuilder::ServerBuilder() : thread_pool_(nullptr) {} -void ServerBuilder::RegisterService(RpcService* service) { +void ServerBuilder::RegisterService(RpcService *service) { services_.push_back(service); } -void ServerBuilder::AddPort(const grpc::string& addr) { +void ServerBuilder::AddPort(const grpc::string &addr) { ports_.push_back(addr); } void ServerBuilder::SetCredentials( - const std::shared_ptr& creds) { + const std::shared_ptr &creds) { GPR_ASSERT(!creds_); creds_ = creds; } -void ServerBuilder::SetThreadPool(ThreadPoolInterface* thread_pool) { +void ServerBuilder::SetThreadPool(ThreadPoolInterface *thread_pool) { thread_pool_ = thread_pool; } std::unique_ptr ServerBuilder::BuildAndStart() { std::unique_ptr server(new Server(thread_pool_, creds_.get())); - for (auto* service : services_) { + for (auto *service : services_) { server->RegisterService(service); } - for (auto& port : ports_) { + for (auto &port : ports_) { server->AddPort(port); } server->Start(); diff --git a/src/cpp/server/server_credentials.cc b/src/cpp/server/server_credentials.cc index 5d899b1cd9..b82a2d821a 100644 --- a/src/cpp/server/server_credentials.cc +++ b/src/cpp/server/server_credentials.cc @@ -37,31 +37,31 @@ namespace grpc { -ServerCredentials::ServerCredentials(grpc_server_credentials* c_creds) +ServerCredentials::ServerCredentials(grpc_server_credentials *c_creds) : creds_(c_creds) {} ServerCredentials::~ServerCredentials() { grpc_server_credentials_release(creds_); } -grpc_server_credentials* ServerCredentials::GetRawCreds() { return creds_; } +grpc_server_credentials *ServerCredentials::GetRawCreds() { return creds_; } std::shared_ptr ServerCredentialsFactory::SslCredentials( - const SslServerCredentialsOptions& options) { - const unsigned char* pem_root_certs = + const SslServerCredentialsOptions &options) { + const unsigned char *pem_root_certs = options.pem_root_certs.empty() ? nullptr - : reinterpret_cast( + : reinterpret_cast( options.pem_root_certs.c_str()); - const unsigned char* pem_private_key = + const unsigned char *pem_private_key = options.pem_private_key.empty() ? nullptr - : reinterpret_cast( + : reinterpret_cast( options.pem_private_key.c_str()); - const unsigned char* pem_cert_chain = + const unsigned char *pem_cert_chain = options.pem_cert_chain.empty() ? nullptr - : reinterpret_cast( + : reinterpret_cast( options.pem_cert_chain.c_str()); - grpc_server_credentials* c_creds = grpc_ssl_server_credentials_create( + grpc_server_credentials *c_creds = grpc_ssl_server_credentials_create( pem_root_certs, options.pem_root_certs.size(), pem_private_key, options.pem_private_key.size(), pem_cert_chain, options.pem_cert_chain.size()); diff --git a/src/cpp/server/server_rpc_handler.cc b/src/cpp/server/server_rpc_handler.cc index 42f8b755b6..061ac1c2f3 100644 --- a/src/cpp/server/server_rpc_handler.cc +++ b/src/cpp/server/server_rpc_handler.cc @@ -41,8 +41,8 @@ namespace grpc { -ServerRpcHandler::ServerRpcHandler(AsyncServerContext* async_server_context, - RpcServiceMethod* method) +ServerRpcHandler::ServerRpcHandler(AsyncServerContext *async_server_context, + RpcServiceMethod *method) : async_server_context_(async_server_context), method_(method) {} void ServerRpcHandler::StartRpc() { @@ -71,7 +71,7 @@ void ServerRpcHandler::StartRpc() { GPR_ASSERT(type == CompletionQueue::SERVER_READ_OK); // Run the application's rpc handler - MethodHandler* handler = method_->handler(); + MethodHandler *handler = method_->handler(); Status status = handler->RunHandler(MethodHandler::HandlerParameter( &user_context, request.get(), response.get())); @@ -97,7 +97,7 @@ void ServerRpcHandler::StartRpc() { cq_.cq(), request.get(), response.get()); // Run the application's rpc handler - MethodHandler* handler = method_->handler(); + MethodHandler *handler = method_->handler(); Status status = handler->RunHandler(MethodHandler::HandlerParameter( &user_context, request.get(), response.get(), &stream_context)); if (status.IsOk() && @@ -110,17 +110,17 @@ void ServerRpcHandler::StartRpc() { } CompletionQueue::CompletionType ServerRpcHandler::WaitForNextEvent() { - void* tag = nullptr; + void *tag = nullptr; CompletionQueue::CompletionType type = cq_.Next(&tag); if (type != CompletionQueue::QUEUE_CLOSED && type != CompletionQueue::RPC_END) { - GPR_ASSERT(static_cast(tag) == + GPR_ASSERT(static_cast(tag) == async_server_context_.get()); } return type; } -void ServerRpcHandler::FinishRpc(const Status& status) { +void ServerRpcHandler::FinishRpc(const Status &status) { async_server_context_->StartWriteStatus(status); CompletionQueue::CompletionType type; diff --git a/src/cpp/server/server_rpc_handler.h b/src/cpp/server/server_rpc_handler.h index 249576d504..a43e07dc5f 100644 --- a/src/cpp/server/server_rpc_handler.h +++ b/src/cpp/server/server_rpc_handler.h @@ -47,17 +47,17 @@ class RpcServiceMethod; class ServerRpcHandler { public: // Takes ownership of async_server_context. - ServerRpcHandler(AsyncServerContext* async_server_context, - RpcServiceMethod* method); + ServerRpcHandler(AsyncServerContext *async_server_context, + RpcServiceMethod *method); void StartRpc(); private: CompletionQueue::CompletionType WaitForNextEvent(); - void FinishRpc(const Status& status); + void FinishRpc(const Status &status); std::unique_ptr async_server_context_; - RpcServiceMethod* method_; + RpcServiceMethod *method_; CompletionQueue cq_; }; diff --git a/src/cpp/server/thread_pool.cc b/src/cpp/server/thread_pool.cc index ce364c4795..a46d4c64d2 100644 --- a/src/cpp/server/thread_pool.cc +++ b/src/cpp/server/thread_pool.cc @@ -63,12 +63,12 @@ ThreadPool::~ThreadPool() { shutdown_ = true; cv_.notify_all(); } - for (auto& t : threads_) { + for (auto &t : threads_) { t.join(); } } -void ThreadPool::ScheduleCallback(const std::function& callback) { +void ThreadPool::ScheduleCallback(const std::function &callback) { std::lock_guard lock(mu_); callbacks_.push(callback); cv_.notify_all(); diff --git a/src/cpp/server/thread_pool.h b/src/cpp/server/thread_pool.h index 6fc71d6695..c53f7a7517 100644 --- a/src/cpp/server/thread_pool.h +++ b/src/cpp/server/thread_pool.h @@ -49,7 +49,7 @@ class ThreadPool : public ThreadPoolInterface { explicit ThreadPool(int num_threads); ~ThreadPool(); - void ScheduleCallback(const std::function& callback) final; + void ScheduleCallback(const std::function &callback) final; private: std::mutex mu_; diff --git a/src/cpp/stream/stream_context.cc b/src/cpp/stream/stream_context.cc index 5ccf8c9682..e64010be64 100644 --- a/src/cpp/stream/stream_context.cc +++ b/src/cpp/stream/stream_context.cc @@ -44,14 +44,14 @@ namespace grpc { // Client only ctor -StreamContext::StreamContext(const RpcMethod& method, ClientContext* context, - const google::protobuf::Message* request, - google::protobuf::Message* result) +StreamContext::StreamContext(const RpcMethod &method, ClientContext *context, + const google::protobuf::Message *request, + google::protobuf::Message *result) : is_client_(true), method_(&method), call_(context->call()), cq_(context->cq()), - request_(const_cast(request)), + request_(const_cast(request)), result_(result), peer_halfclosed_(false), self_halfclosed_(false) { @@ -59,10 +59,10 @@ StreamContext::StreamContext(const RpcMethod& method, ClientContext* context, } // Server only ctor -StreamContext::StreamContext(const RpcMethod& method, grpc_call* call, - grpc_completion_queue* cq, - google::protobuf::Message* request, - google::protobuf::Message* result) +StreamContext::StreamContext(const RpcMethod &method, grpc_call *call, + grpc_completion_queue *cq, + google::protobuf::Message *request, + google::protobuf::Message *result) : is_client_(false), method_(&method), call_(call), @@ -84,7 +84,7 @@ void StreamContext::Start(bool buffered) { client_metadata_read_tag(), finished_tag(), flag); GPR_ASSERT(GRPC_CALL_OK == error); - grpc_event* invoke_ev = + grpc_event *invoke_ev = grpc_completion_queue_pluck(cq(), invoke_tag(), gpr_inf_future); if (invoke_ev->data.invoke_accepted != GRPC_OP_OK) { peer_halfclosed_ = true; @@ -101,11 +101,11 @@ void StreamContext::Start(bool buffered) { } } -bool StreamContext::Read(google::protobuf::Message* msg) { +bool StreamContext::Read(google::protobuf::Message *msg) { // TODO(yangg) check peer_halfclosed_ here for possible early return. grpc_call_error err = grpc_call_start_read(call(), read_tag()); GPR_ASSERT(err == GRPC_CALL_OK); - grpc_event* read_ev = + grpc_event *read_ev = grpc_completion_queue_pluck(cq(), read_tag(), gpr_inf_future); GPR_ASSERT(read_ev->type == GRPC_READ); bool ret = true; @@ -123,13 +123,13 @@ bool StreamContext::Read(google::protobuf::Message* msg) { return ret; } -bool StreamContext::Write(const google::protobuf::Message* msg, bool is_last) { +bool StreamContext::Write(const google::protobuf::Message *msg, bool is_last) { // TODO(yangg) check self_halfclosed_ for possible early return. bool ret = true; - grpc_event* ev = nullptr; + grpc_event *ev = nullptr; if (msg) { - grpc_byte_buffer* out_buf = nullptr; + grpc_byte_buffer *out_buf = nullptr; if (!SerializeProto(*msg, &out_buf)) { grpc_call_cancel_with_status(call(), GRPC_STATUS_INVALID_ARGUMENT, "Failed to serialize outgoing proto"); @@ -163,16 +163,16 @@ bool StreamContext::Write(const google::protobuf::Message* msg, bool is_last) { return ret; } -const Status& StreamContext::Wait() { +const Status &StreamContext::Wait() { // TODO(yangg) properly support metadata - grpc_event* metadata_ev = grpc_completion_queue_pluck( + grpc_event *metadata_ev = grpc_completion_queue_pluck( cq(), client_metadata_read_tag(), gpr_inf_future); grpc_event_finish(metadata_ev); // TODO(yangg) protect states by a mutex, including other places. if (!self_halfclosed_ || !peer_halfclosed_) { Cancel(); } - grpc_event* finish_ev = + grpc_event *finish_ev = grpc_completion_queue_pluck(cq(), finished_tag(), gpr_inf_future); GPR_ASSERT(finish_ev->type == GRPC_FINISHED); final_status_ = Status( diff --git a/src/cpp/stream/stream_context.h b/src/cpp/stream/stream_context.h index 4781f27a77..8697d86e83 100644 --- a/src/cpp/stream/stream_context.h +++ b/src/cpp/stream/stream_context.h @@ -50,43 +50,45 @@ class RpcMethod; class StreamContext final : public StreamContextInterface { public: - StreamContext(const RpcMethod& method, ClientContext* context, - const google::protobuf::Message* request, - google::protobuf::Message* result); - StreamContext(const RpcMethod& method, grpc_call* call, - grpc_completion_queue* cq, google::protobuf::Message* request, - google::protobuf::Message* result); + StreamContext(const RpcMethod &method, ClientContext *context, + const google::protobuf::Message *request, + google::protobuf::Message *result); + StreamContext(const RpcMethod &method, grpc_call *call, + grpc_completion_queue *cq, google::protobuf::Message *request, + google::protobuf::Message *result); ~StreamContext(); // Start the stream, if there is a final write following immediately, set // buffered so that the messages can be sent in batch. void Start(bool buffered) override; - bool Read(google::protobuf::Message* msg) override; - bool Write(const google::protobuf::Message* msg, bool is_last) override; - const Status& Wait() override; + bool Read(google::protobuf::Message *msg) override; + bool Write(const google::protobuf::Message *msg, bool is_last) override; + const Status &Wait() override; void Cancel() override; - google::protobuf::Message* request() override { return request_; } - google::protobuf::Message* response() override { return result_; } + google::protobuf::Message *request() override { return request_; } + google::protobuf::Message *response() override { return result_; } private: // Unique tags for plucking events from the c layer. this pointer is casted // to char* to create single byte step between tags. It implicitly relies on // that StreamContext is large enough to contain all the pointers. - void* finished_tag() { return reinterpret_cast(this); } - void* read_tag() { return reinterpret_cast(this) + 1; } - void* write_tag() { return reinterpret_cast(this) + 2; } - void* halfclose_tag() { return reinterpret_cast(this) + 3; } - void* invoke_tag() { return reinterpret_cast(this) + 4; } - void* client_metadata_read_tag() { return reinterpret_cast(this) + 5; } - grpc_call* call() { return call_; } - grpc_completion_queue* cq() { return cq_; } + void *finished_tag() { return reinterpret_cast(this); } + void *read_tag() { return reinterpret_cast(this) + 1; } + void *write_tag() { return reinterpret_cast(this) + 2; } + void *halfclose_tag() { return reinterpret_cast(this) + 3; } + void *invoke_tag() { return reinterpret_cast(this) + 4; } + void *client_metadata_read_tag() { + return reinterpret_cast(this) + 5; + } + grpc_call *call() { return call_; } + grpc_completion_queue *cq() { return cq_; } bool is_client_; - const RpcMethod* method_; // not owned - grpc_call* call_; // not owned - grpc_completion_queue* cq_; // not owned - google::protobuf::Message* request_; // first request, not owned - google::protobuf::Message* result_; // last response, not owned + const RpcMethod *method_; // not owned + grpc_call *call_; // not owned + grpc_completion_queue *cq_; // not owned + google::protobuf::Message *request_; // first request, not owned + google::protobuf::Message *result_; // last response, not owned bool peer_halfclosed_; bool self_halfclosed_; diff --git a/src/cpp/util/status.cc b/src/cpp/util/status.cc index e7ca41b752..1ca12d0ae9 100644 --- a/src/cpp/util/status.cc +++ b/src/cpp/util/status.cc @@ -35,7 +35,7 @@ namespace grpc { -const Status& Status::OK = Status(); -const Status& Status::Cancelled = Status(StatusCode::CANCELLED); +const Status &Status::OK = Status(); +const Status &Status::Cancelled = Status(StatusCode::CANCELLED); } // namespace grpc diff --git a/src/cpp/util/time.cc b/src/cpp/util/time.cc index e58dde82a3..7ce7a371f5 100644 --- a/src/cpp/util/time.cc +++ b/src/cpp/util/time.cc @@ -43,8 +43,8 @@ using std::chrono::system_clock; namespace grpc { // TODO(yangg) prevent potential overflow. -void Timepoint2Timespec(const system_clock::time_point& from, - gpr_timespec* to) { +void Timepoint2Timespec(const system_clock::time_point &from, + gpr_timespec *to) { system_clock::duration deadline = from.time_since_epoch(); seconds secs = duration_cast(deadline); nanoseconds nsecs = duration_cast(deadline - secs); diff --git a/src/cpp/util/time.h b/src/cpp/util/time.h index 338c4f5119..908395c92b 100644 --- a/src/cpp/util/time.h +++ b/src/cpp/util/time.h @@ -41,8 +41,8 @@ namespace grpc { // from and to should be absolute time. -void Timepoint2Timespec(const std::chrono::system_clock::time_point& from, - gpr_timespec* to); +void Timepoint2Timespec(const std::chrono::system_clock::time_point &from, + gpr_timespec *to); std::chrono::system_clock::time_point Timespec2Timepoint(gpr_timespec t); diff --git a/src/php/ext/grpc/call.c b/src/php/ext/grpc/call.c index c01af34e95..410efbce68 100644 --- a/src/php/ext/grpc/call.c +++ b/src/php/ext/grpc/call.c @@ -423,16 +423,15 @@ PHP_METHOD(Call, start_read) { static zend_function_entry call_methods[] = { PHP_ME(Call, __construct, NULL, ZEND_ACC_PUBLIC | ZEND_ACC_CTOR) - PHP_ME(Call, server_accept, NULL, ZEND_ACC_PUBLIC) - PHP_ME(Call, server_end_initial_metadata, NULL, ZEND_ACC_PUBLIC) - PHP_ME(Call, add_metadata, NULL, ZEND_ACC_PUBLIC) PHP_ME( - Call, cancel, NULL, ZEND_ACC_PUBLIC) - PHP_ME(Call, start_invoke, NULL, ZEND_ACC_PUBLIC) PHP_ME( - Call, start_read, NULL, ZEND_ACC_PUBLIC) - PHP_ME(Call, start_write, NULL, ZEND_ACC_PUBLIC) PHP_ME( - Call, start_write_status, NULL, ZEND_ACC_PUBLIC) - PHP_ME(Call, writes_done, NULL, ZEND_ACC_PUBLIC) - PHP_FE_END}; + PHP_ME(Call, server_accept, NULL, ZEND_ACC_PUBLIC) + PHP_ME(Call, server_end_initial_metadata, NULL, ZEND_ACC_PUBLIC) + PHP_ME(Call, add_metadata, NULL, ZEND_ACC_PUBLIC) + PHP_ME(Call, cancel, NULL, ZEND_ACC_PUBLIC) + PHP_ME(Call, start_invoke, NULL, ZEND_ACC_PUBLIC) + PHP_ME(Call, start_read, NULL, ZEND_ACC_PUBLIC) + PHP_ME(Call, start_write, NULL, ZEND_ACC_PUBLIC) + PHP_ME(Call, start_write_status, NULL, ZEND_ACC_PUBLIC) + PHP_ME(Call, writes_done, NULL, ZEND_ACC_PUBLIC) PHP_FE_END}; void grpc_init_call(TSRMLS_D) { zend_class_entry ce; diff --git a/src/php/ext/grpc/channel.c b/src/php/ext/grpc/channel.c index f0e4153b22..2ab229f5e6 100644 --- a/src/php/ext/grpc/channel.c +++ b/src/php/ext/grpc/channel.c @@ -155,7 +155,7 @@ PHP_METHOD(Channel, close) { static zend_function_entry channel_methods[] = { PHP_ME(Channel, __construct, NULL, ZEND_ACC_PUBLIC | ZEND_ACC_CTOR) - PHP_ME(Channel, close, NULL, ZEND_ACC_PUBLIC) PHP_FE_END}; + PHP_ME(Channel, close, NULL, ZEND_ACC_PUBLIC) PHP_FE_END}; void grpc_init_channel(TSRMLS_D) { zend_class_entry ce; diff --git a/src/php/ext/grpc/completion_queue.c b/src/php/ext/grpc/completion_queue.c index 9785eab8cc..3a93bfcff7 100644 --- a/src/php/ext/grpc/completion_queue.c +++ b/src/php/ext/grpc/completion_queue.c @@ -63,8 +63,8 @@ zend_object_value create_wrapped_grpc_completion_queue( */ PHP_METHOD(CompletionQueue, __construct) { wrapped_grpc_completion_queue *queue = - (wrapped_grpc_completion_queue *)zend_object_store_get_object( - getThis() TSRMLS_CC); + (wrapped_grpc_completion_queue *)zend_object_store_get_object(getThis() + TSRMLS_CC); queue->wrapped = grpc_completion_queue_create(); } @@ -86,8 +86,8 @@ PHP_METHOD(CompletionQueue, next) { return; } wrapped_grpc_completion_queue *completion_queue = - (wrapped_grpc_completion_queue *)zend_object_store_get_object( - getThis() TSRMLS_CC); + (wrapped_grpc_completion_queue *)zend_object_store_get_object(getThis() + TSRMLS_CC); wrapped_grpc_timeval *wrapped_timeout = (wrapped_grpc_timeval *)zend_object_store_get_object(timeout TSRMLS_CC); grpc_event *event = grpc_completion_queue_next(completion_queue->wrapped, @@ -109,8 +109,8 @@ PHP_METHOD(CompletionQueue, pluck) { "pluck needs a long and a Timeval", 1 TSRMLS_CC); } wrapped_grpc_completion_queue *completion_queue = - (wrapped_grpc_completion_queue *)zend_object_store_get_object( - getThis() TSRMLS_CC); + (wrapped_grpc_completion_queue *)zend_object_store_get_object(getThis() + TSRMLS_CC); wrapped_grpc_timeval *wrapped_timeout = (wrapped_grpc_timeval *)zend_object_store_get_object(timeout TSRMLS_CC); grpc_event *event = grpc_completion_queue_pluck( @@ -124,8 +124,8 @@ PHP_METHOD(CompletionQueue, pluck) { static zend_function_entry completion_queue_methods[] = { PHP_ME(CompletionQueue, __construct, NULL, ZEND_ACC_PUBLIC | ZEND_ACC_CTOR) - PHP_ME(CompletionQueue, next, NULL, ZEND_ACC_PUBLIC) - PHP_ME(CompletionQueue, pluck, NULL, ZEND_ACC_PUBLIC) PHP_FE_END}; + PHP_ME(CompletionQueue, next, NULL, ZEND_ACC_PUBLIC) + PHP_ME(CompletionQueue, pluck, NULL, ZEND_ACC_PUBLIC) PHP_FE_END}; void grpc_init_completion_queue(TSRMLS_D) { zend_class_entry ce; diff --git a/src/php/ext/grpc/credentials.c b/src/php/ext/grpc/credentials.c index f486272531..2a83d1cbc1 100644 --- a/src/php/ext/grpc/credentials.c +++ b/src/php/ext/grpc/credentials.c @@ -151,13 +151,12 @@ PHP_METHOD(Credentials, createFake) { static zend_function_entry credentials_methods[] = { PHP_ME(Credentials, createDefault, NULL, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) - PHP_ME(Credentials, createSsl, NULL, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) - PHP_ME(Credentials, createComposite, NULL, - ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) - PHP_ME(Credentials, createGce, NULL, - ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) - PHP_ME(Credentials, createFake, NULL, - ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) PHP_FE_END}; + PHP_ME(Credentials, createSsl, NULL, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) + PHP_ME(Credentials, createComposite, NULL, + ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) + PHP_ME(Credentials, createGce, NULL, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) + PHP_ME(Credentials, createFake, NULL, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) + PHP_FE_END}; void grpc_init_credentials(TSRMLS_D) { zend_class_entry ce; diff --git a/src/php/ext/grpc/php_grpc.c b/src/php/ext/grpc/php_grpc.c index c1042293aa..e8b4643a58 100644 --- a/src/php/ext/grpc/php_grpc.c +++ b/src/php/ext/grpc/php_grpc.c @@ -33,7 +33,8 @@ zend_module_entry grpc_module_entry = { #if ZEND_MODULE_API_NO >= 20010901 STANDARD_MODULE_HEADER, #endif - "grpc", grpc_functions, PHP_MINIT(grpc), PHP_MSHUTDOWN(grpc), NULL, NULL, + "grpc", grpc_functions, PHP_MINIT(grpc), + PHP_MSHUTDOWN(grpc), NULL, NULL, PHP_MINFO(grpc), #if ZEND_MODULE_API_NO >= 20010901 PHP_GRPC_VERSION, diff --git a/src/php/ext/grpc/server.c b/src/php/ext/grpc/server.c index f484375712..38777f3d54 100644 --- a/src/php/ext/grpc/server.c +++ b/src/php/ext/grpc/server.c @@ -176,10 +176,10 @@ PHP_METHOD(Server, start) { static zend_function_entry server_methods[] = { PHP_ME(Server, __construct, NULL, ZEND_ACC_PUBLIC | ZEND_ACC_CTOR) - PHP_ME(Server, request_call, NULL, ZEND_ACC_PUBLIC) - PHP_ME(Server, add_http2_port, NULL, ZEND_ACC_PUBLIC) - PHP_ME(Server, add_secure_http2_port, NULL, ZEND_ACC_PUBLIC) - PHP_ME(Server, start, NULL, ZEND_ACC_PUBLIC) PHP_FE_END}; + PHP_ME(Server, request_call, NULL, ZEND_ACC_PUBLIC) + PHP_ME(Server, add_http2_port, NULL, ZEND_ACC_PUBLIC) + PHP_ME(Server, add_secure_http2_port, NULL, ZEND_ACC_PUBLIC) + PHP_ME(Server, start, NULL, ZEND_ACC_PUBLIC) PHP_FE_END}; void grpc_init_server(TSRMLS_D) { zend_class_entry ce; diff --git a/src/php/ext/grpc/server_credentials.c b/src/php/ext/grpc/server_credentials.c index 5b9ab3390d..1f8e58aa4d 100644 --- a/src/php/ext/grpc/server_credentials.c +++ b/src/php/ext/grpc/server_credentials.c @@ -102,8 +102,8 @@ PHP_METHOD(ServerCredentials, createFake) { static zend_function_entry server_credentials_methods[] = { PHP_ME(ServerCredentials, createSsl, NULL, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) - PHP_ME(ServerCredentials, createFake, NULL, - ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) PHP_FE_END}; + PHP_ME(ServerCredentials, createFake, NULL, + ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) PHP_FE_END}; void grpc_init_server_credentials(TSRMLS_D) { zend_class_entry ce; diff --git a/src/php/ext/grpc/timeval.c b/src/php/ext/grpc/timeval.c index a5508115e4..cbbbf37915 100644 --- a/src/php/ext/grpc/timeval.c +++ b/src/php/ext/grpc/timeval.c @@ -217,20 +217,16 @@ PHP_METHOD(Timeval, sleep_until) { } static zend_function_entry timeval_methods[] = { - PHP_ME(Timeval, __construct, NULL, ZEND_ACC_PUBLIC | ZEND_ACC_CTOR) PHP_ME( - Timeval, add, NULL, - ZEND_ACC_PUBLIC) PHP_ME(Timeval, compare, NULL, - ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) - PHP_ME(Timeval, inf_future, NULL, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) - PHP_ME(Timeval, inf_past, NULL, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) - PHP_ME(Timeval, now, NULL, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) - PHP_ME(Timeval, similar, NULL, - ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) - PHP_ME(Timeval, sleep_until, NULL, ZEND_ACC_PUBLIC) - PHP_ME(Timeval, subtract, NULL, ZEND_ACC_PUBLIC) - PHP_ME(Timeval, zero, NULL, - ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) - PHP_FE_END}; + PHP_ME(Timeval, __construct, NULL, ZEND_ACC_PUBLIC | ZEND_ACC_CTOR) + PHP_ME(Timeval, add, NULL, ZEND_ACC_PUBLIC) + PHP_ME(Timeval, compare, NULL, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) + PHP_ME(Timeval, inf_future, NULL, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) + PHP_ME(Timeval, inf_past, NULL, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) + PHP_ME(Timeval, now, NULL, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) + PHP_ME(Timeval, similar, NULL, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) + PHP_ME(Timeval, sleep_until, NULL, ZEND_ACC_PUBLIC) + PHP_ME(Timeval, subtract, NULL, ZEND_ACC_PUBLIC) + PHP_ME(Timeval, zero, NULL, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) PHP_FE_END}; void grpc_init_timeval(TSRMLS_D) { zend_class_entry ce; diff --git a/test/core/channel/channel_stack_test.c b/test/core/channel/channel_stack_test.c index fb52fe3270..d0ea79c34e 100644 --- a/test/core/channel/channel_stack_test.c +++ b/test/core/channel/channel_stack_test.c @@ -78,9 +78,9 @@ static void channel_func(grpc_channel_element *elem, static void test_create_channel_stack(void) { const grpc_channel_filter filter = { - call_func, channel_func, + call_func, channel_func, - sizeof(int), call_init_func, call_destroy_func, + sizeof(int), call_init_func, call_destroy_func, sizeof(int), channel_init_func, channel_destroy_func, }; diff --git a/test/core/channel/metadata_buffer_test.c b/test/core/channel/metadata_buffer_test.c index 5604e25705..aa2399272f 100644 --- a/test/core/channel/metadata_buffer_test.c +++ b/test/core/channel/metadata_buffer_test.c @@ -78,7 +78,7 @@ static void expect_call_op(grpc_call_element *elem, GPR_ASSERT(op->dir == GRPC_CALL_DOWN); GPR_ASSERT(op->flags == *n); GPR_ASSERT(op->done_cb == do_nothing); - GPR_ASSERT(op->user_data == (void *)(gpr_uintptr)*n); + GPR_ASSERT(op->user_data == (void *)(gpr_uintptr) * n); GPR_ASSERT(0 == gpr_slice_cmp(op->data.metadata->key->slice, key)); GPR_ASSERT(0 == gpr_slice_cmp(op->data.metadata->value->slice, value)); @@ -148,7 +148,7 @@ static void test_case(size_t key_prefix_len, size_t value_prefix_len, op.flags = i; op.data.metadata = grpc_mdelem_from_slices(mdctx, key, value); op.done_cb = do_nothing; - op.user_data = (void *)(gpr_uintptr)i; + op.user_data = (void *)(gpr_uintptr) i; grpc_metadata_buffer_queue(&buffer, &op); } diff --git a/test/core/end2end/cq_verifier.c b/test/core/end2end/cq_verifier.c index 60b0bf3303..9fa513126f 100644 --- a/test/core/end2end/cq_verifier.c +++ b/test/core/end2end/cq_verifier.c @@ -495,4 +495,3 @@ void cq_expect_finished(cq_verifier *v, void *tag, ...) { void cq_expect_server_shutdown(cq_verifier *v, void *tag) { add(v, GRPC_SERVER_SHUTDOWN, tag); } - diff --git a/test/core/end2end/tests/max_concurrent_streams.c b/test/core/end2end/tests/max_concurrent_streams.c index e88f418cb0..1db32b1de9 100644 --- a/test/core/end2end/tests/max_concurrent_streams.c +++ b/test/core/end2end/tests/max_concurrent_streams.c @@ -203,7 +203,7 @@ static void test_max_concurrent_streams(grpc_end2end_test_config config) { GPR_ASSERT(ev->data.invoke_accepted == GRPC_OP_OK); /* The /alpha or /beta calls started above could be invoked (but NOT both); * check this here */ - live_call = (int)(gpr_intptr)ev->tag; + live_call = (int)(gpr_intptr) ev->tag; live_call_obj = live_call == 300 ? c1 : c2; grpc_event_finish(ev); diff --git a/test/core/end2end/tests/thread_stress.c b/test/core/end2end/tests/thread_stress.c index 5410258201..2de0497a7a 100644 --- a/test/core/end2end/tests/thread_stress.c +++ b/test/core/end2end/tests/thread_stress.c @@ -282,11 +282,11 @@ static void run_test(grpc_end2end_test_config config, int requests_in_flight) { /* kick off threads */ for (i = 0; i < CLIENT_THREADS; i++) { gpr_event_init(&g_client_done[i]); - gpr_thd_new(&thd_id, client_thread, (void *)(gpr_intptr)i, NULL); + gpr_thd_new(&thd_id, client_thread, (void *)(gpr_intptr) i, NULL); } for (i = 0; i < SERVER_THREADS; i++) { gpr_event_init(&g_server_done[i]); - gpr_thd_new(&thd_id, server_thread, (void *)(gpr_intptr)i, NULL); + gpr_thd_new(&thd_id, server_thread, (void *)(gpr_intptr) i, NULL); } /* start requests */ diff --git a/test/core/iomgr/alarm_list_test.c b/test/core/iomgr/alarm_list_test.c index a250951231..ce9b7f4c66 100644 --- a/test/core/iomgr/alarm_list_test.c +++ b/test/core/iomgr/alarm_list_test.c @@ -61,13 +61,13 @@ static void add_test(void) { /* 10 ms alarms. will expire in the current epoch */ for (i = 0; i < 10; i++) { grpc_alarm_init(&alarms[i], gpr_time_add(start, gpr_time_from_millis(10)), - cb, (void *)(gpr_intptr)i, start); + cb, (void *)(gpr_intptr) i, start); } /* 1010 ms alarms. will expire in the next epoch */ for (i = 10; i < 20; i++) { grpc_alarm_init(&alarms[i], gpr_time_add(start, gpr_time_from_millis(1010)), - cb, (void *)(gpr_intptr)i, start); + cb, (void *)(gpr_intptr) i, start); } /* collect alarms. Only the first batch should be ready. */ @@ -115,15 +115,15 @@ void destruction_test(void) { memset(cb_called, 0, sizeof(cb_called)); grpc_alarm_init(&alarms[0], gpr_time_from_millis(100), cb, - (void *)(gpr_intptr)0, gpr_time_0); + (void *)(gpr_intptr) 0, gpr_time_0); grpc_alarm_init(&alarms[1], gpr_time_from_millis(3), cb, - (void *)(gpr_intptr)1, gpr_time_0); + (void *)(gpr_intptr) 1, gpr_time_0); grpc_alarm_init(&alarms[2], gpr_time_from_millis(100), cb, - (void *)(gpr_intptr)2, gpr_time_0); + (void *)(gpr_intptr) 2, gpr_time_0); grpc_alarm_init(&alarms[3], gpr_time_from_millis(3), cb, - (void *)(gpr_intptr)3, gpr_time_0); + (void *)(gpr_intptr) 3, gpr_time_0); grpc_alarm_init(&alarms[4], gpr_time_from_millis(1), cb, - (void *)(gpr_intptr)4, gpr_time_0); + (void *)(gpr_intptr) 4, gpr_time_0); GPR_ASSERT(1 == grpc_alarm_check(NULL, gpr_time_from_millis(2), NULL)); GPR_ASSERT(1 == cb_called[4][1]); grpc_alarm_cancel(&alarms[0]); diff --git a/test/core/iomgr/endpoint_tests.c b/test/core/iomgr/endpoint_tests.c index 125cde4678..dc5747bf57 100644 --- a/test/core/iomgr/endpoint_tests.c +++ b/test/core/iomgr/endpoint_tests.c @@ -290,7 +290,7 @@ static void shutdown_during_write_test_read_handler( if (error != GRPC_ENDPOINT_CB_OK) { grpc_endpoint_destroy(st->ep); - gpr_event_set(&st->ev, (void *)(gpr_intptr)error); + gpr_event_set(&st->ev, (void *)(gpr_intptr) error); } else { grpc_endpoint_notify_on_read( st->ep, shutdown_during_write_test_read_handler, user_data); @@ -309,7 +309,7 @@ static void shutdown_during_write_test_write_handler( gpr_log(GPR_ERROR, "shutdown_during_write_test_write_handler completed unexpectedly"); } - gpr_event_set(&st->ev, (void *)(gpr_intptr)1); + gpr_event_set(&st->ev, (void *)(gpr_intptr) 1); } static void shutdown_during_write_test(grpc_endpoint_test_config config, diff --git a/test/core/statistics/hash_table_test.c b/test/core/statistics/hash_table_test.c index 5d05ab5bc4..ebfc2a2a9a 100644 --- a/test/core/statistics/hash_table_test.c +++ b/test/core/statistics/hash_table_test.c @@ -64,8 +64,8 @@ static void free_data(void* data) { gpr_free(data); } static void test_create_table(void) { /* Create table with uint64 key type */ census_ht* ht = NULL; - census_ht_option ht_options = {CENSUS_HT_UINT64, 1999, NULL, NULL, NULL, - NULL}; + census_ht_option ht_options = {CENSUS_HT_UINT64, 1999, NULL, + NULL, NULL, NULL}; ht = census_ht_create(&ht_options); GPR_ASSERT(ht != NULL); GPR_ASSERT(census_ht_get_size(ht) == 0); @@ -119,8 +119,8 @@ static void test_table_with_int_key(void) { /* Test that there is no memory leak when keys and values are owned by table. */ static void test_value_and_key_deleter(void) { - census_ht_option opt = {CENSUS_HT_POINTER, 7, &hash64, &cmp_str_keys, - &free_data, &free_data}; + census_ht_option opt = {CENSUS_HT_POINTER, 7, &hash64, + &cmp_str_keys, &free_data, &free_data}; census_ht* ht = census_ht_create(&opt); census_ht_key key; char* val = NULL; @@ -184,8 +184,8 @@ static void test_simple_add_and_erase(void) { } static void test_insertion_and_deletion_with_high_collision_rate(void) { - census_ht_option opt = {CENSUS_HT_POINTER, 13, &force_collision, - &cmp_str_keys, NULL, NULL}; + census_ht_option opt = {CENSUS_HT_POINTER, 13, &force_collision, + &cmp_str_keys, NULL, NULL}; census_ht* ht = census_ht_create(&opt); char key_str[1000][10]; gpr_uint64 val = 0; @@ -208,12 +208,12 @@ static void test_insertion_and_deletion_with_high_collision_rate(void) { } static void test_table_with_string_key(void) { - census_ht_option opt = {CENSUS_HT_POINTER, 7, &hash64, &cmp_str_keys, NULL, - NULL}; + census_ht_option opt = {CENSUS_HT_POINTER, 7, &hash64, + &cmp_str_keys, NULL, NULL}; census_ht* ht = census_ht_create(&opt); - const char* keys[] = {"k1", "a", "000", "apple", - "banana_a_long_long_long_banana", "%$", "111", "foo", - "b"}; + const char* keys[] = {"k1", "a", "000", + "apple", "banana_a_long_long_long_banana", "%$", + "111", "foo", "b"}; const int vals[] = {0, 1, 2, 3, 4, 5, 6, 7, 8}; int i = 0; GPR_ASSERT(ht != NULL); diff --git a/test/core/surface/completion_queue_benchmark.c b/test/core/surface/completion_queue_benchmark.c index e1b9d0d035..5360d7c6c3 100644 --- a/test/core/surface/completion_queue_benchmark.c +++ b/test/core/surface/completion_queue_benchmark.c @@ -53,23 +53,23 @@ static void producer_thread(void *arg) { test_thread_options *opt = arg; int i; - gpr_event_set(&opt->on_started, (void *)(gpr_intptr)1); + gpr_event_set(&opt->on_started, (void *)(gpr_intptr) 1); GPR_ASSERT(gpr_event_wait(opt->start, gpr_inf_future)); for (i = 0; i < opt->iterations; i++) { grpc_cq_begin_op(opt->cc, NULL, GRPC_WRITE_ACCEPTED); - grpc_cq_end_write_accepted(opt->cc, (void *)(gpr_intptr)1, NULL, NULL, NULL, - GRPC_OP_OK); + grpc_cq_end_write_accepted(opt->cc, (void *)(gpr_intptr) 1, NULL, NULL, + NULL, GRPC_OP_OK); } - gpr_event_set(&opt->on_finished, (void *)(gpr_intptr)1); + gpr_event_set(&opt->on_finished, (void *)(gpr_intptr) 1); } static void consumer_thread(void *arg) { test_thread_options *opt = arg; grpc_event *ev; - gpr_event_set(&opt->on_started, (void *)(gpr_intptr)1); + gpr_event_set(&opt->on_started, (void *)(gpr_intptr) 1); GPR_ASSERT(gpr_event_wait(opt->start, gpr_inf_future)); for (;;) { @@ -78,7 +78,7 @@ static void consumer_thread(void *arg) { case GRPC_WRITE_ACCEPTED: break; case GRPC_QUEUE_SHUTDOWN: - gpr_event_set(&opt->on_finished, (void *)(gpr_intptr)1); + gpr_event_set(&opt->on_finished, (void *)(gpr_intptr) 1); return; default: gpr_log(GPR_ERROR, "Invalid event received: %d", ev->type); @@ -112,7 +112,7 @@ double ops_per_second(int consumers, int producers, int iterations) { /* start the benchmark */ t_start = gpr_now(); - gpr_event_set(&start, (void *)(gpr_intptr)1); + gpr_event_set(&start, (void *)(gpr_intptr) 1); /* wait for producers to finish */ for (i = 0; i < producers; i++) { diff --git a/test/core/surface/completion_queue_test.c b/test/core/surface/completion_queue_test.c index 71f9cc2291..4bbe9cc96f 100644 --- a/test/core/surface/completion_queue_test.c +++ b/test/core/surface/completion_queue_test.c @@ -282,7 +282,7 @@ static void producer_thread(void *arg) { int i; gpr_log(GPR_INFO, "producer %d started", opt->id); - gpr_event_set(&opt->on_started, (void *)(gpr_intptr)1); + gpr_event_set(&opt->on_started, (void *)(gpr_intptr) 1); GPR_ASSERT(gpr_event_wait(opt->phase1, ten_seconds_time())); gpr_log(GPR_INFO, "producer %d phase 1", opt->id); @@ -291,18 +291,18 @@ static void producer_thread(void *arg) { } gpr_log(GPR_INFO, "producer %d phase 1 done", opt->id); - gpr_event_set(&opt->on_phase1_done, (void *)(gpr_intptr)1); + gpr_event_set(&opt->on_phase1_done, (void *)(gpr_intptr) 1); GPR_ASSERT(gpr_event_wait(opt->phase2, ten_seconds_time())); gpr_log(GPR_INFO, "producer %d phase 2", opt->id); for (i = 0; i < TEST_THREAD_EVENTS; i++) { - grpc_cq_end_write_accepted(opt->cc, (void *)(gpr_intptr)1, NULL, NULL, NULL, - GRPC_OP_OK); + grpc_cq_end_write_accepted(opt->cc, (void *)(gpr_intptr) 1, NULL, NULL, + NULL, GRPC_OP_OK); opt->events_triggered++; } gpr_log(GPR_INFO, "producer %d phase 2 done", opt->id); - gpr_event_set(&opt->on_finished, (void *)(gpr_intptr)1); + gpr_event_set(&opt->on_finished, (void *)(gpr_intptr) 1); } static void consumer_thread(void *arg) { @@ -310,13 +310,13 @@ static void consumer_thread(void *arg) { grpc_event *ev; gpr_log(GPR_INFO, "consumer %d started", opt->id); - gpr_event_set(&opt->on_started, (void *)(gpr_intptr)1); + gpr_event_set(&opt->on_started, (void *)(gpr_intptr) 1); GPR_ASSERT(gpr_event_wait(opt->phase1, ten_seconds_time())); gpr_log(GPR_INFO, "consumer %d phase 1", opt->id); gpr_log(GPR_INFO, "consumer %d phase 1 done", opt->id); - gpr_event_set(&opt->on_phase1_done, (void *)(gpr_intptr)1); + gpr_event_set(&opt->on_phase1_done, (void *)(gpr_intptr) 1); GPR_ASSERT(gpr_event_wait(opt->phase2, ten_seconds_time())); gpr_log(GPR_INFO, "consumer %d phase 2", opt->id); @@ -331,7 +331,7 @@ static void consumer_thread(void *arg) { break; case GRPC_QUEUE_SHUTDOWN: gpr_log(GPR_INFO, "consumer %d phase 2 done", opt->id); - gpr_event_set(&opt->on_finished, (void *)(gpr_intptr)1); + gpr_event_set(&opt->on_finished, (void *)(gpr_intptr) 1); grpc_event_finish(ev); return; default: @@ -376,7 +376,7 @@ static void test_threading(int producers, int consumers) { /* start phase1: producers will pre-declare all operations they will complete */ gpr_log(GPR_INFO, "start phase 1"); - gpr_event_set(&phase1, (void *)(gpr_intptr)1); + gpr_event_set(&phase1, (void *)(gpr_intptr) 1); gpr_log(GPR_INFO, "wait phase 1"); for (i = 0; i < producers + consumers; i++) { @@ -386,7 +386,7 @@ static void test_threading(int producers, int consumers) { /* start phase2: operations will complete, and consumers will consume them */ gpr_log(GPR_INFO, "start phase 2"); - gpr_event_set(&phase2, (void *)(gpr_intptr)1); + gpr_event_set(&phase2, (void *)(gpr_intptr) 1); /* in parallel, we shutdown the completion channel - all events should still be consumed */ diff --git a/test/core/transport/chttp2/stream_map_test.c b/test/core/transport/chttp2/stream_map_test.c index 9b4446f7f8..30cd63ca67 100644 --- a/test/core/transport/chttp2/stream_map_test.c +++ b/test/core/transport/chttp2/stream_map_test.c @@ -93,7 +93,7 @@ static void test_basic_add_find(size_t n) { grpc_chttp2_stream_map_init(&map, 8); GPR_ASSERT(0 == grpc_chttp2_stream_map_size(&map)); for (i = 1; i <= n; i++) { - grpc_chttp2_stream_map_add(&map, i, (void *)(gpr_uintptr)i); + grpc_chttp2_stream_map_add(&map, i, (void *)(gpr_uintptr) i); } GPR_ASSERT(n == grpc_chttp2_stream_map_size(&map)); GPR_ASSERT(NULL == grpc_chttp2_stream_map_find(&map, 0)); @@ -148,7 +148,7 @@ static void test_delete_evens_sweep(size_t n) { grpc_chttp2_stream_map_init(&map, 8); for (i = 1; i <= n; i++) { - grpc_chttp2_stream_map_add(&map, i, (void *)(gpr_uintptr)i); + grpc_chttp2_stream_map_add(&map, i, (void *)(gpr_uintptr) i); } for (i = 1; i <= n; i++) { if ((i & 1) == 0) { @@ -170,7 +170,7 @@ static void test_delete_evens_incremental(size_t n) { grpc_chttp2_stream_map_init(&map, 8); for (i = 1; i <= n; i++) { - grpc_chttp2_stream_map_add(&map, i, (void *)(gpr_uintptr)i); + grpc_chttp2_stream_map_add(&map, i, (void *)(gpr_uintptr) i); if ((i & 1) == 0) { grpc_chttp2_stream_map_delete(&map, i); } diff --git a/tools/clang-format/clang-format-all.sh b/tools/clang-format/clang-format-all.sh index c9caea0d61..62228b0b01 100755 --- a/tools/clang-format/clang-format-all.sh +++ b/tools/clang-format/clang-format-all.sh @@ -1,8 +1,9 @@ #!/bin/bash -set -ex +set -e +source $(dirname $0)/config.sh cd $(dirname $0)/../.. for dir in src test include do - find $dir -name '*.c' -or -name '*.cc' -or -name '*.h' | xargs clang-format -i + find $dir -name '*.c' -or -name '*.cc' -or -name '*.h' | xargs $CLANG_FORMAT -i done diff --git a/tools/clang-format/config.sh b/tools/clang-format/config.sh new file mode 100644 index 0000000000..b7168ab2e3 --- /dev/null +++ b/tools/clang-format/config.sh @@ -0,0 +1 @@ +CLANG_FORMAT=clang-format-3.5 -- cgit v1.2.3 From 5246e7a2d133dfdbd0e2edb631c97f51f8afa482 Mon Sep 17 00:00:00 2001 From: Craig Tiller Date: Mon, 19 Jan 2015 14:59:08 -0800 Subject: Disconnect on bad connection prefix --- src/core/transport/chttp2_transport.c | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/core/transport/chttp2_transport.c b/src/core/transport/chttp2_transport.c index 1b90d4715b..26649132fd 100644 --- a/src/core/transport/chttp2_transport.c +++ b/src/core/transport/chttp2_transport.c @@ -1505,6 +1505,7 @@ static int process_read(transport *t, gpr_slice slice) { CLIENT_CONNECT_STRING[t->deframe_state], (int)(gpr_uint8)CLIENT_CONNECT_STRING[t->deframe_state], *cur, (int)*cur, t->deframe_state); + drop_connection(t); return 0; } ++cur; -- cgit v1.2.3 From 44a56ce426eb86bd8eb580078b8a8d1f70955aa8 Mon Sep 17 00:00:00 2001 From: Craig Tiller Date: Mon, 19 Jan 2015 18:42:12 -0800 Subject: Add extern where its required --- src/core/channel/child_channel.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/core/channel/child_channel.h b/src/core/channel/child_channel.h index 3ba4c1b8a9..ece0ff99a9 100644 --- a/src/core/channel/child_channel.h +++ b/src/core/channel/child_channel.h @@ -39,7 +39,7 @@ /* helper for filters that need to host child channel stacks... handles lifetime and upwards propagation cleanly */ -const grpc_channel_filter grpc_child_channel_top_filter; +extern const grpc_channel_filter grpc_child_channel_top_filter; typedef grpc_channel_stack grpc_child_channel; typedef grpc_call_stack grpc_child_call; -- cgit v1.2.3