blob: d21ae7ee273dd528db9d8a6ec37c1138c925d20d [file] [log] [blame]
nnoble097ef9b2014-12-01 17:06:10 -08001# Copyright 2014, Google Inc.
2# All rights reserved.
3#
4# Redistribution and use in source and binary forms, with or without
5# modification, are permitted provided that the following conditions are
6# met:
7#
8# * Redistributions of source code must retain the above copyright
9# notice, this list of conditions and the following disclaimer.
10# * Redistributions in binary form must reproduce the above
11# copyright notice, this list of conditions and the following disclaimer
12# in the documentation and/or other materials provided with the
13# distribution.
14# * Neither the name of Google Inc. nor the names of its
15# contributors may be used to endorse or promote products derived from
16# this software without specific prior written permission.
17#
18# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30#!/usr/bin/env ruby
31#
32# Sample gRPC Ruby server that implements the Math::Calc service and helps
33# validate GRPC::RpcServer as GRPC implementation using proto2 serialization.
34#
35# Usage: $ path/to/math_server.rb
36
37this_dir = File.expand_path(File.dirname(__FILE__))
38lib_dir = File.join(File.dirname(this_dir), 'lib')
39$LOAD_PATH.unshift(lib_dir) unless $LOAD_PATH.include?(lib_dir)
40$LOAD_PATH.unshift(this_dir) unless $LOAD_PATH.include?(this_dir)
41
42require 'forwardable'
43require 'grpc'
44require 'grpc/generic/service'
45require 'grpc/generic/rpc_server'
46require 'math.pb'
nnoble0c475f02014-12-05 15:37:39 -080047require 'optparse'
nnoble097ef9b2014-12-01 17:06:10 -080048
49# Holds state for a fibonacci series
50class Fibber
51
52 def initialize(limit)
53 raise "bad limit: got #{limit}, want limit > 0" if limit < 1
54 @limit = limit
55 end
56
57 def generator
58 return enum_for(:generator) unless block_given?
59 idx, current, previous = 0, 1, 1
60 until idx == @limit
61 if idx == 0 || idx == 1
62 yield Math::Num.new(:num => 1)
63 idx += 1
64 next
65 end
66 tmp = current
67 current = previous + current
68 previous = tmp
69 yield Math::Num.new(:num => current)
70 idx += 1
71 end
72 end
73end
74
75# A EnumeratorQueue wraps a Queue to yield the items added to it.
76class EnumeratorQueue
77 extend Forwardable
78 def_delegators :@q, :push
79
80 def initialize(sentinel)
81 @q = Queue.new
82 @sentinel = sentinel
83 end
84
85 def each_item
86 return enum_for(:each_item) unless block_given?
87 loop do
88 r = @q.pop
89 break if r.equal?(@sentinel)
90 raise r if r.is_a?Exception
91 yield r
92 end
93 end
94
95end
96
97# The Math::Math:: module occurs because the service has the same name as its
98# package. That practice should be avoided by defining real services.
99class Calculator < Math::Math::Service
100
101 def div(div_args, call)
102 if div_args.divisor == 0
103 # To send non-OK status handlers raise a StatusError with the code and
104 # and detail they want sent as a Status.
105 raise GRPC::StatusError.new(GRPC::Status::INVALID_ARGUMENT,
106 'divisor cannot be 0')
107 end
108
109 Math::DivReply.new(:quotient => div_args.dividend/div_args.divisor,
110 :remainder => div_args.dividend % div_args.divisor)
111 end
112
113 def sum(call)
114 # the requests are accesible as the Enumerator call#each_request
115 nums = call.each_remote_read.collect { |x| x.num }
116 sum = nums.inject { |sum,x| sum + x }
117 Math::Num.new(:num => sum)
118 end
119
120 def fib(fib_args, call)
121 if fib_args.limit < 1
122 raise StatusError.new(Status::INVALID_ARGUMENT, 'limit must be >= 0')
123 end
124
125 # return an Enumerator of Nums
126 Fibber.new(fib_args.limit).generator()
127 # just return the generator, GRPC::GenericServer sends each actual response
128 end
129
130 def div_many(requests)
131 # requests is an lazy Enumerator of the requests sent by the client.
132 q = EnumeratorQueue.new(self)
133 t = Thread.new do
134 begin
135 requests.each do |req|
136 logger.info("read #{req.inspect}")
137 resp = Math::DivReply.new(:quotient => req.dividend/req.divisor,
138 :remainder => req.dividend % req.divisor)
139 q.push(resp)
140 Thread::pass # let the internal Bidi threads run
141 end
142 logger.info('finished reads')
143 q.push(self)
144 rescue StandardError => e
145 q.push(e) # share the exception with the enumerator
146 raise e
147 end
148 end
149 t.priority = -2 # hint that the div_many thread should not be favoured
150 q.each_item
151 end
152
153end
154
nnoble0c475f02014-12-05 15:37:39 -0800155def load_test_certs
156 this_dir = File.expand_path(File.dirname(__FILE__))
157 data_dir = File.join(File.dirname(this_dir), 'spec/testdata')
158 files = ['ca.pem', 'server1.key', 'server1.pem']
159 files.map { |f| File.open(File.join(data_dir, f)).read }
160end
161
162def test_server_creds
163 certs = load_test_certs
164 server_creds = GRPC::Core::ServerCredentials.new(nil, certs[1], certs[2])
165end
166
nnoble097ef9b2014-12-01 17:06:10 -0800167def main
nnoble0c475f02014-12-05 15:37:39 -0800168 options = {
169 'host' => 'localhost:7071',
170 'secure' => false
171 }
172 OptionParser.new do |opts|
173 opts.banner = 'Usage: [--host|-h <hostname>:<port>] [--secure|-s]'
174 opts.on('-h', '--host', '<hostname>:<port>') do |v|
175 options['host'] = v
176 end
177 opts.on('-s', '--secure', 'access using test creds') do |v|
178 options['secure'] = true
179 end
180 end.parse!
181
182 if options['secure']
183 s = GRPC::RpcServer.new(creds: test_server_creds)
184 s.add_http2_port(options['host'], true)
185 logger.info("... running securely on #{options['host']}")
186 else
187 s = GRPC::RpcServer.new
188 s.add_http2_port(options['host'])
189 logger.info("... running insecurely on #{options['host']}")
nnoble097ef9b2014-12-01 17:06:10 -0800190 end
191
nnoble097ef9b2014-12-01 17:06:10 -0800192 s.handle(Calculator)
193 s.run
194end
195
196main