xref: /aosp_15_r20/external/grpc-grpc/src/ruby/end2end/echo_server.rb (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1#!/usr/bin/env ruby
2#
3# Copyright 2016 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
17this_dir = File.expand_path(File.dirname(__FILE__))
18protos_lib_dir = File.join(this_dir, 'lib')
19grpc_lib_dir = File.join(File.dirname(this_dir), 'lib')
20$LOAD_PATH.unshift(grpc_lib_dir) unless $LOAD_PATH.include?(grpc_lib_dir)
21$LOAD_PATH.unshift(protos_lib_dir) unless $LOAD_PATH.include?(protos_lib_dir)
22$LOAD_PATH.unshift(this_dir) unless $LOAD_PATH.include?(this_dir)
23
24require 'grpc'
25require 'end2end_common'
26
27def create_server_creds
28  test_root = File.join(File.dirname(__FILE__), '..', 'spec', 'testdata')
29  GRPC.logger.info("test root: #{test_root}")
30  files = ['ca.pem', 'server1.key', 'server1.pem']
31  creds = files.map { |f| File.open(File.join(test_root, f)).read }
32  GRPC::Core::ServerCredentials.new(
33    creds[0],
34    [{ private_key: creds[1], cert_chain: creds[2] }],
35    true) # force client auth
36end
37
38# Runs an echo server. Once the server is running, this writes the port of the
39# server to stdout. Terminates after reading EOF on stdin.
40def main
41  secure = false
42  OptionParser.new do |opts|
43    opts.on('--secure') do
44      secure = true
45    end
46  end.parse!
47  STDERR.puts 'start server'
48  if secure
49    server_runner = ServerRunner.new(SecureEchoServerImpl)
50    server_runner.server_creds = create_server_creds
51  else
52    server_runner = ServerRunner.new(EchoServerImpl)
53  end
54  server_port = server_runner.run
55  p server_port
56  STDIN.read
57  server_runner.stop
58end
59
60main
61