grpc

package
v0.0.0-...-3056823 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 27, 2016 License: Apache-2.0, BSD-3-Clause Imports: 28 Imported by: 0

Documentation

Overview

Package grpc implements an RPC system called gRPC.

See www.grpc.io for more information about gRPC.

Index

Constants

View Source
const SupportPackageIsVersion3 = true

SupportPackageIsVersion3 is referenced from generated protocol buffer files to assert that that code is compatible with this version of the grpc package.

This constant may be renamed in the future if a change in the generated code requires a synchronised update of grpc-go and protoc-gen-go. This constant should not be referenced from any other code.

Variables

View Source
var (
	// ErrClientConnClosing indicates that the operation is illegal because
	// the ClientConn is closing.
	ErrClientConnClosing = errors.New("grpc: the client connection is closing")
	// ErrClientConnTimeout indicates that the ClientConn cannot establish the
	// underlying connections within the specified timeout.
	ErrClientConnTimeout = errors.New("grpc: timed out when dialing")
)
View Source
var (
	DefaultBackoffConfig = BackoffConfig{
		MaxDelay: 120 * time.Second,
		// contains filtered or unexported fields
	}
)

DefaultBackoffConfig uses values specified for backoff in https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md.

View Source
var EnableTracing = true

EnableTracing controls whether to trace RPCs using the golang.org/x/net/trace package. This should only be set before any RPCs are sent or received by this program.

View Source
var (
	// ErrServerStopped indicates that the operation is now illegal because of
	// the server being stopped.
	ErrServerStopped = errors.New("grpc: the server has been stopped")
)

Functions

func Code

func Code(err error) codes.Code

Code returns the error code for err if it was produced by the rpc system. Otherwise, it returns codes.Unknown.

func ErrorDesc

func ErrorDesc(err error) string

ErrorDesc returns the error description of err if it was produced by the rpc system. Otherwise, it returns err.Error() or empty string when err is nil.

func Errorf

func Errorf(c codes.Code, format string, a ...interface{}) error

Errorf returns an error containing an error code and a description; Errorf returns nil if c is OK.

func Invoke

func Invoke(ctx context.Context, method string, args, reply interface{}, cc *ClientConn, opts ...CallOption) (err error)

Invoke sends the RPC request on the wire and returns after response is received. Invoke is called by generated code. Also users can call Invoke directly when it is really needed in their use cases.

func SendHeader

func SendHeader(ctx context.Context, md metadata.MD) error

SendHeader sends header metadata. It may be called at most once from a unary RPC handler. The ctx is the RPC handler's Context or one derived from it.

func SetTrailer

func SetTrailer(ctx context.Context, md metadata.MD) error

SetTrailer sets the trailer metadata that will be sent when an RPC returns. It may be called at most once from a unary RPC handler. The ctx is the RPC handler's Context or one derived from it.

Types

type Address

type Address struct {
	// Addr is the server address on which a connection will be established.
	Addr string
	// Metadata is the information associated with Addr, which may be used
	// to make load balancing decision.
	Metadata interface{}
}

Address represents a server the client connects to. This is the EXPERIMENTAL API and may be changed or extended in the future.

type BackoffConfig

type BackoffConfig struct {
	// MaxDelay is the upper bound of backoff delay.
	MaxDelay time.Duration
	// contains filtered or unexported fields
}

BackoffConfig defines the parameters for the default gRPC backoff strategy.

type Balancer

