blob: 86f00e5a2d1ff0e10e4b4059cf5d4ed85da81427 [file] [log] [blame]
khenaidooac637102019-01-14 15:44:34 -05001/*
2 *
3 * Copyright 2014 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 *
17 */
18
19package grpc
20
21import (
22 "bytes"
23 "compress/gzip"
24 "context"
25 "encoding/binary"
26 "fmt"
27 "io"
28 "io/ioutil"
29 "math"
30 "net/url"
31 "strings"
32 "sync"
33 "time"
34
35 "google.golang.org/grpc/codes"
36 "google.golang.org/grpc/credentials"
37 "google.golang.org/grpc/encoding"
38 "google.golang.org/grpc/encoding/proto"
39 "google.golang.org/grpc/internal/transport"
40 "google.golang.org/grpc/metadata"
41 "google.golang.org/grpc/peer"
42 "google.golang.org/grpc/stats"
43 "google.golang.org/grpc/status"
44)
45
46// Compressor defines the interface gRPC uses to compress a message.
47//
48// Deprecated: use package encoding.
49type Compressor interface {
50 // Do compresses p into w.
51 Do(w io.Writer, p []byte) error
52 // Type returns the compression algorithm the Compressor uses.
53 Type() string
54}
55
56type gzipCompressor struct {
57 pool sync.Pool
58}
59
60// NewGZIPCompressor creates a Compressor based on GZIP.
61//
62// Deprecated: use package encoding/gzip.
63func NewGZIPCompressor() Compressor {
64 c, _ := NewGZIPCompressorWithLevel(gzip.DefaultCompression)
65 return c
66}
67
68// NewGZIPCompressorWithLevel is like NewGZIPCompressor but specifies the gzip compression level instead
69// of assuming DefaultCompression.
70//
71// The error returned will be nil if the level is valid.
72//
73// Deprecated: use package encoding/gzip.
74func NewGZIPCompressorWithLevel(level int) (Compressor, error) {
75 if level < gzip.DefaultCompression || level > gzip.BestCompression {
76 return nil, fmt.Errorf("grpc: invalid compression level: %d", level)
77 }
78 return &gzipCompressor{
79 pool: sync.Pool{
80 New: func() interface{} {
81 w, err := gzip.NewWriterLevel(ioutil.Discard, level)
82 if err != nil {
83 panic(err)
84 }
85 return w
86 },
87 },
88 }, nil
89}
90
91func (c *gzipCompressor) Do(w io.Writer, p []byte) error {
92 z := c.pool.Get().(*gzip.Writer)
93 defer c.pool.Put(z)
94 z.Reset(w)
95 if _, err := z.Write(p); err != nil {
96 return err
97 }
98 return z.Close()
99}
100
101func (c *gzipCompressor) Type() string {
102 return "gzip"
103}
104
105// Decompressor defines the interface gRPC uses to decompress a message.
106//
107// Deprecated: use package encoding.
108type Decompressor interface {
109 // Do reads the data from r and uncompress them.
110 Do(r io.Reader) ([]byte, error)
111 // Type returns the compression algorithm the Decompressor uses.
112 Type() string
113}
114
115type gzipDecompressor struct {
116 pool sync.Pool
117}
118
119// NewGZIPDecompressor creates a Decompressor based on GZIP.
120//
121// Deprecated: use package encoding/gzip.
122func NewGZIPDecompressor() Decompressor {
123 return &gzipDecompressor{}
124}
125
126func (d *gzipDecompressor) Do(r io.Reader) ([]byte, error) {
127 var z *gzip.Reader
128 switch maybeZ := d.pool.Get().(type) {
129 case nil:
130 newZ, err := gzip.NewReader(r)
131 if err != nil {
132 return nil, err
133 }
134 z = newZ
135 case *gzip.Reader:
136 z = maybeZ
137 if err := z.Reset(r); err != nil {
138 d.pool.Put(z)
139 return nil, err
140 }
141 }
142
143 defer func() {
144 z.Close()
145 d.pool.Put(z)
146 }()
147 return ioutil.ReadAll(z)
148}
149
150func (d *gzipDecompressor) Type() string {
151 return "gzip"
152}
153
154// callInfo contains all related configuration and information about an RPC.
155type callInfo struct {
156 compressorType string
157 failFast bool
158 stream ClientStream
159 maxReceiveMessageSize *int
160 maxSendMessageSize *int
161 creds credentials.PerRPCCredentials
162 contentSubtype string
163 codec baseCodec
164 maxRetryRPCBufferSize int
165}
166
167func defaultCallInfo() *callInfo {
168 return &callInfo{
169 failFast: true,
170 maxRetryRPCBufferSize: 256 * 1024, // 256KB
171 }
172}
173
174// CallOption configures a Call before it starts or extracts information from
175// a Call after it completes.
176type CallOption interface {
177 // before is called before the call is sent to any server. If before
178 // returns a non-nil error, the RPC fails with that error.
179 before(*callInfo) error
180
181 // after is called after the call has completed. after cannot return an
182 // error, so any failures should be reported via output parameters.
183 after(*callInfo)
184}
185
186// EmptyCallOption does not alter the Call configuration.
187// It can be embedded in another structure to carry satellite data for use
188// by interceptors.
189type EmptyCallOption struct{}
190
191func (EmptyCallOption) before(*callInfo) error { return nil }
192func (EmptyCallOption) after(*callInfo) {}
193
194// Header returns a CallOptions that retrieves the header metadata
195// for a unary RPC.
196func Header(md *metadata.MD) CallOption {
197 return HeaderCallOption{HeaderAddr: md}
198}
199
200// HeaderCallOption is a CallOption for collecting response header metadata.
201// The metadata field will be populated *after* the RPC completes.
202// This is an EXPERIMENTAL API.
203type HeaderCallOption struct {
204 HeaderAddr *metadata.MD
205}
206
207func (o HeaderCallOption) before(c *callInfo) error { return nil }
208func (o HeaderCallOption) after(c *callInfo) {
209 if c.stream != nil {
210 *o.HeaderAddr, _ = c.stream.Header()
211 }
212}
213
214// Trailer returns a CallOptions that retrieves the trailer metadata
215// for a unary RPC.
216func Trailer(md *metadata.MD) CallOption {
217 return TrailerCallOption{TrailerAddr: md}
218}
219
220// TrailerCallOption is a CallOption for collecting response trailer metadata.
221// The metadata field will be populated *after* the RPC completes.
222// This is an EXPERIMENTAL API.
223type TrailerCallOption struct {
224 TrailerAddr *metadata.MD
225}
226
227func (o TrailerCallOption) before(c *callInfo) error { return nil }
228func (o TrailerCallOption) after(c *callInfo) {
229 if c.stream != nil {
230 *o.TrailerAddr = c.stream.Trailer()
231 }
232}
233
234// Peer returns a CallOption that retrieves peer information for a unary RPC.
235// The peer field will be populated *after* the RPC completes.
236func Peer(p *peer.Peer) CallOption {
237 return PeerCallOption{PeerAddr: p}
238}
239
240// PeerCallOption is a CallOption for collecting the identity of the remote
241// peer. The peer field will be populated *after* the RPC completes.
242// This is an EXPERIMENTAL API.
243type PeerCallOption struct {
244 PeerAddr *peer.Peer
245}
246
247func (o PeerCallOption) before(c *callInfo) error { return nil }
248func (o PeerCallOption) after(c *callInfo) {
249 if c.stream != nil {
250 if x, ok := peer.FromContext(c.stream.Context()); ok {
251 *o.PeerAddr = *x
252 }
253 }
254}
255
256// FailFast configures the action to take when an RPC is attempted on broken
257// connections or unreachable servers. If failFast is true, the RPC will fail
258// immediately. Otherwise, the RPC client will block the call until a
259// connection is available (or the call is canceled or times out) and will
260// retry the call if it fails due to a transient error. gRPC will not retry if
261// data was written to the wire unless the server indicates it did not process
262// the data. Please refer to
263// https://github.com/grpc/grpc/blob/master/doc/wait-for-ready.md.
264//
265// By default, RPCs are "Fail Fast".
266func FailFast(failFast bool) CallOption {
267 return FailFastCallOption{FailFast: failFast}
268}
269
270// FailFastCallOption is a CallOption for indicating whether an RPC should fail
271// fast or not.
272// This is an EXPERIMENTAL API.
273type FailFastCallOption struct {
274 FailFast bool
275}
276
277func (o FailFastCallOption) before(c *callInfo) error {
278 c.failFast = o.FailFast
279 return nil
280}
281func (o FailFastCallOption) after(c *callInfo) {}
282
283// MaxCallRecvMsgSize returns a CallOption which sets the maximum message size the client can receive.
284func MaxCallRecvMsgSize(s int) CallOption {
285 return MaxRecvMsgSizeCallOption{MaxRecvMsgSize: s}
286}
287
288// MaxRecvMsgSizeCallOption is a CallOption that indicates the maximum message
289// size the client can receive.
290// This is an EXPERIMENTAL API.
291type MaxRecvMsgSizeCallOption struct {
292 MaxRecvMsgSize int
293}
294
295func (o MaxRecvMsgSizeCallOption) before(c *callInfo) error {
296 c.maxReceiveMessageSize = &o.MaxRecvMsgSize
297 return nil
298}
299func (o MaxRecvMsgSizeCallOption) after(c *callInfo) {}
300
301// MaxCallSendMsgSize returns a CallOption which sets the maximum message size the client can send.
302func MaxCallSendMsgSize(s int) CallOption {
303 return MaxSendMsgSizeCallOption{MaxSendMsgSize: s}
304}
305
306// MaxSendMsgSizeCallOption is a CallOption that indicates the maximum message
307// size the client can send.
308// This is an EXPERIMENTAL API.
309type MaxSendMsgSizeCallOption struct {
310 MaxSendMsgSize int
311}
312
313func (o MaxSendMsgSizeCallOption) before(c *callInfo) error {
314 c.maxSendMessageSize = &o.MaxSendMsgSize
315 return nil
316}
317func (o MaxSendMsgSizeCallOption) after(c *callInfo) {}
318
319// PerRPCCredentials returns a CallOption that sets credentials.PerRPCCredentials
320// for a call.
321func PerRPCCredentials(creds credentials.PerRPCCredentials) CallOption {
322 return PerRPCCredsCallOption{Creds: creds}
323}
324
325// PerRPCCredsCallOption is a CallOption that indicates the per-RPC
326// credentials to use for the call.
327// This is an EXPERIMENTAL API.
328type PerRPCCredsCallOption struct {
329 Creds credentials.PerRPCCredentials
330}
331
332func (o PerRPCCredsCallOption) before(c *callInfo) error {
333 c.creds = o.Creds
334 return nil
335}
336func (o PerRPCCredsCallOption) after(c *callInfo) {}
337
338// UseCompressor returns a CallOption which sets the compressor used when
339// sending the request. If WithCompressor is also set, UseCompressor has
340// higher priority.
341//
342// This API is EXPERIMENTAL.
343func UseCompressor(name string) CallOption {
344 return CompressorCallOption{CompressorType: name}
345}
346
347// CompressorCallOption is a CallOption that indicates the compressor to use.
348// This is an EXPERIMENTAL API.
349type CompressorCallOption struct {
350 CompressorType string
351}
352
353func (o CompressorCallOption) before(c *callInfo) error {
354 c.compressorType = o.CompressorType
355 return nil
356}
357func (o CompressorCallOption) after(c *callInfo) {}
358
359// CallContentSubtype returns a CallOption that will set the content-subtype
360// for a call. For example, if content-subtype is "json", the Content-Type over
361// the wire will be "application/grpc+json". The content-subtype is converted
362// to lowercase before being included in Content-Type. See Content-Type on
363// https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for
364// more details.
365//
366// If CallCustomCodec is not also used, the content-subtype will be used to
367// look up the Codec to use in the registry controlled by RegisterCodec. See
368// the documentation on RegisterCodec for details on registration. The lookup
369// of content-subtype is case-insensitive. If no such Codec is found, the call
370// will result in an error with code codes.Internal.
371//
372// If CallCustomCodec is also used, that Codec will be used for all request and
373// response messages, with the content-subtype set to the given contentSubtype
374// here for requests.
375func CallContentSubtype(contentSubtype string) CallOption {
376 return ContentSubtypeCallOption{ContentSubtype: strings.ToLower(contentSubtype)}
377}
378
379// ContentSubtypeCallOption is a CallOption that indicates the content-subtype
380// used for marshaling messages.
381// This is an EXPERIMENTAL API.
382type ContentSubtypeCallOption struct {
383 ContentSubtype string
384}
385
386func (o ContentSubtypeCallOption) before(c *callInfo) error {
387 c.contentSubtype = o.ContentSubtype
388 return nil
389}
390func (o ContentSubtypeCallOption) after(c *callInfo) {}
391
392// CallCustomCodec returns a CallOption that will set the given Codec to be
393// used for all request and response messages for a call. The result of calling
394// String() will be used as the content-subtype in a case-insensitive manner.
395//
396// See Content-Type on
397// https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for
398// more details. Also see the documentation on RegisterCodec and
399// CallContentSubtype for more details on the interaction between Codec and
400// content-subtype.
401//
402// This function is provided for advanced users; prefer to use only
403// CallContentSubtype to select a registered codec instead.
404func CallCustomCodec(codec Codec) CallOption {
405 return CustomCodecCallOption{Codec: codec}
406}
407
408// CustomCodecCallOption is a CallOption that indicates the codec used for
409// marshaling messages.
410// This is an EXPERIMENTAL API.
411type CustomCodecCallOption struct {
412 Codec Codec
413}
414
415func (o CustomCodecCallOption) before(c *callInfo) error {
416 c.codec = o.Codec
417 return nil
418}
419func (o CustomCodecCallOption) after(c *callInfo) {}
420
421// MaxRetryRPCBufferSize returns a CallOption that limits the amount of memory
422// used for buffering this RPC's requests for retry purposes.
423//
424// This API is EXPERIMENTAL.
425func MaxRetryRPCBufferSize(bytes int) CallOption {
426 return MaxRetryRPCBufferSizeCallOption{bytes}
427}
428
429// MaxRetryRPCBufferSizeCallOption is a CallOption indicating the amount of
430// memory to be used for caching this RPC for retry purposes.
431// This is an EXPERIMENTAL API.
432type MaxRetryRPCBufferSizeCallOption struct {
433 MaxRetryRPCBufferSize int
434}
435
436func (o MaxRetryRPCBufferSizeCallOption) before(c *callInfo) error {
437 c.maxRetryRPCBufferSize = o.MaxRetryRPCBufferSize
438 return nil
439}
440func (o MaxRetryRPCBufferSizeCallOption) after(c *callInfo) {}
441
442// The format of the payload: compressed or not?
443type payloadFormat uint8
444
445const (
446 compressionNone payloadFormat = 0 // no compression
447 compressionMade payloadFormat = 1 // compressed
448)
449
450// parser reads complete gRPC messages from the underlying reader.
451type parser struct {
452 // r is the underlying reader.
453 // See the comment on recvMsg for the permissible
454 // error types.
455 r io.Reader
456
457 // The header of a gRPC message. Find more detail at
458 // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md
459 header [5]byte
460}
461
462// recvMsg reads a complete gRPC message from the stream.
463//
464// It returns the message and its payload (compression/encoding)
465// format. The caller owns the returned msg memory.
466//
467// If there is an error, possible values are:
468// * io.EOF, when no messages remain
469// * io.ErrUnexpectedEOF
470// * of type transport.ConnectionError
471// * an error from the status package
472// No other error values or types must be returned, which also means
473// that the underlying io.Reader must not return an incompatible
474// error.
475func (p *parser) recvMsg(maxReceiveMessageSize int) (pf payloadFormat, msg []byte, err error) {
476 if _, err := p.r.Read(p.header[:]); err != nil {
477 return 0, nil, err
478 }
479
480 pf = payloadFormat(p.header[0])
481 length := binary.BigEndian.Uint32(p.header[1:])
482
483 if length == 0 {
484 return pf, nil, nil
485 }
486 if int64(length) > int64(maxInt) {
487 return 0, nil, status.Errorf(codes.ResourceExhausted, "grpc: received message larger than max length allowed on current machine (%d vs. %d)", length, maxInt)
488 }
489 if int(length) > maxReceiveMessageSize {
490 return 0, nil, status.Errorf(codes.ResourceExhausted, "grpc: received message larger than max (%d vs. %d)", length, maxReceiveMessageSize)
491 }
492 // TODO(bradfitz,zhaoq): garbage. reuse buffer after proto decoding instead
493 // of making it for each message:
494 msg = make([]byte, int(length))
495 if _, err := p.r.Read(msg); err != nil {
496 if err == io.EOF {
497 err = io.ErrUnexpectedEOF
498 }
499 return 0, nil, err
500 }
501 return pf, msg, nil
502}
503
504// encode serializes msg and returns a buffer containing the message, or an
505// error if it is too large to be transmitted by grpc. If msg is nil, it
506// generates an empty message.
507func encode(c baseCodec, msg interface{}) ([]byte, error) {
508 if msg == nil { // NOTE: typed nils will not be caught by this check
509 return nil, nil
510 }
511 b, err := c.Marshal(msg)
512 if err != nil {
513 return nil, status.Errorf(codes.Internal, "grpc: error while marshaling: %v", err.Error())
514 }
515 if uint(len(b)) > math.MaxUint32 {
516 return nil, status.Errorf(codes.ResourceExhausted, "grpc: message too large (%d bytes)", len(b))
517 }
518 return b, nil
519}
520
521// compress returns the input bytes compressed by compressor or cp. If both
522// compressors are nil, returns nil.
523//
524// TODO(dfawley): eliminate cp parameter by wrapping Compressor in an encoding.Compressor.
525func compress(in []byte, cp Compressor, compressor encoding.Compressor) ([]byte, error) {
526 if compressor == nil && cp == nil {
527 return nil, nil
528 }
529 wrapErr := func(err error) error {
530 return status.Errorf(codes.Internal, "grpc: error while compressing: %v", err.Error())
531 }
532 cbuf := &bytes.Buffer{}
533 if compressor != nil {
534 z, err := compressor.Compress(cbuf)
535 if err != nil {
536 return nil, wrapErr(err)
537 }
538 if _, err := z.Write(in); err != nil {
539 return nil, wrapErr(err)
540 }
541 if err := z.Close(); err != nil {
542 return nil, wrapErr(err)
543 }
544 } else {
545 if err := cp.Do(cbuf, in); err != nil {
546 return nil, wrapErr(err)
547 }
548 }
549 return cbuf.Bytes(), nil
550}
551
552const (
553 payloadLen = 1
554 sizeLen = 4
555 headerLen = payloadLen + sizeLen
556)
557
558// msgHeader returns a 5-byte header for the message being transmitted and the
559// payload, which is compData if non-nil or data otherwise.
560func msgHeader(data, compData []byte) (hdr []byte, payload []byte) {
561 hdr = make([]byte, headerLen)
562 if compData != nil {
563 hdr[0] = byte(compressionMade)
564 data = compData
565 } else {
566 hdr[0] = byte(compressionNone)
567 }
568
569 // Write length of payload into buf
570 binary.BigEndian.PutUint32(hdr[payloadLen:], uint32(len(data)))
571 return hdr, data
572}
573
574func outPayload(client bool, msg interface{}, data, payload []byte, t time.Time) *stats.OutPayload {
575 return &stats.OutPayload{
576 Client: client,
577 Payload: msg,
578 Data: data,
579 Length: len(data),
580 WireLength: len(payload) + headerLen,
581 SentTime: t,
582 }
583}
584
585func checkRecvPayload(pf payloadFormat, recvCompress string, haveCompressor bool) *status.Status {
586 switch pf {
587 case compressionNone:
588 case compressionMade:
589 if recvCompress == "" || recvCompress == encoding.Identity {
590 return status.New(codes.Internal, "grpc: compressed flag set with identity or empty encoding")
591 }
592 if !haveCompressor {
593 return status.Newf(codes.Unimplemented, "grpc: Decompressor is not installed for grpc-encoding %q", recvCompress)
594 }
595 default:
596 return status.Newf(codes.Internal, "grpc: received unexpected payload format %d", pf)
597 }
598 return nil
599}
600
601type payloadInfo struct {
602 wireLength int // The compressed length got from wire.
603 uncompressedBytes []byte
604}
605
606func recvAndDecompress(p *parser, s *transport.Stream, dc Decompressor, maxReceiveMessageSize int, payInfo *payloadInfo, compressor encoding.Compressor) ([]byte, error) {
607 pf, d, err := p.recvMsg(maxReceiveMessageSize)
608 if err != nil {
609 return nil, err
610 }
611 if payInfo != nil {
612 payInfo.wireLength = len(d)
613 }
614
615 if st := checkRecvPayload(pf, s.RecvCompress(), compressor != nil || dc != nil); st != nil {
616 return nil, st.Err()
617 }
618
619 if pf == compressionMade {
620 // To match legacy behavior, if the decompressor is set by WithDecompressor or RPCDecompressor,
621 // use this decompressor as the default.
622 if dc != nil {
623 d, err = dc.Do(bytes.NewReader(d))
624 if err != nil {
625 return nil, status.Errorf(codes.Internal, "grpc: failed to decompress the received message %v", err)
626 }
627 } else {
628 dcReader, err := compressor.Decompress(bytes.NewReader(d))
629 if err != nil {
630 return nil, status.Errorf(codes.Internal, "grpc: failed to decompress the received message %v", err)
631 }
632 d, err = ioutil.ReadAll(dcReader)
633 if err != nil {
634 return nil, status.Errorf(codes.Internal, "grpc: failed to decompress the received message %v", err)
635 }
636 }
637 }
638 if len(d) > maxReceiveMessageSize {
639 // TODO: Revisit the error code. Currently keep it consistent with java
640 // implementation.
641 return nil, status.Errorf(codes.ResourceExhausted, "grpc: received message larger than max (%d vs. %d)", len(d), maxReceiveMessageSize)
642 }
643 return d, nil
644}
645
646// For the two compressor parameters, both should not be set, but if they are,
647// dc takes precedence over compressor.
648// TODO(dfawley): wrap the old compressor/decompressor using the new API?
649func recv(p *parser, c baseCodec, s *transport.Stream, dc Decompressor, m interface{}, maxReceiveMessageSize int, payInfo *payloadInfo, compressor encoding.Compressor) error {
650 d, err := recvAndDecompress(p, s, dc, maxReceiveMessageSize, payInfo, compressor)
651 if err != nil {
652 return err
653 }
654 if err := c.Unmarshal(d, m); err != nil {
655 return status.Errorf(codes.Internal, "grpc: failed to unmarshal the received message %v", err)
656 }
657 if payInfo != nil {
658 payInfo.uncompressedBytes = d
659 }
660 return nil
661}
662
663type rpcInfo struct {
664 failfast bool
665}
666
667type rpcInfoContextKey struct{}
668
669func newContextWithRPCInfo(ctx context.Context, failfast bool) context.Context {
670 return context.WithValue(ctx, rpcInfoContextKey{}, &rpcInfo{failfast: failfast})
671}
672
673func rpcInfoFromContext(ctx context.Context) (s *rpcInfo, ok bool) {
674 s, ok = ctx.Value(rpcInfoContextKey{}).(*rpcInfo)
675 return
676}
677
678// Code returns the error code for err if it was produced by the rpc system.
679// Otherwise, it returns codes.Unknown.
680//
681// Deprecated: use status.FromError and Code method instead.
682func Code(err error) codes.Code {
683 if s, ok := status.FromError(err); ok {
684 return s.Code()
685 }
686 return codes.Unknown
687}
688
689// ErrorDesc returns the error description of err if it was produced by the rpc system.
690// Otherwise, it returns err.Error() or empty string when err is nil.
691//
692// Deprecated: use status.FromError and Message method instead.
693func ErrorDesc(err error) string {
694 if s, ok := status.FromError(err); ok {
695 return s.Message()
696 }
697 return err.Error()
698}
699
700// Errorf returns an error containing an error code and a description;
701// Errorf returns nil if c is OK.
702//
703// Deprecated: use status.Errorf instead.
704func Errorf(c codes.Code, format string, a ...interface{}) error {
705 return status.Errorf(c, format, a...)
706}
707
708// toRPCErr converts an error into an error from the status package.
709func toRPCErr(err error) error {
710 if err == nil || err == io.EOF {
711 return err
712 }
713 if err == io.ErrUnexpectedEOF {
714 return status.Error(codes.Internal, err.Error())
715 }
716 if _, ok := status.FromError(err); ok {
717 return err
718 }
719 switch e := err.(type) {
720 case transport.ConnectionError:
721 return status.Error(codes.Unavailable, e.Desc)
722 default:
723 switch err {
724 case context.DeadlineExceeded:
725 return status.Error(codes.DeadlineExceeded, err.Error())
726 case context.Canceled:
727 return status.Error(codes.Canceled, err.Error())
728 }
729 }
730 return status.Error(codes.Unknown, err.Error())
731}
732
733// setCallInfoCodec should only be called after CallOptions have been applied.
734func setCallInfoCodec(c *callInfo) error {
735 if c.codec != nil {
736 // codec was already set by a CallOption; use it.
737 return nil
738 }
739
740 if c.contentSubtype == "" {
741 // No codec specified in CallOptions; use proto by default.
742 c.codec = encoding.GetCodec(proto.Name)
743 return nil
744 }
745
746 // c.contentSubtype is already lowercased in CallContentSubtype
747 c.codec = encoding.GetCodec(c.contentSubtype)
748 if c.codec == nil {
749 return status.Errorf(codes.Internal, "no codec registered for content-subtype %s", c.contentSubtype)
750 }
751 return nil
752}
753
754// parseDialTarget returns the network and address to pass to dialer
755func parseDialTarget(target string) (net string, addr string) {
756 net = "tcp"
757
758 m1 := strings.Index(target, ":")
759 m2 := strings.Index(target, ":/")
760
761 // handle unix:addr which will fail with url.Parse
762 if m1 >= 0 && m2 < 0 {
763 if n := target[0:m1]; n == "unix" {
764 net = n
765 addr = target[m1+1:]
766 return net, addr
767 }
768 }
769 if m2 >= 0 {
770 t, err := url.Parse(target)
771 if err != nil {
772 return net, target
773 }
774 scheme := t.Scheme
775 addr = t.Path
776 if scheme == "unix" {
777 net = scheme
778 if addr == "" {
779 addr = t.Host
780 }
781 return net, addr
782 }
783 }
784
785 return net, target
786}
787
788// channelzData is used to store channelz related data for ClientConn, addrConn and Server.
789// These fields cannot be embedded in the original structs (e.g. ClientConn), since to do atomic
790// operation on int64 variable on 32-bit machine, user is responsible to enforce memory alignment.
791// Here, by grouping those int64 fields inside a struct, we are enforcing the alignment.
792type channelzData struct {
793 callsStarted int64
794 callsFailed int64
795 callsSucceeded int64
796 // lastCallStartedTime stores the timestamp that last call starts. It is of int64 type instead of
797 // time.Time since it's more costly to atomically update time.Time variable than int64 variable.
798 lastCallStartedTime int64
799}
800
801// The SupportPackageIsVersion variables are referenced from generated protocol
802// buffer files to ensure compatibility with the gRPC version used. The latest
803// support package version is 5.
804//
805// Older versions are kept for compatibility. They may be removed if
806// compatibility cannot be maintained.
807//
808// These constants should not be referenced from any other code.
809const (
810 SupportPackageIsVersion3 = true
811 SupportPackageIsVersion4 = true
812 SupportPackageIsVersion5 = true
813)
814
815const grpcUA = "grpc-go/" + Version