Home | History | Annotate | Download | only in bin
      1 #!/usr/bin/env ruby
      2 
      3 # Copyright 2015 gRPC authors.
      4 #
      5 # Licensed under the Apache License, Version 2.0 (the "License");
      6 # you may not use this file except in compliance with the License.
      7 # You may obtain a copy of the License at
      8 #
      9 #     http://www.apache.org/licenses/LICENSE-2.0
     10 #
     11 # Unless required by applicable law or agreed to in writing, software
     12 # distributed under the License is distributed on an "AS IS" BASIS,
     13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     14 # See the License for the specific language governing permissions and
     15 # limitations under the License.
     16 
     17 # Sample gRPC Ruby server that implements the Math::Calc service and helps
     18 # validate GRPC::RpcServer as GRPC implementation using proto2 serialization.
     19 #
     20 # Usage: $ path/to/math_server.rb
     21 
     22 this_dir = File.expand_path(File.dirname(__FILE__))
     23 lib_dir = File.join(File.dirname(this_dir), 'lib')
     24 $LOAD_PATH.unshift(lib_dir) unless $LOAD_PATH.include?(lib_dir)
     25 $LOAD_PATH.unshift(this_dir) unless $LOAD_PATH.include?(this_dir)
     26 
     27 require 'forwardable'
     28 require 'grpc'
     29 require 'logger'
     30 require 'math_services_pb'
     31 require 'optparse'
     32 
     33 # RubyLogger defines a logger for gRPC based on the standard ruby logger.
     34 module RubyLogger
     35   def logger
     36     LOGGER
     37   end
     38 
     39   LOGGER = Logger.new(STDOUT)
     40 end
     41 
     42 # GRPC is the general RPC module
     43 module GRPC
     44   # Inject the noop #logger if no module-level logger method has been injected.
     45   extend RubyLogger
     46 end
     47 
     48 # Holds state for a fibonacci series
     49 class Fibber
     50   def initialize(limit)
     51     fail "bad limit: got #{limit}, want limit > 0" if limit < 1
     52     @limit = limit
     53   end
     54 
     55   def generator
     56     return enum_for(:generator) unless block_given?
     57     idx, current, previous = 0, 1, 1
     58     until idx == @limit
     59       if idx.zero? || idx == 1
     60         yield Math::Num.new(num: 1)
     61         idx += 1
     62         next
     63       end
     64       tmp = current
     65       current = previous + current
     66       previous = tmp
     67       yield Math::Num.new(num: current)
     68       idx += 1
     69     end
     70   end
     71 end
     72 
     73 # A EnumeratorQueue wraps a Queue to yield the items added to it.
     74 class EnumeratorQueue
     75   extend Forwardable
     76   def_delegators :@q, :push
     77 
     78   def initialize(sentinel)
     79     @q = Queue.new
     80     @sentinel = sentinel
     81   end
     82 
     83   def each_item
     84     return enum_for(:each_item) unless block_given?
     85     loop do
     86       r = @q.pop
     87       break if r.equal?(@sentinel)
     88       fail r if r.is_a? Exception
     89       yield r
     90     end
     91   end
     92 end
     93 
     94 # The Math::Math:: module occurs because the service has the same name as its
     95 # package. That practice should be avoided by defining real services.
     96 class Calculator < Math::Math::Service
     97   def div(div_args, _call)
     98     if div_args.divisor.zero?
     99       # To send non-OK status handlers raise a StatusError with the code and
    100       # and detail they want sent as a Status.
    101       fail GRPC::StatusError.new(GRPC::Status::INVALID_ARGUMENT,
    102                                  'divisor cannot be 0')
    103     end
    104 
    105     Math::DivReply.new(quotient: div_args.dividend / div_args.divisor,
    106                        remainder: div_args.dividend % div_args.divisor)
    107   end
    108 
    109   def sum(call)
    110     # the requests are accesible as the Enumerator call#each_request
    111     nums = call.each_remote_read.collect(&:num)
    112     sum = nums.inject { |s, x| s + x }
    113     Math::Num.new(num: sum)
    114   end
    115 
    116   def fib(fib_args, _call)
    117     if fib_args.limit < 1
    118       fail StatusError.new(Status::INVALID_ARGUMENT, 'limit must be >= 0')
    119     end
    120 
    121     # return an Enumerator of Nums
    122     Fibber.new(fib_args.limit).generator
    123     # just return the generator, GRPC::GenericServer sends each actual response
    124   end
    125 
    126   def div_many(requests)
    127     # requests is an lazy Enumerator of the requests sent by the client.
    128     q = EnumeratorQueue.new(self)
    129     t = Thread.new do
    130       begin
    131         requests.each do |req|
    132           GRPC.logger.info("read #{req.inspect}")
    133           resp = Math::DivReply.new(quotient: req.dividend / req.divisor,
    134                                     remainder: req.dividend % req.divisor)
    135           q.push(resp)
    136           Thread.pass  # let the internal Bidi threads run
    137         end
    138         GRPC.logger.info('finished reads')
    139         q.push(self)
    140       rescue StandardError => e
    141         q.push(e)  # share the exception with the enumerator
    142         raise e
    143       end
    144     end
    145     t.priority = -2  # hint that the div_many thread should not be favoured
    146     q.each_item
    147   end
    148 end
    149 
    150 def load_test_certs
    151   this_dir = File.expand_path(File.dirname(__FILE__))
    152   data_dir = File.join(File.dirname(this_dir), 'spec/testdata')
    153   files = ['ca.pem', 'server1.key', 'server1.pem']
    154   files.map { |f| File.open(File.join(data_dir, f)).read }
    155 end
    156 
    157 def test_server_creds
    158   certs = load_test_certs
    159   GRPC::Core::ServerCredentials.new(
    160     nil, [{ private_key: certs[1], cert_chain: certs[2] }], false)
    161 end
    162 
    163 def main
    164   options = {
    165     'host' => 'localhost:7071',
    166     'secure' => false
    167   }
    168   OptionParser.new do |opts|
    169     opts.banner = 'Usage: [--host <hostname>:<port>] [--secure|-s]'
    170     opts.on('--host HOST', '<hostname>:<port>') do |v|
    171       options['host'] = v
    172     end
    173     opts.on('-s', '--secure', 'access using test creds') do |v|
    174       options['secure'] = v
    175     end
    176   end.parse!
    177 
    178   s = GRPC::RpcServer.new
    179   if options['secure']
    180     s.add_http2_port(options['host'], test_server_creds)
    181     GRPC.logger.info("... running securely on #{options['host']}")
    182   else
    183     s.add_http2_port(options['host'], :this_port_is_insecure)
    184     GRPC.logger.info("... running insecurely on #{options['host']}")
    185   end
    186 
    187   s.handle(Calculator)
    188   s.run_till_terminated
    189 end
    190 
    191 main
    192