type Balancer interface {
	// Start does the initialization work to bootstrap a Balancer. For example,
	// this function may start the name resolution and watch the updates. It will
	// be called when dialing.
	Start(target string) error
	// Up informs the Balancer that gRPC has a connection to the server at
	// addr. It returns down which is called once the connection to addr gets
	// lost or closed.
	// TODO: It is not clear how to construct and take advantage the meaningful error
	// parameter for down. Need realistic demands to guide.
	Up(addr Address) (down func(error))
	// Get gets the address of a server for the RPC corresponding to ctx.
	// i) If it returns a connected address, gRPC internals issues the RPC on the
	// connection to this address;
	// ii) If it returns an address on which the connection is under construction
	// (initiated by Notify(...)) but not connected, gRPC internals
	//  * fails RPC if the RPC is fail-fast and connection is in the TransientFailure or
	//  Shutdown state;
	//  or
	//  * issues RPC on the connection otherwise.
	// iii) If it returns an address on which the connection does not exist, gRPC
	// internals treats it as an error and will fail the corresponding RPC.
	//
	// Therefore, the following is the recommended rule when writing a custom Balancer.
	// If opts.BlockingWait is true, it should return a connected address or
	// block if there is no connected address. It should respect the timeout or
	// cancellation of ctx when blocking. If opts.BlockingWait is false (for fail-fast
	// RPCs), it should return an address it has notified via Notify(...) immediately
	// instead of blocking.
	//
	// The function returns put which is called once the rpc has completed or failed.
	// put can collect and report RPC stats to a remote load balancer.
	//
	// This function should only return the errors Balancer cannot recover by itself.
	// gRPC internals will fail the RPC if an error is returned.
	Get(ctx context.Context, opts BalancerGetOptions) (addr Address, put func(), err error)
	// Notify returns a channel that is used by gRPC internals to watch the addresses
	// gRPC needs to connect. The addresses might be from a name resolver or remote
	// load balancer. gRPC internals will compare it with the existing connected
	// addresses. If the address Balancer notified is not in the existing connected
	// addresses, gRPC starts to connect the address. If an address in the existing
	// connected addresses is not in the notification list, the corresponding connection
	// is shutdown gracefully. Otherwise, there are no operations to take. Note that
	// the Address slice must be the full list of the Addresses which should be connected.
	// It is NOT delta.
	Notify() <-chan []Address
	// Close shuts down the balancer.
	Close() error
}

Balancer chooses network addresses for RPCs. This is the EXPERIMENTAL API and may be changed or extended in the future.

func RoundRobin

func RoundRobin(r naming.Resolver) Balancer

RoundRobin returns a Balancer that selects addresses round-robin. It uses r to watch the name resolution updates and updates the addresses available correspondingly.

type BalancerGetOptions

type BalancerGetOptions struct {
	// BlockingWait specifies whether Get should block when there is no
	// connected address.
	BlockingWait bool
}

BalancerGetOptions configures a Get call. This is the EXPERIMENTAL API and may be changed or extended in the future.

type CallOption

type CallOption interface {
	// contains filtered or unexported methods
}

CallOption configures a Call before it starts or extracts information from a Call after it completes.

func FailFast

func FailFast(failFast bool) CallOption

FailFast configures the action to take when an RPC is attempted on broken connections or unreachable servers. If failfast is true, the RPC will fail immediately. Otherwise, the RPC client will block the call until a connection is available (or the call is canceled or times out) and will retry the call if it fails due to a transient error. Please refer to https://github.com/grpc/grpc/blob/master/doc/fail_fast.md

func Header(md *metadata.MD) CallOption

Header returns a CallOptions that retrieves the header metadata for a unary RPC.

func Trailer

func Trailer(md *metadata.MD) CallOption

Trailer returns a CallOptions that retrieves the trailer metadata for a unary RPC.

type ClientConn

type ClientConn struct {
	// contains filtered or unexported fields
}

ClientConn represents a client connection to an RPC server.

func Dial

func Dial(target string, opts ...DialOption) (*ClientConn, error)

Dial creates a client connection the given target.

func (*ClientConn) Close

func (cc *ClientConn) Close() error

Close tears down the ClientConn and all underlying connections.

type ClientStream

type ClientStream interface {
	// Header returns the header metadata received from the server if there
	// is any. It blocks if the metadata is not ready to read.
	Header() (metadata.MD, error)
	// Trailer returns the trailer metadata from the server. It must be called
	// after stream.Recv() returns non-nil error (including io.EOF) for
	// bi-directional streaming and server streaming or stream.CloseAndRecv()
	// returns for client streaming in order to receive trailer metadata if
	// present. Otherwise, it could returns an empty MD even though trailer
	// is present.
	Trailer() metadata.MD
	// CloseSend closes the send direction of the stream. It closes the stream
	// when non-nil error is met.
	CloseSend() error
	Stream
}

ClientStream defines the interface a client stream has to satisfy.

func NewClientStream

func NewClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (ClientStream, error)

NewClientStream creates a new Stream for the client side. This is called by generated code.

