Opensourcetechブログ

OpensourcetechによるNGINX/Kubernetes/Zabbix/Neo4j/Linuxなどオープンソース技術に関するブログです。

gRPCを触ってみる

 

こんにちは、LinuCエバンジェリストこと、鯨井貴博@opensourcetechです。

igore sysoevさんと一緒

 

今回は、学習目的で gRPCを使ってみます。

 

 

gRPCとは

以下にある言葉を拝借すると、「A high performance, open-source universal RPC framework(高性能、オープンソースのユニバーサルRPCフレームワーク)」となります。

https://grpc.io/

 

なぜ、gRPCなのか?

->めっちゃざっくりいうと、サービスへ効率的に接続できる手段とのこと。

Why, gRPC?

gRPCは現代のオープンソースの高性能RPCフレームワークであり、どんな環境でも動作することができます。 ロードバランシング、トレース、ヘルスチェック、および認証のためのプラグ可能なサポートにより、データセンター内およびデータセンター間でサービスを効率的に接続できます。 デバイス、モバイルアプリケーション、およびブラウザをバックエンドサービスに接続することも、分散コンピューティングのラストマイルに適用できます。

 

 

 

gRPCのインストール

https://grpc.io/blog/installation/

上記に書く環境におけるインストール方法があります。

今回はPython(pip)を使ってますが、Node.js/Ruby/PHP/Go/Objective-C/C#/Java/C++でも可能です。

 

まず、クライアント側でインストールします。

bash-3.2$ pip list | grep grpc
grpcio 1.13.0
bash-3.2$ pip install --upgrade grpcio
Collecting grpcio
Downloading https://files.pythonhosted.org/packages/7b/61/1bf3bc7ed4772d81b480e6934c526707c7b799a359fea5c32d61b9715b48/grpcio-1.21.1-cp36-cp36m-macosx_10_9_x86_64.whl (2.0MB)
|████████████████████████████████| 2.0MB 6.6MB/s
Requirement already satisfied, skipping upgrade: six>=1.5.2 in ./anaconda3/lib/python3.6/site-packages (from grpcio) (1.11.0)
Installing collected packages: grpcio
Found existing installation: grpcio 1.13.0
Uninstalling grpcio-1.13.0:
Successfully uninstalled grpcio-1.13.0
Successfully installed grpcio-1.21.1
bash-3.2$ pip list | grep grpc
grpcio 1.21.1

 

続いて、サーバ側となるCentOS7でgRPCをインストールします。

[root@localhost ~]# cat /etc/centos-release
CentOS Linux release 7.6.1810 (Core)
[root@localhost ~]# ls /etc/yum.repos.d/
CentOS-Base.repo CentOS-Sources.repo pgdg-redhat-all.repo
CentOS-CR.repo CentOS-Vault.repo timescale_timescaledb.repo
CentOS-Debuginfo.repo CentOS-fasttrack.repo unit.repo
CentOS-Media.repo nginx.repo zabbix.repo
[root@localhost ~]# yum install -y https://centos7.iuscommunity.org/ius-release.rpm
読み込んだプラグイン:fastestmirror
ius-release.rpm | 8.2 kB 00:00
.
.
省略
.
.
インストール:
ius-release.noarch 0:2-1.el7.ius

依存性関連をインストールしました:
epel-release.noarch 0:7-11

完了しました!
[root@localhost ~]# ls /etc/yum.repos.d/
CentOS-Base.repo CentOS-fasttrack.repo nginx.repo
CentOS-CR.repo epel-testing.repo pgdg-redhat-all.repo
CentOS-Debuginfo.repo epel.repo timescale_timescaledb.repo
CentOS-Media.repo ius-archive.repo unit.repo
CentOS-Sources.repo ius-testing.repo zabbix.repo
CentOS-Vault.repo ius.repo

[root@localhost ~]# yum -y install python36
読み込んだプラグイン:fastestmirror
Loading mirror speeds from cached hostfile
.
.
省略
.
.
Running transaction
インストール中 : python36-libs-3.6.8-1.el7.x86_64 1/2
インストール中 : python36-3.6.8-1.el7.x86_64 2/2
検証中 : python36-3.6.8-1.el7.x86_64 1/2
検証中 : python36-libs-3.6.8-1.el7.x86_64 2/2

インストール:
python36.x86_64 0:3.6.8-1.el7

依存性関連をインストールしました:
python36-libs.x86_64 0:3.6.8-1.el7

完了しました!
[root@localhost ~]# yum search python36u-pip
読み込んだプラグイン:fastestmirror
Loading mirror speeds from cached hostfile
.
.
省略
.
.
Running transaction
インストール中 : python36u-setuptools-39.0.1-1.ius.el7.noarch 1/2
インストール中 : python36u-pip-9.0.1-1.ius.el7.noarch 2/2
検証中 : python36u-setuptools-39.0.1-1.ius.el7.noarch 1/2
検証中 : python36u-pip-9.0.1-1.ius.el7.noarch 2/2

