CSE224 - RPC
Introduction
Remote Procedure Call (RPC) is a way for a program to call a function defined on a different computer as if it were calling a local function.
Issues:
- A remote machine might use a different language, so it represent data types using different sizes.
- Use a different byte ordering (endianness).
- Have different data alignment requirements.
- Represent floating point numbers differently.
Interface Description Language (IDL)
Mechanism to pass procedure parameters and return values in a machine and language independent way.
Protobuf
Protocol Buffers (protobuf) is a language-neutral format for defining structured data by gPRC.
1 |
|
.proto
file defines
- Service APIs (rpc methods)
- Message formats
Then run protoc --go_out=. --go-grpc_out=. your_file.proto
will generate
- Client stub code (for calling SendNumber)
- Server stub code (for implementing SendNumber)
- Marshalling code (for turning NumberEntry into bytes and back)
Workflow
- Client calls stub function
- Stub marshals parameters to a network message
- OS sends a network message to the server
- Server OS receives message, sends it up to stub
- Server stub unmarshals params, calls server function
- Server function runs, returns a value
- Server stub marshals the return value, sends msg
- Server OS sends the reply back across the network
- Client OS receives the reply and passes up to stub
- Client stub unmarshals return value, returns to client
Example
Building a Replicated KV Store:
- To run the system, run the code in each node machine.
- Each node is both a server and a client, server is run by a go routine, client is also run by a go routine.
- The server code listens to rpc calls from other nodes
- The client code interprets commands, and handle the command by sending rpc
Define the proto file:
1 |
|
Then, protoc --go_out=. --go-grpc_out=. rkvs.proto
will generate a pb package with:
- RKVSServiceServer interface for the server to implement
1 |
|
- RKVSServiceClient for calling remote methods
1
2
3
4type RKVSServiceClient interface {
Replicate(ctx context.Context, in *ReplicateRequest, opts ...grpc.CallOption) (*ReplicateResponse, error)
Stop(ctx context.Context, in *StopRequest, opts ...grpc.CallOption) (*StopResponse, error)
}
Implement the gRPC Server in Go:
After defining a service, we need to implement rpc functions.
1 |
|
pb.UnimplementedRKVSServiceServer
: It contains default (empty) implementations of all the methods declared in your .proto file. Since your server struct must implement all methods defined in the .proto file’s service section to satisfy the RKVSServiceServer interface. But often, you only want to implement some of them. So when you include pb.UnimplementedRKVSServiceServer
, your struct now inherits those defaults, and you only need to override the ones you care about.
Start the gRPC Server
1 |
|
Make gRPC Requests as a Client
1 |
|