type Codec

type Codec interface {
	// Marshal returns the wire format of v.
	Marshal(v interface{}) ([]byte, error)
	// Unmarshal parses the wire format into v.
	Unmarshal(data []byte, v interface{}) error
	// String returns the name of the Codec implementation. The returned
	// string will be used as part of content type in transmission.
	String() string
}

Codec defines the interface gRPC uses to encode and decode messages.

type Compressor

type Compressor interface {
	// Do compresses p into w.
	Do(w io.Writer, p []byte) error
	// Type returns the compression algorithm the Compressor uses.
	Type() string
}

Compressor defines the interface gRPC uses to compress a message.

func NewGZIPCompressor

func NewGZIPCompressor() Compressor

NewGZIPCompressor creates a Compressor based on GZIP.

type ConnectivityState

type ConnectivityState int

ConnectivityState indicates the state of a client connection.

const (
	// Idle indicates the ClientConn is idle.
	Idle ConnectivityState = iota
	// Connecting indicates the ClienConn is connecting.
	Connecting
	// Ready indicates the ClientConn is ready for work.
	Ready
	// TransientFailure indicates the ClientConn has seen a failure but expects to recover.
	TransientFailure
	// Shutdown indicates the ClientConn has started shutting down.
	Shutdown
)

func (ConnectivityState) String

func (s ConnectivityState) String() string

type Decompressor

type Decompressor interface {
	// Do reads the data from r and uncompress them.
	Do(r io.Reader) ([]byte, error)
	// Type returns the compression algorithm the Decompressor uses.
	Type() string
}

Decompressor defines the interface gRPC uses to decompress a message.

func NewGZIPDecompressor

func NewGZIPDecompressor() Decompressor

NewGZIPDecompressor creates a Decompressor based on GZIP.

type DialOption

type DialOption func(*dialOptions)

DialOption configures how we set up the connection.

func WithBackoffConfig

func WithBackoffConfig(b BackoffConfig) DialOption

WithBackoffConfig configures the dialer to use the provided backoff parameters after connection failures.

Use WithBackoffMaxDelay until more parameters on BackoffConfig are opened up for use.

func WithBackoffMaxDelay

func WithBackoffMaxDelay(md time.Duration) DialOption

WithBackoffMaxDelay configures the dialer to use the provided maximum delay when backing off after failed connection attempts.

func WithBalancer

func WithBalancer(b Balancer) DialOption

WithBalancer returns a DialOption which sets a load balancer.

func WithBlock

func WithBlock() DialOption

WithBlock returns a DialOption which makes caller of Dial blocks until the underlying connection is up. Without this, Dial returns immediately and connecting the server happens in background.

func WithCodec

func WithCodec(c Codec) DialOption

WithCodec returns a DialOption which sets a codec for message marshaling and unmarshaling.

func WithCompressor

func WithCompressor(cp Compressor) DialOption

WithCompressor returns a DialOption which sets a CompressorGenerator for generating message compressor.

func WithDecompressor

func WithDecompressor(dc Decompressor) DialOption

WithDecompressor returns a DialOption which sets a DecompressorGenerator for generating message decompressor.

func WithDialer

func WithDialer(f func(addr string, timeout time.Duration) (net.Conn, error)) DialOption

WithDialer returns a DialOption that specifies a function to use for dialing network addresses.

func WithInsecure

func WithInsecure() DialOption

WithInsecure returns a DialOption which disables transport security for this ClientConn. Note that transport security is required unless WithInsecure is set.

func WithPerRPCCredentials

func WithPerRPCCredentials(creds credentials.PerRPCCredentials) DialOption

WithPerRPCCredentials returns a DialOption which sets credentials which will place auth state on each outbound RPC.

func WithTimeout

func WithTimeout(d time.Duration) DialOption

WithTimeout returns a DialOption that configures a timeout for dialing a ClientConn initially. This is valid if and only if WithBlock() is present.

func WithTransportCredentials

func WithTransportCredentials(creds credentials.TransportCredentials) DialOption

WithTransportCredentials returns a DialOption which configures a connection level security credentials (e.g., TLS/SSL).

func WithUserAgent

func WithUserAgent(s string) DialOption

WithUserAgent returns a DialOption that specifies a user agent string for all the RPCs.

