blob: 7618eec0c9b60b8615fa90b9f3a553a901f48dcf [file] [log] [blame]
Tim Emiola3acf05a2015-01-13 07:55:34 -08001#!/usr/bin/env ruby
2
Jan Tattermusch7897ae92017-06-07 22:57:36 +02003# Copyright 2015 gRPC authors.
nnoble097ef9b2014-12-01 17:06:10 -08004#
Jan Tattermusch7897ae92017-06-07 22:57:36 +02005# 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
nnoble097ef9b2014-12-01 17:06:10 -08008#
Jan Tattermusch7897ae92017-06-07 22:57:36 +02009# http://www.apache.org/licenses/LICENSE-2.0
nnoble097ef9b2014-12-01 17:06:10 -080010#
Jan Tattermusch7897ae92017-06-07 22:57:36 +020011# 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.
nnoble097ef9b2014-12-01 17:06:10 -080016
nnoble097ef9b2014-12-01 17:06:10 -080017# 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
22this_dir = File.expand_path(File.dirname(__FILE__))
23lib_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
27require 'forwardable'
28require 'grpc'
Tim Emiola81d950a2015-08-28 16:57:28 -070029require 'logger'
Ken Payson5a2c9182016-07-26 17:15:08 -070030require 'math_services_pb'
nnoble0c475f02014-12-05 15:37:39 -080031require 'optparse'
nnoble097ef9b2014-12-01 17:06:10 -080032
Tim Emiola81d950a2015-08-28 16:57:28 -070033# RubyLogger defines a logger for gRPC based on the standard ruby logger.
34module RubyLogger
35 def logger
36 LOGGER
37 end
38
39 LOGGER = Logger.new(STDOUT)
40end
41
42# GRPC is the general RPC module
43module GRPC
44 # Inject the noop #logger if no module-level logger method has been injected.
45 extend RubyLogger
46end
47
nnoble097ef9b2014-12-01 17:06:10 -080048# Holds state for a fibonacci series
49class Fibber
nnoble097ef9b2014-12-01 17:06:10 -080050 def initialize(limit)
Tim Emiolae2860c52015-01-16 02:58:41 -080051 fail "bad limit: got #{limit}, want limit > 0" if limit < 1
nnoble097ef9b2014-12-01 17:06:10 -080052 @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
Aggelos Avgerinos57e7dc82015-05-09 13:08:03 +030059 if idx.zero? || idx == 1
Tim Emiolae2860c52015-01-16 02:58:41 -080060 yield Math::Num.new(num: 1)
nnoble097ef9b2014-12-01 17:06:10 -080061 idx += 1
62 next
63 end
64 tmp = current
65 current = previous + current
66 previous = tmp
Tim Emiolae2860c52015-01-16 02:58:41 -080067 yield Math::Num.new(num: current)
nnoble097ef9b2014-12-01 17:06:10 -080068 idx += 1
69 end
70 end
71end
72
73# A EnumeratorQueue wraps a Queue to yield the items added to it.
74class 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)
Tim Emiolae2860c52015-01-16 02:58:41 -080088 fail r if r.is_a? Exception
nnoble097ef9b2014-12-01 17:06:10 -080089 yield r
90 end
91 end
nnoble097ef9b2014-12-01 17:06:10 -080092end
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.
96class Calculator < Math::Math::Service
Tim Emiolae2860c52015-01-16 02:58:41 -080097 def div(div_args, _call)
Aggelos Avgerinos57e7dc82015-05-09 13:08:03 +030098 if div_args.divisor.zero?
nnoble097ef9b2014-12-01 17:06:10 -080099 # To send non-OK status handlers raise a StatusError with the code and
100 # and detail they want sent as a Status.
Tim Emiolae2860c52015-01-16 02:58:41 -0800101 fail GRPC::StatusError.new(GRPC::Status::INVALID_ARGUMENT,
102 'divisor cannot be 0')
nnoble097ef9b2014-12-01 17:06:10 -0800103 end
104
Tim Emiolae2860c52015-01-16 02:58:41 -0800105 Math::DivReply.new(quotient: div_args.dividend / div_args.divisor,
106 remainder: div_args.dividend % div_args.divisor)
nnoble097ef9b2014-12-01 17:06:10 -0800107 end
108
109 def sum(call)
110 # the requests are accesible as the Enumerator call#each_request
Tim Emiolae2860c52015-01-16 02:58:41 -0800111 nums = call.each_remote_read.collect(&:num)
112 sum = nums.inject { |s, x| s + x }
113 Math::Num.new(num: sum)
nnoble097ef9b2014-12-01 17:06:10 -0800114 end
115
Tim Emiolae2860c52015-01-16 02:58:41 -0800116 def fib(fib_args, _call)
nnoble097ef9b2014-12-01 17:06:10 -0800117 if fib_args.limit < 1
Tim Emiolae2860c52015-01-16 02:58:41 -0800118 fail StatusError.new(Status::INVALID_ARGUMENT, 'limit must be >= 0')
nnoble097ef9b2014-12-01 17:06:10 -0800119 end
120
121 # return an Enumerator of Nums
Tim Emiolae2860c52015-01-16 02:58:41 -0800122 Fibber.new(fib_args.limit).generator
nnoble097ef9b2014-12-01 17:06:10 -0800123 # 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|
Nick Gauthierf233d962015-05-20 14:02:50 -0400132 GRPC.logger.info("read #{req.inspect}")
Tim Emiolae2860c52015-01-16 02:58:41 -0800133 resp = Math::DivReply.new(quotient: req.dividend / req.divisor,
134 remainder: req.dividend % req.divisor)
nnoble097ef9b2014-12-01 17:06:10 -0800135 q.push(resp)
Tim Emiolae2860c52015-01-16 02:58:41 -0800136 Thread.pass # let the internal Bidi threads run
nnoble097ef9b2014-12-01 17:06:10 -0800137 end
Nick Gauthierf233d962015-05-20 14:02:50 -0400138 GRPC.logger.info('finished reads')
nnoble097ef9b2014-12-01 17:06:10 -0800139 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
nnoble097ef9b2014-12-01 17:06:10 -0800148end
149
nnoble0c475f02014-12-05 15:37:39 -0800150def 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 }
155end
156
157def test_server_creds
158 certs = load_test_certs
Tim Emiola73a540a2015-08-28 18:56:17 -0700159 GRPC::Core::ServerCredentials.new(
160 nil, [{ private_key: certs[1], cert_chain: certs[2] }], false)
nnoble0c475f02014-12-05 15:37:39 -0800161end
162
nnoble097ef9b2014-12-01 17:06:10 -0800163def main
nnoble0c475f02014-12-05 15:37:39 -0800164 options = {
165 'host' => 'localhost:7071',
166 'secure' => false
167 }
168 OptionParser.new do |opts|
temiola0f0a6bc2015-01-07 18:43:40 -0800169 opts.banner = 'Usage: [--host <hostname>:<port>] [--secure|-s]'
170 opts.on('--host HOST', '<hostname>:<port>') do |v|
nnoble0c475f02014-12-05 15:37:39 -0800171 options['host'] = v
172 end
173 opts.on('-s', '--secure', 'access using test creds') do |v|
Tim Emiolae2860c52015-01-16 02:58:41 -0800174 options['secure'] = v
nnoble0c475f02014-12-05 15:37:39 -0800175 end
176 end.parse!
177
Tim Emiola0ce8edc2015-03-05 15:17:30 -0800178 s = GRPC::RpcServer.new
nnoble0c475f02014-12-05 15:37:39 -0800179 if options['secure']
Tim Emiola0ce8edc2015-03-05 15:17:30 -0800180 s.add_http2_port(options['host'], test_server_creds)
Nick Gauthierf233d962015-05-20 14:02:50 -0400181 GRPC.logger.info("... running securely on #{options['host']}")
nnoble0c475f02014-12-05 15:37:39 -0800182 else
Tim Emiolac03138a2015-09-24 13:11:03 -0700183 s.add_http2_port(options['host'], :this_port_is_insecure)
Nick Gauthierf233d962015-05-20 14:02:50 -0400184 GRPC.logger.info("... running insecurely on #{options['host']}")
nnoble097ef9b2014-12-01 17:06:10 -0800185 end
186
nnoble097ef9b2014-12-01 17:06:10 -0800187 s.handle(Calculator)
Tim Emiola321871e2015-04-16 12:56:11 -0700188 s.run_till_terminated
nnoble097ef9b2014-12-01 17:06:10 -0800189end
190
Craig Tiller190d3602015-02-18 09:23:38 -0800191main