インストール:
python36u-pip.noarch 0:9.0.1-1.ius.el7

依存性関連をインストールしました:
python36u-setuptools.noarch 0:39.0.1-1.ius.el7

完了しました!
[root@localhost ~]# pip3.6 list
DEPRECATION: The default format will switch to columns in the future. You can use --format=(legacy|columns) (or define a format=(legacy|columns) in your pip.conf under the [list] section) to disable this warning.
pip (9.0.1)
setuptools (39.0.1)
You are using pip version 9.0.1, however version 19.1.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
[root@localhost ~]# pip3.6 install --upgrade pip
Collecting pip
Downloading https://files.pythonhosted.org/packages/5c/e0/be401c003291b56efc55aeba6a80ab790d3d4cece2778288d65323009420/pip-19.1.1-py2.py3-none-any.whl (1.4MB)
100% |████████████████████████████████| 1.4MB 411kB/s
Installing collected packages: pip
Found existing installation: pip 9.0.1
Uninstalling pip-9.0.1:
Successfully uninstalled pip-9.0.1
Successfully installed pip-19.1.1
[root@localhost ~]# pip list
Package Version
---------- -------
pip 19.1.1
setuptools 39.0.1
[root@localhost ~]# pip install grpcio
Collecting grpcio
Downloading https://files.pythonhosted.org/packages/99/83/18f374294bf34128a448ee2fae37651f943b0b5fa473b5b3aff262c15bf8/grpcio-1.21.1-cp36-cp36m-manylinux1_x86_64.whl (2.2MB)
|████████████████████████████████| 2.2MB 37kB/s
Collecting six>=1.5.2 (from grpcio)
Downloading https://files.pythonhosted.org/packages/73/fb/00a976f728d0d1fecfe898238ce23f502a721c0ac0ecfedb80e0d88c64e9/six-1.12.0-py2.py3-none-any.whl
Installing collected packages: six, grpcio
Successfully installed grpcio-1.21.1 six-1.12.0
[root@localhost ~]# pip list
Package Version
---------- -------
grpcio 1.21.1
pip 19.1.1
setuptools 39.0.1
six 1.12.0

 

 

 

 

gRPC-toolsのインストール

こちらは、クライアント・サーバともに同じ方法でインストールできます。

bash-3.2$ pip install grpcio-tools
Collecting grpcio-tools
Downloading https://files.pythonhosted.org/packages/49/aa/c11923d7c132c4550b7d7c216e5a8d1090c7d0e9ff5d7185d9f2e65fa53d/grpcio_tools-1.21.1-cp36-cp36m-macosx_10_9_x86_64.whl (1.9MB)
|████████████████████████████████| 1.9MB 8.8MB/s
Requirement already satisfied: protobuf>=3.5.0.post1 in ./anaconda3/lib/python3.6/site-packages (from grpcio-tools) (3.7.0)
Requirement already satisfied: grpcio>=1.21.1 in ./anaconda3/lib/python3.6/site-packages (from grpcio-tools) (1.21.1)
Requirement already satisfied: six>=1.9 in ./anaconda3/lib/python3.6/site-packages (from protobuf>=3.5.0.post1->grpcio-tools) (1.11.0)
Requirement already satisfied: setuptools in ./anaconda3/lib/python3.6/site-packages (from protobuf>=3.5.0.post1->grpcio-tools) (39.1.0)
Installing collected packages: grpcio-tools
Successfully installed grpcio-tools-1.21.1
bash-3.2$ pip list | grep grpcio
grpcio 1.21.1
grpcio-tools 1.21.1

 

 

 

gRPCサンプルのダウンロード

gitでgRPCのサンプルをダウンロード(git clone)します。 

こちらも、クライアント・サーバともに操作内容は同じです。

bash-3.2$ git clone -b v1.21.0 https://github.com/grpc/grpc
Cloning into 'grpc'...
remote: Enumerating objects: 24, done.
remote: Counting objects: 100% (24/24), done.
remote: Compressing objects: 100% (6/6), done.
remote: Total 447872 (delta 19), reused 19 (delta 18), pack-reused 447848
Receiving objects: 100% (447872/447872), 203.35 MiB | 10.68 MiB/s, done.
Resolving deltas: 100% (348374/348374), done.
Note: checking out '7569ba7a66a2b4dd93b04ad355cc401d06285ee7'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

git checkout -b <new-branch-name>

Checking out files: 100% (10137/10137), done.
bash-3.2$ ls
grpc
bash-3.2$ ls grpc/ ・・・ダウンロードされたディレクトリ
AUTHORS TROUBLESHOOTING.md grpc.bzl
BUILD WORKSPACE grpc.def
BUILD.gn bazel grpc.gemspec
BUILDING.md build.yaml grpc.gyp
CMakeLists.txt build_config.rb include
CODE-OF-CONDUCT.md cmake package.xml
CONCEPTS.md composer.json requirements.bazel.txt
CONTRIBUTING.md config.m4 requirements.txt
Gemfile config.w32 setup.cfg
LICENSE doc setup.py
MANIFEST.md etc src
Makefile examples summerofcode
NOTICE.txt gRPC-C++.podspec templates
OWNERS gRPC-Core.podspec test
PYTHON-MANIFEST.in gRPC-ProtoRPC.podspec third_party
README.md gRPC-RxLibrary.podspec tools
Rakefile gRPC.podspec
bash-3.2$ ls grpc/examples/ ・・・サンプルコードが格納されているディレクトリ
BUILD cpp objective-c python
README.md csharp php ruby
android node protos
bash-3.2$ ls grpc/examples/python/ ・・・Pythonのサンプルコード
README.md helloworld metadata multiprocessing wait_for_ready
errors interceptors multiplex route_guide
bash-3.2$ ls grpc/examples/python/helloworld/ ・・・HelloWorldのサンプルコード
README.md greeter_server_with_reflection.py
greeter_client.py helloworld_pb2.py
greeter_client_with_options.py helloworld_pb2_grpc.py
greeter_server.py

 

 

 

gRPCの実行(サーバ)

サーバで、gRPCのHello Worldサンプルコード(Python)を実行します。

実行するのは、grpc/examples/python/helloworld/ にある「greeter_server.py」です。

クライアントからのアクセスがあると、「Hello, ユーザー名!」というシンプルなメッセージを返してくれます。

[root@localhost ~]# cat grpc/examples/protos/helloworld.proto
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

syntax = "proto3";

option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto";
option objc_class_prefix = "HLW";

package helloworld;

// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
}

// The request message containing the user's name.
message HelloRequest {
string name = 1;
}

// The response message containing the greetings
message HelloReply {
string message = 1;
}

 

 コード実行後、TCP/50051が解放されています。

[root@localhost ~]# python3.6 grpc/examples/python/helloworld/greeter_server.py

[root@localhost ~]# ss -tanl ※別のターミナルから実行
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 :::50051 :::*

 

 

 

 gRPCの実行(クライアント)

続いて、クライアントからgRPCを実行します。

 なお、用意されているgreeter_client.pyはデフォルトでは以下のように書かれています。

・「localhost:50051」へアクセス

・ユーザー名は「you」

 

なので、それぞれサーバのIPアドレス、適当なユーザーめいへ変更します。

※30行目と32行目が変更箇所。

bash-3.2$ vi /Users/beatmania/GitHub/beatmania/grpc/examples/python/helloworld/greeter_client.py
bash-3.2$ cat -n /Users/beatmania/GitHub/beatmania/grpc/examples/python/helloworld/greeter_client.py
1 # Copyright 2015 gRPC authors.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 """The Python implementation of the GRPC helloworld.Greeter client."""
15
16 from __future__ import print_function
17 import logging
18
19 import grpc
20
21 import helloworld_pb2
22 import helloworld_pb2_grpc
23
24
25 def run():
26 # NOTE(gRPC Python Team): .close() is possible on a channel and should be
27 # used in circumstances in which the with statement does not fit the needs
28 # of the code.
29 #with grpc.insecure_channel('localhost:50051') as channel:
30 with grpc.insecure_channel('192.168.10.61:50051') as channel:
31 stub = helloworld_pb2_grpc.GreeterStub(channel)
32 response = stub.SayHello(helloworld_pb2.HelloRequest(name='submattnesk'))
33 print("Greeter client received: " + response.message)
34
35
36 if __name__ == '__main__':
37 logging.basicConfig()
38 run()

 

クライアントコードを実行すると、想定通り「Hello, submattnesk!」と返されました。

bash-3.2$ python /Users/beatmania/GitHub/beatmania/grpc/examples/python/helloworld/greeter_client.py
Greeter client received: Hello, submattnesk!

 

 

 

パケットキャプチャ

通信中のキャプチャーも取得してみました。

こちらの方が、やりとりされているメッセージは読みやすいですね。

packet capture1

packet capture2

 

 

 

おわりに

今回はチュートリアル通りにgRPCを体験してみましたが、

nginxでは1.13.10よりgRPC proxy機能が追加されました。

nginx mainline 1.13.10 リリース! - Opensourcetechブログ

 

なので、次回はnginxでgRPC proxyをやってみたいところです!

https://www.nginx.com/blog/nginx-1-13-10-grpc/

nginx gRPC1

nginx gRPC2

nginx gRPC3

 

 

参考にしたサイト

 https://grpc.io/

https://grpc.io/docs/guides/concepts/

https://grpc.io/docs/#install-grpc

https://grpc.io/docs/quickstart/python/

 

アフィリエイトのアクセストレード

 

 

 

 

 

 

www.slideshare.net

github.com

www.facebook.com

twitter.com

www.instagram.com

 

 

にほんブログ村 IT技術ブログ Linuxへ
Linux

にほんブログ村 IT技術ブログ オープンソースへ
オープンソース

 

 

Opensourcetech by Takahiro Kujirai