type MethodDesc

type MethodDesc struct {
	MethodName string
	Handler    methodHandler
}

MethodDesc represents an RPC service's method specification.

type MethodInfo

type MethodInfo struct {
	// Name is the method name only, without the service name or package name.
	Name string
	// IsClientStream indicates whether the RPC is a client streaming RPC.
	IsClientStream bool
	// IsServerStream indicates whether the RPC is a server streaming RPC.
	IsServerStream bool
}

MethodInfo contains the information of an RPC including its method name and type.

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server is a gRPC server to serve RPC requests.

func NewServer

func NewServer(opt ...ServerOption) *Server

NewServer creates a gRPC server which has no service registered and has not started to accept requests yet.

func (*Server) GetServiceInfo

func (s *Server) GetServiceInfo() map[string]*ServiceInfo

GetServiceInfo returns a map from service names to ServiceInfo. Service names include the package names, in the form of <package>.<service>.

func (*Server) RegisterService

func (s *Server) RegisterService(sd *ServiceDesc, ss interface{})

RegisterService register a service and its implementation to the gRPC server. Called from the IDL generated code. This must be called before invoking Serve.

func (*Server) Serve

func (s *Server) Serve(lis net.Listener) error

Serve accepts incoming connections on the listener lis, creating a new ServerTransport and service goroutine for each. The service goroutines read gRPC requests and then call the registered handlers to reply to them. Service returns when lis.Accept fails. lis will be closed when this method returns.

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Server) Stop

func (s *Server) Stop()

Stop stops the gRPC server. It immediately closes all open connections and listeners. It cancels all active RPCs on the server side and the corresponding pending RPCs on the client side will get notified by connection errors.

type ServerOption

type ServerOption func(*options)

A ServerOption sets options.

func Creds

Creds returns a ServerOption that sets credentials for server connections.

func CustomCodec

func CustomCodec(codec Codec) ServerOption

CustomCodec returns a ServerOption that sets a codec for message marshaling and unmarshaling.

func MaxConcurrentStreams

func MaxConcurrentStreams(n uint32) ServerOption

MaxConcurrentStreams returns a ServerOption that will apply a limit on the number of concurrent streams to each ServerTransport.

func RPCCompressor

func RPCCompressor(cp Compressor) ServerOption

RPCCompressor returns a ServerOption that sets a compressor for outbound message.

func RPCDecompressor

func RPCDecompressor(dc Decompressor) ServerOption

RPCDecompressor returns a ServerOption that sets a decompressor for inbound message.

func StreamInterceptor

func StreamInterceptor(i StreamServerInterceptor) ServerOption

StreamInterceptor returns a ServerOption that sets the StreamServerInterceptor for the server. Only one stream interceptor can be installed.

func UnaryInterceptor

func UnaryInterceptor(i UnaryServerInterceptor) ServerOption

UnaryInterceptor returns a ServerOption that sets the UnaryServerInterceptor for the server. Only one unary interceptor can be installed. The construction of multiple interceptors (e.g., chaining) can be implemented at the caller.

type ServerStream

type ServerStream interface {
	// SendHeader sends the header metadata. It should not be called
	// after SendProto. It fails if called multiple times or if
	// called after SendProto.
	SendHeader(metadata.MD) error
	// SetTrailer sets the trailer metadata which will be sent with the
	// RPC status.
	SetTrailer(metadata.MD)
	Stream
}

ServerStream defines the interface a server stream has to satisfy.

type ServiceDesc

type ServiceDesc struct {
	ServiceName string
	// The pointer to the service interface. Used to check whether the user
	// provided implementation satisfies the interface requirements.
	HandlerType interface{}
	Methods     []MethodDesc
	Streams     []StreamDesc
	Metadata    interface{}
}

ServiceDesc represents an RPC service's specification.

type ServiceInfo

type ServiceInfo struct {
	Methods []MethodInfo
	// Metadata is the metadata specified in ServiceDesc when registering service.
	Metadata interface{}
}

ServiceInfo contains unary RPC method info, streaming RPC methid info and metadata for a service.

type Stream

type Stream interface {
	// Context returns the context for this stream.
	Context() context.Context
	// SendMsg blocks until it sends m, the stream is done or the stream
	// breaks.
	// On error, it aborts the stream and returns an RPC status on client
	// side. On server side, it simply returns the error to the caller.
	// SendMsg is called by generated code. Also Users can call SendMsg
	// directly when it is really needed in their use cases.
	SendMsg(m interface{}) error
	// RecvMsg blocks until it receives a message or the stream is
	// done. On client side, it returns io.EOF when the stream is done. On
	// any other error, it aborts the stream and returns an RPC status. On
	// server side, it simply returns the error to the caller.
	RecvMsg(m interface{}) error
}

Stream defines the common interface a client or server stream has to satisfy.

type StreamDesc

type StreamDesc struct {
	StreamName string
	Handler    StreamHandler

	// At least one of these is true.
	ServerStreams bool
	ClientStreams bool
}

StreamDesc represents a streaming RPC service's method specification.

type StreamHandler

type StreamHandler func(srv interface{}, stream ServerStream) error

StreamHandler defines the handler called by gRPC server to complete the execution of a streaming RPC.

type StreamServerInfo

type StreamServerInfo struct {
	// FullMethod is the full RPC method string, i.e., /package.service/method.
	FullMethod string
	// IsClientStream indicates whether the RPC is a client streaming RPC.
	IsClientStream bool
	// IsServerStream indicates whether the RPC is a server streaming RPC.
	IsServerStream bool
}

StreamServerInfo consists of various information about a streaming RPC on server side. All per-rpc information may be mutated by the interceptor.

type StreamServerInterceptor

type StreamServerInterceptor func(srv interface{}, ss ServerStream, info *StreamServerInfo, handler StreamHandler) error

StreamServerInterceptor provides a hook to intercept the execution of a streaming RPC on the server. info contains all the information of this RPC the interceptor can operate on. And handler is the service method implementation. It is the responsibility of the interceptor to invoke handler to complete the RPC.

type UnaryHandler

type UnaryHandler func(ctx context.Context, req interface{}) (interface{}, error)

UnaryHandler defines the handler invoked by UnaryServerInterceptor to complete the normal execution of a unary RPC.

type UnaryServerInfo

type UnaryServerInfo struct {
	// Server is the service implementation the user provides. This is read-only.
	Server interface{}
	// FullMethod is the full RPC method string, i.e., /package.service/method.
	FullMethod string
}

UnaryServerInfo consists of various information about a unary RPC on server side. All per-rpc information may be mutated by the interceptor.

type UnaryServerInterceptor

type UnaryServerInterceptor func(ctx context.Context, req interface{}, info *UnaryServerInfo, handler UnaryHandler) (resp interface{}, err error)

UnaryServerInterceptor provides a hook to intercept the execution of a unary RPC on the server. info contains all the information of this RPC the interceptor can operate on. And handler is the wrapper of the service method implementation. It is the responsibility of the interceptor to invoke handler to complete the RPC.

Directories

Path Synopsis
Package codes defines the canonical error codes used by gRPC.
Package codes defines the canonical error codes used by gRPC.
Package credentials implements various credentials supported by gRPC library, which encapsulate all the state needed by a client to authenticate with a server and make various assertions, e.g., about the client's identity, role, or whether it is authorized to make a particular call.
Package credentials implements various credentials supported by gRPC library, which encapsulate all the state needed by a client to authenticate with a server and make various assertions, e.g., about the client's identity, role, or whether it is authorized to make a particular call.
Package grpclog defines logging for grpc.
Package grpclog defines logging for grpc.
Package internal contains gRPC-internal code for testing, to avoid polluting the godoc of the top-level grpc package.
Package internal contains gRPC-internal code for testing, to avoid polluting the godoc of the top-level grpc package.
Package metadata define the structure of the metadata supported by gRPC library.
Package metadata define the structure of the metadata supported by gRPC library.
Package naming defines the naming API and related data structures for gRPC.
Package naming defines the naming API and related data structures for gRPC.
Package peer defines various peer information associated with RPCs and corresponding utils.
Package peer defines various peer information associated with RPCs and corresponding utils.
Package transport defines and implements message oriented communication channel to complete various transactions (e.g., an RPC).
Package transport defines and implements message oriented communication channel to complete various transactions (e.g., an RPC).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL