repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/encoding/encoding_v2.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/encoding/encoding_v2.go
/* * * Copyright 2024 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. * */ package encoding import ( "strings" "google.golang.org/grpc/mem" ) // CodecV2 defines the interface gRPC uses to encode and decode messages. Note // that implementations of this interface must be thread safe; a CodecV2's // methods can be called from concurrent goroutines. type CodecV2 interface { // Marshal returns the wire format of v. The buffers in the returned // [mem.BufferSlice] must have at least one reference each, which will be freed // by gRPC when they are no longer needed. Marshal(v any) (out mem.BufferSlice, err error) // Unmarshal parses the wire format into v. Note that data will be freed as soon // as this function returns. If the codec wishes to guarantee access to the data // after this function, it must take its own reference that it frees when it is // no longer needed. Unmarshal(data mem.BufferSlice, v any) error // Name returns the name of the Codec implementation. The returned string // will be used as part of content type in transmission. The result must be // static; the result cannot change between calls. Name() string } // RegisterCodecV2 registers the provided CodecV2 for use with all gRPC clients and // servers. // // The CodecV2 will be stored and looked up by result of its Name() method, which // should match the content-subtype of the encoding handled by the CodecV2. This // is case-insensitive, and is stored and looked up as lowercase. If the // result of calling Name() is an empty string, RegisterCodecV2 will panic. See // Content-Type on // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for // more details. // // If both a Codec and CodecV2 are registered with the same name, the CodecV2 // will be used. // // NOTE: this function must only be called during initialization time (i.e. in // an init() function), and is not thread-safe. If multiple Codecs are // registered with the same name, the one registered last will take effect. func RegisterCodecV2(codec CodecV2) { if codec == nil { panic("cannot register a nil CodecV2") } if codec.Name() == "" { panic("cannot register CodecV2 with empty string result for Name()") } contentSubtype := strings.ToLower(codec.Name()) registeredCodecs[contentSubtype] = codec } // GetCodecV2 gets a registered CodecV2 by content-subtype, or nil if no CodecV2 is // registered for the content-subtype. // // The content-subtype is expected to be lowercase. func GetCodecV2(contentSubtype string) CodecV2 { c, _ := registeredCodecs[contentSubtype].(CodecV2) return c }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/encoding/proto/proto.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/encoding/proto/proto.go
/* * * Copyright 2024 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. * */ // Package proto defines the protobuf codec. Importing this package will // register the codec. package proto import ( "fmt" "google.golang.org/grpc/encoding" "google.golang.org/grpc/mem" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/protoadapt" ) // Name is the name registered for the proto compressor. const Name = "proto" func init() { encoding.RegisterCodecV2(&codecV2{}) } // codec is a CodecV2 implementation with protobuf. It is the default codec for // gRPC. type codecV2 struct{} func (c *codecV2) Marshal(v any) (data mem.BufferSlice, err error) { vv := messageV2Of(v) if vv == nil { return nil, fmt.Errorf("proto: failed to marshal, message is %T, want proto.Message", v) } size := proto.Size(vv) if mem.IsBelowBufferPoolingThreshold(size) { buf, err := proto.Marshal(vv) if err != nil { return nil, err } data = append(data, mem.SliceBuffer(buf)) } else { pool := mem.DefaultBufferPool() buf := pool.Get(size) if _, err := (proto.MarshalOptions{}).MarshalAppend((*buf)[:0], vv); err != nil { pool.Put(buf) return nil, err } data = append(data, mem.NewBuffer(buf, pool)) } return data, nil } func (c *codecV2) Unmarshal(data mem.BufferSlice, v any) (err error) { vv := messageV2Of(v) if vv == nil { return fmt.Errorf("failed to unmarshal, message is %T, want proto.Message", v) } buf := data.MaterializeToBuffer(mem.DefaultBufferPool()) defer buf.Free() // TODO: Upgrade proto.Unmarshal to support mem.BufferSlice. Right now, it's not // really possible without a major overhaul of the proto package, but the // vtprotobuf library may be able to support this. return proto.Unmarshal(buf.ReadOnlyData(), vv) } func messageV2Of(v any) proto.Message { switch v := v.(type) { case protoadapt.MessageV1: return protoadapt.MessageV2Of(v) case protoadapt.MessageV2: return v } return nil } func (c *codecV2) Name() string { return Name }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/metadata/metadata.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/metadata/metadata.go
/* * * Copyright 2014 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. * */ // Package metadata define the structure of the metadata supported by gRPC library. // Please refer to https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md // for more information about custom-metadata. package metadata // import "google.golang.org/grpc/metadata" import ( "context" "fmt" "strings" "google.golang.org/grpc/internal" ) func init() { internal.FromOutgoingContextRaw = fromOutgoingContextRaw } // DecodeKeyValue returns k, v, nil. // // Deprecated: use k and v directly instead. func DecodeKeyValue(k, v string) (string, string, error) { return k, v, nil } // MD is a mapping from metadata keys to values. Users should use the following // two convenience functions New and Pairs to generate MD. type MD map[string][]string // New creates an MD from a given key-value map. // // Only the following ASCII characters are allowed in keys: // - digits: 0-9 // - uppercase letters: A-Z (normalized to lower) // - lowercase letters: a-z // - special characters: -_. // // Uppercase letters are automatically converted to lowercase. // // Keys beginning with "grpc-" are reserved for grpc-internal use only and may // result in errors if set in metadata. func New(m map[string]string) MD { md := make(MD, len(m)) for k, val := range m { key := strings.ToLower(k) md[key] = append(md[key], val) } return md } // Pairs returns an MD formed by the mapping of key, value ... // Pairs panics if len(kv) is odd. // // Only the following ASCII characters are allowed in keys: // - digits: 0-9 // - uppercase letters: A-Z (normalized to lower) // - lowercase letters: a-z // - special characters: -_. // // Uppercase letters are automatically converted to lowercase. // // Keys beginning with "grpc-" are reserved for grpc-internal use only and may // result in errors if set in metadata. func Pairs(kv ...string) MD { if len(kv)%2 == 1 { panic(fmt.Sprintf("metadata: Pairs got the odd number of input pairs for metadata: %d", len(kv))) } md := make(MD, len(kv)/2) for i := 0; i < len(kv); i += 2 { key := strings.ToLower(kv[i]) md[key] = append(md[key], kv[i+1]) } return md } // Len returns the number of items in md. func (md MD) Len() int { return len(md) } // Copy returns a copy of md. func (md MD) Copy() MD { out := make(MD, len(md)) for k, v := range md { out[k] = copyOf(v) } return out } // Get obtains the values for a given key. // // k is converted to lowercase before searching in md. func (md MD) Get(k string) []string { k = strings.ToLower(k) return md[k] } // Set sets the value of a given key with a slice of values. // // k is converted to lowercase before storing in md. func (md MD) Set(k string, vals ...string) { if len(vals) == 0 { return } k = strings.ToLower(k) md[k] = vals } // Append adds the values to key k, not overwriting what was already stored at // that key. // // k is converted to lowercase before storing in md. func (md MD) Append(k string, vals ...string) { if len(vals) == 0 { return } k = strings.ToLower(k) md[k] = append(md[k], vals...) } // Delete removes the values for a given key k which is converted to lowercase // before removing it from md. func (md MD) Delete(k string) { k = strings.ToLower(k) delete(md, k) } // Join joins any number of mds into a single MD. // // The order of values for each key is determined by the order in which the mds // containing those values are presented to Join. func Join(mds ...MD) MD { out := MD{} for _, md := range mds { for k, v := range md { out[k] = append(out[k], v...) } } return out } type mdIncomingKey struct{} type mdOutgoingKey struct{} // NewIncomingContext creates a new context with incoming md attached. md must // not be modified after calling this function. func NewIncomingContext(ctx context.Context, md MD) context.Context { return context.WithValue(ctx, mdIncomingKey{}, md) } // NewOutgoingContext creates a new context with outgoing md attached. If used // in conjunction with AppendToOutgoingContext, NewOutgoingContext will // overwrite any previously-appended metadata. md must not be modified after // calling this function. func NewOutgoingContext(ctx context.Context, md MD) context.Context { return context.WithValue(ctx, mdOutgoingKey{}, rawMD{md: md}) } // AppendToOutgoingContext returns a new context with the provided kv merged // with any existing metadata in the context. Please refer to the documentation // of Pairs for a description of kv. func AppendToOutgoingContext(ctx context.Context, kv ...string) context.Context { if len(kv)%2 == 1 { panic(fmt.Sprintf("metadata: AppendToOutgoingContext got an odd number of input pairs for metadata: %d", len(kv))) } md, _ := ctx.Value(mdOutgoingKey{}).(rawMD) added := make([][]string, len(md.added)+1) copy(added, md.added) kvCopy := make([]string, 0, len(kv)) for i := 0; i < len(kv); i += 2 { kvCopy = append(kvCopy, strings.ToLower(kv[i]), kv[i+1]) } added[len(added)-1] = kvCopy return context.WithValue(ctx, mdOutgoingKey{}, rawMD{md: md.md, added: added}) } // FromIncomingContext returns the incoming metadata in ctx if it exists. // // All keys in the returned MD are lowercase. func FromIncomingContext(ctx context.Context) (MD, bool) { md, ok := ctx.Value(mdIncomingKey{}).(MD) if !ok { return nil, false } out := make(MD, len(md)) for k, v := range md { // We need to manually convert all keys to lower case, because MD is a // map, and there's no guarantee that the MD attached to the context is // created using our helper functions. key := strings.ToLower(k) out[key] = copyOf(v) } return out, true } // ValueFromIncomingContext returns the metadata value corresponding to the metadata // key from the incoming metadata if it exists. Keys are matched in a case insensitive // manner. func ValueFromIncomingContext(ctx context.Context, key string) []string { md, ok := ctx.Value(mdIncomingKey{}).(MD) if !ok { return nil } if v, ok := md[key]; ok { return copyOf(v) } for k, v := range md { // Case insensitive comparison: MD is a map, and there's no guarantee // that the MD attached to the context is created using our helper // functions. if strings.EqualFold(k, key) { return copyOf(v) } } return nil } func copyOf(v []string) []string { vals := make([]string, len(v)) copy(vals, v) return vals } // fromOutgoingContextRaw returns the un-merged, intermediary contents of rawMD. // // Remember to perform strings.ToLower on the keys, for both the returned MD (MD // is a map, there's no guarantee it's created using our helper functions) and // the extra kv pairs (AppendToOutgoingContext doesn't turn them into // lowercase). func fromOutgoingContextRaw(ctx context.Context) (MD, [][]string, bool) { raw, ok := ctx.Value(mdOutgoingKey{}).(rawMD) if !ok { return nil, nil, false } return raw.md, raw.added, true } // FromOutgoingContext returns the outgoing metadata in ctx if it exists. // // All keys in the returned MD are lowercase. func FromOutgoingContext(ctx context.Context) (MD, bool) { raw, ok := ctx.Value(mdOutgoingKey{}).(rawMD) if !ok { return nil, false } mdSize := len(raw.md) for i := range raw.added { mdSize += len(raw.added[i]) / 2 } out := make(MD, mdSize) for k, v := range raw.md { // We need to manually convert all keys to lower case, because MD is a // map, and there's no guarantee that the MD attached to the context is // created using our helper functions. key := strings.ToLower(k) out[key] = copyOf(v) } for _, added := range raw.added { if len(added)%2 == 1 { panic(fmt.Sprintf("metadata: FromOutgoingContext got an odd number of input pairs for metadata: %d", len(added))) } for i := 0; i < len(added); i += 2 { key := strings.ToLower(added[i]) out[key] = append(out[key], added[i+1]) } } return out, ok } type rawMD struct { md MD added [][]string }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/tap/tap.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/tap/tap.go
/* * * Copyright 2016 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. * */ // Package tap defines the function handles which are executed on the transport // layer of gRPC-Go and related information. // // # Experimental // // Notice: This API is EXPERIMENTAL and may be changed or removed in a // later release. package tap import ( "context" "google.golang.org/grpc/metadata" ) // Info defines the relevant information needed by the handles. type Info struct { // FullMethodName is the string of grpc method (in the format of // /package.service/method). FullMethodName string // Header contains the header metadata received. Header metadata.MD // TODO: More to be added. } // ServerInHandle defines the function which runs before a new stream is // created on the server side. If it returns a non-nil error, the stream will // not be created and an error will be returned to the client. If the error // returned is a status error, that status code and message will be used, // otherwise PermissionDenied will be the code and err.Error() will be the // message. // // It's intended to be used in situations where you don't want to waste the // resources to accept the new stream (e.g. rate-limiting). For other general // usages, please use interceptors. // // Note that it is executed in the per-connection I/O goroutine(s) instead of // per-RPC goroutine. Therefore, users should NOT have any // blocking/time-consuming work in this handle. Otherwise all the RPCs would // slow down. Also, for the same reason, this handle won't be called // concurrently by gRPC. type ServerInHandle func(ctx context.Context, info *Info) (context.Context, error)
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/backoff/backoff.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/backoff/backoff.go
/* * * Copyright 2019 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. * */ // Package backoff provides configuration options for backoff. // // More details can be found at: // https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md. // // All APIs in this package are experimental. package backoff import "time" // Config defines the configuration options for backoff. type Config struct { // BaseDelay is the amount of time to backoff after the first failure. BaseDelay time.Duration // Multiplier is the factor with which to multiply backoffs after a // failed retry. Should ideally be greater than 1. Multiplier float64 // Jitter is the factor with which backoffs are randomized. Jitter float64 // MaxDelay is the upper bound of backoff delay. MaxDelay time.Duration } // DefaultConfig is a backoff configuration with the default values specified // at https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md. // // This should be useful for callers who want to configure backoff with // non-default values only for a subset of the options. var DefaultConfig = Config{ BaseDelay: 1.0 * time.Second, Multiplier: 1.6, Jitter: 0.2, MaxDelay: 120 * time.Second, }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/stats/metrics.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/stats/metrics.go
/* * Copyright 2024 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. */ package stats import "maps" // MetricSet is a set of metrics to record. Once created, MetricSet is immutable, // however Add and Remove can make copies with specific metrics added or // removed, respectively. // // Do not construct directly; use NewMetricSet instead. type MetricSet struct { // metrics are the set of metrics to initialize. metrics map[string]bool } // NewMetricSet returns a MetricSet containing metricNames. func NewMetricSet(metricNames ...string) *MetricSet { newMetrics := make(map[string]bool) for _, metric := range metricNames { newMetrics[metric] = true } return &MetricSet{metrics: newMetrics} } // Metrics returns the metrics set. The returned map is read-only and must not // be modified. func (m *MetricSet) Metrics() map[string]bool { return m.metrics } // Add adds the metricNames to the metrics set and returns a new copy with the // additional metrics. func (m *MetricSet) Add(metricNames ...string) *MetricSet { newMetrics := make(map[string]bool) for metric := range m.metrics { newMetrics[metric] = true } for _, metric := range metricNames { newMetrics[metric] = true } return &MetricSet{metrics: newMetrics} } // Join joins the metrics passed in with the metrics set, and returns a new copy // with the merged metrics. func (m *MetricSet) Join(metrics *MetricSet) *MetricSet { newMetrics := make(map[string]bool) maps.Copy(newMetrics, m.metrics) maps.Copy(newMetrics, metrics.metrics) return &MetricSet{metrics: newMetrics} } // Remove removes the metricNames from the metrics set and returns a new copy // with the metrics removed. func (m *MetricSet) Remove(metricNames ...string) *MetricSet { newMetrics := make(map[string]bool) for metric := range m.metrics { newMetrics[metric] = true } for _, metric := range metricNames { delete(newMetrics, metric) } return &MetricSet{metrics: newMetrics} }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/stats/stats.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/stats/stats.go
/* * * Copyright 2016 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. * */ // Package stats is for collecting and reporting various network and RPC stats. // This package is for monitoring purpose only. All fields are read-only. // All APIs are experimental. package stats // import "google.golang.org/grpc/stats" import ( "context" "net" "time" "google.golang.org/grpc/metadata" ) // RPCStats contains stats information about RPCs. type RPCStats interface { isRPCStats() // IsClient returns true if this RPCStats is from client side. IsClient() bool } // Begin contains stats when an RPC attempt begins. // FailFast is only valid if this Begin is from client side. type Begin struct { // Client is true if this Begin is from client side. Client bool // BeginTime is the time when the RPC attempt begins. BeginTime time.Time // FailFast indicates if this RPC is failfast. FailFast bool // IsClientStream indicates whether the RPC is a client streaming RPC. IsClientStream bool // IsServerStream indicates whether the RPC is a server streaming RPC. IsServerStream bool // IsTransparentRetryAttempt indicates whether this attempt was initiated // due to transparently retrying a previous attempt. IsTransparentRetryAttempt bool } // IsClient indicates if the stats information is from client side. func (s *Begin) IsClient() bool { return s.Client } func (s *Begin) isRPCStats() {} // PickerUpdated indicates that the LB policy provided a new picker while the // RPC was waiting for one. type PickerUpdated struct{} // IsClient indicates if the stats information is from client side. Only Client // Side interfaces with a Picker, thus always returns true. func (*PickerUpdated) IsClient() bool { return true } func (*PickerUpdated) isRPCStats() {} // InPayload contains the information for an incoming payload. type InPayload struct { // Client is true if this InPayload is from client side. Client bool // Payload is the payload with original type. This may be modified after // the call to HandleRPC which provides the InPayload returns and must be // copied if needed later. Payload any // Length is the size of the uncompressed payload data. Does not include any // framing (gRPC or HTTP/2). Length int // CompressedLength is the size of the compressed payload data. Does not // include any framing (gRPC or HTTP/2). Same as Length if compression not // enabled. CompressedLength int // WireLength is the size of the compressed payload data plus gRPC framing. // Does not include HTTP/2 framing. WireLength int // RecvTime is the time when the payload is received. RecvTime time.Time } // IsClient indicates if the stats information is from client side. func (s *InPayload) IsClient() bool { return s.Client } func (s *InPayload) isRPCStats() {} // InHeader contains stats when a header is received. type InHeader struct { // Client is true if this InHeader is from client side. Client bool // WireLength is the wire length of header. WireLength int // Compression is the compression algorithm used for the RPC. Compression string // Header contains the header metadata received. Header metadata.MD // The following fields are valid only if Client is false. // FullMethod is the full RPC method string, i.e., /package.service/method. FullMethod string // RemoteAddr is the remote address of the corresponding connection. RemoteAddr net.Addr // LocalAddr is the local address of the corresponding connection. LocalAddr net.Addr } // IsClient indicates if the stats information is from client side. func (s *InHeader) IsClient() bool { return s.Client } func (s *InHeader) isRPCStats() {} // InTrailer contains stats when a trailer is received. type InTrailer struct { // Client is true if this InTrailer is from client side. Client bool // WireLength is the wire length of trailer. WireLength int // Trailer contains the trailer metadata received from the server. This // field is only valid if this InTrailer is from the client side. Trailer metadata.MD } // IsClient indicates if the stats information is from client side. func (s *InTrailer) IsClient() bool { return s.Client } func (s *InTrailer) isRPCStats() {} // OutPayload contains the information for an outgoing payload. type OutPayload struct { // Client is true if this OutPayload is from client side. Client bool // Payload is the payload with original type. This may be modified after // the call to HandleRPC which provides the OutPayload returns and must be // copied if needed later. Payload any // Length is the size of the uncompressed payload data. Does not include any // framing (gRPC or HTTP/2). Length int // CompressedLength is the size of the compressed payload data. Does not // include any framing (gRPC or HTTP/2). Same as Length if compression not // enabled. CompressedLength int // WireLength is the size of the compressed payload data plus gRPC framing. // Does not include HTTP/2 framing. WireLength int // SentTime is the time when the payload is sent. SentTime time.Time } // IsClient indicates if this stats information is from client side. func (s *OutPayload) IsClient() bool { return s.Client } func (s *OutPayload) isRPCStats() {} // OutHeader contains stats when a header is sent. type OutHeader struct { // Client is true if this OutHeader is from client side. Client bool // Compression is the compression algorithm used for the RPC. Compression string // Header contains the header metadata sent. Header metadata.MD // The following fields are valid only if Client is true. // FullMethod is the full RPC method string, i.e., /package.service/method. FullMethod string // RemoteAddr is the remote address of the corresponding connection. RemoteAddr net.Addr // LocalAddr is the local address of the corresponding connection. LocalAddr net.Addr } // IsClient indicates if this stats information is from client side. func (s *OutHeader) IsClient() bool { return s.Client } func (s *OutHeader) isRPCStats() {} // OutTrailer contains stats when a trailer is sent. type OutTrailer struct { // Client is true if this OutTrailer is from client side. Client bool // WireLength is the wire length of trailer. // // Deprecated: This field is never set. The length is not known when this message is // emitted because the trailer fields are compressed with hpack after that. WireLength int // Trailer contains the trailer metadata sent to the client. This // field is only valid if this OutTrailer is from the server side. Trailer metadata.MD } // IsClient indicates if this stats information is from client side. func (s *OutTrailer) IsClient() bool { return s.Client } func (s *OutTrailer) isRPCStats() {} // End contains stats when an RPC ends. type End struct { // Client is true if this End is from client side. Client bool // BeginTime is the time when the RPC began. BeginTime time.Time // EndTime is the time when the RPC ends. EndTime time.Time // Trailer contains the trailer metadata received from the server. This // field is only valid if this End is from the client side. // Deprecated: use Trailer in InTrailer instead. Trailer metadata.MD // Error is the error the RPC ended with. It is an error generated from // status.Status and can be converted back to status.Status using // status.FromError if non-nil. Error error } // IsClient indicates if this is from client side. func (s *End) IsClient() bool { return s.Client } func (s *End) isRPCStats() {} // ConnStats contains stats information about connections. type ConnStats interface { isConnStats() // IsClient returns true if this ConnStats is from client side. IsClient() bool } // ConnBegin contains the stats of a connection when it is established. type ConnBegin struct { // Client is true if this ConnBegin is from client side. Client bool } // IsClient indicates if this is from client side. func (s *ConnBegin) IsClient() bool { return s.Client } func (s *ConnBegin) isConnStats() {} // ConnEnd contains the stats of a connection when it ends. type ConnEnd struct { // Client is true if this ConnEnd is from client side. Client bool } // IsClient indicates if this is from client side. func (s *ConnEnd) IsClient() bool { return s.Client } func (s *ConnEnd) isConnStats() {} // SetTags attaches stats tagging data to the context, which will be sent in // the outgoing RPC with the header grpc-tags-bin. Subsequent calls to // SetTags will overwrite the values from earlier calls. // // Deprecated: set the `grpc-tags-bin` header in the metadata instead. func SetTags(ctx context.Context, b []byte) context.Context { return metadata.AppendToOutgoingContext(ctx, "grpc-tags-bin", string(b)) } // Tags returns the tags from the context for the inbound RPC. // // Deprecated: obtain the `grpc-tags-bin` header from metadata instead. func Tags(ctx context.Context) []byte { traceValues := metadata.ValueFromIncomingContext(ctx, "grpc-tags-bin") if len(traceValues) == 0 { return nil } return []byte(traceValues[len(traceValues)-1]) } // SetTrace attaches stats tagging data to the context, which will be sent in // the outgoing RPC with the header grpc-trace-bin. Subsequent calls to // SetTrace will overwrite the values from earlier calls. // // Deprecated: set the `grpc-trace-bin` header in the metadata instead. func SetTrace(ctx context.Context, b []byte) context.Context { return metadata.AppendToOutgoingContext(ctx, "grpc-trace-bin", string(b)) } // Trace returns the trace from the context for the inbound RPC. // // Deprecated: obtain the `grpc-trace-bin` header from metadata instead. func Trace(ctx context.Context) []byte { traceValues := metadata.ValueFromIncomingContext(ctx, "grpc-trace-bin") if len(traceValues) == 0 { return nil } return []byte(traceValues[len(traceValues)-1]) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/stats/handlers.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/stats/handlers.go
/* * * Copyright 2016 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. * */ package stats import ( "context" "net" ) // ConnTagInfo defines the relevant information needed by connection context tagger. type ConnTagInfo struct { // RemoteAddr is the remote address of the corresponding connection. RemoteAddr net.Addr // LocalAddr is the local address of the corresponding connection. LocalAddr net.Addr } // RPCTagInfo defines the relevant information needed by RPC context tagger. type RPCTagInfo struct { // FullMethodName is the RPC method in the format of /package.service/method. FullMethodName string // FailFast indicates if this RPC is failfast. // This field is only valid on client side, it's always false on server side. FailFast bool } // Handler defines the interface for the related stats handling (e.g., RPCs, connections). type Handler interface { // TagRPC can attach some information to the given context. // The context used for the rest lifetime of the RPC will be derived from // the returned context. TagRPC(context.Context, *RPCTagInfo) context.Context // HandleRPC processes the RPC stats. HandleRPC(context.Context, RPCStats) // TagConn can attach some information to the given context. // The returned context will be used for stats handling. // For conn stats handling, the context used in HandleConn for this // connection will be derived from the context returned. // For RPC stats handling, // - On server side, the context used in HandleRPC for all RPCs on this // connection will be derived from the context returned. // - On client side, the context is not derived from the context returned. TagConn(context.Context, *ConnTagInfo) context.Context // HandleConn processes the Conn stats. HandleConn(context.Context, ConnStats) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/codes/code_string.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/codes/code_string.go
/* * * Copyright 2017 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. * */ package codes import ( "strconv" "google.golang.org/grpc/internal" ) func init() { internal.CanonicalString = canonicalString } func (c Code) String() string { switch c { case OK: return "OK" case Canceled: return "Canceled" case Unknown: return "Unknown" case InvalidArgument: return "InvalidArgument" case DeadlineExceeded: return "DeadlineExceeded" case NotFound: return "NotFound" case AlreadyExists: return "AlreadyExists" case PermissionDenied: return "PermissionDenied" case ResourceExhausted: return "ResourceExhausted" case FailedPrecondition: return "FailedPrecondition" case Aborted: return "Aborted" case OutOfRange: return "OutOfRange" case Unimplemented: return "Unimplemented" case Internal: return "Internal" case Unavailable: return "Unavailable" case DataLoss: return "DataLoss" case Unauthenticated: return "Unauthenticated" default: return "Code(" + strconv.FormatInt(int64(c), 10) + ")" } } func canonicalString(c Code) string { switch c { case OK: return "OK" case Canceled: return "CANCELLED" case Unknown: return "UNKNOWN" case InvalidArgument: return "INVALID_ARGUMENT" case DeadlineExceeded: return "DEADLINE_EXCEEDED" case NotFound: return "NOT_FOUND" case AlreadyExists: return "ALREADY_EXISTS" case PermissionDenied: return "PERMISSION_DENIED" case ResourceExhausted: return "RESOURCE_EXHAUSTED" case FailedPrecondition: return "FAILED_PRECONDITION" case Aborted: return "ABORTED" case OutOfRange: return "OUT_OF_RANGE" case Unimplemented: return "UNIMPLEMENTED" case Internal: return "INTERNAL" case Unavailable: return "UNAVAILABLE" case DataLoss: return "DATA_LOSS" case Unauthenticated: return "UNAUTHENTICATED" default: return "CODE(" + strconv.FormatInt(int64(c), 10) + ")" } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/codes/codes.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/codes/codes.go
/* * * Copyright 2014 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. * */ // Package codes defines the canonical error codes used by gRPC. It is // consistent across various languages. package codes // import "google.golang.org/grpc/codes" import ( "fmt" "strconv" ) // A Code is a status code defined according to the [gRPC documentation]. // // Only the codes defined as consts in this package are valid codes. Do not use // other code values. Behavior of other codes is implementation-specific and // interoperability between implementations is not guaranteed. // // [gRPC documentation]: https://github.com/grpc/grpc/blob/master/doc/statuscodes.md type Code uint32 const ( // OK is returned on success. OK Code = 0 // Canceled indicates the operation was canceled (typically by the caller). // // The gRPC framework will generate this error code when cancellation // is requested. Canceled Code = 1 // Unknown error. An example of where this error may be returned is // if a Status value received from another address space belongs to // an error-space that is not known in this address space. Also // errors raised by APIs that do not return enough error information // may be converted to this error. // // The gRPC framework will generate this error code in the above two // mentioned cases. Unknown Code = 2 // InvalidArgument indicates client specified an invalid argument. // Note that this differs from FailedPrecondition. It indicates arguments // that are problematic regardless of the state of the system // (e.g., a malformed file name). // // This error code will not be generated by the gRPC framework. InvalidArgument Code = 3 // DeadlineExceeded means operation expired before completion. // For operations that change the state of the system, this error may be // returned even if the operation has completed successfully. For // example, a successful response from a server could have been delayed // long enough for the deadline to expire. // // The gRPC framework will generate this error code when the deadline is // exceeded. DeadlineExceeded Code = 4 // NotFound means some requested entity (e.g., file or directory) was // not found. // // This error code will not be generated by the gRPC framework. NotFound Code = 5 // AlreadyExists means an attempt to create an entity failed because one // already exists. // // This error code will not be generated by the gRPC framework. AlreadyExists Code = 6 // PermissionDenied indicates the caller does not have permission to // execute the specified operation. It must not be used for rejections // caused by exhausting some resource (use ResourceExhausted // instead for those errors). It must not be // used if the caller cannot be identified (use Unauthenticated // instead for those errors). // // This error code will not be generated by the gRPC core framework, // but expect authentication middleware to use it. PermissionDenied Code = 7 // ResourceExhausted indicates some resource has been exhausted, perhaps // a per-user quota, or perhaps the entire file system is out of space. // // This error code will be generated by the gRPC framework in // out-of-memory and server overload situations, or when a message is // larger than the configured maximum size. ResourceExhausted Code = 8 // FailedPrecondition indicates operation was rejected because the // system is not in a state required for the operation's execution. // For example, directory to be deleted may be non-empty, an rmdir // operation is applied to a non-directory, etc. // // A litmus test that may help a service implementor in deciding // between FailedPrecondition, Aborted, and Unavailable: // (a) Use Unavailable if the client can retry just the failing call. // (b) Use Aborted if the client should retry at a higher-level // (e.g., restarting a read-modify-write sequence). // (c) Use FailedPrecondition if the client should not retry until // the system state has been explicitly fixed. E.g., if an "rmdir" // fails because the directory is non-empty, FailedPrecondition // should be returned since the client should not retry unless // they have first fixed up the directory by deleting files from it. // (d) Use FailedPrecondition if the client performs conditional // REST Get/Update/Delete on a resource and the resource on the // server does not match the condition. E.g., conflicting // read-modify-write on the same resource. // // This error code will not be generated by the gRPC framework. FailedPrecondition Code = 9 // Aborted indicates the operation was aborted, typically due to a // concurrency issue like sequencer check failures, transaction aborts, // etc. // // See litmus test above for deciding between FailedPrecondition, // Aborted, and Unavailable. // // This error code will not be generated by the gRPC framework. Aborted Code = 10 // OutOfRange means operation was attempted past the valid range. // E.g., seeking or reading past end of file. // // Unlike InvalidArgument, this error indicates a problem that may // be fixed if the system state changes. For example, a 32-bit file // system will generate InvalidArgument if asked to read at an // offset that is not in the range [0,2^32-1], but it will generate // OutOfRange if asked to read from an offset past the current // file size. // // There is a fair bit of overlap between FailedPrecondition and // OutOfRange. We recommend using OutOfRange (the more specific // error) when it applies so that callers who are iterating through // a space can easily look for an OutOfRange error to detect when // they are done. // // This error code will not be generated by the gRPC framework. OutOfRange Code = 11 // Unimplemented indicates operation is not implemented or not // supported/enabled in this service. // // This error code will be generated by the gRPC framework. Most // commonly, you will see this error code when a method implementation // is missing on the server. It can also be generated for unknown // compression algorithms or a disagreement as to whether an RPC should // be streaming. Unimplemented Code = 12 // Internal errors. Means some invariants expected by underlying // system has been broken. If you see one of these errors, // something is very broken. // // This error code will be generated by the gRPC framework in several // internal error conditions. Internal Code = 13 // Unavailable indicates the service is currently unavailable. // This is a most likely a transient condition and may be corrected // by retrying with a backoff. Note that it is not always safe to retry // non-idempotent operations. // // See litmus test above for deciding between FailedPrecondition, // Aborted, and Unavailable. // // This error code will be generated by the gRPC framework during // abrupt shutdown of a server process or network connection. Unavailable Code = 14 // DataLoss indicates unrecoverable data loss or corruption. // // This error code will not be generated by the gRPC framework. DataLoss Code = 15 // Unauthenticated indicates the request does not have valid // authentication credentials for the operation. // // The gRPC framework will generate this error code when the // authentication metadata is invalid or a Credentials callback fails, // but also expect authentication middleware to generate it. Unauthenticated Code = 16 _maxCode = 17 ) var strToCode = map[string]Code{ `"OK"`: OK, `"CANCELLED"`:/* [sic] */ Canceled, `"UNKNOWN"`: Unknown, `"INVALID_ARGUMENT"`: InvalidArgument, `"DEADLINE_EXCEEDED"`: DeadlineExceeded, `"NOT_FOUND"`: NotFound, `"ALREADY_EXISTS"`: AlreadyExists, `"PERMISSION_DENIED"`: PermissionDenied, `"RESOURCE_EXHAUSTED"`: ResourceExhausted, `"FAILED_PRECONDITION"`: FailedPrecondition, `"ABORTED"`: Aborted, `"OUT_OF_RANGE"`: OutOfRange, `"UNIMPLEMENTED"`: Unimplemented, `"INTERNAL"`: Internal, `"UNAVAILABLE"`: Unavailable, `"DATA_LOSS"`: DataLoss, `"UNAUTHENTICATED"`: Unauthenticated, } // UnmarshalJSON unmarshals b into the Code. func (c *Code) UnmarshalJSON(b []byte) error { // From json.Unmarshaler: By convention, to approximate the behavior of // Unmarshal itself, Unmarshalers implement UnmarshalJSON([]byte("null")) as // a no-op. if string(b) == "null" { return nil } if c == nil { return fmt.Errorf("nil receiver passed to UnmarshalJSON") } if ci, err := strconv.ParseUint(string(b), 10, 32); err == nil { if ci >= _maxCode { return fmt.Errorf("invalid code: %d", ci) } *c = Code(ci) return nil } if jc, ok := strToCode[string(b)]; ok { *c = jc return nil } return fmt.Errorf("invalid code: %q", string(b)) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/balancer/subconn.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/balancer/subconn.go
/* * * Copyright 2024 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. * */ package balancer import ( "google.golang.org/grpc/connectivity" "google.golang.org/grpc/internal" "google.golang.org/grpc/resolver" ) // A SubConn represents a single connection to a gRPC backend service. // // All SubConns start in IDLE, and will not try to connect. To trigger a // connection attempt, Balancers must call Connect. // // If the connection attempt fails, the SubConn will transition to // TRANSIENT_FAILURE for a backoff period, and then return to IDLE. If the // connection attempt succeeds, it will transition to READY. // // If a READY SubConn becomes disconnected, the SubConn will transition to IDLE. // // If a connection re-enters IDLE, Balancers must call Connect again to trigger // a new connection attempt. // // Each SubConn contains a list of addresses. gRPC will try to connect to the // addresses in sequence, and stop trying the remainder once the first // connection is successful. However, this behavior is deprecated. SubConns // should only use a single address. // // NOTICE: This interface is intended to be implemented by gRPC, or intercepted // by custom load balancing polices. Users should not need their own complete // implementation of this interface -- they should always delegate to a SubConn // returned by ClientConn.NewSubConn() by embedding it in their implementations. // An embedded SubConn must never be nil, or runtime panics will occur. type SubConn interface { // UpdateAddresses updates the addresses used in this SubConn. // gRPC checks if currently-connected address is still in the new list. // If it's in the list, the connection will be kept. // If it's not in the list, the connection will gracefully close, and // a new connection will be created. // // This will trigger a state transition for the SubConn. // // Deprecated: this method will be removed. Create new SubConns for new // addresses instead. UpdateAddresses([]resolver.Address) // Connect starts the connecting for this SubConn. Connect() // GetOrBuildProducer returns a reference to the existing Producer for this // ProducerBuilder in this SubConn, or, if one does not currently exist, // creates a new one and returns it. Returns a close function which may be // called when the Producer is no longer needed. Otherwise the producer // will automatically be closed upon connection loss or subchannel close. // Should only be called on a SubConn in state Ready. Otherwise the // producer will be unable to create streams. GetOrBuildProducer(ProducerBuilder) (p Producer, close func()) // Shutdown shuts down the SubConn gracefully. Any started RPCs will be // allowed to complete. No future calls should be made on the SubConn. // One final state update will be delivered to the StateListener (or // UpdateSubConnState; deprecated) with ConnectivityState of Shutdown to // indicate the shutdown operation. This may be delivered before // in-progress RPCs are complete and the actual connection is closed. Shutdown() // RegisterHealthListener registers a health listener that receives health // updates for a Ready SubConn. Only one health listener can be registered // at a time. A health listener should be registered each time the SubConn's // connectivity state changes to READY. Registering a health listener when // the connectivity state is not READY may result in undefined behaviour. // This method must not be called synchronously while handling an update // from a previously registered health listener. RegisterHealthListener(func(SubConnState)) // EnforceSubConnEmbedding is included to force implementers to embed // another implementation of this interface, allowing gRPC to add methods // without breaking users. internal.EnforceSubConnEmbedding } // A ProducerBuilder is a simple constructor for a Producer. It is used by the // SubConn to create producers when needed. type ProducerBuilder interface { // Build creates a Producer. The first parameter is always a // grpc.ClientConnInterface (a type to allow creating RPCs/streams on the // associated SubConn), but is declared as `any` to avoid a dependency // cycle. Build also returns a close function that will be called when all // references to the Producer have been given up for a SubConn, or when a // connectivity state change occurs on the SubConn. The close function // should always block until all asynchronous cleanup work is completed. Build(grpcClientConnInterface any) (p Producer, close func()) } // SubConnState describes the state of a SubConn. type SubConnState struct { // ConnectivityState is the connectivity state of the SubConn. ConnectivityState connectivity.State // ConnectionError is set if the ConnectivityState is TransientFailure, // describing the reason the SubConn failed. Otherwise, it is nil. ConnectionError error // connectedAddr contains the connected address when ConnectivityState is // Ready. Otherwise, it is indeterminate. connectedAddress resolver.Address } // connectedAddress returns the connected address for a SubConnState. The // address is only valid if the state is READY. func connectedAddress(scs SubConnState) resolver.Address { return scs.connectedAddress } // setConnectedAddress sets the connected address for a SubConnState. func setConnectedAddress(scs *SubConnState, addr resolver.Address) { scs.connectedAddress = addr } // A Producer is a type shared among potentially many consumers. It is // associated with a SubConn, and an implementation will typically contain // other methods to provide additional functionality, e.g. configuration or // subscription registration. type Producer any
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/balancer/balancer.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/balancer/balancer.go
/* * * Copyright 2017 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. * */ // Package balancer defines APIs for load balancing in gRPC. // All APIs in this package are experimental. package balancer import ( "context" "encoding/json" "errors" "net" "strings" "google.golang.org/grpc/channelz" "google.golang.org/grpc/connectivity" "google.golang.org/grpc/credentials" estats "google.golang.org/grpc/experimental/stats" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/internal" "google.golang.org/grpc/metadata" "google.golang.org/grpc/resolver" "google.golang.org/grpc/serviceconfig" ) var ( // m is a map from name to balancer builder. m = make(map[string]Builder) logger = grpclog.Component("balancer") ) // Register registers the balancer builder to the balancer map. b.Name // (lowercased) will be used as the name registered with this builder. If the // Builder implements ConfigParser, ParseConfig will be called when new service // configs are received by the resolver, and the result will be provided to the // Balancer in UpdateClientConnState. // // NOTE: this function must only be called during initialization time (i.e. in // an init() function), and is not thread-safe. If multiple Balancers are // registered with the same name, the one registered last will take effect. func Register(b Builder) { name := strings.ToLower(b.Name()) if name != b.Name() { // TODO: Skip the use of strings.ToLower() to index the map after v1.59 // is released to switch to case sensitive balancer registry. Also, // remove this warning and update the docstrings for Register and Get. logger.Warningf("Balancer registered with name %q. grpc-go will be switching to case sensitive balancer registries soon", b.Name()) } m[name] = b } // unregisterForTesting deletes the balancer with the given name from the // balancer map. // // This function is not thread-safe. func unregisterForTesting(name string) { delete(m, name) } func init() { internal.BalancerUnregister = unregisterForTesting internal.ConnectedAddress = connectedAddress internal.SetConnectedAddress = setConnectedAddress } // Get returns the resolver builder registered with the given name. // Note that the compare is done in a case-insensitive fashion. // If no builder is register with the name, nil will be returned. func Get(name string) Builder { if strings.ToLower(name) != name { // TODO: Skip the use of strings.ToLower() to index the map after v1.59 // is released to switch to case sensitive balancer registry. Also, // remove this warning and update the docstrings for Register and Get. logger.Warningf("Balancer retrieved for name %q. grpc-go will be switching to case sensitive balancer registries soon", name) } if b, ok := m[strings.ToLower(name)]; ok { return b } return nil } // NewSubConnOptions contains options to create new SubConn. type NewSubConnOptions struct { // CredsBundle is the credentials bundle that will be used in the created // SubConn. If it's nil, the original creds from grpc DialOptions will be // used. // // Deprecated: Use the Attributes field in resolver.Address to pass // arbitrary data to the credential handshaker. CredsBundle credentials.Bundle // HealthCheckEnabled indicates whether health check service should be // enabled on this SubConn HealthCheckEnabled bool // StateListener is called when the state of the subconn changes. If nil, // Balancer.UpdateSubConnState will be called instead. Will never be // invoked until after Connect() is called on the SubConn created with // these options. StateListener func(SubConnState) } // State contains the balancer's state relevant to the gRPC ClientConn. type State struct { // State contains the connectivity state of the balancer, which is used to // determine the state of the ClientConn. ConnectivityState connectivity.State // Picker is used to choose connections (SubConns) for RPCs. Picker Picker } // ClientConn represents a gRPC ClientConn. // // This interface is to be implemented by gRPC. Users should not need a // brand new implementation of this interface. For the situations like // testing, the new implementation should embed this interface. This allows // gRPC to add new methods to this interface. // // NOTICE: This interface is intended to be implemented by gRPC, or intercepted // by custom load balancing polices. Users should not need their own complete // implementation of this interface -- they should always delegate to a // ClientConn passed to Builder.Build() by embedding it in their // implementations. An embedded ClientConn must never be nil, or runtime panics // will occur. type ClientConn interface { // NewSubConn is called by balancer to create a new SubConn. // It doesn't block and wait for the connections to be established. // Behaviors of the SubConn can be controlled by options. // // Deprecated: please be aware that in a future version, SubConns will only // support one address per SubConn. NewSubConn([]resolver.Address, NewSubConnOptions) (SubConn, error) // RemoveSubConn removes the SubConn from ClientConn. // The SubConn will be shutdown. // // Deprecated: use SubConn.Shutdown instead. RemoveSubConn(SubConn) // UpdateAddresses updates the addresses used in the passed in SubConn. // gRPC checks if the currently connected address is still in the new list. // If so, the connection will be kept. Else, the connection will be // gracefully closed, and a new connection will be created. // // This may trigger a state transition for the SubConn. // // Deprecated: this method will be removed. Create new SubConns for new // addresses instead. UpdateAddresses(SubConn, []resolver.Address) // UpdateState notifies gRPC that the balancer's internal state has // changed. // // gRPC will update the connectivity state of the ClientConn, and will call // Pick on the new Picker to pick new SubConns. UpdateState(State) // ResolveNow is called by balancer to notify gRPC to do a name resolving. ResolveNow(resolver.ResolveNowOptions) // Target returns the dial target for this ClientConn. // // Deprecated: Use the Target field in the BuildOptions instead. Target() string // MetricsRecorder provides the metrics recorder that balancers can use to // record metrics. Balancer implementations which do not register metrics on // metrics registry and record on them can ignore this method. The returned // MetricsRecorder is guaranteed to never be nil. MetricsRecorder() estats.MetricsRecorder // EnforceClientConnEmbedding is included to force implementers to embed // another implementation of this interface, allowing gRPC to add methods // without breaking users. internal.EnforceClientConnEmbedding } // BuildOptions contains additional information for Build. type BuildOptions struct { // DialCreds is the transport credentials to use when communicating with a // remote load balancer server. Balancer implementations which do not // communicate with a remote load balancer server can ignore this field. DialCreds credentials.TransportCredentials // CredsBundle is the credentials bundle to use when communicating with a // remote load balancer server. Balancer implementations which do not // communicate with a remote load balancer server can ignore this field. CredsBundle credentials.Bundle // Dialer is the custom dialer to use when communicating with a remote load // balancer server. Balancer implementations which do not communicate with a // remote load balancer server can ignore this field. Dialer func(context.Context, string) (net.Conn, error) // Authority is the server name to use as part of the authentication // handshake when communicating with a remote load balancer server. Balancer // implementations which do not communicate with a remote load balancer // server can ignore this field. Authority string // ChannelzParent is the parent ClientConn's channelz channel. ChannelzParent channelz.Identifier // CustomUserAgent is the custom user agent set on the parent ClientConn. // The balancer should set the same custom user agent if it creates a // ClientConn. CustomUserAgent string // Target contains the parsed address info of the dial target. It is the // same resolver.Target as passed to the resolver. See the documentation for // the resolver.Target type for details about what it contains. Target resolver.Target } // Builder creates a balancer. type Builder interface { // Build creates a new balancer with the ClientConn. Build(cc ClientConn, opts BuildOptions) Balancer // Name returns the name of balancers built by this builder. // It will be used to pick balancers (for example in service config). Name() string } // ConfigParser parses load balancer configs. type ConfigParser interface { // ParseConfig parses the JSON load balancer config provided into an // internal form or returns an error if the config is invalid. For future // compatibility reasons, unknown fields in the config should be ignored. ParseConfig(LoadBalancingConfigJSON json.RawMessage) (serviceconfig.LoadBalancingConfig, error) } // PickInfo contains additional information for the Pick operation. type PickInfo struct { // FullMethodName is the method name that NewClientStream() is called // with. The canonical format is /service/Method. FullMethodName string // Ctx is the RPC's context, and may contain relevant RPC-level information // like the outgoing header metadata. Ctx context.Context } // DoneInfo contains additional information for done. type DoneInfo struct { // Err is the rpc error the RPC finished with. It could be nil. Err error // Trailer contains the metadata from the RPC's trailer, if present. Trailer metadata.MD // BytesSent indicates if any bytes have been sent to the server. BytesSent bool // BytesReceived indicates if any byte has been received from the server. BytesReceived bool // ServerLoad is the load received from server. It's usually sent as part of // trailing metadata. // // The only supported type now is *orca_v3.LoadReport. ServerLoad any } var ( // ErrNoSubConnAvailable indicates no SubConn is available for pick(). // gRPC will block the RPC until a new picker is available via UpdateState(). ErrNoSubConnAvailable = errors.New("no SubConn is available") // ErrTransientFailure indicates all SubConns are in TransientFailure. // WaitForReady RPCs will block, non-WaitForReady RPCs will fail. // // Deprecated: return an appropriate error based on the last resolution or // connection attempt instead. The behavior is the same for any non-gRPC // status error. ErrTransientFailure = errors.New("all SubConns are in TransientFailure") ) // PickResult contains information related to a connection chosen for an RPC. type PickResult struct { // SubConn is the connection to use for this pick, if its state is Ready. // If the state is not Ready, gRPC will block the RPC until a new Picker is // provided by the balancer (using ClientConn.UpdateState). The SubConn // must be one returned by ClientConn.NewSubConn. SubConn SubConn // Done is called when the RPC is completed. If the SubConn is not ready, // this will be called with a nil parameter. If the SubConn is not a valid // type, Done may not be called. May be nil if the balancer does not wish // to be notified when the RPC completes. Done func(DoneInfo) // Metadata provides a way for LB policies to inject arbitrary per-call // metadata. Any metadata returned here will be merged with existing // metadata added by the client application. // // LB policies with child policies are responsible for propagating metadata // injected by their children to the ClientConn, as part of Pick(). Metadata metadata.MD } // TransientFailureError returns e. It exists for backward compatibility and // will be deleted soon. // // Deprecated: no longer necessary, picker errors are treated this way by // default. func TransientFailureError(e error) error { return e } // Picker is used by gRPC to pick a SubConn to send an RPC. // Balancer is expected to generate a new picker from its snapshot every time its // internal state has changed. // // The pickers used by gRPC can be updated by ClientConn.UpdateState(). type Picker interface { // Pick returns the connection to use for this RPC and related information. // // Pick should not block. If the balancer needs to do I/O or any blocking // or time-consuming work to service this call, it should return // ErrNoSubConnAvailable, and the Pick call will be repeated by gRPC when // the Picker is updated (using ClientConn.UpdateState). // // If an error is returned: // // - If the error is ErrNoSubConnAvailable, gRPC will block until a new // Picker is provided by the balancer (using ClientConn.UpdateState). // // - If the error is a status error (implemented by the grpc/status // package), gRPC will terminate the RPC with the code and message // provided. // // - For all other errors, wait for ready RPCs will wait, but non-wait for // ready RPCs will be terminated with this error's Error() string and // status code Unavailable. Pick(info PickInfo) (PickResult, error) } // Balancer takes input from gRPC, manages SubConns, and collects and aggregates // the connectivity states. // // It also generates and updates the Picker used by gRPC to pick SubConns for RPCs. // // UpdateClientConnState, ResolverError, UpdateSubConnState, and Close are // guaranteed to be called synchronously from the same goroutine. There's no // guarantee on picker.Pick, it may be called anytime. type Balancer interface { // UpdateClientConnState is called by gRPC when the state of the ClientConn // changes. If the error returned is ErrBadResolverState, the ClientConn // will begin calling ResolveNow on the active name resolver with // exponential backoff until a subsequent call to UpdateClientConnState // returns a nil error. Any other errors are currently ignored. UpdateClientConnState(ClientConnState) error // ResolverError is called by gRPC when the name resolver reports an error. ResolverError(error) // UpdateSubConnState is called by gRPC when the state of a SubConn // changes. // // Deprecated: Use NewSubConnOptions.StateListener when creating the // SubConn instead. UpdateSubConnState(SubConn, SubConnState) // Close closes the balancer. The balancer is not currently required to // call SubConn.Shutdown for its existing SubConns; however, this will be // required in a future release, so it is recommended. Close() } // ExitIdler is an optional interface for balancers to implement. If // implemented, ExitIdle will be called when ClientConn.Connect is called, if // the ClientConn is idle. If unimplemented, ClientConn.Connect will cause // all SubConns to connect. // // Notice: it will be required for all balancers to implement this in a future // release. type ExitIdler interface { // ExitIdle instructs the LB policy to reconnect to backends / exit the // IDLE state, if appropriate and possible. Note that SubConns that enter // the IDLE state will not reconnect until SubConn.Connect is called. ExitIdle() } // ClientConnState describes the state of a ClientConn relevant to the // balancer. type ClientConnState struct { ResolverState resolver.State // The parsed load balancing configuration returned by the builder's // ParseConfig method, if implemented. BalancerConfig serviceconfig.LoadBalancingConfig } // ErrBadResolverState may be returned by UpdateClientConnState to indicate a // problem with the provided name resolver data. var ErrBadResolverState = errors.New("bad resolver state")
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/balancer/conn_state_evaluator.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/balancer/conn_state_evaluator.go
/* * * Copyright 2022 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. * */ package balancer import "google.golang.org/grpc/connectivity" // ConnectivityStateEvaluator takes the connectivity states of multiple SubConns // and returns one aggregated connectivity state. // // It's not thread safe. type ConnectivityStateEvaluator struct { numReady uint64 // Number of addrConns in ready state. numConnecting uint64 // Number of addrConns in connecting state. numTransientFailure uint64 // Number of addrConns in transient failure state. numIdle uint64 // Number of addrConns in idle state. } // RecordTransition records state change happening in subConn and based on that // it evaluates what aggregated state should be. // // - If at least one SubConn in Ready, the aggregated state is Ready; // - Else if at least one SubConn in Connecting, the aggregated state is Connecting; // - Else if at least one SubConn is Idle, the aggregated state is Idle; // - Else if at least one SubConn is TransientFailure (or there are no SubConns), the aggregated state is Transient Failure. // // Shutdown is not considered. func (cse *ConnectivityStateEvaluator) RecordTransition(oldState, newState connectivity.State) connectivity.State { // Update counters. for idx, state := range []connectivity.State{oldState, newState} { updateVal := 2*uint64(idx) - 1 // -1 for oldState and +1 for new. switch state { case connectivity.Ready: cse.numReady += updateVal case connectivity.Connecting: cse.numConnecting += updateVal case connectivity.TransientFailure: cse.numTransientFailure += updateVal case connectivity.Idle: cse.numIdle += updateVal } } return cse.CurrentState() } // CurrentState returns the current aggregate conn state by evaluating the counters func (cse *ConnectivityStateEvaluator) CurrentState() connectivity.State { // Evaluate. if cse.numReady > 0 { return connectivity.Ready } if cse.numConnecting > 0 { return connectivity.Connecting } if cse.numIdle > 0 { return connectivity.Idle } return connectivity.TransientFailure }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/balancer/endpointsharding/endpointsharding.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/balancer/endpointsharding/endpointsharding.go
/* * * Copyright 2024 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. * */ // Package endpointsharding implements a load balancing policy that manages // homogeneous child policies each owning a single endpoint. // // # Experimental // // Notice: This package is EXPERIMENTAL and may be changed or removed in a // later release. package endpointsharding import ( "errors" rand "math/rand/v2" "sync" "sync/atomic" "google.golang.org/grpc/balancer" "google.golang.org/grpc/balancer/base" "google.golang.org/grpc/connectivity" "google.golang.org/grpc/resolver" ) // ChildState is the balancer state of a child along with the endpoint which // identifies the child balancer. type ChildState struct { Endpoint resolver.Endpoint State balancer.State // Balancer exposes only the ExitIdler interface of the child LB policy. // Other methods of the child policy are called only by endpointsharding. Balancer balancer.ExitIdler } // Options are the options to configure the behaviour of the // endpointsharding balancer. type Options struct { // DisableAutoReconnect allows the balancer to keep child balancer in the // IDLE state until they are explicitly triggered to exit using the // ChildState obtained from the endpointsharding picker. When set to false, // the endpointsharding balancer will automatically call ExitIdle on child // connections that report IDLE. DisableAutoReconnect bool } // ChildBuilderFunc creates a new balancer with the ClientConn. It has the same // type as the balancer.Builder.Build method. type ChildBuilderFunc func(cc balancer.ClientConn, opts balancer.BuildOptions) balancer.Balancer // NewBalancer returns a load balancing policy that manages homogeneous child // policies each owning a single endpoint. The endpointsharding balancer // forwards the LoadBalancingConfig in ClientConn state updates to its children. func NewBalancer(cc balancer.ClientConn, opts balancer.BuildOptions, childBuilder ChildBuilderFunc, esOpts Options) balancer.Balancer { es := &endpointSharding{ cc: cc, bOpts: opts, esOpts: esOpts, childBuilder: childBuilder, } es.children.Store(resolver.NewEndpointMap()) return es } // endpointSharding is a balancer that wraps child balancers. It creates a child // balancer with child config for every unique Endpoint received. It updates the // child states on any update from parent or child. type endpointSharding struct { cc balancer.ClientConn bOpts balancer.BuildOptions esOpts Options childBuilder ChildBuilderFunc // childMu synchronizes calls to any single child. It must be held for all // calls into a child. To avoid deadlocks, do not acquire childMu while // holding mu. childMu sync.Mutex children atomic.Pointer[resolver.EndpointMap] // endpoint -> *balancerWrapper // inhibitChildUpdates is set during UpdateClientConnState/ResolverError // calls (calls to children will each produce an update, only want one // update). inhibitChildUpdates atomic.Bool // mu synchronizes access to the state stored in balancerWrappers in the // children field. mu must not be held during calls into a child since // synchronous calls back from the child may require taking mu, causing a // deadlock. To avoid deadlocks, do not acquire childMu while holding mu. mu sync.Mutex } // UpdateClientConnState creates a child for new endpoints and deletes children // for endpoints that are no longer present. It also updates all the children, // and sends a single synchronous update of the childrens' aggregated state at // the end of the UpdateClientConnState operation. If any endpoint has no // addresses it will ignore that endpoint. Otherwise, returns first error found // from a child, but fully processes the new update. func (es *endpointSharding) UpdateClientConnState(state balancer.ClientConnState) error { es.childMu.Lock() defer es.childMu.Unlock() es.inhibitChildUpdates.Store(true) defer func() { es.inhibitChildUpdates.Store(false) es.updateState() }() var ret error children := es.children.Load() newChildren := resolver.NewEndpointMap() // Update/Create new children. for _, endpoint := range state.ResolverState.Endpoints { if _, ok := newChildren.Get(endpoint); ok { // Endpoint child was already created, continue to avoid duplicate // update. continue } var childBalancer *balancerWrapper if val, ok := children.Get(endpoint); ok { childBalancer = val.(*balancerWrapper) // Endpoint attributes may have changed, update the stored endpoint. es.mu.Lock() childBalancer.childState.Endpoint = endpoint es.mu.Unlock() } else { childBalancer = &balancerWrapper{ childState: ChildState{Endpoint: endpoint}, ClientConn: es.cc, es: es, } childBalancer.childState.Balancer = childBalancer childBalancer.child = es.childBuilder(childBalancer, es.bOpts) } newChildren.Set(endpoint, childBalancer) if err := childBalancer.updateClientConnStateLocked(balancer.ClientConnState{ BalancerConfig: state.BalancerConfig, ResolverState: resolver.State{ Endpoints: []resolver.Endpoint{endpoint}, Attributes: state.ResolverState.Attributes, }, }); err != nil && ret == nil { // Return first error found, and always commit full processing of // updating children. If desired to process more specific errors // across all endpoints, caller should make these specific // validations, this is a current limitation for simplicity sake. ret = err } } // Delete old children that are no longer present. for _, e := range children.Keys() { child, _ := children.Get(e) if _, ok := newChildren.Get(e); !ok { child.(*balancerWrapper).closeLocked() } } es.children.Store(newChildren) if newChildren.Len() == 0 { return balancer.ErrBadResolverState } return ret } // ResolverError forwards the resolver error to all of the endpointSharding's // children and sends a single synchronous update of the childStates at the end // of the ResolverError operation. func (es *endpointSharding) ResolverError(err error) { es.childMu.Lock() defer es.childMu.Unlock() es.inhibitChildUpdates.Store(true) defer func() { es.inhibitChildUpdates.Store(false) es.updateState() }() children := es.children.Load() for _, child := range children.Values() { child.(*balancerWrapper).resolverErrorLocked(err) } } func (es *endpointSharding) UpdateSubConnState(balancer.SubConn, balancer.SubConnState) { // UpdateSubConnState is deprecated. } func (es *endpointSharding) Close() { es.childMu.Lock() defer es.childMu.Unlock() children := es.children.Load() for _, child := range children.Values() { child.(*balancerWrapper).closeLocked() } } // updateState updates this component's state. It sends the aggregated state, // and a picker with round robin behavior with all the child states present if // needed. func (es *endpointSharding) updateState() { if es.inhibitChildUpdates.Load() { return } var readyPickers, connectingPickers, idlePickers, transientFailurePickers []balancer.Picker es.mu.Lock() defer es.mu.Unlock() children := es.children.Load() childStates := make([]ChildState, 0, children.Len()) for _, child := range children.Values() { bw := child.(*balancerWrapper) childState := bw.childState childStates = append(childStates, childState) childPicker := childState.State.Picker switch childState.State.ConnectivityState { case connectivity.Ready: readyPickers = append(readyPickers, childPicker) case connectivity.Connecting: connectingPickers = append(connectingPickers, childPicker) case connectivity.Idle: idlePickers = append(idlePickers, childPicker) case connectivity.TransientFailure: transientFailurePickers = append(transientFailurePickers, childPicker) // connectivity.Shutdown shouldn't appear. } } // Construct the round robin picker based off the aggregated state. Whatever // the aggregated state, use the pickers present that are currently in that // state only. var aggState connectivity.State var pickers []balancer.Picker if len(readyPickers) >= 1 { aggState = connectivity.Ready pickers = readyPickers } else if len(connectingPickers) >= 1 { aggState = connectivity.Connecting pickers = connectingPickers } else if len(idlePickers) >= 1 { aggState = connectivity.Idle pickers = idlePickers } else if len(transientFailurePickers) >= 1 { aggState = connectivity.TransientFailure pickers = transientFailurePickers } else { aggState = connectivity.TransientFailure pickers = []balancer.Picker{base.NewErrPicker(errors.New("no children to pick from"))} } // No children (resolver error before valid update). p := &pickerWithChildStates{ pickers: pickers, childStates: childStates, next: uint32(rand.IntN(len(pickers))), } es.cc.UpdateState(balancer.State{ ConnectivityState: aggState, Picker: p, }) } // pickerWithChildStates delegates to the pickers it holds in a round robin // fashion. It also contains the childStates of all the endpointSharding's // children. type pickerWithChildStates struct { pickers []balancer.Picker childStates []ChildState next uint32 } func (p *pickerWithChildStates) Pick(info balancer.PickInfo) (balancer.PickResult, error) { nextIndex := atomic.AddUint32(&p.next, 1) picker := p.pickers[nextIndex%uint32(len(p.pickers))] return picker.Pick(info) } // ChildStatesFromPicker returns the state of all the children managed by the // endpoint sharding balancer that created this picker. func ChildStatesFromPicker(picker balancer.Picker) []ChildState { p, ok := picker.(*pickerWithChildStates) if !ok { return nil } return p.childStates } // balancerWrapper is a wrapper of a balancer. It ID's a child balancer by // endpoint, and persists recent child balancer state. type balancerWrapper struct { // The following fields are initialized at build time and read-only after // that and therefore do not need to be guarded by a mutex. // child contains the wrapped balancer. Access its methods only through // methods on balancerWrapper to ensure proper synchronization child balancer.Balancer balancer.ClientConn // embed to intercept UpdateState, doesn't deal with SubConns es *endpointSharding // Access to the following fields is guarded by es.mu. childState ChildState isClosed bool } func (bw *balancerWrapper) UpdateState(state balancer.State) { bw.es.mu.Lock() bw.childState.State = state bw.es.mu.Unlock() if state.ConnectivityState == connectivity.Idle && !bw.es.esOpts.DisableAutoReconnect { bw.ExitIdle() } bw.es.updateState() } // ExitIdle pings an IDLE child balancer to exit idle in a new goroutine to // avoid deadlocks due to synchronous balancer state updates. func (bw *balancerWrapper) ExitIdle() { if ei, ok := bw.child.(balancer.ExitIdler); ok { go func() { bw.es.childMu.Lock() if !bw.isClosed { ei.ExitIdle() } bw.es.childMu.Unlock() }() } } // updateClientConnStateLocked delivers the ClientConnState to the child // balancer. Callers must hold the child mutex of the parent endpointsharding // balancer. func (bw *balancerWrapper) updateClientConnStateLocked(ccs balancer.ClientConnState) error { return bw.child.UpdateClientConnState(ccs) } // closeLocked closes the child balancer. Callers must hold the child mutext of // the parent endpointsharding balancer. func (bw *balancerWrapper) closeLocked() { bw.child.Close() bw.isClosed = true } func (bw *balancerWrapper) resolverErrorLocked(err error) { bw.child.ResolverError(err) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/balancer/base/base.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/balancer/base/base.go
/* * * Copyright 2017 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. * */ // Package base defines a balancer base that can be used to build balancers with // different picking algorithms. // // The base balancer creates a new SubConn for each resolved address. The // provided picker will only be notified about READY SubConns. // // This package is the base of round_robin balancer, its purpose is to be used // to build round_robin like balancers with complex picking algorithms. // Balancers with more complicated logic should try to implement a balancer // builder from scratch. // // All APIs in this package are experimental. package base import ( "google.golang.org/grpc/balancer" "google.golang.org/grpc/resolver" ) // PickerBuilder creates balancer.Picker. type PickerBuilder interface { // Build returns a picker that will be used by gRPC to pick a SubConn. Build(info PickerBuildInfo) balancer.Picker } // PickerBuildInfo contains information needed by the picker builder to // construct a picker. type PickerBuildInfo struct { // ReadySCs is a map from all ready SubConns to the Addresses used to // create them. ReadySCs map[balancer.SubConn]SubConnInfo } // SubConnInfo contains information about a SubConn created by the base // balancer. type SubConnInfo struct { Address resolver.Address // the address used to create this SubConn } // Config contains the config info about the base balancer builder. type Config struct { // HealthCheck indicates whether health checking should be enabled for this specific balancer. HealthCheck bool } // NewBalancerBuilder returns a base balancer builder configured by the provided config. func NewBalancerBuilder(name string, pb PickerBuilder, config Config) balancer.Builder { return &baseBuilder{ name: name, pickerBuilder: pb, config: config, } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/balancer/base/balancer.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/balancer/base/balancer.go
/* * * Copyright 2017 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. * */ package base import ( "errors" "fmt" "google.golang.org/grpc/balancer" "google.golang.org/grpc/connectivity" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/resolver" ) var logger = grpclog.Component("balancer") type baseBuilder struct { name string pickerBuilder PickerBuilder config Config } func (bb *baseBuilder) Build(cc balancer.ClientConn, _ balancer.BuildOptions) balancer.Balancer { bal := &baseBalancer{ cc: cc, pickerBuilder: bb.pickerBuilder, subConns: resolver.NewAddressMap(), scStates: make(map[balancer.SubConn]connectivity.State), csEvltr: &balancer.ConnectivityStateEvaluator{}, config: bb.config, state: connectivity.Connecting, } // Initialize picker to a picker that always returns // ErrNoSubConnAvailable, because when state of a SubConn changes, we // may call UpdateState with this picker. bal.picker = NewErrPicker(balancer.ErrNoSubConnAvailable) return bal } func (bb *baseBuilder) Name() string { return bb.name } type baseBalancer struct { cc balancer.ClientConn pickerBuilder PickerBuilder csEvltr *balancer.ConnectivityStateEvaluator state connectivity.State subConns *resolver.AddressMap scStates map[balancer.SubConn]connectivity.State picker balancer.Picker config Config resolverErr error // the last error reported by the resolver; cleared on successful resolution connErr error // the last connection error; cleared upon leaving TransientFailure } func (b *baseBalancer) ResolverError(err error) { b.resolverErr = err if b.subConns.Len() == 0 { b.state = connectivity.TransientFailure } if b.state != connectivity.TransientFailure { // The picker will not change since the balancer does not currently // report an error. return } b.regeneratePicker() b.cc.UpdateState(balancer.State{ ConnectivityState: b.state, Picker: b.picker, }) } func (b *baseBalancer) UpdateClientConnState(s balancer.ClientConnState) error { // TODO: handle s.ResolverState.ServiceConfig? if logger.V(2) { logger.Info("base.baseBalancer: got new ClientConn state: ", s) } // Successful resolution; clear resolver error and ensure we return nil. b.resolverErr = nil // addrsSet is the set converted from addrs, it's used for quick lookup of an address. addrsSet := resolver.NewAddressMap() for _, a := range s.ResolverState.Addresses { addrsSet.Set(a, nil) if _, ok := b.subConns.Get(a); !ok { // a is a new address (not existing in b.subConns). var sc balancer.SubConn opts := balancer.NewSubConnOptions{ HealthCheckEnabled: b.config.HealthCheck, StateListener: func(scs balancer.SubConnState) { b.updateSubConnState(sc, scs) }, } sc, err := b.cc.NewSubConn([]resolver.Address{a}, opts) if err != nil { logger.Warningf("base.baseBalancer: failed to create new SubConn: %v", err) continue } b.subConns.Set(a, sc) b.scStates[sc] = connectivity.Idle b.csEvltr.RecordTransition(connectivity.Shutdown, connectivity.Idle) sc.Connect() } } for _, a := range b.subConns.Keys() { sci, _ := b.subConns.Get(a) sc := sci.(balancer.SubConn) // a was removed by resolver. if _, ok := addrsSet.Get(a); !ok { sc.Shutdown() b.subConns.Delete(a) // Keep the state of this sc in b.scStates until sc's state becomes Shutdown. // The entry will be deleted in updateSubConnState. } } // If resolver state contains no addresses, return an error so ClientConn // will trigger re-resolve. Also records this as a resolver error, so when // the overall state turns transient failure, the error message will have // the zero address information. if len(s.ResolverState.Addresses) == 0 { b.ResolverError(errors.New("produced zero addresses")) return balancer.ErrBadResolverState } b.regeneratePicker() b.cc.UpdateState(balancer.State{ConnectivityState: b.state, Picker: b.picker}) return nil } // mergeErrors builds an error from the last connection error and the last // resolver error. Must only be called if b.state is TransientFailure. func (b *baseBalancer) mergeErrors() error { // connErr must always be non-nil unless there are no SubConns, in which // case resolverErr must be non-nil. if b.connErr == nil { return fmt.Errorf("last resolver error: %v", b.resolverErr) } if b.resolverErr == nil { return fmt.Errorf("last connection error: %v", b.connErr) } return fmt.Errorf("last connection error: %v; last resolver error: %v", b.connErr, b.resolverErr) } // regeneratePicker takes a snapshot of the balancer, and generates a picker // from it. The picker is // - errPicker if the balancer is in TransientFailure, // - built by the pickerBuilder with all READY SubConns otherwise. func (b *baseBalancer) regeneratePicker() { if b.state == connectivity.TransientFailure { b.picker = NewErrPicker(b.mergeErrors()) return } readySCs := make(map[balancer.SubConn]SubConnInfo) // Filter out all ready SCs from full subConn map. for _, addr := range b.subConns.Keys() { sci, _ := b.subConns.Get(addr) sc := sci.(balancer.SubConn) if st, ok := b.scStates[sc]; ok && st == connectivity.Ready { readySCs[sc] = SubConnInfo{Address: addr} } } b.picker = b.pickerBuilder.Build(PickerBuildInfo{ReadySCs: readySCs}) } // UpdateSubConnState is a nop because a StateListener is always set in NewSubConn. func (b *baseBalancer) UpdateSubConnState(sc balancer.SubConn, state balancer.SubConnState) { logger.Errorf("base.baseBalancer: UpdateSubConnState(%v, %+v) called unexpectedly", sc, state) } func (b *baseBalancer) updateSubConnState(sc balancer.SubConn, state balancer.SubConnState) { s := state.ConnectivityState if logger.V(2) { logger.Infof("base.baseBalancer: handle SubConn state change: %p, %v", sc, s) } oldS, ok := b.scStates[sc] if !ok { if logger.V(2) { logger.Infof("base.baseBalancer: got state changes for an unknown SubConn: %p, %v", sc, s) } return } if oldS == connectivity.TransientFailure && (s == connectivity.Connecting || s == connectivity.Idle) { // Once a subconn enters TRANSIENT_FAILURE, ignore subsequent IDLE or // CONNECTING transitions to prevent the aggregated state from being // always CONNECTING when many backends exist but are all down. if s == connectivity.Idle { sc.Connect() } return } b.scStates[sc] = s switch s { case connectivity.Idle: sc.Connect() case connectivity.Shutdown: // When an address was removed by resolver, b called Shutdown but kept // the sc's state in scStates. Remove state for this sc here. delete(b.scStates, sc) case connectivity.TransientFailure: // Save error to be reported via picker. b.connErr = state.ConnectionError } b.state = b.csEvltr.RecordTransition(oldS, s) // Regenerate picker when one of the following happens: // - this sc entered or left ready // - the aggregated state of balancer is TransientFailure // (may need to update error message) if (s == connectivity.Ready) != (oldS == connectivity.Ready) || b.state == connectivity.TransientFailure { b.regeneratePicker() } b.cc.UpdateState(balancer.State{ConnectivityState: b.state, Picker: b.picker}) } // Close is a nop because base balancer doesn't have internal state to clean up, // and it doesn't need to call Shutdown for the SubConns. func (b *baseBalancer) Close() { } // ExitIdle is a nop because the base balancer attempts to stay connected to // all SubConns at all times. func (b *baseBalancer) ExitIdle() { } // NewErrPicker returns a Picker that always returns err on Pick(). func NewErrPicker(err error) balancer.Picker { return &errPicker{err: err} } // NewErrPickerV2 is temporarily defined for backward compatibility reasons. // // Deprecated: use NewErrPicker instead. var NewErrPickerV2 = NewErrPicker type errPicker struct { err error // Pick() always returns this err. } func (p *errPicker) Pick(balancer.PickInfo) (balancer.PickResult, error) { return balancer.PickResult{}, p.err }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/balancer/pickfirst/pickfirst.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/balancer/pickfirst/pickfirst.go
/* * * Copyright 2017 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. * */ // Package pickfirst contains the pick_first load balancing policy. package pickfirst import ( "encoding/json" "errors" "fmt" rand "math/rand/v2" "google.golang.org/grpc/balancer" "google.golang.org/grpc/balancer/pickfirst/internal" "google.golang.org/grpc/connectivity" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/internal/envconfig" internalgrpclog "google.golang.org/grpc/internal/grpclog" "google.golang.org/grpc/internal/pretty" "google.golang.org/grpc/resolver" "google.golang.org/grpc/serviceconfig" _ "google.golang.org/grpc/balancer/pickfirst/pickfirstleaf" // For automatically registering the new pickfirst if required. ) func init() { if envconfig.NewPickFirstEnabled { return } balancer.Register(pickfirstBuilder{}) } var logger = grpclog.Component("pick-first-lb") const ( // Name is the name of the pick_first balancer. Name = "pick_first" logPrefix = "[pick-first-lb %p] " ) type pickfirstBuilder struct{} func (pickfirstBuilder) Build(cc balancer.ClientConn, _ balancer.BuildOptions) balancer.Balancer { b := &pickfirstBalancer{cc: cc} b.logger = internalgrpclog.NewPrefixLogger(logger, fmt.Sprintf(logPrefix, b)) return b } func (pickfirstBuilder) Name() string { return Name } type pfConfig struct { serviceconfig.LoadBalancingConfig `json:"-"` // If set to true, instructs the LB policy to shuffle the order of the list // of endpoints received from the name resolver before attempting to // connect to them. ShuffleAddressList bool `json:"shuffleAddressList"` } func (pickfirstBuilder) ParseConfig(js json.RawMessage) (serviceconfig.LoadBalancingConfig, error) { var cfg pfConfig if err := json.Unmarshal(js, &cfg); err != nil { return nil, fmt.Errorf("pickfirst: unable to unmarshal LB policy config: %s, error: %v", string(js), err) } return cfg, nil } type pickfirstBalancer struct { logger *internalgrpclog.PrefixLogger state connectivity.State cc balancer.ClientConn subConn balancer.SubConn } func (b *pickfirstBalancer) ResolverError(err error) { if b.logger.V(2) { b.logger.Infof("Received error from the name resolver: %v", err) } if b.subConn == nil { b.state = connectivity.TransientFailure } if b.state != connectivity.TransientFailure { // The picker will not change since the balancer does not currently // report an error. return } b.cc.UpdateState(balancer.State{ ConnectivityState: connectivity.TransientFailure, Picker: &picker{err: fmt.Errorf("name resolver error: %v", err)}, }) } // Shuffler is an interface for shuffling an address list. type Shuffler interface { ShuffleAddressListForTesting(n int, swap func(i, j int)) } // ShuffleAddressListForTesting pseudo-randomizes the order of addresses. n // is the number of elements. swap swaps the elements with indexes i and j. func ShuffleAddressListForTesting(n int, swap func(i, j int)) { rand.Shuffle(n, swap) } func (b *pickfirstBalancer) UpdateClientConnState(state balancer.ClientConnState) error { if len(state.ResolverState.Addresses) == 0 && len(state.ResolverState.Endpoints) == 0 { // The resolver reported an empty address list. Treat it like an error by // calling b.ResolverError. if b.subConn != nil { // Shut down the old subConn. All addresses were removed, so it is // no longer valid. b.subConn.Shutdown() b.subConn = nil } b.ResolverError(errors.New("produced zero addresses")) return balancer.ErrBadResolverState } // We don't have to guard this block with the env var because ParseConfig // already does so. cfg, ok := state.BalancerConfig.(pfConfig) if state.BalancerConfig != nil && !ok { return fmt.Errorf("pickfirst: received illegal BalancerConfig (type %T): %v", state.BalancerConfig, state.BalancerConfig) } if b.logger.V(2) { b.logger.Infof("Received new config %s, resolver state %s", pretty.ToJSON(cfg), pretty.ToJSON(state.ResolverState)) } var addrs []resolver.Address if endpoints := state.ResolverState.Endpoints; len(endpoints) != 0 { // Perform the optional shuffling described in gRFC A62. The shuffling will // change the order of endpoints but not touch the order of the addresses // within each endpoint. - A61 if cfg.ShuffleAddressList { endpoints = append([]resolver.Endpoint{}, endpoints...) internal.RandShuffle(len(endpoints), func(i, j int) { endpoints[i], endpoints[j] = endpoints[j], endpoints[i] }) } // "Flatten the list by concatenating the ordered list of addresses for each // of the endpoints, in order." - A61 for _, endpoint := range endpoints { // "In the flattened list, interleave addresses from the two address // families, as per RFC-8304 section 4." - A61 // TODO: support the above language. addrs = append(addrs, endpoint.Addresses...) } } else { // Endpoints not set, process addresses until we migrate resolver // emissions fully to Endpoints. The top channel does wrap emitted // addresses with endpoints, however some balancers such as weighted // target do not forward the corresponding correct endpoints down/split // endpoints properly. Once all balancers correctly forward endpoints // down, can delete this else conditional. addrs = state.ResolverState.Addresses if cfg.ShuffleAddressList { addrs = append([]resolver.Address{}, addrs...) rand.Shuffle(len(addrs), func(i, j int) { addrs[i], addrs[j] = addrs[j], addrs[i] }) } } if b.subConn != nil { b.cc.UpdateAddresses(b.subConn, addrs) return nil } var subConn balancer.SubConn subConn, err := b.cc.NewSubConn(addrs, balancer.NewSubConnOptions{ StateListener: func(state balancer.SubConnState) { b.updateSubConnState(subConn, state) }, }) if err != nil { if b.logger.V(2) { b.logger.Infof("Failed to create new SubConn: %v", err) } b.state = connectivity.TransientFailure b.cc.UpdateState(balancer.State{ ConnectivityState: connectivity.TransientFailure, Picker: &picker{err: fmt.Errorf("error creating connection: %v", err)}, }) return balancer.ErrBadResolverState } b.subConn = subConn b.state = connectivity.Idle b.cc.UpdateState(balancer.State{ ConnectivityState: connectivity.Connecting, Picker: &picker{err: balancer.ErrNoSubConnAvailable}, }) b.subConn.Connect() return nil } // UpdateSubConnState is unused as a StateListener is always registered when // creating SubConns. func (b *pickfirstBalancer) UpdateSubConnState(subConn balancer.SubConn, state balancer.SubConnState) { b.logger.Errorf("UpdateSubConnState(%v, %+v) called unexpectedly", subConn, state) } func (b *pickfirstBalancer) updateSubConnState(subConn balancer.SubConn, state balancer.SubConnState) { if b.logger.V(2) { b.logger.Infof("Received SubConn state update: %p, %+v", subConn, state) } if b.subConn != subConn { if b.logger.V(2) { b.logger.Infof("Ignored state change because subConn is not recognized") } return } if state.ConnectivityState == connectivity.Shutdown { b.subConn = nil return } switch state.ConnectivityState { case connectivity.Ready: b.cc.UpdateState(balancer.State{ ConnectivityState: state.ConnectivityState, Picker: &picker{result: balancer.PickResult{SubConn: subConn}}, }) case connectivity.Connecting: if b.state == connectivity.TransientFailure { // We stay in TransientFailure until we are Ready. See A62. return } b.cc.UpdateState(balancer.State{ ConnectivityState: state.ConnectivityState, Picker: &picker{err: balancer.ErrNoSubConnAvailable}, }) case connectivity.Idle: if b.state == connectivity.TransientFailure { // We stay in TransientFailure until we are Ready. Also kick the // subConn out of Idle into Connecting. See A62. b.subConn.Connect() return } b.cc.UpdateState(balancer.State{ ConnectivityState: state.ConnectivityState, Picker: &idlePicker{subConn: subConn}, }) case connectivity.TransientFailure: b.cc.UpdateState(balancer.State{ ConnectivityState: state.ConnectivityState, Picker: &picker{err: state.ConnectionError}, }) } b.state = state.ConnectivityState } func (b *pickfirstBalancer) Close() { } func (b *pickfirstBalancer) ExitIdle() { if b.subConn != nil && b.state == connectivity.Idle { b.subConn.Connect() } } type picker struct { result balancer.PickResult err error } func (p *picker) Pick(balancer.PickInfo) (balancer.PickResult, error) { return p.result, p.err } // idlePicker is used when the SubConn is IDLE and kicks the SubConn into // CONNECTING when Pick is called. type idlePicker struct { subConn balancer.SubConn } func (i *idlePicker) Pick(balancer.PickInfo) (balancer.PickResult, error) { i.subConn.Connect() return balancer.PickResult{}, balancer.ErrNoSubConnAvailable }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/balancer/pickfirst/pickfirstleaf/pickfirstleaf.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/balancer/pickfirst/pickfirstleaf/pickfirstleaf.go
/* * * Copyright 2024 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. * */ // Package pickfirstleaf contains the pick_first load balancing policy which // will be the universal leaf policy after dualstack changes are implemented. // // # Experimental // // Notice: This package is EXPERIMENTAL and may be changed or removed in a // later release. package pickfirstleaf import ( "encoding/json" "errors" "fmt" "net" "net/netip" "sync" "time" "google.golang.org/grpc/balancer" "google.golang.org/grpc/balancer/pickfirst/internal" "google.golang.org/grpc/connectivity" expstats "google.golang.org/grpc/experimental/stats" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/internal/envconfig" internalgrpclog "google.golang.org/grpc/internal/grpclog" "google.golang.org/grpc/internal/pretty" "google.golang.org/grpc/resolver" "google.golang.org/grpc/serviceconfig" ) func init() { if envconfig.NewPickFirstEnabled { // Register as the default pick_first balancer. Name = "pick_first" } balancer.Register(pickfirstBuilder{}) } type ( // enableHealthListenerKeyType is a unique key type used in resolver // attributes to indicate whether the health listener usage is enabled. enableHealthListenerKeyType struct{} // managedByPickfirstKeyType is an attribute key type to inform Outlier // Detection that the generic health listener is being used. // TODO: https://github.com/grpc/grpc-go/issues/7915 - Remove this when // implementing the dualstack design. This is a hack. Once Dualstack is // completed, outlier detection will stop sending ejection updates through // the connectivity listener. managedByPickfirstKeyType struct{} ) var ( logger = grpclog.Component("pick-first-leaf-lb") // Name is the name of the pick_first_leaf balancer. // It is changed to "pick_first" in init() if this balancer is to be // registered as the default pickfirst. Name = "pick_first_leaf" disconnectionsMetric = expstats.RegisterInt64Count(expstats.MetricDescriptor{ Name: "grpc.lb.pick_first.disconnections", Description: "EXPERIMENTAL. Number of times the selected subchannel becomes disconnected.", Unit: "disconnection", Labels: []string{"grpc.target"}, Default: false, }) connectionAttemptsSucceededMetric = expstats.RegisterInt64Count(expstats.MetricDescriptor{ Name: "grpc.lb.pick_first.connection_attempts_succeeded", Description: "EXPERIMENTAL. Number of successful connection attempts.", Unit: "attempt", Labels: []string{"grpc.target"}, Default: false, }) connectionAttemptsFailedMetric = expstats.RegisterInt64Count(expstats.MetricDescriptor{ Name: "grpc.lb.pick_first.connection_attempts_failed", Description: "EXPERIMENTAL. Number of failed connection attempts.", Unit: "attempt", Labels: []string{"grpc.target"}, Default: false, }) ) const ( // TODO: change to pick-first when this becomes the default pick_first policy. logPrefix = "[pick-first-leaf-lb %p] " // connectionDelayInterval is the time to wait for during the happy eyeballs // pass before starting the next connection attempt. connectionDelayInterval = 250 * time.Millisecond ) type ipAddrFamily int const ( // ipAddrFamilyUnknown represents strings that can't be parsed as an IP // address. ipAddrFamilyUnknown ipAddrFamily = iota ipAddrFamilyV4 ipAddrFamilyV6 ) type pickfirstBuilder struct{} func (pickfirstBuilder) Build(cc balancer.ClientConn, bo balancer.BuildOptions) balancer.Balancer { b := &pickfirstBalancer{ cc: cc, target: bo.Target.String(), metricsRecorder: cc.MetricsRecorder(), subConns: resolver.NewAddressMap(), state: connectivity.Connecting, cancelConnectionTimer: func() {}, } b.logger = internalgrpclog.NewPrefixLogger(logger, fmt.Sprintf(logPrefix, b)) return b } func (b pickfirstBuilder) Name() string { return Name } func (pickfirstBuilder) ParseConfig(js json.RawMessage) (serviceconfig.LoadBalancingConfig, error) { var cfg pfConfig if err := json.Unmarshal(js, &cfg); err != nil { return nil, fmt.Errorf("pickfirst: unable to unmarshal LB policy config: %s, error: %v", string(js), err) } return cfg, nil } // EnableHealthListener updates the state to configure pickfirst for using a // generic health listener. func EnableHealthListener(state resolver.State) resolver.State { state.Attributes = state.Attributes.WithValue(enableHealthListenerKeyType{}, true) return state } // IsManagedByPickfirst returns whether an address belongs to a SubConn // managed by the pickfirst LB policy. // TODO: https://github.com/grpc/grpc-go/issues/7915 - This is a hack to disable // outlier_detection via the with connectivity listener when using pick_first. // Once Dualstack changes are complete, all SubConns will be created by // pick_first and outlier detection will only use the health listener for // ejection. This hack can then be removed. func IsManagedByPickfirst(addr resolver.Address) bool { return addr.BalancerAttributes.Value(managedByPickfirstKeyType{}) != nil } type pfConfig struct { serviceconfig.LoadBalancingConfig `json:"-"` // If set to true, instructs the LB policy to shuffle the order of the list // of endpoints received from the name resolver before attempting to // connect to them. ShuffleAddressList bool `json:"shuffleAddressList"` } // scData keeps track of the current state of the subConn. // It is not safe for concurrent access. type scData struct { // The following fields are initialized at build time and read-only after // that. subConn balancer.SubConn addr resolver.Address rawConnectivityState connectivity.State // The effective connectivity state based on raw connectivity, health state // and after following sticky TransientFailure behaviour defined in A62. effectiveState connectivity.State lastErr error connectionFailedInFirstPass bool } func (b *pickfirstBalancer) newSCData(addr resolver.Address) (*scData, error) { addr.BalancerAttributes = addr.BalancerAttributes.WithValue(managedByPickfirstKeyType{}, true) sd := &scData{ rawConnectivityState: connectivity.Idle, effectiveState: connectivity.Idle, addr: addr, } sc, err := b.cc.NewSubConn([]resolver.Address{addr}, balancer.NewSubConnOptions{ StateListener: func(state balancer.SubConnState) { b.updateSubConnState(sd, state) }, }) if err != nil { return nil, err } sd.subConn = sc return sd, nil } type pickfirstBalancer struct { // The following fields are initialized at build time and read-only after // that and therefore do not need to be guarded by a mutex. logger *internalgrpclog.PrefixLogger cc balancer.ClientConn target string metricsRecorder expstats.MetricsRecorder // guaranteed to be non nil // The mutex is used to ensure synchronization of updates triggered // from the idle picker and the already serialized resolver, // SubConn state updates. mu sync.Mutex // State reported to the channel based on SubConn states and resolver // updates. state connectivity.State // scData for active subonns mapped by address. subConns *resolver.AddressMap addressList addressList firstPass bool numTF int cancelConnectionTimer func() healthCheckingEnabled bool } // ResolverError is called by the ClientConn when the name resolver produces // an error or when pickfirst determined the resolver update to be invalid. func (b *pickfirstBalancer) ResolverError(err error) { b.mu.Lock() defer b.mu.Unlock() b.resolverErrorLocked(err) } func (b *pickfirstBalancer) resolverErrorLocked(err error) { if b.logger.V(2) { b.logger.Infof("Received error from the name resolver: %v", err) } // The picker will not change since the balancer does not currently // report an error. If the balancer hasn't received a single good resolver // update yet, transition to TRANSIENT_FAILURE. if b.state != connectivity.TransientFailure && b.addressList.size() > 0 { if b.logger.V(2) { b.logger.Infof("Ignoring resolver error because balancer is using a previous good update.") } return } b.updateBalancerState(balancer.State{ ConnectivityState: connectivity.TransientFailure, Picker: &picker{err: fmt.Errorf("name resolver error: %v", err)}, }) } func (b *pickfirstBalancer) UpdateClientConnState(state balancer.ClientConnState) error { b.mu.Lock() defer b.mu.Unlock() b.cancelConnectionTimer() if len(state.ResolverState.Addresses) == 0 && len(state.ResolverState.Endpoints) == 0 { // Cleanup state pertaining to the previous resolver state. // Treat an empty address list like an error by calling b.ResolverError. b.closeSubConnsLocked() b.addressList.updateAddrs(nil) b.resolverErrorLocked(errors.New("produced zero addresses")) return balancer.ErrBadResolverState } b.healthCheckingEnabled = state.ResolverState.Attributes.Value(enableHealthListenerKeyType{}) != nil cfg, ok := state.BalancerConfig.(pfConfig) if state.BalancerConfig != nil && !ok { return fmt.Errorf("pickfirst: received illegal BalancerConfig (type %T): %v: %w", state.BalancerConfig, state.BalancerConfig, balancer.ErrBadResolverState) } if b.logger.V(2) { b.logger.Infof("Received new config %s, resolver state %s", pretty.ToJSON(cfg), pretty.ToJSON(state.ResolverState)) } var newAddrs []resolver.Address if endpoints := state.ResolverState.Endpoints; len(endpoints) != 0 { // Perform the optional shuffling described in gRFC A62. The shuffling // will change the order of endpoints but not touch the order of the // addresses within each endpoint. - A61 if cfg.ShuffleAddressList { endpoints = append([]resolver.Endpoint{}, endpoints...) internal.RandShuffle(len(endpoints), func(i, j int) { endpoints[i], endpoints[j] = endpoints[j], endpoints[i] }) } // "Flatten the list by concatenating the ordered list of addresses for // each of the endpoints, in order." - A61 for _, endpoint := range endpoints { newAddrs = append(newAddrs, endpoint.Addresses...) } } else { // Endpoints not set, process addresses until we migrate resolver // emissions fully to Endpoints. The top channel does wrap emitted // addresses with endpoints, however some balancers such as weighted // target do not forward the corresponding correct endpoints down/split // endpoints properly. Once all balancers correctly forward endpoints // down, can delete this else conditional. newAddrs = state.ResolverState.Addresses if cfg.ShuffleAddressList { newAddrs = append([]resolver.Address{}, newAddrs...) internal.RandShuffle(len(endpoints), func(i, j int) { endpoints[i], endpoints[j] = endpoints[j], endpoints[i] }) } } // If an address appears in multiple endpoints or in the same endpoint // multiple times, we keep it only once. We will create only one SubConn // for the address because an AddressMap is used to store SubConns. // Not de-duplicating would result in attempting to connect to the same // SubConn multiple times in the same pass. We don't want this. newAddrs = deDupAddresses(newAddrs) newAddrs = interleaveAddresses(newAddrs) prevAddr := b.addressList.currentAddress() prevSCData, found := b.subConns.Get(prevAddr) prevAddrsCount := b.addressList.size() isPrevRawConnectivityStateReady := found && prevSCData.(*scData).rawConnectivityState == connectivity.Ready b.addressList.updateAddrs(newAddrs) // If the previous ready SubConn exists in new address list, // keep this connection and don't create new SubConns. if isPrevRawConnectivityStateReady && b.addressList.seekTo(prevAddr) { return nil } b.reconcileSubConnsLocked(newAddrs) // If it's the first resolver update or the balancer was already READY // (but the new address list does not contain the ready SubConn) or // CONNECTING, enter CONNECTING. // We may be in TRANSIENT_FAILURE due to a previous empty address list, // we should still enter CONNECTING because the sticky TF behaviour // mentioned in A62 applies only when the TRANSIENT_FAILURE is reported // due to connectivity failures. if isPrevRawConnectivityStateReady || b.state == connectivity.Connecting || prevAddrsCount == 0 { // Start connection attempt at first address. b.forceUpdateConcludedStateLocked(balancer.State{ ConnectivityState: connectivity.Connecting, Picker: &picker{err: balancer.ErrNoSubConnAvailable}, }) b.startFirstPassLocked() } else if b.state == connectivity.TransientFailure { // If we're in TRANSIENT_FAILURE, we stay in TRANSIENT_FAILURE until // we're READY. See A62. b.startFirstPassLocked() } return nil } // UpdateSubConnState is unused as a StateListener is always registered when // creating SubConns. func (b *pickfirstBalancer) UpdateSubConnState(subConn balancer.SubConn, state balancer.SubConnState) { b.logger.Errorf("UpdateSubConnState(%v, %+v) called unexpectedly", subConn, state) } func (b *pickfirstBalancer) Close() { b.mu.Lock() defer b.mu.Unlock() b.closeSubConnsLocked() b.cancelConnectionTimer() b.state = connectivity.Shutdown } // ExitIdle moves the balancer out of idle state. It can be called concurrently // by the idlePicker and clientConn so access to variables should be // synchronized. func (b *pickfirstBalancer) ExitIdle() { b.mu.Lock() defer b.mu.Unlock() if b.state == connectivity.Idle { b.startFirstPassLocked() } } func (b *pickfirstBalancer) startFirstPassLocked() { b.firstPass = true b.numTF = 0 // Reset the connection attempt record for existing SubConns. for _, sd := range b.subConns.Values() { sd.(*scData).connectionFailedInFirstPass = false } b.requestConnectionLocked() } func (b *pickfirstBalancer) closeSubConnsLocked() { for _, sd := range b.subConns.Values() { sd.(*scData).subConn.Shutdown() } b.subConns = resolver.NewAddressMap() } // deDupAddresses ensures that each address appears only once in the slice. func deDupAddresses(addrs []resolver.Address) []resolver.Address { seenAddrs := resolver.NewAddressMap() retAddrs := []resolver.Address{} for _, addr := range addrs { if _, ok := seenAddrs.Get(addr); ok { continue } retAddrs = append(retAddrs, addr) } return retAddrs } // interleaveAddresses interleaves addresses of both families (IPv4 and IPv6) // as per RFC-8305 section 4. // Whichever address family is first in the list is followed by an address of // the other address family; that is, if the first address in the list is IPv6, // then the first IPv4 address should be moved up in the list to be second in // the list. It doesn't support configuring "First Address Family Count", i.e. // there will always be a single member of the first address family at the // beginning of the interleaved list. // Addresses that are neither IPv4 nor IPv6 are treated as part of a third // "unknown" family for interleaving. // See: https://datatracker.ietf.org/doc/html/rfc8305#autoid-6 func interleaveAddresses(addrs []resolver.Address) []resolver.Address { familyAddrsMap := map[ipAddrFamily][]resolver.Address{} interleavingOrder := []ipAddrFamily{} for _, addr := range addrs { family := addressFamily(addr.Addr) if _, found := familyAddrsMap[family]; !found { interleavingOrder = append(interleavingOrder, family) } familyAddrsMap[family] = append(familyAddrsMap[family], addr) } interleavedAddrs := make([]resolver.Address, 0, len(addrs)) for curFamilyIdx := 0; len(interleavedAddrs) < len(addrs); curFamilyIdx = (curFamilyIdx + 1) % len(interleavingOrder) { // Some IP types may have fewer addresses than others, so we look for // the next type that has a remaining member to add to the interleaved // list. family := interleavingOrder[curFamilyIdx] remainingMembers := familyAddrsMap[family] if len(remainingMembers) > 0 { interleavedAddrs = append(interleavedAddrs, remainingMembers[0]) familyAddrsMap[family] = remainingMembers[1:] } } return interleavedAddrs } // addressFamily returns the ipAddrFamily after parsing the address string. // If the address isn't of the format "ip-address:port", it returns // ipAddrFamilyUnknown. The address may be valid even if it's not an IP when // using a resolver like passthrough where the address may be a hostname in // some format that the dialer can resolve. func addressFamily(address string) ipAddrFamily { // Parse the IP after removing the port. host, _, err := net.SplitHostPort(address) if err != nil { return ipAddrFamilyUnknown } ip, err := netip.ParseAddr(host) if err != nil { return ipAddrFamilyUnknown } switch { case ip.Is4() || ip.Is4In6(): return ipAddrFamilyV4 case ip.Is6(): return ipAddrFamilyV6 default: return ipAddrFamilyUnknown } } // reconcileSubConnsLocked updates the active subchannels based on a new address // list from the resolver. It does this by: // - closing subchannels: any existing subchannels associated with addresses // that are no longer in the updated list are shut down. // - removing subchannels: entries for these closed subchannels are removed // from the subchannel map. // // This ensures that the subchannel map accurately reflects the current set of // addresses received from the name resolver. func (b *pickfirstBalancer) reconcileSubConnsLocked(newAddrs []resolver.Address) { newAddrsMap := resolver.NewAddressMap() for _, addr := range newAddrs { newAddrsMap.Set(addr, true) } for _, oldAddr := range b.subConns.Keys() { if _, ok := newAddrsMap.Get(oldAddr); ok { continue } val, _ := b.subConns.Get(oldAddr) val.(*scData).subConn.Shutdown() b.subConns.Delete(oldAddr) } } // shutdownRemainingLocked shuts down remaining subConns. Called when a subConn // becomes ready, which means that all other subConn must be shutdown. func (b *pickfirstBalancer) shutdownRemainingLocked(selected *scData) { b.cancelConnectionTimer() for _, v := range b.subConns.Values() { sd := v.(*scData) if sd.subConn != selected.subConn { sd.subConn.Shutdown() } } b.subConns = resolver.NewAddressMap() b.subConns.Set(selected.addr, selected) } // requestConnectionLocked starts connecting on the subchannel corresponding to // the current address. If no subchannel exists, one is created. If the current // subchannel is in TransientFailure, a connection to the next address is // attempted until a subchannel is found. func (b *pickfirstBalancer) requestConnectionLocked() { if !b.addressList.isValid() { return } var lastErr error for valid := true; valid; valid = b.addressList.increment() { curAddr := b.addressList.currentAddress() sd, ok := b.subConns.Get(curAddr) if !ok { var err error // We want to assign the new scData to sd from the outer scope, // hence we can't use := below. sd, err = b.newSCData(curAddr) if err != nil { // This should never happen, unless the clientConn is being shut // down. if b.logger.V(2) { b.logger.Infof("Failed to create a subConn for address %v: %v", curAddr.String(), err) } // Do nothing, the LB policy will be closed soon. return } b.subConns.Set(curAddr, sd) } scd := sd.(*scData) switch scd.rawConnectivityState { case connectivity.Idle: scd.subConn.Connect() b.scheduleNextConnectionLocked() return case connectivity.TransientFailure: // The SubConn is being re-used and failed during a previous pass // over the addressList. It has not completed backoff yet. // Mark it as having failed and try the next address. scd.connectionFailedInFirstPass = true lastErr = scd.lastErr continue case connectivity.Connecting: // Wait for the connection attempt to complete or the timer to fire // before attempting the next address. b.scheduleNextConnectionLocked() return default: b.logger.Errorf("SubConn with unexpected state %v present in SubConns map.", scd.rawConnectivityState) return } } // All the remaining addresses in the list are in TRANSIENT_FAILURE, end the // first pass if possible. b.endFirstPassIfPossibleLocked(lastErr) } func (b *pickfirstBalancer) scheduleNextConnectionLocked() { b.cancelConnectionTimer() if !b.addressList.hasNext() { return } curAddr := b.addressList.currentAddress() cancelled := false // Access to this is protected by the balancer's mutex. closeFn := internal.TimeAfterFunc(connectionDelayInterval, func() { b.mu.Lock() defer b.mu.Unlock() // If the scheduled task is cancelled while acquiring the mutex, return. if cancelled { return } if b.logger.V(2) { b.logger.Infof("Happy Eyeballs timer expired while waiting for connection to %q.", curAddr.Addr) } if b.addressList.increment() { b.requestConnectionLocked() } }) // Access to the cancellation callback held by the balancer is guarded by // the balancer's mutex, so it's safe to set the boolean from the callback. b.cancelConnectionTimer = sync.OnceFunc(func() { cancelled = true closeFn() }) } func (b *pickfirstBalancer) updateSubConnState(sd *scData, newState balancer.SubConnState) { b.mu.Lock() defer b.mu.Unlock() oldState := sd.rawConnectivityState sd.rawConnectivityState = newState.ConnectivityState // Previously relevant SubConns can still callback with state updates. // To prevent pickers from returning these obsolete SubConns, this logic // is included to check if the current list of active SubConns includes this // SubConn. if !b.isActiveSCData(sd) { return } if newState.ConnectivityState == connectivity.Shutdown { sd.effectiveState = connectivity.Shutdown return } // Record a connection attempt when exiting CONNECTING. if newState.ConnectivityState == connectivity.TransientFailure { sd.connectionFailedInFirstPass = true connectionAttemptsFailedMetric.Record(b.metricsRecorder, 1, b.target) } if newState.ConnectivityState == connectivity.Ready { connectionAttemptsSucceededMetric.Record(b.metricsRecorder, 1, b.target) b.shutdownRemainingLocked(sd) if !b.addressList.seekTo(sd.addr) { // This should not fail as we should have only one SubConn after // entering READY. The SubConn should be present in the addressList. b.logger.Errorf("Address %q not found address list in %v", sd.addr, b.addressList.addresses) return } if !b.healthCheckingEnabled { if b.logger.V(2) { b.logger.Infof("SubConn %p reported connectivity state READY and the health listener is disabled. Transitioning SubConn to READY.", sd.subConn) } sd.effectiveState = connectivity.Ready b.updateBalancerState(balancer.State{ ConnectivityState: connectivity.Ready, Picker: &picker{result: balancer.PickResult{SubConn: sd.subConn}}, }) return } if b.logger.V(2) { b.logger.Infof("SubConn %p reported connectivity state READY. Registering health listener.", sd.subConn) } // Send a CONNECTING update to take the SubConn out of sticky-TF if // required. sd.effectiveState = connectivity.Connecting b.updateBalancerState(balancer.State{ ConnectivityState: connectivity.Connecting, Picker: &picker{err: balancer.ErrNoSubConnAvailable}, }) sd.subConn.RegisterHealthListener(func(scs balancer.SubConnState) { b.updateSubConnHealthState(sd, scs) }) return } // If the LB policy is READY, and it receives a subchannel state change, // it means that the READY subchannel has failed. // A SubConn can also transition from CONNECTING directly to IDLE when // a transport is successfully created, but the connection fails // before the SubConn can send the notification for READY. We treat // this as a successful connection and transition to IDLE. // TODO: https://github.com/grpc/grpc-go/issues/7862 - Remove the second // part of the if condition below once the issue is fixed. if oldState == connectivity.Ready || (oldState == connectivity.Connecting && newState.ConnectivityState == connectivity.Idle) { // Once a transport fails, the balancer enters IDLE and starts from // the first address when the picker is used. b.shutdownRemainingLocked(sd) sd.effectiveState = newState.ConnectivityState // READY SubConn interspliced in between CONNECTING and IDLE, need to // account for that. if oldState == connectivity.Connecting { // A known issue (https://github.com/grpc/grpc-go/issues/7862) // causes a race that prevents the READY state change notification. // This works around it. connectionAttemptsSucceededMetric.Record(b.metricsRecorder, 1, b.target) } disconnectionsMetric.Record(b.metricsRecorder, 1, b.target) b.addressList.reset() b.updateBalancerState(balancer.State{ ConnectivityState: connectivity.Idle, Picker: &idlePicker{exitIdle: sync.OnceFunc(b.ExitIdle)}, }) return } if b.firstPass { switch newState.ConnectivityState { case connectivity.Connecting: // The effective state can be in either IDLE, CONNECTING or // TRANSIENT_FAILURE. If it's TRANSIENT_FAILURE, stay in // TRANSIENT_FAILURE until it's READY. See A62. if sd.effectiveState != connectivity.TransientFailure { sd.effectiveState = connectivity.Connecting b.updateBalancerState(balancer.State{ ConnectivityState: connectivity.Connecting, Picker: &picker{err: balancer.ErrNoSubConnAvailable}, }) } case connectivity.TransientFailure: sd.lastErr = newState.ConnectionError sd.effectiveState = connectivity.TransientFailure // Since we're re-using common SubConns while handling resolver // updates, we could receive an out of turn TRANSIENT_FAILURE from // a pass over the previous address list. Happy Eyeballs will also // cause out of order updates to arrive. if curAddr := b.addressList.currentAddress(); equalAddressIgnoringBalAttributes(&curAddr, &sd.addr) { b.cancelConnectionTimer() if b.addressList.increment() { b.requestConnectionLocked() return } } // End the first pass if we've seen a TRANSIENT_FAILURE from all // SubConns once. b.endFirstPassIfPossibleLocked(newState.ConnectionError) } return } // We have finished the first pass, keep re-connecting failing SubConns. switch newState.ConnectivityState { case connectivity.TransientFailure: b.numTF = (b.numTF + 1) % b.subConns.Len() sd.lastErr = newState.ConnectionError if b.numTF%b.subConns.Len() == 0 { b.updateBalancerState(balancer.State{ ConnectivityState: connectivity.TransientFailure, Picker: &picker{err: newState.ConnectionError}, }) } // We don't need to request re-resolution since the SubConn already // does that before reporting TRANSIENT_FAILURE. // TODO: #7534 - Move re-resolution requests from SubConn into // pick_first. case connectivity.Idle: sd.subConn.Connect() } } // endFirstPassIfPossibleLocked ends the first happy-eyeballs pass if all the // addresses are tried and their SubConns have reported a failure. func (b *pickfirstBalancer) endFirstPassIfPossibleLocked(lastErr error) { // An optimization to avoid iterating over the entire SubConn map. if b.addressList.isValid() { return } // Connect() has been called on all the SubConns. The first pass can be // ended if all the SubConns have reported a failure. for _, v := range b.subConns.Values() { sd := v.(*scData) if !sd.connectionFailedInFirstPass { return } } b.firstPass = false b.updateBalancerState(balancer.State{ ConnectivityState: connectivity.TransientFailure, Picker: &picker{err: lastErr}, }) // Start re-connecting all the SubConns that are already in IDLE. for _, v := range b.subConns.Values() { sd := v.(*scData) if sd.rawConnectivityState == connectivity.Idle { sd.subConn.Connect() } } } func (b *pickfirstBalancer) isActiveSCData(sd *scData) bool { activeSD, found := b.subConns.Get(sd.addr) return found && activeSD == sd } func (b *pickfirstBalancer) updateSubConnHealthState(sd *scData, state balancer.SubConnState) { b.mu.Lock() defer b.mu.Unlock() // Previously relevant SubConns can still callback with state updates. // To prevent pickers from returning these obsolete SubConns, this logic // is included to check if the current list of active SubConns includes // this SubConn. if !b.isActiveSCData(sd) { return } sd.effectiveState = state.ConnectivityState switch state.ConnectivityState { case connectivity.Ready: b.updateBalancerState(balancer.State{ ConnectivityState: connectivity.Ready, Picker: &picker{result: balancer.PickResult{SubConn: sd.subConn}}, }) case connectivity.TransientFailure: b.updateBalancerState(balancer.State{ ConnectivityState: connectivity.TransientFailure, Picker: &picker{err: fmt.Errorf("pickfirst: health check failure: %v", state.ConnectionError)}, }) case connectivity.Connecting: b.updateBalancerState(balancer.State{ ConnectivityState: connectivity.Connecting, Picker: &picker{err: balancer.ErrNoSubConnAvailable}, }) default: b.logger.Errorf("Got unexpected health update for SubConn %p: %v", state) } } // updateBalancerState stores the state reported to the channel and calls // ClientConn.UpdateState(). As an optimization, it avoids sending duplicate // updates to the channel. func (b *pickfirstBalancer) updateBalancerState(newState balancer.State) { // In case of TransientFailures allow the picker to be updated to update // the connectivity error, in all other cases don't send duplicate state // updates. if newState.ConnectivityState == b.state && b.state != connectivity.TransientFailure { return } b.forceUpdateConcludedStateLocked(newState) } // forceUpdateConcludedStateLocked stores the state reported to the channel and // calls ClientConn.UpdateState(). // A separate function is defined to force update the ClientConn state since the // channel doesn't correctly assume that LB policies start in CONNECTING and // relies on LB policy to send an initial CONNECTING update. func (b *pickfirstBalancer) forceUpdateConcludedStateLocked(newState balancer.State) { b.state = newState.ConnectivityState b.cc.UpdateState(newState) } type picker struct { result balancer.PickResult err error } func (p *picker) Pick(balancer.PickInfo) (balancer.PickResult, error) { return p.result, p.err } // idlePicker is used when the SubConn is IDLE and kicks the SubConn into // CONNECTING when Pick is called. type idlePicker struct { exitIdle func() } func (i *idlePicker) Pick(balancer.PickInfo) (balancer.PickResult, error) { i.exitIdle() return balancer.PickResult{}, balancer.ErrNoSubConnAvailable } // addressList manages sequentially iterating over addresses present in a list // of endpoints. It provides a 1 dimensional view of the addresses present in // the endpoints. // This type is not safe for concurrent access. type addressList struct { addresses []resolver.Address idx int } func (al *addressList) isValid() bool { return al.idx < len(al.addresses) } func (al *addressList) size() int { return len(al.addresses) } // increment moves to the next index in the address list. // This method returns false if it went off the list, true otherwise. func (al *addressList) increment() bool { if !al.isValid() { return false } al.idx++ return al.idx < len(al.addresses) } // currentAddress returns the current address pointed to in the addressList. // If the list is in an invalid state, it returns an empty address instead. func (al *addressList) currentAddress() resolver.Address { if !al.isValid() { return resolver.Address{} } return al.addresses[al.idx] } func (al *addressList) reset() { al.idx = 0 } func (al *addressList) updateAddrs(addrs []resolver.Address) { al.addresses = addrs al.reset() } // seekTo returns false if the needle was not found and the current index was // left unchanged. func (al *addressList) seekTo(needle resolver.Address) bool { for ai, addr := range al.addresses { if !equalAddressIgnoringBalAttributes(&addr, &needle) { continue } al.idx = ai return true } return false } // hasNext returns whether incrementing the addressList will result in moving
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
true
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/balancer/pickfirst/internal/internal.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/balancer/pickfirst/internal/internal.go
/* * Copyright 2024 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. * */ // Package internal contains code internal to the pickfirst package. package internal import ( rand "math/rand/v2" "time" ) var ( // RandShuffle pseudo-randomizes the order of addresses. RandShuffle = rand.Shuffle // TimeAfterFunc allows mocking the timer for testing connection delay // related functionality. TimeAfterFunc = func(d time.Duration, f func()) func() { timer := time.AfterFunc(d, f) return func() { timer.Stop() } } )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/balancer/roundrobin/roundrobin.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/balancer/roundrobin/roundrobin.go
/* * * Copyright 2017 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. * */ // Package roundrobin defines a roundrobin balancer. Roundrobin balancer is // installed as one of the default balancers in gRPC, users don't need to // explicitly install this balancer. package roundrobin import ( "fmt" "google.golang.org/grpc/balancer" "google.golang.org/grpc/balancer/endpointsharding" "google.golang.org/grpc/balancer/pickfirst/pickfirstleaf" "google.golang.org/grpc/grpclog" internalgrpclog "google.golang.org/grpc/internal/grpclog" ) // Name is the name of round_robin balancer. const Name = "round_robin" var logger = grpclog.Component("roundrobin") func init() { balancer.Register(builder{}) } type builder struct{} func (bb builder) Name() string { return Name } func (bb builder) Build(cc balancer.ClientConn, opts balancer.BuildOptions) balancer.Balancer { childBuilder := balancer.Get(pickfirstleaf.Name).Build bal := &rrBalancer{ cc: cc, Balancer: endpointsharding.NewBalancer(cc, opts, childBuilder, endpointsharding.Options{}), } bal.logger = internalgrpclog.NewPrefixLogger(logger, fmt.Sprintf("[%p] ", bal)) bal.logger.Infof("Created") return bal } type rrBalancer struct { balancer.Balancer cc balancer.ClientConn logger *internalgrpclog.PrefixLogger } func (b *rrBalancer) UpdateClientConnState(ccs balancer.ClientConnState) error { return b.Balancer.UpdateClientConnState(balancer.ClientConnState{ // Enable the health listener in pickfirst children for client side health // checks and outlier detection, if configured. ResolverState: pickfirstleaf.EnableHealthListener(ccs.ResolverState), }) } func (b *rrBalancer) ExitIdle() { // Should always be ok, as child is endpoint sharding. if ei, ok := b.Balancer.(balancer.ExitIdler); ok { ei.ExitIdle() } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/balancer/grpclb/state/state.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/balancer/grpclb/state/state.go
/* * * Copyright 2020 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. * */ // Package state declares grpclb types to be set by resolvers wishing to pass // information to grpclb via resolver.State Attributes. package state import ( "google.golang.org/grpc/resolver" ) // keyType is the key to use for storing State in Attributes. type keyType string const key = keyType("grpc.grpclb.state") // State contains gRPCLB-relevant data passed from the name resolver. type State struct { // BalancerAddresses contains the remote load balancer address(es). If // set, overrides any resolver-provided addresses with Type of GRPCLB. BalancerAddresses []resolver.Address } // Set returns a copy of the provided state with attributes containing s. s's // data should not be mutated after calling Set. func Set(state resolver.State, s *State) resolver.State { state.Attributes = state.Attributes.WithValue(key, s) return state } // Get returns the grpclb State in the resolver.State, or nil if not present. // The returned data should not be mutated. func Get(state resolver.State) *State { s, _ := state.Attributes.Value(key).(*State) return s }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/resolver/resolver.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/resolver/resolver.go
/* * * Copyright 2017 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. * */ // Package resolver defines APIs for name resolution in gRPC. // All APIs in this package are experimental. package resolver import ( "context" "errors" "fmt" "net" "net/url" "strings" "google.golang.org/grpc/attributes" "google.golang.org/grpc/credentials" "google.golang.org/grpc/experimental/stats" "google.golang.org/grpc/internal" "google.golang.org/grpc/serviceconfig" ) var ( // m is a map from scheme to resolver builder. m = make(map[string]Builder) // defaultScheme is the default scheme to use. defaultScheme = "passthrough" ) // TODO(bar) install dns resolver in init(){}. // Register registers the resolver builder to the resolver map. b.Scheme will // be used as the scheme registered with this builder. The registry is case // sensitive, and schemes should not contain any uppercase characters. // // NOTE: this function must only be called during initialization time (i.e. in // an init() function), and is not thread-safe. If multiple Resolvers are // registered with the same name, the one registered last will take effect. func Register(b Builder) { m[b.Scheme()] = b } // Get returns the resolver builder registered with the given scheme. // // If no builder is register with the scheme, nil will be returned. func Get(scheme string) Builder { if b, ok := m[scheme]; ok { return b } return nil } // SetDefaultScheme sets the default scheme that will be used. The default // scheme is initially set to "passthrough". // // NOTE: this function must only be called during initialization time (i.e. in // an init() function), and is not thread-safe. The scheme set last overrides // previously set values. func SetDefaultScheme(scheme string) { defaultScheme = scheme internal.UserSetDefaultScheme = true } // GetDefaultScheme gets the default scheme that will be used by grpc.Dial. If // SetDefaultScheme is never called, the default scheme used by grpc.NewClient is "dns" instead. func GetDefaultScheme() string { return defaultScheme } // Address represents a server the client connects to. // // # Experimental // // Notice: This type is EXPERIMENTAL and may be changed or removed in a // later release. type Address struct { // Addr is the server address on which a connection will be established. Addr string // ServerName is the name of this address. // If non-empty, the ServerName is used as the transport certification authority for // the address, instead of the hostname from the Dial target string. In most cases, // this should not be set. // // WARNING: ServerName must only be populated with trusted values. It // is insecure to populate it with data from untrusted inputs since untrusted // values could be used to bypass the authority checks performed by TLS. ServerName string // Attributes contains arbitrary data about this address intended for // consumption by the SubConn. Attributes *attributes.Attributes // BalancerAttributes contains arbitrary data about this address intended // for consumption by the LB policy. These attributes do not affect SubConn // creation, connection establishment, handshaking, etc. // // Deprecated: when an Address is inside an Endpoint, this field should not // be used, and it will eventually be removed entirely. BalancerAttributes *attributes.Attributes // Metadata is the information associated with Addr, which may be used // to make load balancing decision. // // Deprecated: use Attributes instead. Metadata any } // Equal returns whether a and o are identical. Metadata is compared directly, // not with any recursive introspection. // // This method compares all fields of the address. When used to tell apart // addresses during subchannel creation or connection establishment, it might be // more appropriate for the caller to implement custom equality logic. func (a Address) Equal(o Address) bool { return a.Addr == o.Addr && a.ServerName == o.ServerName && a.Attributes.Equal(o.Attributes) && a.BalancerAttributes.Equal(o.BalancerAttributes) && a.Metadata == o.Metadata } // String returns JSON formatted string representation of the address. func (a Address) String() string { var sb strings.Builder sb.WriteString(fmt.Sprintf("{Addr: %q, ", a.Addr)) sb.WriteString(fmt.Sprintf("ServerName: %q, ", a.ServerName)) if a.Attributes != nil { sb.WriteString(fmt.Sprintf("Attributes: %v, ", a.Attributes.String())) } if a.BalancerAttributes != nil { sb.WriteString(fmt.Sprintf("BalancerAttributes: %v", a.BalancerAttributes.String())) } sb.WriteString("}") return sb.String() } // BuildOptions includes additional information for the builder to create // the resolver. type BuildOptions struct { // DisableServiceConfig indicates whether a resolver implementation should // fetch service config data. DisableServiceConfig bool // DialCreds is the transport credentials used by the ClientConn for // communicating with the target gRPC service (set via // WithTransportCredentials). In cases where a name resolution service // requires the same credentials, the resolver may use this field. In most // cases though, it is not appropriate, and this field may be ignored. DialCreds credentials.TransportCredentials // CredsBundle is the credentials bundle used by the ClientConn for // communicating with the target gRPC service (set via // WithCredentialsBundle). In cases where a name resolution service // requires the same credentials, the resolver may use this field. In most // cases though, it is not appropriate, and this field may be ignored. CredsBundle credentials.Bundle // Dialer is the custom dialer used by the ClientConn for dialling the // target gRPC service (set via WithDialer). In cases where a name // resolution service requires the same dialer, the resolver may use this // field. In most cases though, it is not appropriate, and this field may // be ignored. Dialer func(context.Context, string) (net.Conn, error) // Authority is the effective authority of the clientconn for which the // resolver is built. Authority string // MetricsRecorder is the metrics recorder to do recording. MetricsRecorder stats.MetricsRecorder } // An Endpoint is one network endpoint, or server, which may have multiple // addresses with which it can be accessed. type Endpoint struct { // Addresses contains a list of addresses used to access this endpoint. Addresses []Address // Attributes contains arbitrary data about this endpoint intended for // consumption by the LB policy. Attributes *attributes.Attributes } // State contains the current Resolver state relevant to the ClientConn. type State struct { // Addresses is the latest set of resolved addresses for the target. // // If a resolver sets Addresses but does not set Endpoints, one Endpoint // will be created for each Address before the State is passed to the LB // policy. The BalancerAttributes of each entry in Addresses will be set // in Endpoints.Attributes, and be cleared in the Endpoint's Address's // BalancerAttributes. // // Soon, Addresses will be deprecated and replaced fully by Endpoints. Addresses []Address // Endpoints is the latest set of resolved endpoints for the target. // // If a resolver produces a State containing Endpoints but not Addresses, // it must take care to ensure the LB policies it selects will support // Endpoints. Endpoints []Endpoint // ServiceConfig contains the result from parsing the latest service // config. If it is nil, it indicates no service config is present or the // resolver does not provide service configs. ServiceConfig *serviceconfig.ParseResult // Attributes contains arbitrary data about the resolver intended for // consumption by the load balancing policy. Attributes *attributes.Attributes } // ClientConn contains the callbacks for resolver to notify any updates // to the gRPC ClientConn. // // This interface is to be implemented by gRPC. Users should not need a // brand new implementation of this interface. For the situations like // testing, the new implementation should embed this interface. This allows // gRPC to add new methods to this interface. type ClientConn interface { // UpdateState updates the state of the ClientConn appropriately. // // If an error is returned, the resolver should try to resolve the // target again. The resolver should use a backoff timer to prevent // overloading the server with requests. If a resolver is certain that // reresolving will not change the result, e.g. because it is // a watch-based resolver, returned errors can be ignored. // // If the resolved State is the same as the last reported one, calling // UpdateState can be omitted. UpdateState(State) error // ReportError notifies the ClientConn that the Resolver encountered an // error. The ClientConn then forwards this error to the load balancing // policy. ReportError(error) // NewAddress is called by resolver to notify ClientConn a new list // of resolved addresses. // The address list should be the complete list of resolved addresses. // // Deprecated: Use UpdateState instead. NewAddress(addresses []Address) // ParseServiceConfig parses the provided service config and returns an // object that provides the parsed config. ParseServiceConfig(serviceConfigJSON string) *serviceconfig.ParseResult } // Target represents a target for gRPC, as specified in: // https://github.com/grpc/grpc/blob/master/doc/naming.md. // It is parsed from the target string that gets passed into Dial or DialContext // by the user. And gRPC passes it to the resolver and the balancer. // // If the target follows the naming spec, and the parsed scheme is registered // with gRPC, we will parse the target string according to the spec. If the // target does not contain a scheme or if the parsed scheme is not registered // (i.e. no corresponding resolver available to resolve the endpoint), we will // apply the default scheme, and will attempt to reparse it. type Target struct { // URL contains the parsed dial target with an optional default scheme added // to it if the original dial target contained no scheme or contained an // unregistered scheme. Any query params specified in the original dial // target can be accessed from here. URL url.URL } // Endpoint retrieves endpoint without leading "/" from either `URL.Path` // or `URL.Opaque`. The latter is used when the former is empty. func (t Target) Endpoint() string { endpoint := t.URL.Path if endpoint == "" { endpoint = t.URL.Opaque } // For targets of the form "[scheme]://[authority]/endpoint, the endpoint // value returned from url.Parse() contains a leading "/". Although this is // in accordance with RFC 3986, we do not want to break existing resolver // implementations which expect the endpoint without the leading "/". So, we // end up stripping the leading "/" here. But this will result in an // incorrect parsing for something like "unix:///path/to/socket". Since we // own the "unix" resolver, we can workaround in the unix resolver by using // the `URL` field. return strings.TrimPrefix(endpoint, "/") } // String returns the canonical string representation of Target. func (t Target) String() string { return t.URL.Scheme + "://" + t.URL.Host + "/" + t.Endpoint() } // Builder creates a resolver that will be used to watch name resolution updates. type Builder interface { // Build creates a new resolver for the given target. // // gRPC dial calls Build synchronously, and fails if the returned error is // not nil. Build(target Target, cc ClientConn, opts BuildOptions) (Resolver, error) // Scheme returns the scheme supported by this resolver. Scheme is defined // at https://github.com/grpc/grpc/blob/master/doc/naming.md. The returned // string should not contain uppercase characters, as they will not match // the parsed target's scheme as defined in RFC 3986. Scheme() string } // ResolveNowOptions includes additional information for ResolveNow. type ResolveNowOptions struct{} // Resolver watches for the updates on the specified target. // Updates include address updates and service config updates. type Resolver interface { // ResolveNow will be called by gRPC to try to resolve the target name // again. It's just a hint, resolver can ignore this if it's not necessary. // // It could be called multiple times concurrently. ResolveNow(ResolveNowOptions) // Close closes the resolver. Close() } // AuthorityOverrider is implemented by Builders that wish to override the // default authority for the ClientConn. // By default, the authority used is target.Endpoint(). type AuthorityOverrider interface { // OverrideAuthority returns the authority to use for a ClientConn with the // given target. The implementation must generate it without blocking, // typically in line, and must keep it unchanged. OverrideAuthority(Target) string } // ValidateEndpoints validates endpoints from a petiole policy's perspective. // Petiole policies should call this before calling into their children. See // [gRPC A61](https://github.com/grpc/proposal/blob/master/A61-IPv4-IPv6-dualstack-backends.md) // for details. func ValidateEndpoints(endpoints []Endpoint) error { if len(endpoints) == 0 { return errors.New("endpoints list is empty") } for _, endpoint := range endpoints { for range endpoint.Addresses { return nil } } return errors.New("endpoints list contains no addresses") }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/resolver/map.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/resolver/map.go
/* * * Copyright 2021 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. * */ package resolver type addressMapEntry struct { addr Address value any } // AddressMap is a map of addresses to arbitrary values taking into account // Attributes. BalancerAttributes are ignored, as are Metadata and Type. // Multiple accesses may not be performed concurrently. Must be created via // NewAddressMap; do not construct directly. type AddressMap struct { // The underlying map is keyed by an Address with fields that we don't care // about being set to their zero values. The only fields that we care about // are `Addr`, `ServerName` and `Attributes`. Since we need to be able to // distinguish between addresses with same `Addr` and `ServerName`, but // different `Attributes`, we cannot store the `Attributes` in the map key. // // The comparison operation for structs work as follows: // Struct values are comparable if all their fields are comparable. Two // struct values are equal if their corresponding non-blank fields are equal. // // The value type of the map contains a slice of addresses which match the key // in their `Addr` and `ServerName` fields and contain the corresponding value // associated with them. m map[Address]addressMapEntryList } func toMapKey(addr *Address) Address { return Address{Addr: addr.Addr, ServerName: addr.ServerName} } type addressMapEntryList []*addressMapEntry // NewAddressMap creates a new AddressMap. func NewAddressMap() *AddressMap { return &AddressMap{m: make(map[Address]addressMapEntryList)} } // find returns the index of addr in the addressMapEntry slice, or -1 if not // present. func (l addressMapEntryList) find(addr Address) int { for i, entry := range l { // Attributes are the only thing to match on here, since `Addr` and // `ServerName` are already equal. if entry.addr.Attributes.Equal(addr.Attributes) { return i } } return -1 } // Get returns the value for the address in the map, if present. func (a *AddressMap) Get(addr Address) (value any, ok bool) { addrKey := toMapKey(&addr) entryList := a.m[addrKey] if entry := entryList.find(addr); entry != -1 { return entryList[entry].value, true } return nil, false } // Set updates or adds the value to the address in the map. func (a *AddressMap) Set(addr Address, value any) { addrKey := toMapKey(&addr) entryList := a.m[addrKey] if entry := entryList.find(addr); entry != -1 { entryList[entry].value = value return } a.m[addrKey] = append(entryList, &addressMapEntry{addr: addr, value: value}) } // Delete removes addr from the map. func (a *AddressMap) Delete(addr Address) { addrKey := toMapKey(&addr) entryList := a.m[addrKey] entry := entryList.find(addr) if entry == -1 { return } if len(entryList) == 1 { entryList = nil } else { copy(entryList[entry:], entryList[entry+1:]) entryList = entryList[:len(entryList)-1] } a.m[addrKey] = entryList } // Len returns the number of entries in the map. func (a *AddressMap) Len() int { ret := 0 for _, entryList := range a.m { ret += len(entryList) } return ret } // Keys returns a slice of all current map keys. func (a *AddressMap) Keys() []Address { ret := make([]Address, 0, a.Len()) for _, entryList := range a.m { for _, entry := range entryList { ret = append(ret, entry.addr) } } return ret } // Values returns a slice of all current map values. func (a *AddressMap) Values() []any { ret := make([]any, 0, a.Len()) for _, entryList := range a.m { for _, entry := range entryList { ret = append(ret, entry.value) } } return ret } type endpointNode struct { addrs map[string]struct{} } // Equal returns whether the unordered set of addrs are the same between the // endpoint nodes. func (en *endpointNode) Equal(en2 *endpointNode) bool { if len(en.addrs) != len(en2.addrs) { return false } for addr := range en.addrs { if _, ok := en2.addrs[addr]; !ok { return false } } return true } func toEndpointNode(endpoint Endpoint) endpointNode { en := make(map[string]struct{}) for _, addr := range endpoint.Addresses { en[addr.Addr] = struct{}{} } return endpointNode{ addrs: en, } } // EndpointMap is a map of endpoints to arbitrary values keyed on only the // unordered set of address strings within an endpoint. This map is not thread // safe, thus it is unsafe to access concurrently. Must be created via // NewEndpointMap; do not construct directly. type EndpointMap struct { endpoints map[*endpointNode]any } // NewEndpointMap creates a new EndpointMap. func NewEndpointMap() *EndpointMap { return &EndpointMap{ endpoints: make(map[*endpointNode]any), } } // Get returns the value for the address in the map, if present. func (em *EndpointMap) Get(e Endpoint) (value any, ok bool) { en := toEndpointNode(e) if endpoint := em.find(en); endpoint != nil { return em.endpoints[endpoint], true } return nil, false } // Set updates or adds the value to the address in the map. func (em *EndpointMap) Set(e Endpoint, value any) { en := toEndpointNode(e) if endpoint := em.find(en); endpoint != nil { em.endpoints[endpoint] = value return } em.endpoints[&en] = value } // Len returns the number of entries in the map. func (em *EndpointMap) Len() int { return len(em.endpoints) } // Keys returns a slice of all current map keys, as endpoints specifying the // addresses present in the endpoint keys, in which uniqueness is determined by // the unordered set of addresses. Thus, endpoint information returned is not // the full endpoint data (drops duplicated addresses and attributes) but can be // used for EndpointMap accesses. func (em *EndpointMap) Keys() []Endpoint { ret := make([]Endpoint, 0, len(em.endpoints)) for en := range em.endpoints { var endpoint Endpoint for addr := range en.addrs { endpoint.Addresses = append(endpoint.Addresses, Address{Addr: addr}) } ret = append(ret, endpoint) } return ret } // Values returns a slice of all current map values. func (em *EndpointMap) Values() []any { ret := make([]any, 0, len(em.endpoints)) for _, val := range em.endpoints { ret = append(ret, val) } return ret } // find returns a pointer to the endpoint node in em if the endpoint node is // already present. If not found, nil is returned. The comparisons are done on // the unordered set of addresses within an endpoint. func (em EndpointMap) find(e endpointNode) *endpointNode { for endpoint := range em.endpoints { if e.Equal(endpoint) { return endpoint } } return nil } // Delete removes the specified endpoint from the map. func (em *EndpointMap) Delete(e Endpoint) { en := toEndpointNode(e) if entry := em.find(en); entry != nil { delete(em.endpoints, entry) } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/resolver/dns/dns_resolver.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/resolver/dns/dns_resolver.go
/* * * Copyright 2018 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. * */ // Package dns implements a dns resolver to be installed as the default resolver // in grpc. package dns import ( "time" "google.golang.org/grpc/internal/resolver/dns" "google.golang.org/grpc/resolver" ) // SetResolvingTimeout sets the maximum duration for DNS resolution requests. // // This function affects the global timeout used by all channels using the DNS // name resolver scheme. // // It must be called only at application startup, before any gRPC calls are // made. Modifying this value after initialization is not thread-safe. // // The default value is 30 seconds. Setting the timeout too low may result in // premature timeouts during resolution, while setting it too high may lead to // unnecessary delays in service discovery. Choose a value appropriate for your // specific needs and network environment. func SetResolvingTimeout(timeout time.Duration) { dns.ResolvingTimeout = timeout } // NewBuilder creates a dnsBuilder which is used to factory DNS resolvers. // // Deprecated: import grpc and use resolver.Get("dns") instead. func NewBuilder() resolver.Builder { return dns.NewBuilder() } // SetMinResolutionInterval sets the default minimum interval at which DNS // re-resolutions are allowed. This helps to prevent excessive re-resolution. // // It must be called only at application startup, before any gRPC calls are // made. Modifying this value after initialization is not thread-safe. func SetMinResolutionInterval(d time.Duration) { dns.MinResolutionInterval = d }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/credentials/credentials.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/credentials/credentials.go
/* * * Copyright 2014 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. * */ // 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 // import "google.golang.org/grpc/credentials" import ( "context" "errors" "fmt" "net" "google.golang.org/grpc/attributes" icredentials "google.golang.org/grpc/internal/credentials" "google.golang.org/protobuf/proto" ) // PerRPCCredentials defines the common interface for the credentials which need to // attach security information to every RPC (e.g., oauth2). type PerRPCCredentials interface { // GetRequestMetadata gets the current request metadata, refreshing tokens // if required. This should be called by the transport layer on each // request, and the data should be populated in headers or other // context. If a status code is returned, it will be used as the status for // the RPC (restricted to an allowable set of codes as defined by gRFC // A54). uri is the URI of the entry point for the request. When supported // by the underlying implementation, ctx can be used for timeout and // cancellation. Additionally, RequestInfo data will be available via ctx // to this call. TODO(zhaoq): Define the set of the qualified keys instead // of leaving it as an arbitrary string. GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) // RequireTransportSecurity indicates whether the credentials requires // transport security. RequireTransportSecurity() bool } // SecurityLevel defines the protection level on an established connection. // // This API is experimental. type SecurityLevel int const ( // InvalidSecurityLevel indicates an invalid security level. // The zero SecurityLevel value is invalid for backward compatibility. InvalidSecurityLevel SecurityLevel = iota // NoSecurity indicates a connection is insecure. NoSecurity // IntegrityOnly indicates a connection only provides integrity protection. IntegrityOnly // PrivacyAndIntegrity indicates a connection provides both privacy and integrity protection. PrivacyAndIntegrity ) // String returns SecurityLevel in a string format. func (s SecurityLevel) String() string { switch s { case NoSecurity: return "NoSecurity" case IntegrityOnly: return "IntegrityOnly" case PrivacyAndIntegrity: return "PrivacyAndIntegrity" } return fmt.Sprintf("invalid SecurityLevel: %v", int(s)) } // CommonAuthInfo contains authenticated information common to AuthInfo implementations. // It should be embedded in a struct implementing AuthInfo to provide additional information // about the credentials. // // This API is experimental. type CommonAuthInfo struct { SecurityLevel SecurityLevel } // GetCommonAuthInfo returns the pointer to CommonAuthInfo struct. func (c CommonAuthInfo) GetCommonAuthInfo() CommonAuthInfo { return c } // ProtocolInfo provides information regarding the gRPC wire protocol version, // security protocol, security protocol version in use, server name, etc. type ProtocolInfo struct { // ProtocolVersion is the gRPC wire protocol version. ProtocolVersion string // SecurityProtocol is the security protocol in use. SecurityProtocol string // SecurityVersion is the security protocol version. It is a static version string from the // credentials, not a value that reflects per-connection protocol negotiation. To retrieve // details about the credentials used for a connection, use the Peer's AuthInfo field instead. // // Deprecated: please use Peer.AuthInfo. SecurityVersion string // ServerName is the user-configured server name. ServerName string } // AuthInfo defines the common interface for the auth information the users are interested in. // A struct that implements AuthInfo should embed CommonAuthInfo by including additional // information about the credentials in it. type AuthInfo interface { AuthType() string } // ErrConnDispatched indicates that rawConn has been dispatched out of gRPC // and the caller should not close rawConn. var ErrConnDispatched = errors.New("credentials: rawConn is dispatched out of gRPC") // TransportCredentials defines the common interface for all the live gRPC wire // protocols and supported transport security protocols (e.g., TLS, SSL). type TransportCredentials interface { // ClientHandshake does the authentication handshake specified by the // corresponding authentication protocol on rawConn for clients. It returns // the authenticated connection and the corresponding auth information // about the connection. The auth information should embed CommonAuthInfo // to return additional information about the credentials. Implementations // must use the provided context to implement timely cancellation. gRPC // will try to reconnect if the error returned is a temporary error // (io.EOF, context.DeadlineExceeded or err.Temporary() == true). If the // returned error is a wrapper error, implementations should make sure that // the error implements Temporary() to have the correct retry behaviors. // Additionally, ClientHandshakeInfo data will be available via the context // passed to this call. // // The second argument to this method is the `:authority` header value used // while creating new streams on this connection after authentication // succeeds. Implementations must use this as the server name during the // authentication handshake. // // If the returned net.Conn is closed, it MUST close the net.Conn provided. ClientHandshake(context.Context, string, net.Conn) (net.Conn, AuthInfo, error) // ServerHandshake does the authentication handshake for servers. It returns // the authenticated connection and the corresponding auth information about // the connection. The auth information should embed CommonAuthInfo to return additional information // about the credentials. // // If the returned net.Conn is closed, it MUST close the net.Conn provided. ServerHandshake(net.Conn) (net.Conn, AuthInfo, error) // Info provides the ProtocolInfo of this TransportCredentials. Info() ProtocolInfo // Clone makes a copy of this TransportCredentials. Clone() TransportCredentials // OverrideServerName specifies the value used for the following: // - verifying the hostname on the returned certificates // - as SNI in the client's handshake to support virtual hosting // - as the value for `:authority` header at stream creation time // // Deprecated: use grpc.WithAuthority instead. Will be supported // throughout 1.x. OverrideServerName(string) error } // Bundle is a combination of TransportCredentials and PerRPCCredentials. // // It also contains a mode switching method, so it can be used as a combination // of different credential policies. // // Bundle cannot be used together with individual TransportCredentials. // PerRPCCredentials from Bundle will be appended to other PerRPCCredentials. // // This API is experimental. type Bundle interface { // TransportCredentials returns the transport credentials from the Bundle. // // Implementations must return non-nil transport credentials. If transport // security is not needed by the Bundle, implementations may choose to // return insecure.NewCredentials(). TransportCredentials() TransportCredentials // PerRPCCredentials returns the per-RPC credentials from the Bundle. // // May be nil if per-RPC credentials are not needed. PerRPCCredentials() PerRPCCredentials // NewWithMode should make a copy of Bundle, and switch mode. Modifying the // existing Bundle may cause races. // // NewWithMode returns nil if the requested mode is not supported. NewWithMode(mode string) (Bundle, error) } // RequestInfo contains request data attached to the context passed to GetRequestMetadata calls. // // This API is experimental. type RequestInfo struct { // The method passed to Invoke or NewStream for this RPC. (For proto methods, this has the format "/some.Service/Method") Method string // AuthInfo contains the information from a security handshake (TransportCredentials.ClientHandshake, TransportCredentials.ServerHandshake) AuthInfo AuthInfo } // RequestInfoFromContext extracts the RequestInfo from the context if it exists. // // This API is experimental. func RequestInfoFromContext(ctx context.Context) (ri RequestInfo, ok bool) { ri, ok = icredentials.RequestInfoFromContext(ctx).(RequestInfo) return ri, ok } // ClientHandshakeInfo holds data to be passed to ClientHandshake. This makes // it possible to pass arbitrary data to the handshaker from gRPC, resolver, // balancer etc. Individual credential implementations control the actual // format of the data that they are willing to receive. // // This API is experimental. type ClientHandshakeInfo struct { // Attributes contains the attributes for the address. It could be provided // by the gRPC, resolver, balancer etc. Attributes *attributes.Attributes } // ClientHandshakeInfoFromContext returns the ClientHandshakeInfo struct stored // in ctx. // // This API is experimental. func ClientHandshakeInfoFromContext(ctx context.Context) ClientHandshakeInfo { chi, _ := icredentials.ClientHandshakeInfoFromContext(ctx).(ClientHandshakeInfo) return chi } // CheckSecurityLevel checks if a connection's security level is greater than or equal to the specified one. // It returns success if 1) the condition is satisfied or 2) AuthInfo struct does not implement GetCommonAuthInfo() method // or 3) CommonAuthInfo.SecurityLevel has an invalid zero value. For 2) and 3), it is for the purpose of backward-compatibility. // // This API is experimental. func CheckSecurityLevel(ai AuthInfo, level SecurityLevel) error { type internalInfo interface { GetCommonAuthInfo() CommonAuthInfo } if ai == nil { return errors.New("AuthInfo is nil") } if ci, ok := ai.(internalInfo); ok { // CommonAuthInfo.SecurityLevel has an invalid value. if ci.GetCommonAuthInfo().SecurityLevel == InvalidSecurityLevel { return nil } if ci.GetCommonAuthInfo().SecurityLevel < level { return fmt.Errorf("requires SecurityLevel %v; connection has %v", level, ci.GetCommonAuthInfo().SecurityLevel) } } // The condition is satisfied or AuthInfo struct does not implement GetCommonAuthInfo() method. return nil } // ChannelzSecurityInfo defines the interface that security protocols should implement // in order to provide security info to channelz. // // This API is experimental. type ChannelzSecurityInfo interface { GetSecurityValue() ChannelzSecurityValue } // ChannelzSecurityValue defines the interface that GetSecurityValue() return value // should satisfy. This interface should only be satisfied by *TLSChannelzSecurityValue // and *OtherChannelzSecurityValue. // // This API is experimental. type ChannelzSecurityValue interface { isChannelzSecurityValue() } // OtherChannelzSecurityValue defines the struct that non-TLS protocol should return // from GetSecurityValue(), which contains protocol specific security info. Note // the Value field will be sent to users of channelz requesting channel info, and // thus sensitive info should better be avoided. // // This API is experimental. type OtherChannelzSecurityValue struct { ChannelzSecurityValue Name string Value proto.Message }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/credentials/tls.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/credentials/tls.go
/* * * Copyright 2014 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. * */ package credentials import ( "context" "crypto/tls" "crypto/x509" "fmt" "net" "net/url" "os" "google.golang.org/grpc/grpclog" credinternal "google.golang.org/grpc/internal/credentials" "google.golang.org/grpc/internal/envconfig" ) const alpnFailureHelpMessage = "If you upgraded from a grpc-go version earlier than 1.67, your TLS connections may have stopped working due to ALPN enforcement. For more details, see: https://github.com/grpc/grpc-go/issues/434" var logger = grpclog.Component("credentials") // TLSInfo contains the auth information for a TLS authenticated connection. // It implements the AuthInfo interface. type TLSInfo struct { State tls.ConnectionState CommonAuthInfo // This API is experimental. SPIFFEID *url.URL } // AuthType returns the type of TLSInfo as a string. func (t TLSInfo) AuthType() string { return "tls" } // cipherSuiteLookup returns the string version of a TLS cipher suite ID. func cipherSuiteLookup(cipherSuiteID uint16) string { for _, s := range tls.CipherSuites() { if s.ID == cipherSuiteID { return s.Name } } for _, s := range tls.InsecureCipherSuites() { if s.ID == cipherSuiteID { return s.Name } } return fmt.Sprintf("unknown ID: %v", cipherSuiteID) } // GetSecurityValue returns security info requested by channelz. func (t TLSInfo) GetSecurityValue() ChannelzSecurityValue { v := &TLSChannelzSecurityValue{ StandardName: cipherSuiteLookup(t.State.CipherSuite), } // Currently there's no way to get LocalCertificate info from tls package. if len(t.State.PeerCertificates) > 0 { v.RemoteCertificate = t.State.PeerCertificates[0].Raw } return v } // tlsCreds is the credentials required for authenticating a connection using TLS. type tlsCreds struct { // TLS configuration config *tls.Config } func (c tlsCreds) Info() ProtocolInfo { return ProtocolInfo{ SecurityProtocol: "tls", SecurityVersion: "1.2", ServerName: c.config.ServerName, } } func (c *tlsCreds) ClientHandshake(ctx context.Context, authority string, rawConn net.Conn) (_ net.Conn, _ AuthInfo, err error) { // use local cfg to avoid clobbering ServerName if using multiple endpoints cfg := credinternal.CloneTLSConfig(c.config) if cfg.ServerName == "" { serverName, _, err := net.SplitHostPort(authority) if err != nil { // If the authority had no host port or if the authority cannot be parsed, use it as-is. serverName = authority } cfg.ServerName = serverName } conn := tls.Client(rawConn, cfg) errChannel := make(chan error, 1) go func() { errChannel <- conn.Handshake() close(errChannel) }() select { case err := <-errChannel: if err != nil { conn.Close() return nil, nil, err } case <-ctx.Done(): conn.Close() return nil, nil, ctx.Err() } // The negotiated protocol can be either of the following: // 1. h2: When the server supports ALPN. Only HTTP/2 can be negotiated since // it is the only protocol advertised by the client during the handshake. // The tls library ensures that the server chooses a protocol advertised // by the client. // 2. "" (empty string): If the server doesn't support ALPN. ALPN is a requirement // for using HTTP/2 over TLS. We can terminate the connection immediately. np := conn.ConnectionState().NegotiatedProtocol if np == "" { if envconfig.EnforceALPNEnabled { conn.Close() return nil, nil, fmt.Errorf("credentials: cannot check peer: missing selected ALPN property. %s", alpnFailureHelpMessage) } logger.Warningf("Allowing TLS connection to server %q with ALPN disabled. TLS connections to servers with ALPN disabled will be disallowed in future grpc-go releases", cfg.ServerName) } tlsInfo := TLSInfo{ State: conn.ConnectionState(), CommonAuthInfo: CommonAuthInfo{ SecurityLevel: PrivacyAndIntegrity, }, } id := credinternal.SPIFFEIDFromState(conn.ConnectionState()) if id != nil { tlsInfo.SPIFFEID = id } return credinternal.WrapSyscallConn(rawConn, conn), tlsInfo, nil } func (c *tlsCreds) ServerHandshake(rawConn net.Conn) (net.Conn, AuthInfo, error) { conn := tls.Server(rawConn, c.config) if err := conn.Handshake(); err != nil { conn.Close() return nil, nil, err } cs := conn.ConnectionState() // The negotiated application protocol can be empty only if the client doesn't // support ALPN. In such cases, we can close the connection since ALPN is required // for using HTTP/2 over TLS. if cs.NegotiatedProtocol == "" { if envconfig.EnforceALPNEnabled { conn.Close() return nil, nil, fmt.Errorf("credentials: cannot check peer: missing selected ALPN property. %s", alpnFailureHelpMessage) } else if logger.V(2) { logger.Info("Allowing TLS connection from client with ALPN disabled. TLS connections with ALPN disabled will be disallowed in future grpc-go releases") } } tlsInfo := TLSInfo{ State: cs, CommonAuthInfo: CommonAuthInfo{ SecurityLevel: PrivacyAndIntegrity, }, } id := credinternal.SPIFFEIDFromState(conn.ConnectionState()) if id != nil { tlsInfo.SPIFFEID = id } return credinternal.WrapSyscallConn(rawConn, conn), tlsInfo, nil } func (c *tlsCreds) Clone() TransportCredentials { return NewTLS(c.config) } func (c *tlsCreds) OverrideServerName(serverNameOverride string) error { c.config.ServerName = serverNameOverride return nil } // The following cipher suites are forbidden for use with HTTP/2 by // https://datatracker.ietf.org/doc/html/rfc7540#appendix-A var tls12ForbiddenCipherSuites = map[uint16]struct{}{ tls.TLS_RSA_WITH_AES_128_CBC_SHA: {}, tls.TLS_RSA_WITH_AES_256_CBC_SHA: {}, tls.TLS_RSA_WITH_AES_128_GCM_SHA256: {}, tls.TLS_RSA_WITH_AES_256_GCM_SHA384: {}, tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA: {}, tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA: {}, tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: {}, tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA: {}, } // NewTLS uses c to construct a TransportCredentials based on TLS. func NewTLS(c *tls.Config) TransportCredentials { config := applyDefaults(c) if config.GetConfigForClient != nil { oldFn := config.GetConfigForClient config.GetConfigForClient = func(hello *tls.ClientHelloInfo) (*tls.Config, error) { cfgForClient, err := oldFn(hello) if err != nil || cfgForClient == nil { return cfgForClient, err } return applyDefaults(cfgForClient), nil } } return &tlsCreds{config: config} } func applyDefaults(c *tls.Config) *tls.Config { config := credinternal.CloneTLSConfig(c) config.NextProtos = credinternal.AppendH2ToNextProtos(config.NextProtos) // If the user did not configure a MinVersion and did not configure a // MaxVersion < 1.2, use MinVersion=1.2, which is required by // https://datatracker.ietf.org/doc/html/rfc7540#section-9.2 if config.MinVersion == 0 && (config.MaxVersion == 0 || config.MaxVersion >= tls.VersionTLS12) { config.MinVersion = tls.VersionTLS12 } // If the user did not configure CipherSuites, use all "secure" cipher // suites reported by the TLS package, but remove some explicitly forbidden // by https://datatracker.ietf.org/doc/html/rfc7540#appendix-A if config.CipherSuites == nil { for _, cs := range tls.CipherSuites() { if _, ok := tls12ForbiddenCipherSuites[cs.ID]; !ok { config.CipherSuites = append(config.CipherSuites, cs.ID) } } } return config } // NewClientTLSFromCert constructs TLS credentials from the provided root // certificate authority certificate(s) to validate server connections. If // certificates to establish the identity of the client need to be included in // the credentials (eg: for mTLS), use NewTLS instead, where a complete // tls.Config can be specified. // serverNameOverride is for testing only. If set to a non empty string, // it will override the virtual host name of authority (e.g. :authority header // field) in requests. func NewClientTLSFromCert(cp *x509.CertPool, serverNameOverride string) TransportCredentials { return NewTLS(&tls.Config{ServerName: serverNameOverride, RootCAs: cp}) } // NewClientTLSFromFile constructs TLS credentials from the provided root // certificate authority certificate file(s) to validate server connections. If // certificates to establish the identity of the client need to be included in // the credentials (eg: for mTLS), use NewTLS instead, where a complete // tls.Config can be specified. // serverNameOverride is for testing only. If set to a non empty string, // it will override the virtual host name of authority (e.g. :authority header // field) in requests. func NewClientTLSFromFile(certFile, serverNameOverride string) (TransportCredentials, error) { b, err := os.ReadFile(certFile) if err != nil { return nil, err } cp := x509.NewCertPool() if !cp.AppendCertsFromPEM(b) { return nil, fmt.Errorf("credentials: failed to append certificates") } return NewTLS(&tls.Config{ServerName: serverNameOverride, RootCAs: cp}), nil } // NewServerTLSFromCert constructs TLS credentials from the input certificate for server. func NewServerTLSFromCert(cert *tls.Certificate) TransportCredentials { return NewTLS(&tls.Config{Certificates: []tls.Certificate{*cert}}) } // NewServerTLSFromFile constructs TLS credentials from the input certificate file and key // file for server. func NewServerTLSFromFile(certFile, keyFile string) (TransportCredentials, error) { cert, err := tls.LoadX509KeyPair(certFile, keyFile) if err != nil { return nil, err } return NewTLS(&tls.Config{Certificates: []tls.Certificate{cert}}), nil } // TLSChannelzSecurityValue defines the struct that TLS protocol should return // from GetSecurityValue(), containing security info like cipher and certificate used. // // # Experimental // // Notice: This type is EXPERIMENTAL and may be changed or removed in a // later release. type TLSChannelzSecurityValue struct { ChannelzSecurityValue StandardName string LocalCertificate []byte RemoteCertificate []byte }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/credentials/insecure/insecure.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/credentials/insecure/insecure.go
/* * * Copyright 2020 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. * */ // Package insecure provides an implementation of the // credentials.TransportCredentials interface which disables transport security. package insecure import ( "context" "net" "google.golang.org/grpc/credentials" ) // NewCredentials returns a credentials which disables transport security. // // Note that using this credentials with per-RPC credentials which require // transport security is incompatible and will cause grpc.Dial() to fail. func NewCredentials() credentials.TransportCredentials { return insecureTC{} } // insecureTC implements the insecure transport credentials. The handshake // methods simply return the passed in net.Conn and set the security level to // NoSecurity. type insecureTC struct{} func (insecureTC) ClientHandshake(_ context.Context, _ string, conn net.Conn) (net.Conn, credentials.AuthInfo, error) { return conn, info{credentials.CommonAuthInfo{SecurityLevel: credentials.NoSecurity}}, nil } func (insecureTC) ServerHandshake(conn net.Conn) (net.Conn, credentials.AuthInfo, error) { return conn, info{credentials.CommonAuthInfo{SecurityLevel: credentials.NoSecurity}}, nil } func (insecureTC) Info() credentials.ProtocolInfo { return credentials.ProtocolInfo{SecurityProtocol: "insecure"} } func (insecureTC) Clone() credentials.TransportCredentials { return insecureTC{} } func (insecureTC) OverrideServerName(string) error { return nil } // info contains the auth information for an insecure connection. // It implements the AuthInfo interface. type info struct { credentials.CommonAuthInfo } // AuthType returns the type of info as a string. func (info) AuthType() string { return "insecure" } // insecureBundle implements an insecure bundle. // An insecure bundle provides a thin wrapper around insecureTC to support // the credentials.Bundle interface. type insecureBundle struct{} // NewBundle returns a bundle with disabled transport security and no per rpc credential. func NewBundle() credentials.Bundle { return insecureBundle{} } // NewWithMode returns a new insecure Bundle. The mode is ignored. func (insecureBundle) NewWithMode(string) (credentials.Bundle, error) { return insecureBundle{}, nil } // PerRPCCredentials returns an nil implementation as insecure // bundle does not support a per rpc credential. func (insecureBundle) PerRPCCredentials() credentials.PerRPCCredentials { return nil } // TransportCredentials returns the underlying insecure transport credential. func (insecureBundle) TransportCredentials() credentials.TransportCredentials { return NewCredentials() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/keepalive/keepalive.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/keepalive/keepalive.go
/* * * Copyright 2017 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. * */ // Package keepalive defines configurable parameters for point-to-point // healthcheck. package keepalive import ( "time" ) // ClientParameters is used to set keepalive parameters on the client-side. // These configure how the client will actively probe to notice when a // connection is broken and send pings so intermediaries will be aware of the // liveness of the connection. Make sure these parameters are set in // coordination with the keepalive policy on the server, as incompatible // settings can result in closing of connection. type ClientParameters struct { // After a duration of this time if the client doesn't see any activity it // pings the server to see if the transport is still alive. // If set below 10s, a minimum value of 10s will be used instead. // // Note that gRPC servers have a default EnforcementPolicy.MinTime of 5 // minutes (which means the client shouldn't ping more frequently than every // 5 minutes). // // Though not ideal, it's not a strong requirement for Time to be less than // EnforcementPolicy.MinTime. Time will automatically double if the server // disconnects due to its enforcement policy. // // For more details, see // https://github.com/grpc/proposal/blob/master/A8-client-side-keepalive.md Time time.Duration // After having pinged for keepalive check, the client waits for a duration // of Timeout and if no activity is seen even after that the connection is // closed. // // If keepalive is enabled, and this value is not explicitly set, the default // is 20 seconds. Timeout time.Duration // If true, client sends keepalive pings even with no active RPCs. If false, // when there are no active RPCs, Time and Timeout will be ignored and no // keepalive pings will be sent. PermitWithoutStream bool } // ServerParameters is used to set keepalive and max-age parameters on the // server-side. type ServerParameters struct { // MaxConnectionIdle is a duration for the amount of time after which an // idle connection would be closed by sending a GoAway. Idleness duration is // defined since the most recent time the number of outstanding RPCs became // zero or the connection establishment. MaxConnectionIdle time.Duration // The current default value is infinity. // MaxConnectionAge is a duration for the maximum amount of time a // connection may exist before it will be closed by sending a GoAway. A // random jitter of +/-10% will be added to MaxConnectionAge to spread out // connection storms. MaxConnectionAge time.Duration // The current default value is infinity. // MaxConnectionAgeGrace is an additive period after MaxConnectionAge after // which the connection will be forcibly closed. MaxConnectionAgeGrace time.Duration // The current default value is infinity. // After a duration of this time if the server doesn't see any activity it // pings the client to see if the transport is still alive. // If set below 1s, a minimum value of 1s will be used instead. Time time.Duration // The current default value is 2 hours. // After having pinged for keepalive check, the server waits for a duration // of Timeout and if no activity is seen even after that the connection is // closed. Timeout time.Duration // The current default value is 20 seconds. } // EnforcementPolicy is used to set keepalive enforcement policy on the // server-side. Server will close connection with a client that violates this // policy. type EnforcementPolicy struct { // MinTime is the minimum amount of time a client should wait before sending // a keepalive ping. MinTime time.Duration // The current default value is 5 minutes. // If true, server allows keepalive pings even when there are no active // streams(RPCs). If false, and client sends ping when there are no active // streams, server will send GOAWAY and close the connection. PermitWithoutStream bool // false by default. }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/attributes/attributes.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/attributes/attributes.go
/* * * Copyright 2019 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. * */ // Package attributes defines a generic key/value store used in various gRPC // components. // // # Experimental // // Notice: This package is EXPERIMENTAL and may be changed or removed in a // later release. package attributes import ( "fmt" "strings" ) // Attributes is an immutable struct for storing and retrieving generic // key/value pairs. Keys must be hashable, and users should define their own // types for keys. Values should not be modified after they are added to an // Attributes or if they were received from one. If values implement 'Equal(o // any) bool', it will be called by (*Attributes).Equal to determine whether // two values with the same key should be considered equal. type Attributes struct { m map[any]any } // New returns a new Attributes containing the key/value pair. func New(key, value any) *Attributes { return &Attributes{m: map[any]any{key: value}} } // WithValue returns a new Attributes containing the previous keys and values // and the new key/value pair. If the same key appears multiple times, the // last value overwrites all previous values for that key. To remove an // existing key, use a nil value. value should not be modified later. func (a *Attributes) WithValue(key, value any) *Attributes { if a == nil { return New(key, value) } n := &Attributes{m: make(map[any]any, len(a.m)+1)} for k, v := range a.m { n.m[k] = v } n.m[key] = value return n } // Value returns the value associated with these attributes for key, or nil if // no value is associated with key. The returned value should not be modified. func (a *Attributes) Value(key any) any { if a == nil { return nil } return a.m[key] } // Equal returns whether a and o are equivalent. If 'Equal(o any) bool' is // implemented for a value in the attributes, it is called to determine if the // value matches the one stored in the other attributes. If Equal is not // implemented, standard equality is used to determine if the two values are // equal. Note that some types (e.g. maps) aren't comparable by default, so // they must be wrapped in a struct, or in an alias type, with Equal defined. func (a *Attributes) Equal(o *Attributes) bool { if a == nil && o == nil { return true } if a == nil || o == nil { return false } if len(a.m) != len(o.m) { return false } for k, v := range a.m { ov, ok := o.m[k] if !ok { // o missing element of a return false } if eq, ok := v.(interface{ Equal(o any) bool }); ok { if !eq.Equal(ov) { return false } } else if v != ov { // Fallback to a standard equality check if Value is unimplemented. return false } } return true } // String prints the attribute map. If any key or values throughout the map // implement fmt.Stringer, it calls that method and appends. func (a *Attributes) String() string { var sb strings.Builder sb.WriteString("{") first := true for k, v := range a.m { if !first { sb.WriteString(", ") } sb.WriteString(fmt.Sprintf("%q: %q ", str(k), str(v))) first = false } sb.WriteString("}") return sb.String() } func str(x any) (s string) { if v, ok := x.(fmt.Stringer); ok { return fmt.Sprint(v) } else if v, ok := x.(string); ok { return v } return fmt.Sprintf("<%p>", x) } // MarshalJSON helps implement the json.Marshaler interface, thereby rendering // the Attributes correctly when printing (via pretty.JSON) structs containing // Attributes as fields. // // Is it impossible to unmarshal attributes from a JSON representation and this // method is meant only for debugging purposes. func (a *Attributes) MarshalJSON() ([]byte, error) { return []byte(a.String()), nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/experimental.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/experimental.go
/* * Copyright 2023 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. * */ package internal var ( // WithBufferPool is implemented by the grpc package and returns a dial // option to configure a shared buffer pool for a grpc.ClientConn. WithBufferPool any // func (grpc.SharedBufferPool) grpc.DialOption // BufferPool is implemented by the grpc package and returns a server // option to configure a shared buffer pool for a grpc.Server. BufferPool any // func (grpc.SharedBufferPool) grpc.ServerOption )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/tcp_keepalive_windows.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/tcp_keepalive_windows.go
//go:build windows /* * Copyright 2023 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. * */ package internal import ( "net" "syscall" "time" "golang.org/x/sys/windows" ) // NetDialerWithTCPKeepalive returns a net.Dialer that enables TCP keepalives on // the underlying connection with OS default values for keepalive parameters. // // TODO: Once https://github.com/golang/go/issues/62254 lands, and the // appropriate Go version becomes less than our least supported Go version, we // should look into using the new API to make things more straightforward. func NetDialerWithTCPKeepalive() *net.Dialer { return &net.Dialer{ // Setting a negative value here prevents the Go stdlib from overriding // the values of TCP keepalive time and interval. It also prevents the // Go stdlib from enabling TCP keepalives by default. KeepAlive: time.Duration(-1), // This method is called after the underlying network socket is created, // but before dialing the socket (or calling its connect() method). The // combination of unconditionally enabling TCP keepalives here, and // disabling the overriding of TCP keepalive parameters by setting the // KeepAlive field to a negative value above, results in OS defaults for // the TCP keepalive interval and time parameters. Control: func(_, _ string, c syscall.RawConn) error { return c.Control(func(fd uintptr) { windows.SetsockoptInt(windows.Handle(fd), windows.SOL_SOCKET, windows.SO_KEEPALIVE, 1) }) }, } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/tcp_keepalive_unix.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/tcp_keepalive_unix.go
//go:build unix /* * Copyright 2023 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. * */ package internal import ( "net" "syscall" "time" "golang.org/x/sys/unix" ) // NetDialerWithTCPKeepalive returns a net.Dialer that enables TCP keepalives on // the underlying connection with OS default values for keepalive parameters. // // TODO: Once https://github.com/golang/go/issues/62254 lands, and the // appropriate Go version becomes less than our least supported Go version, we // should look into using the new API to make things more straightforward. func NetDialerWithTCPKeepalive() *net.Dialer { return &net.Dialer{ // Setting a negative value here prevents the Go stdlib from overriding // the values of TCP keepalive time and interval. It also prevents the // Go stdlib from enabling TCP keepalives by default. KeepAlive: time.Duration(-1), // This method is called after the underlying network socket is created, // but before dialing the socket (or calling its connect() method). The // combination of unconditionally enabling TCP keepalives here, and // disabling the overriding of TCP keepalive parameters by setting the // KeepAlive field to a negative value above, results in OS defaults for // the TCP keepalive interval and time parameters. Control: func(_, _ string, c syscall.RawConn) error { return c.Control(func(fd uintptr) { unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_KEEPALIVE, 1) }) }, } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/tcp_keepalive_others.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/tcp_keepalive_others.go
//go:build !unix && !windows /* * Copyright 2023 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. * */ package internal import ( "net" ) // NetDialerWithTCPKeepalive returns a vanilla net.Dialer on non-unix platforms. func NetDialerWithTCPKeepalive() *net.Dialer { return &net.Dialer{} }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/internal.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/internal.go
/* * Copyright 2016 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. * */ // Package internal contains gRPC-internal code, to avoid polluting // the godoc of the top-level grpc package. It must not import any grpc // symbols to avoid circular dependencies. package internal import ( "context" "time" "google.golang.org/grpc/connectivity" "google.golang.org/grpc/serviceconfig" ) var ( // HealthCheckFunc is used to provide client-side LB channel health checking HealthCheckFunc HealthChecker // RegisterClientHealthCheckListener is used to provide a listener for // updates from the client-side health checking service. It returns a // function that can be called to stop the health producer. RegisterClientHealthCheckListener any // func(ctx context.Context, sc balancer.SubConn, serviceName string, listener func(balancer.SubConnState)) func() // BalancerUnregister is exported by package balancer to unregister a balancer. BalancerUnregister func(name string) // KeepaliveMinPingTime is the minimum ping interval. This must be 10s by // default, but tests may wish to set it lower for convenience. KeepaliveMinPingTime = 10 * time.Second // KeepaliveMinServerPingTime is the minimum ping interval for servers. // This must be 1s by default, but tests may wish to set it lower for // convenience. KeepaliveMinServerPingTime = time.Second // ParseServiceConfig parses a JSON representation of the service config. ParseServiceConfig any // func(string) *serviceconfig.ParseResult // EqualServiceConfigForTesting is for testing service config generation and // parsing. Both a and b should be returned by ParseServiceConfig. // This function compares the config without rawJSON stripped, in case the // there's difference in white space. EqualServiceConfigForTesting func(a, b serviceconfig.Config) bool // GetCertificateProviderBuilder returns the registered builder for the // given name. This is set by package certprovider for use from xDS // bootstrap code while parsing certificate provider configs in the // bootstrap file. GetCertificateProviderBuilder any // func(string) certprovider.Builder // GetXDSHandshakeInfoForTesting returns a pointer to the xds.HandshakeInfo // stored in the passed in attributes. This is set by // credentials/xds/xds.go. GetXDSHandshakeInfoForTesting any // func (*attributes.Attributes) *unsafe.Pointer // GetServerCredentials returns the transport credentials configured on a // gRPC server. An xDS-enabled server needs to know what type of credentials // is configured on the underlying gRPC server. This is set by server.go. GetServerCredentials any // func (*grpc.Server) credentials.TransportCredentials // MetricsRecorderForServer returns the MetricsRecorderList derived from a // server's stats handlers. MetricsRecorderForServer any // func (*grpc.Server) estats.MetricsRecorder // CanonicalString returns the canonical string of the code defined here: // https://github.com/grpc/grpc/blob/master/doc/statuscodes.md. // // This is used in the 1.0 release of gcp/observability, and thus must not be // deleted or changed. CanonicalString any // func (codes.Code) string // IsRegisteredMethod returns whether the passed in method is registered as // a method on the server. IsRegisteredMethod any // func(*grpc.Server, string) bool // ServerFromContext returns the server from the context. ServerFromContext any // func(context.Context) *grpc.Server // AddGlobalServerOptions adds an array of ServerOption that will be // effective globally for newly created servers. The priority will be: 1. // user-provided; 2. this method; 3. default values. // // This is used in the 1.0 release of gcp/observability, and thus must not be // deleted or changed. AddGlobalServerOptions any // func(opt ...ServerOption) // ClearGlobalServerOptions clears the array of extra ServerOption. This // method is useful in testing and benchmarking. // // This is used in the 1.0 release of gcp/observability, and thus must not be // deleted or changed. ClearGlobalServerOptions func() // AddGlobalDialOptions adds an array of DialOption that will be effective // globally for newly created client channels. The priority will be: 1. // user-provided; 2. this method; 3. default values. // // This is used in the 1.0 release of gcp/observability, and thus must not be // deleted or changed. AddGlobalDialOptions any // func(opt ...DialOption) // DisableGlobalDialOptions returns a DialOption that prevents the // ClientConn from applying the global DialOptions (set via // AddGlobalDialOptions). // // This is used in the 1.0 release of gcp/observability, and thus must not be // deleted or changed. DisableGlobalDialOptions any // func() grpc.DialOption // ClearGlobalDialOptions clears the array of extra DialOption. This // method is useful in testing and benchmarking. // // This is used in the 1.0 release of gcp/observability, and thus must not be // deleted or changed. ClearGlobalDialOptions func() // AddGlobalPerTargetDialOptions adds a PerTargetDialOption that will be // configured for newly created ClientConns. AddGlobalPerTargetDialOptions any // func (opt any) // ClearGlobalPerTargetDialOptions clears the slice of global late apply // dial options. ClearGlobalPerTargetDialOptions func() // JoinDialOptions combines the dial options passed as arguments into a // single dial option. JoinDialOptions any // func(...grpc.DialOption) grpc.DialOption // JoinServerOptions combines the server options passed as arguments into a // single server option. JoinServerOptions any // func(...grpc.ServerOption) grpc.ServerOption // WithBinaryLogger returns a DialOption that specifies the binary logger // for a ClientConn. // // This is used in the 1.0 release of gcp/observability, and thus must not be // deleted or changed. WithBinaryLogger any // func(binarylog.Logger) grpc.DialOption // BinaryLogger returns a ServerOption that can set the binary logger for a // server. // // This is used in the 1.0 release of gcp/observability, and thus must not be // deleted or changed. BinaryLogger any // func(binarylog.Logger) grpc.ServerOption // SubscribeToConnectivityStateChanges adds a grpcsync.Subscriber to a // provided grpc.ClientConn. SubscribeToConnectivityStateChanges any // func(*grpc.ClientConn, grpcsync.Subscriber) // NewXDSResolverWithConfigForTesting creates a new xds resolver builder using // the provided xds bootstrap config instead of the global configuration from // the supported environment variables. The resolver.Builder is meant to be // used in conjunction with the grpc.WithResolvers DialOption. // // Testing Only // // This function should ONLY be used for testing and may not work with some // other features, including the CSDS service. NewXDSResolverWithConfigForTesting any // func([]byte) (resolver.Builder, error) // NewXDSResolverWithPoolForTesting creates a new xDS resolver builder // using the provided xDS pool instead of creating a new one using the // bootstrap configuration specified by the supported environment variables. // The resolver.Builder is meant to be used in conjunction with the // grpc.WithResolvers DialOption. The resolver.Builder does not take // ownership of the provided xDS client and it is the responsibility of the // caller to close the client when no longer required. // // Testing Only // // This function should ONLY be used for testing and may not work with some // other features, including the CSDS service. NewXDSResolverWithPoolForTesting any // func(*xdsclient.Pool) (resolver.Builder, error) // NewXDSResolverWithClientForTesting creates a new xDS resolver builder // using the provided xDS client instead of creating a new one using the // bootstrap configuration specified by the supported environment variables. // The resolver.Builder is meant to be used in conjunction with the // grpc.WithResolvers DialOption. The resolver.Builder does not take // ownership of the provided xDS client and it is the responsibility of the // caller to close the client when no longer required. // // Testing Only // // This function should ONLY be used for testing and may not work with some // other features, including the CSDS service. NewXDSResolverWithClientForTesting any // func(xdsclient.XDSClient) (resolver.Builder, error) // RegisterRLSClusterSpecifierPluginForTesting registers the RLS Cluster // Specifier Plugin for testing purposes, regardless of the XDSRLS environment // variable. // // TODO: Remove this function once the RLS env var is removed. RegisterRLSClusterSpecifierPluginForTesting func() // UnregisterRLSClusterSpecifierPluginForTesting unregisters the RLS Cluster // Specifier Plugin for testing purposes. This is needed because there is no way // to unregister the RLS Cluster Specifier Plugin after registering it solely // for testing purposes using RegisterRLSClusterSpecifierPluginForTesting(). // // TODO: Remove this function once the RLS env var is removed. UnregisterRLSClusterSpecifierPluginForTesting func() // RegisterRBACHTTPFilterForTesting registers the RBAC HTTP Filter for testing // purposes, regardless of the RBAC environment variable. // // TODO: Remove this function once the RBAC env var is removed. RegisterRBACHTTPFilterForTesting func() // UnregisterRBACHTTPFilterForTesting unregisters the RBAC HTTP Filter for // testing purposes. This is needed because there is no way to unregister the // HTTP Filter after registering it solely for testing purposes using // RegisterRBACHTTPFilterForTesting(). // // TODO: Remove this function once the RBAC env var is removed. UnregisterRBACHTTPFilterForTesting func() // ORCAAllowAnyMinReportingInterval is for examples/orca use ONLY. ORCAAllowAnyMinReportingInterval any // func(so *orca.ServiceOptions) // GRPCResolverSchemeExtraMetadata determines when gRPC will add extra // metadata to RPCs. GRPCResolverSchemeExtraMetadata = "xds" // EnterIdleModeForTesting gets the ClientConn to enter IDLE mode. EnterIdleModeForTesting any // func(*grpc.ClientConn) // ExitIdleModeForTesting gets the ClientConn to exit IDLE mode. ExitIdleModeForTesting any // func(*grpc.ClientConn) error // ChannelzTurnOffForTesting disables the Channelz service for testing // purposes. ChannelzTurnOffForTesting func() // TriggerXDSResourceNotFoundForTesting causes the provided xDS Client to // invoke resource-not-found error for the given resource type and name. TriggerXDSResourceNotFoundForTesting any // func(xdsclient.XDSClient, xdsresource.Type, string) error // FromOutgoingContextRaw returns the un-merged, intermediary contents of // metadata.rawMD. FromOutgoingContextRaw any // func(context.Context) (metadata.MD, [][]string, bool) // UserSetDefaultScheme is set to true if the user has overridden the // default resolver scheme. UserSetDefaultScheme = false // ConnectedAddress returns the connected address for a SubConnState. The // address is only valid if the state is READY. ConnectedAddress any // func (scs SubConnState) resolver.Address // SetConnectedAddress sets the connected address for a SubConnState. SetConnectedAddress any // func(scs *SubConnState, addr resolver.Address) // SnapshotMetricRegistryForTesting snapshots the global data of the metric // registry. Returns a cleanup function that sets the metric registry to its // original state. Only called in testing functions. SnapshotMetricRegistryForTesting func() func() // SetDefaultBufferPoolForTesting updates the default buffer pool, for // testing purposes. SetDefaultBufferPoolForTesting any // func(mem.BufferPool) // SetBufferPoolingThresholdForTesting updates the buffer pooling threshold, for // testing purposes. SetBufferPoolingThresholdForTesting any // func(int) ) // HealthChecker defines the signature of the client-side LB channel health // checking function. // // The implementation is expected to create a health checking RPC stream by // calling newStream(), watch for the health status of serviceName, and report // its health back by calling setConnectivityState(). // // The health checking protocol is defined at: // https://github.com/grpc/grpc/blob/master/doc/health-checking.md type HealthChecker func(ctx context.Context, newStream func(string) (any, error), setConnectivityState func(connectivity.State, error), serviceName string) error const ( // CredsBundleModeFallback switches GoogleDefaultCreds to fallback mode. CredsBundleModeFallback = "fallback" // CredsBundleModeBalancer switches GoogleDefaultCreds to grpclb balancer // mode. CredsBundleModeBalancer = "balancer" // CredsBundleModeBackendFromBalancer switches GoogleDefaultCreds to mode // that supports backend returned by grpclb balancer. CredsBundleModeBackendFromBalancer = "backend-from-balancer" ) // RLSLoadBalancingPolicyName is the name of the RLS LB policy. // // It currently has an experimental suffix which would be removed once // end-to-end testing of the policy is completed. const RLSLoadBalancingPolicyName = "rls_experimental" // EnforceSubConnEmbedding is used to enforce proper SubConn implementation // embedding. type EnforceSubConnEmbedding interface { enforceSubConnEmbedding() } // EnforceClientConnEmbedding is used to enforce proper ClientConn implementation // embedding. type EnforceClientConnEmbedding interface { enforceClientConnEmbedding() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/grpcutil/compressor.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/grpcutil/compressor.go
/* * * Copyright 2022 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. * */ package grpcutil import ( "strings" ) // RegisteredCompressorNames holds names of the registered compressors. var RegisteredCompressorNames []string // IsCompressorNameRegistered returns true when name is available in registry. func IsCompressorNameRegistered(name string) bool { for _, compressor := range RegisteredCompressorNames { if compressor == name { return true } } return false } // RegisteredCompressors returns a string of registered compressor names // separated by comma. func RegisteredCompressors() string { return strings.Join(RegisteredCompressorNames, ",") }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/grpcutil/metadata.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/grpcutil/metadata.go
/* * * Copyright 2020 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. * */ package grpcutil import ( "context" "google.golang.org/grpc/metadata" ) type mdExtraKey struct{} // WithExtraMetadata creates a new context with incoming md attached. func WithExtraMetadata(ctx context.Context, md metadata.MD) context.Context { return context.WithValue(ctx, mdExtraKey{}, md) } // ExtraMetadata returns the incoming metadata in ctx if it exists. The // returned MD should not be modified. Writing to it may cause races. // Modification should be made to copies of the returned MD. func ExtraMetadata(ctx context.Context) (md metadata.MD, ok bool) { md, ok = ctx.Value(mdExtraKey{}).(metadata.MD) return }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/grpcutil/encode_duration.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/grpcutil/encode_duration.go
/* * * Copyright 2020 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. * */ package grpcutil import ( "strconv" "time" ) const maxTimeoutValue int64 = 100000000 - 1 // div does integer division and round-up the result. Note that this is // equivalent to (d+r-1)/r but has less chance to overflow. func div(d, r time.Duration) int64 { if d%r > 0 { return int64(d/r + 1) } return int64(d / r) } // EncodeDuration encodes the duration to the format grpc-timeout header // accepts. // // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests func EncodeDuration(t time.Duration) string { // TODO: This is simplistic and not bandwidth efficient. Improve it. if t <= 0 { return "0n" } if d := div(t, time.Nanosecond); d <= maxTimeoutValue { return strconv.FormatInt(d, 10) + "n" } if d := div(t, time.Microsecond); d <= maxTimeoutValue { return strconv.FormatInt(d, 10) + "u" } if d := div(t, time.Millisecond); d <= maxTimeoutValue { return strconv.FormatInt(d, 10) + "m" } if d := div(t, time.Second); d <= maxTimeoutValue { return strconv.FormatInt(d, 10) + "S" } if d := div(t, time.Minute); d <= maxTimeoutValue { return strconv.FormatInt(d, 10) + "M" } // Note that maxTimeoutValue * time.Hour > MaxInt64. return strconv.FormatInt(div(t, time.Hour), 10) + "H" }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/grpcutil/regex.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/grpcutil/regex.go
/* * * Copyright 2021 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. * */ package grpcutil import "regexp" // FullMatchWithRegex returns whether the full text matches the regex provided. func FullMatchWithRegex(re *regexp.Regexp, text string) bool { if len(text) == 0 { return re.MatchString(text) } re.Longest() rem := re.FindString(text) return len(rem) == len(text) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/grpcutil/method.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/grpcutil/method.go
/* * * Copyright 2018 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. * */ package grpcutil import ( "errors" "strings" ) // ParseMethod splits service and method from the input. It expects format // "/service/method". func ParseMethod(methodName string) (service, method string, _ error) { if !strings.HasPrefix(methodName, "/") { return "", "", errors.New("invalid method name: should start with /") } methodName = methodName[1:] pos := strings.LastIndex(methodName, "/") if pos < 0 { return "", "", errors.New("invalid method name: suffix /method is missing") } return methodName[:pos], methodName[pos+1:], nil } // baseContentType is the base content-type for gRPC. This is a valid // content-type on its own, but can also include a content-subtype such as // "proto" as a suffix after "+" or ";". See // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests // for more details. const baseContentType = "application/grpc" // ContentSubtype returns the content-subtype for the given content-type. The // given content-type must be a valid content-type that starts with // "application/grpc". A content-subtype will follow "application/grpc" after a // "+" or ";". See // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for // more details. // // If contentType is not a valid content-type for gRPC, the boolean // will be false, otherwise true. If content-type == "application/grpc", // "application/grpc+", or "application/grpc;", the boolean will be true, // but no content-subtype will be returned. // // contentType is assumed to be lowercase already. func ContentSubtype(contentType string) (string, bool) { if contentType == baseContentType { return "", true } if !strings.HasPrefix(contentType, baseContentType) { return "", false } // guaranteed since != baseContentType and has baseContentType prefix switch contentType[len(baseContentType)] { case '+', ';': // this will return true for "application/grpc+" or "application/grpc;" // which the previous validContentType function tested to be valid, so we // just say that no content-subtype is specified in this case return contentType[len(baseContentType)+1:], true default: return "", false } } // ContentType builds full content type with the given sub-type. // // contentSubtype is assumed to be lowercase func ContentType(contentSubtype string) string { if contentSubtype == "" { return baseContentType } return baseContentType + "+" + contentSubtype }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/grpcutil/grpcutil.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/grpcutil/grpcutil.go
/* * * Copyright 2021 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. * */ // Package grpcutil provides utility functions used across the gRPC codebase. package grpcutil
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/serviceconfig/serviceconfig.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/serviceconfig/serviceconfig.go
/* * * Copyright 2020 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. * */ // Package serviceconfig contains utility functions to parse service config. package serviceconfig import ( "encoding/json" "fmt" "time" "google.golang.org/grpc/balancer" "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" externalserviceconfig "google.golang.org/grpc/serviceconfig" ) var logger = grpclog.Component("core") // BalancerConfig wraps the name and config associated with one load balancing // policy. It corresponds to a single entry of the loadBalancingConfig field // from ServiceConfig. // // It implements the json.Unmarshaler interface. // // https://github.com/grpc/grpc-proto/blob/54713b1e8bc6ed2d4f25fb4dff527842150b91b2/grpc/service_config/service_config.proto#L247 type BalancerConfig struct { Name string Config externalserviceconfig.LoadBalancingConfig } type intermediateBalancerConfig []map[string]json.RawMessage // MarshalJSON implements the json.Marshaler interface. // // It marshals the balancer and config into a length-1 slice // ([]map[string]config). func (bc *BalancerConfig) MarshalJSON() ([]byte, error) { if bc.Config == nil { // If config is nil, return empty config `{}`. return []byte(fmt.Sprintf(`[{%q: %v}]`, bc.Name, "{}")), nil } c, err := json.Marshal(bc.Config) if err != nil { return nil, err } return []byte(fmt.Sprintf(`[{%q: %s}]`, bc.Name, c)), nil } // UnmarshalJSON implements the json.Unmarshaler interface. // // ServiceConfig contains a list of loadBalancingConfigs, each with a name and // config. This method iterates through that list in order, and stops at the // first policy that is supported. // - If the config for the first supported policy is invalid, the whole service // config is invalid. // - If the list doesn't contain any supported policy, the whole service config // is invalid. func (bc *BalancerConfig) UnmarshalJSON(b []byte) error { var ir intermediateBalancerConfig err := json.Unmarshal(b, &ir) if err != nil { return err } var names []string for i, lbcfg := range ir { if len(lbcfg) != 1 { return fmt.Errorf("invalid loadBalancingConfig: entry %v does not contain exactly 1 policy/config pair: %q", i, lbcfg) } var ( name string jsonCfg json.RawMessage ) // Get the key:value pair from the map. We have already made sure that // the map contains a single entry. for name, jsonCfg = range lbcfg { } names = append(names, name) builder := balancer.Get(name) if builder == nil { // If the balancer is not registered, move on to the next config. // This is not an error. continue } bc.Name = name parser, ok := builder.(balancer.ConfigParser) if !ok { if string(jsonCfg) != "{}" { logger.Warningf("non-empty balancer configuration %q, but balancer does not implement ParseConfig", string(jsonCfg)) } // Stop at this, though the builder doesn't support parsing config. return nil } cfg, err := parser.ParseConfig(jsonCfg) if err != nil { return fmt.Errorf("error parsing loadBalancingConfig for policy %q: %v", name, err) } bc.Config = cfg return nil } // This is reached when the for loop iterates over all entries, but didn't // return. This means we had a loadBalancingConfig slice but did not // encounter a registered policy. The config is considered invalid in this // case. return fmt.Errorf("invalid loadBalancingConfig: no supported policies found in %v", names) } // MethodConfig defines the configuration recommended by the service providers for a // particular method. type MethodConfig struct { // WaitForReady indicates whether RPCs sent to this method should wait until // the connection is ready by default (!failfast). The value specified via the // gRPC client API will override the value set here. WaitForReady *bool // Timeout is the default timeout for RPCs sent to this method. The actual // deadline used will be the minimum of the value specified here and the value // set by the application via the gRPC client API. If either one is not set, // then the other will be used. If neither is set, then the RPC has no deadline. Timeout *time.Duration // MaxReqSize is the maximum allowed payload size for an individual request in a // stream (client->server) in bytes. The size which is measured is the serialized // payload after per-message compression (but before stream compression) in bytes. // The actual value used is the minimum of the value specified here and the value set // by the application via the gRPC client API. If either one is not set, then the other // will be used. If neither is set, then the built-in default is used. MaxReqSize *int // MaxRespSize is the maximum allowed payload size for an individual response in a // stream (server->client) in bytes. MaxRespSize *int // RetryPolicy configures retry options for the method. RetryPolicy *RetryPolicy } // RetryPolicy defines the go-native version of the retry policy defined by the // service config here: // https://github.com/grpc/proposal/blob/master/A6-client-retries.md#integration-with-service-config type RetryPolicy struct { // MaxAttempts is the maximum number of attempts, including the original RPC. // // This field is required and must be two or greater. MaxAttempts int // Exponential backoff parameters. The initial retry attempt will occur at // random(0, initialBackoff). In general, the nth attempt will occur at // random(0, // min(initialBackoff*backoffMultiplier**(n-1), maxBackoff)). // // These fields are required and must be greater than zero. InitialBackoff time.Duration MaxBackoff time.Duration BackoffMultiplier float64 // The set of status codes which may be retried. // // Status codes are specified as strings, e.g., "UNAVAILABLE". // // This field is required and must be non-empty. // Note: a set is used to store this for easy lookup. RetryableStatusCodes map[codes.Code]bool }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/serviceconfig/duration.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/serviceconfig/duration.go
/* * * Copyright 2023 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. * */ package serviceconfig import ( "encoding/json" "fmt" "math" "strconv" "strings" "time" ) // Duration defines JSON marshal and unmarshal methods to conform to the // protobuf JSON spec defined [here]. // // [here]: https://protobuf.dev/reference/protobuf/google.protobuf/#duration type Duration time.Duration func (d Duration) String() string { return fmt.Sprint(time.Duration(d)) } // MarshalJSON converts from d to a JSON string output. func (d Duration) MarshalJSON() ([]byte, error) { ns := time.Duration(d).Nanoseconds() sec := ns / int64(time.Second) ns = ns % int64(time.Second) var sign string if sec < 0 || ns < 0 { sign, sec, ns = "-", -1*sec, -1*ns } // Generated output always contains 0, 3, 6, or 9 fractional digits, // depending on required precision. str := fmt.Sprintf("%s%d.%09d", sign, sec, ns) str = strings.TrimSuffix(str, "000") str = strings.TrimSuffix(str, "000") str = strings.TrimSuffix(str, ".000") return []byte(fmt.Sprintf("\"%ss\"", str)), nil } // UnmarshalJSON unmarshals b as a duration JSON string into d. func (d *Duration) UnmarshalJSON(b []byte) error { var s string if err := json.Unmarshal(b, &s); err != nil { return err } if !strings.HasSuffix(s, "s") { return fmt.Errorf("malformed duration %q: missing seconds unit", s) } neg := false if s[0] == '-' { neg = true s = s[1:] } ss := strings.SplitN(s[:len(s)-1], ".", 3) if len(ss) > 2 { return fmt.Errorf("malformed duration %q: too many decimals", s) } // hasDigits is set if either the whole or fractional part of the number is // present, since both are optional but one is required. hasDigits := false var sec, ns int64 if len(ss[0]) > 0 { var err error if sec, err = strconv.ParseInt(ss[0], 10, 64); err != nil { return fmt.Errorf("malformed duration %q: %v", s, err) } // Maximum seconds value per the durationpb spec. const maxProtoSeconds = 315_576_000_000 if sec > maxProtoSeconds { return fmt.Errorf("out of range: %q", s) } hasDigits = true } if len(ss) == 2 && len(ss[1]) > 0 { if len(ss[1]) > 9 { return fmt.Errorf("malformed duration %q: too many digits after decimal", s) } var err error if ns, err = strconv.ParseInt(ss[1], 10, 64); err != nil { return fmt.Errorf("malformed duration %q: %v", s, err) } for i := 9; i > len(ss[1]); i-- { ns *= 10 } hasDigits = true } if !hasDigits { return fmt.Errorf("malformed duration %q: contains no numbers", s) } if neg { sec *= -1 ns *= -1 } // Maximum/minimum seconds/nanoseconds representable by Go's time.Duration. const maxSeconds = math.MaxInt64 / int64(time.Second) const maxNanosAtMaxSeconds = math.MaxInt64 % int64(time.Second) const minSeconds = math.MinInt64 / int64(time.Second) const minNanosAtMinSeconds = math.MinInt64 % int64(time.Second) if sec > maxSeconds || (sec == maxSeconds && ns >= maxNanosAtMaxSeconds) { *d = Duration(math.MaxInt64) } else if sec < minSeconds || (sec == minSeconds && ns <= minNanosAtMinSeconds) { *d = Duration(math.MinInt64) } else { *d = Duration(sec*int64(time.Second) + ns) } return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/balancerload/load.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/balancerload/load.go
/* * Copyright 2019 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. */ // Package balancerload defines APIs to parse server loads in trailers. The // parsed loads are sent to balancers in DoneInfo. package balancerload import ( "google.golang.org/grpc/metadata" ) // Parser converts loads from metadata into a concrete type. type Parser interface { // Parse parses loads from metadata. Parse(md metadata.MD) any } var parser Parser // SetParser sets the load parser. // // Not mutex-protected, should be called before any gRPC functions. func SetParser(lr Parser) { parser = lr } // Parse calls parser.Read(). func Parse(md metadata.MD) any { if parser == nil { return nil } return parser.Parse(md) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/metadata/metadata.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/metadata/metadata.go
/* * * Copyright 2020 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. * */ // Package metadata contains functions to set and get metadata from addresses. // // This package is experimental. package metadata import ( "fmt" "strings" "google.golang.org/grpc/metadata" "google.golang.org/grpc/resolver" ) type mdKeyType string const mdKey = mdKeyType("grpc.internal.address.metadata") type mdValue metadata.MD func (m mdValue) Equal(o any) bool { om, ok := o.(mdValue) if !ok { return false } if len(m) != len(om) { return false } for k, v := range m { ov := om[k] if len(ov) != len(v) { return false } for i, ve := range v { if ov[i] != ve { return false } } } return true } // Get returns the metadata of addr. func Get(addr resolver.Address) metadata.MD { attrs := addr.Attributes if attrs == nil { return nil } md, _ := attrs.Value(mdKey).(mdValue) return metadata.MD(md) } // Set sets (overrides) the metadata in addr. // // When a SubConn is created with this address, the RPCs sent on it will all // have this metadata. func Set(addr resolver.Address, md metadata.MD) resolver.Address { addr.Attributes = addr.Attributes.WithValue(mdKey, mdValue(md)) return addr } // Validate validates every pair in md with ValidatePair. func Validate(md metadata.MD) error { for k, vals := range md { if err := ValidatePair(k, vals...); err != nil { return err } } return nil } // hasNotPrintable return true if msg contains any characters which are not in %x20-%x7E func hasNotPrintable(msg string) bool { // for i that saving a conversion if not using for range for i := 0; i < len(msg); i++ { if msg[i] < 0x20 || msg[i] > 0x7E { return true } } return false } // ValidatePair validate a key-value pair with the following rules (the pseudo-header will be skipped) : // // - key must contain one or more characters. // - the characters in the key must be contained in [0-9 a-z _ - .]. // - if the key ends with a "-bin" suffix, no validation of the corresponding value is performed. // - the characters in the every value must be printable (in [%x20-%x7E]). func ValidatePair(key string, vals ...string) error { // key should not be empty if key == "" { return fmt.Errorf("there is an empty key in the header") } // pseudo-header will be ignored if key[0] == ':' { return nil } // check key, for i that saving a conversion if not using for range for i := 0; i < len(key); i++ { r := key[i] if !(r >= 'a' && r <= 'z') && !(r >= '0' && r <= '9') && r != '.' && r != '-' && r != '_' { return fmt.Errorf("header key %q contains illegal characters not in [0-9a-z-_.]", key) } } if strings.HasSuffix(key, "-bin") { return nil } // check value for _, val := range vals { if hasNotPrintable(val) { return fmt.Errorf("header key %q contains value with non-printable ASCII characters", key) } } return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/syscall/syscall_linux.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/syscall/syscall_linux.go
/* * * Copyright 2018 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. * */ // Package syscall provides functionalities that grpc uses to get low-level operating system // stats/info. package syscall import ( "fmt" "net" "syscall" "time" "golang.org/x/sys/unix" "google.golang.org/grpc/grpclog" ) var logger = grpclog.Component("core") // GetCPUTime returns the how much CPU time has passed since the start of this process. func GetCPUTime() int64 { var ts unix.Timespec if err := unix.ClockGettime(unix.CLOCK_PROCESS_CPUTIME_ID, &ts); err != nil { logger.Fatal(err) } return ts.Nano() } // Rusage is an alias for syscall.Rusage under linux environment. type Rusage = syscall.Rusage // GetRusage returns the resource usage of current process. func GetRusage() *Rusage { rusage := new(Rusage) syscall.Getrusage(syscall.RUSAGE_SELF, rusage) return rusage } // CPUTimeDiff returns the differences of user CPU time and system CPU time used // between two Rusage structs. func CPUTimeDiff(first *Rusage, latest *Rusage) (float64, float64) { var ( utimeDiffs = latest.Utime.Sec - first.Utime.Sec utimeDiffus = latest.Utime.Usec - first.Utime.Usec stimeDiffs = latest.Stime.Sec - first.Stime.Sec stimeDiffus = latest.Stime.Usec - first.Stime.Usec ) uTimeElapsed := float64(utimeDiffs) + float64(utimeDiffus)*1.0e-6 sTimeElapsed := float64(stimeDiffs) + float64(stimeDiffus)*1.0e-6 return uTimeElapsed, sTimeElapsed } // SetTCPUserTimeout sets the TCP user timeout on a connection's socket func SetTCPUserTimeout(conn net.Conn, timeout time.Duration) error { tcpconn, ok := conn.(*net.TCPConn) if !ok { // not a TCP connection. exit early return nil } rawConn, err := tcpconn.SyscallConn() if err != nil { return fmt.Errorf("error getting raw connection: %v", err) } err = rawConn.Control(func(fd uintptr) { err = syscall.SetsockoptInt(int(fd), syscall.IPPROTO_TCP, unix.TCP_USER_TIMEOUT, int(timeout/time.Millisecond)) }) if err != nil { return fmt.Errorf("error setting option on socket: %v", err) } return nil } // GetTCPUserTimeout gets the TCP user timeout on a connection's socket func GetTCPUserTimeout(conn net.Conn) (opt int, err error) { tcpconn, ok := conn.(*net.TCPConn) if !ok { err = fmt.Errorf("conn is not *net.TCPConn. got %T", conn) return } rawConn, err := tcpconn.SyscallConn() if err != nil { err = fmt.Errorf("error getting raw connection: %v", err) return } err = rawConn.Control(func(fd uintptr) { opt, err = syscall.GetsockoptInt(int(fd), syscall.IPPROTO_TCP, unix.TCP_USER_TIMEOUT) }) if err != nil { err = fmt.Errorf("error getting option on socket: %v", err) return } return }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/syscall/syscall_nonlinux.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/syscall/syscall_nonlinux.go
//go:build !linux // +build !linux /* * * Copyright 2018 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. * */ // Package syscall provides functionalities that grpc uses to get low-level // operating system stats/info. package syscall import ( "net" "sync" "time" "google.golang.org/grpc/grpclog" ) var once sync.Once var logger = grpclog.Component("core") func log() { once.Do(func() { logger.Info("CPU time info is unavailable on non-linux environments.") }) } // GetCPUTime returns the how much CPU time has passed since the start of this // process. It always returns 0 under non-linux environments. func GetCPUTime() int64 { log() return 0 } // Rusage is an empty struct under non-linux environments. type Rusage struct{} // GetRusage is a no-op function under non-linux environments. func GetRusage() *Rusage { log() return nil } // CPUTimeDiff returns the differences of user CPU time and system CPU time used // between two Rusage structs. It a no-op function for non-linux environments. func CPUTimeDiff(*Rusage, *Rusage) (float64, float64) { log() return 0, 0 } // SetTCPUserTimeout is a no-op function under non-linux environments. func SetTCPUserTimeout(net.Conn, time.Duration) error { log() return nil } // GetTCPUserTimeout is a no-op function under non-linux environments. // A negative return value indicates the operation is not supported func GetTCPUserTimeout(net.Conn) (int, error) { log() return -1, nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/proxyattributes/proxyattributes.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/proxyattributes/proxyattributes.go
/* * * Copyright 2024 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. * */ // Package proxyattributes contains functions for getting and setting proxy // attributes like the CONNECT address and user info. package proxyattributes import ( "net/url" "google.golang.org/grpc/resolver" ) type keyType string const proxyOptionsKey = keyType("grpc.resolver.delegatingresolver.proxyOptions") // Options holds the proxy connection details needed during the CONNECT // handshake. type Options struct { User *url.Userinfo ConnectAddr string } // Set returns a copy of addr with opts set in its attributes. func Set(addr resolver.Address, opts Options) resolver.Address { addr.Attributes = addr.Attributes.WithValue(proxyOptionsKey, opts) return addr } // Get returns the Options for the proxy [resolver.Address] and a boolean // value representing if the attribute is present or not. The returned data // should not be mutated. func Get(addr resolver.Address) (Options, bool) { if a := addr.Attributes.Value(proxyOptionsKey); a != nil { return a.(Options), true } return Options{}, false }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/pretty/pretty.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/pretty/pretty.go
/* * * Copyright 2021 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. * */ // Package pretty defines helper functions to pretty-print structs for logging. package pretty import ( "bytes" "encoding/json" "fmt" "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/protoadapt" ) const jsonIndent = " " // ToJSON marshals the input into a json string. // // If marshal fails, it falls back to fmt.Sprintf("%+v"). func ToJSON(e any) string { if ee, ok := e.(protoadapt.MessageV1); ok { e = protoadapt.MessageV2Of(ee) } if ee, ok := e.(protoadapt.MessageV2); ok { mm := protojson.MarshalOptions{ Indent: jsonIndent, Multiline: true, } ret, err := mm.Marshal(ee) if err != nil { // This may fail for proto.Anys, e.g. for xDS v2, LDS, the v2 // messages are not imported, and this will fail because the message // is not found. return fmt.Sprintf("%+v", ee) } return string(ret) } ret, err := json.MarshalIndent(e, "", jsonIndent) if err != nil { return fmt.Sprintf("%+v", e) } return string(ret) } // FormatJSON formats the input json bytes with indentation. // // If Indent fails, it returns the unchanged input as string. func FormatJSON(b []byte) string { var out bytes.Buffer err := json.Indent(&out, b, "", jsonIndent) if err != nil { return string(b) } return out.String() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/backoff/backoff.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/backoff/backoff.go
/* * * Copyright 2017 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. * */ // Package backoff implement the backoff strategy for gRPC. // // This is kept in internal until the gRPC project decides whether or not to // allow alternative backoff strategies. package backoff import ( "context" "errors" rand "math/rand/v2" "time" grpcbackoff "google.golang.org/grpc/backoff" ) // Strategy defines the methodology for backing off after a grpc connection // failure. type Strategy interface { // Backoff returns the amount of time to wait before the next retry given // the number of consecutive failures. Backoff(retries int) time.Duration } // DefaultExponential is an exponential backoff implementation using the // default values for all the configurable knobs defined in // https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md. var DefaultExponential = Exponential{Config: grpcbackoff.DefaultConfig} // Exponential implements exponential backoff algorithm as defined in // https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md. type Exponential struct { // Config contains all options to configure the backoff algorithm. Config grpcbackoff.Config } // Backoff returns the amount of time to wait before the next retry given the // number of retries. func (bc Exponential) Backoff(retries int) time.Duration { if retries == 0 { return bc.Config.BaseDelay } backoff, max := float64(bc.Config.BaseDelay), float64(bc.Config.MaxDelay) for backoff < max && retries > 0 { backoff *= bc.Config.Multiplier retries-- } if backoff > max { backoff = max } // Randomize backoff delays so that if a cluster of requests start at // the same time, they won't operate in lockstep. backoff *= 1 + bc.Config.Jitter*(rand.Float64()*2-1) if backoff < 0 { return 0 } return time.Duration(backoff) } // ErrResetBackoff is the error to be returned by the function executed by RunF, // to instruct the latter to reset its backoff state. var ErrResetBackoff = errors.New("reset backoff state") // RunF provides a convenient way to run a function f repeatedly until the // context expires or f returns a non-nil error that is not ErrResetBackoff. // When f returns ErrResetBackoff, RunF continues to run f, but resets its // backoff state before doing so. backoff accepts an integer representing the // number of retries, and returns the amount of time to backoff. func RunF(ctx context.Context, f func() error, backoff func(int) time.Duration) { attempt := 0 timer := time.NewTimer(0) for ctx.Err() == nil { select { case <-timer.C: case <-ctx.Done(): timer.Stop() return } err := f() if errors.Is(err, ErrResetBackoff) { timer.Reset(0) attempt = 0 continue } if err != nil { return } timer.Reset(backoff(attempt)) attempt++ } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/stats/metrics_recorder_list.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/stats/metrics_recorder_list.go
/* * Copyright 2024 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. */ package stats import ( "fmt" estats "google.golang.org/grpc/experimental/stats" "google.golang.org/grpc/stats" ) // MetricsRecorderList forwards Record calls to all of its metricsRecorders. // // It eats any record calls where the label values provided do not match the // number of label keys. type MetricsRecorderList struct { // metricsRecorders are the metrics recorders this list will forward to. metricsRecorders []estats.MetricsRecorder } // NewMetricsRecorderList creates a new metric recorder list with all the stats // handlers provided which implement the MetricsRecorder interface. // If no stats handlers provided implement the MetricsRecorder interface, // the MetricsRecorder list returned is a no-op. func NewMetricsRecorderList(shs []stats.Handler) *MetricsRecorderList { var mrs []estats.MetricsRecorder for _, sh := range shs { if mr, ok := sh.(estats.MetricsRecorder); ok { mrs = append(mrs, mr) } } return &MetricsRecorderList{ metricsRecorders: mrs, } } func verifyLabels(desc *estats.MetricDescriptor, labelsRecv ...string) { if got, want := len(labelsRecv), len(desc.Labels)+len(desc.OptionalLabels); got != want { panic(fmt.Sprintf("Received %d labels in call to record metric %q, but expected %d.", got, desc.Name, want)) } } // RecordInt64Count records the measurement alongside labels on the int // count associated with the provided handle. func (l *MetricsRecorderList) RecordInt64Count(handle *estats.Int64CountHandle, incr int64, labels ...string) { verifyLabels(handle.Descriptor(), labels...) for _, metricRecorder := range l.metricsRecorders { metricRecorder.RecordInt64Count(handle, incr, labels...) } } // RecordFloat64Count records the measurement alongside labels on the float // count associated with the provided handle. func (l *MetricsRecorderList) RecordFloat64Count(handle *estats.Float64CountHandle, incr float64, labels ...string) { verifyLabels(handle.Descriptor(), labels...) for _, metricRecorder := range l.metricsRecorders { metricRecorder.RecordFloat64Count(handle, incr, labels...) } } // RecordInt64Histo records the measurement alongside labels on the int // histo associated with the provided handle. func (l *MetricsRecorderList) RecordInt64Histo(handle *estats.Int64HistoHandle, incr int64, labels ...string) { verifyLabels(handle.Descriptor(), labels...) for _, metricRecorder := range l.metricsRecorders { metricRecorder.RecordInt64Histo(handle, incr, labels...) } } // RecordFloat64Histo records the measurement alongside labels on the float // histo associated with the provided handle. func (l *MetricsRecorderList) RecordFloat64Histo(handle *estats.Float64HistoHandle, incr float64, labels ...string) { verifyLabels(handle.Descriptor(), labels...) for _, metricRecorder := range l.metricsRecorders { metricRecorder.RecordFloat64Histo(handle, incr, labels...) } } // RecordInt64Gauge records the measurement alongside labels on the int // gauge associated with the provided handle. func (l *MetricsRecorderList) RecordInt64Gauge(handle *estats.Int64GaugeHandle, incr int64, labels ...string) { verifyLabels(handle.Descriptor(), labels...) for _, metricRecorder := range l.metricsRecorders { metricRecorder.RecordInt64Gauge(handle, incr, labels...) } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/stats/labels.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/stats/labels.go
/* * * Copyright 2024 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. * */ // Package stats provides internal stats related functionality. package stats import "context" // Labels are the labels for metrics. type Labels struct { // TelemetryLabels are the telemetry labels to record. TelemetryLabels map[string]string } type labelsKey struct{} // GetLabels returns the Labels stored in the context, or nil if there is one. func GetLabels(ctx context.Context) *Labels { labels, _ := ctx.Value(labelsKey{}).(*Labels) return labels } // SetLabels sets the Labels in the context. func SetLabels(ctx context.Context, labels *Labels) context.Context { // could also append return context.WithValue(ctx, labelsKey{}, labels) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/balancer/gracefulswitch/gracefulswitch.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/balancer/gracefulswitch/gracefulswitch.go
/* * * Copyright 2022 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. * */ // Package gracefulswitch implements a graceful switch load balancer. package gracefulswitch import ( "errors" "fmt" "sync" "google.golang.org/grpc/balancer" "google.golang.org/grpc/balancer/base" "google.golang.org/grpc/connectivity" "google.golang.org/grpc/resolver" ) var errBalancerClosed = errors.New("gracefulSwitchBalancer is closed") var _ balancer.Balancer = (*Balancer)(nil) // NewBalancer returns a graceful switch Balancer. func NewBalancer(cc balancer.ClientConn, opts balancer.BuildOptions) *Balancer { return &Balancer{ cc: cc, bOpts: opts, } } // Balancer is a utility to gracefully switch from one balancer to // a new balancer. It implements the balancer.Balancer interface. type Balancer struct { bOpts balancer.BuildOptions cc balancer.ClientConn // mu protects the following fields and all fields within balancerCurrent // and balancerPending. mu does not need to be held when calling into the // child balancers, as all calls into these children happen only as a direct // result of a call into the gracefulSwitchBalancer, which are also // guaranteed to be synchronous. There is one exception: an UpdateState call // from a child balancer when current and pending are populated can lead to // calling Close() on the current. To prevent that racing with an // UpdateSubConnState from the channel, we hold currentMu during Close and // UpdateSubConnState calls. mu sync.Mutex balancerCurrent *balancerWrapper balancerPending *balancerWrapper closed bool // set to true when this balancer is closed // currentMu must be locked before mu. This mutex guards against this // sequence of events: UpdateSubConnState() called, finds the // balancerCurrent, gives up lock, updateState comes in, causes Close() on // balancerCurrent before the UpdateSubConnState is called on the // balancerCurrent. currentMu sync.Mutex } // swap swaps out the current lb with the pending lb and updates the ClientConn. // The caller must hold gsb.mu. func (gsb *Balancer) swap() { gsb.cc.UpdateState(gsb.balancerPending.lastState) cur := gsb.balancerCurrent gsb.balancerCurrent = gsb.balancerPending gsb.balancerPending = nil go func() { gsb.currentMu.Lock() defer gsb.currentMu.Unlock() cur.Close() }() } // Helper function that checks if the balancer passed in is current or pending. // The caller must hold gsb.mu. func (gsb *Balancer) balancerCurrentOrPending(bw *balancerWrapper) bool { return bw == gsb.balancerCurrent || bw == gsb.balancerPending } // SwitchTo initializes the graceful switch process, which completes based on // connectivity state changes on the current/pending balancer. Thus, the switch // process is not complete when this method returns. This method must be called // synchronously alongside the rest of the balancer.Balancer methods this // Graceful Switch Balancer implements. // // Deprecated: use ParseConfig and pass a parsed config to UpdateClientConnState // to cause the Balancer to automatically change to the new child when necessary. func (gsb *Balancer) SwitchTo(builder balancer.Builder) error { _, err := gsb.switchTo(builder) return err } func (gsb *Balancer) switchTo(builder balancer.Builder) (*balancerWrapper, error) { gsb.mu.Lock() if gsb.closed { gsb.mu.Unlock() return nil, errBalancerClosed } bw := &balancerWrapper{ ClientConn: gsb.cc, builder: builder, gsb: gsb, lastState: balancer.State{ ConnectivityState: connectivity.Connecting, Picker: base.NewErrPicker(balancer.ErrNoSubConnAvailable), }, subconns: make(map[balancer.SubConn]bool), } balToClose := gsb.balancerPending // nil if there is no pending balancer if gsb.balancerCurrent == nil { gsb.balancerCurrent = bw } else { gsb.balancerPending = bw } gsb.mu.Unlock() balToClose.Close() // This function takes a builder instead of a balancer because builder.Build // can call back inline, and this utility needs to handle the callbacks. newBalancer := builder.Build(bw, gsb.bOpts) if newBalancer == nil { // This is illegal and should never happen; we clear the balancerWrapper // we were constructing if it happens to avoid a potential panic. gsb.mu.Lock() if gsb.balancerPending != nil { gsb.balancerPending = nil } else { gsb.balancerCurrent = nil } gsb.mu.Unlock() return nil, balancer.ErrBadResolverState } // This write doesn't need to take gsb.mu because this field never gets read // or written to on any calls from the current or pending. Calls from grpc // to this balancer are guaranteed to be called synchronously, so this // bw.Balancer field will never be forwarded to until this SwitchTo() // function returns. bw.Balancer = newBalancer return bw, nil } // Returns nil if the graceful switch balancer is closed. func (gsb *Balancer) latestBalancer() *balancerWrapper { gsb.mu.Lock() defer gsb.mu.Unlock() if gsb.balancerPending != nil { return gsb.balancerPending } return gsb.balancerCurrent } // UpdateClientConnState forwards the update to the latest balancer created. // // If the state's BalancerConfig is the config returned by a call to // gracefulswitch.ParseConfig, then this function will automatically SwitchTo // the balancer indicated by the config before forwarding its config to it, if // necessary. func (gsb *Balancer) UpdateClientConnState(state balancer.ClientConnState) error { // The resolver data is only relevant to the most recent LB Policy. balToUpdate := gsb.latestBalancer() gsbCfg, ok := state.BalancerConfig.(*lbConfig) if ok { // Switch to the child in the config unless it is already active. if balToUpdate == nil || gsbCfg.childBuilder.Name() != balToUpdate.builder.Name() { var err error balToUpdate, err = gsb.switchTo(gsbCfg.childBuilder) if err != nil { return fmt.Errorf("could not switch to new child balancer: %w", err) } } // Unwrap the child balancer's config. state.BalancerConfig = gsbCfg.childConfig } if balToUpdate == nil { return errBalancerClosed } // Perform this call without gsb.mu to prevent deadlocks if the child calls // back into the channel. The latest balancer can never be closed during a // call from the channel, even without gsb.mu held. return balToUpdate.UpdateClientConnState(state) } // ResolverError forwards the error to the latest balancer created. func (gsb *Balancer) ResolverError(err error) { // The resolver data is only relevant to the most recent LB Policy. balToUpdate := gsb.latestBalancer() if balToUpdate == nil { gsb.cc.UpdateState(balancer.State{ ConnectivityState: connectivity.TransientFailure, Picker: base.NewErrPicker(err), }) return } // Perform this call without gsb.mu to prevent deadlocks if the child calls // back into the channel. The latest balancer can never be closed during a // call from the channel, even without gsb.mu held. balToUpdate.ResolverError(err) } // ExitIdle forwards the call to the latest balancer created. // // If the latest balancer does not support ExitIdle, the subConns are // re-connected to manually. func (gsb *Balancer) ExitIdle() { balToUpdate := gsb.latestBalancer() if balToUpdate == nil { return } // There is no need to protect this read with a mutex, as the write to the // Balancer field happens in SwitchTo, which completes before this can be // called. if ei, ok := balToUpdate.Balancer.(balancer.ExitIdler); ok { ei.ExitIdle() return } gsb.mu.Lock() defer gsb.mu.Unlock() for sc := range balToUpdate.subconns { sc.Connect() } } // updateSubConnState forwards the update to the appropriate child. func (gsb *Balancer) updateSubConnState(sc balancer.SubConn, state balancer.SubConnState, cb func(balancer.SubConnState)) { gsb.currentMu.Lock() defer gsb.currentMu.Unlock() gsb.mu.Lock() // Forward update to the appropriate child. Even if there is a pending // balancer, the current balancer should continue to get SubConn updates to // maintain the proper state while the pending is still connecting. var balToUpdate *balancerWrapper if gsb.balancerCurrent != nil && gsb.balancerCurrent.subconns[sc] { balToUpdate = gsb.balancerCurrent } else if gsb.balancerPending != nil && gsb.balancerPending.subconns[sc] { balToUpdate = gsb.balancerPending } if balToUpdate == nil { // SubConn belonged to a stale lb policy that has not yet fully closed, // or the balancer was already closed. gsb.mu.Unlock() return } if state.ConnectivityState == connectivity.Shutdown { delete(balToUpdate.subconns, sc) } gsb.mu.Unlock() if cb != nil { cb(state) } else { balToUpdate.UpdateSubConnState(sc, state) } } // UpdateSubConnState forwards the update to the appropriate child. func (gsb *Balancer) UpdateSubConnState(sc balancer.SubConn, state balancer.SubConnState) { gsb.updateSubConnState(sc, state, nil) } // Close closes any active child balancers. func (gsb *Balancer) Close() { gsb.mu.Lock() gsb.closed = true currentBalancerToClose := gsb.balancerCurrent gsb.balancerCurrent = nil pendingBalancerToClose := gsb.balancerPending gsb.balancerPending = nil gsb.mu.Unlock() currentBalancerToClose.Close() pendingBalancerToClose.Close() } // balancerWrapper wraps a balancer.Balancer, and overrides some Balancer // methods to help cleanup SubConns created by the wrapped balancer. // // It implements the balancer.ClientConn interface and is passed down in that // capacity to the wrapped balancer. It maintains a set of subConns created by // the wrapped balancer and calls from the latter to create/update/shutdown // SubConns update this set before being forwarded to the parent ClientConn. // State updates from the wrapped balancer can result in invocation of the // graceful switch logic. type balancerWrapper struct { balancer.ClientConn balancer.Balancer gsb *Balancer builder balancer.Builder lastState balancer.State subconns map[balancer.SubConn]bool // subconns created by this balancer } // Close closes the underlying LB policy and shuts down the subconns it // created. bw must not be referenced via balancerCurrent or balancerPending in // gsb when called. gsb.mu must not be held. Does not panic with a nil // receiver. func (bw *balancerWrapper) Close() { // before Close is called. if bw == nil { return } // There is no need to protect this read with a mutex, as Close() is // impossible to be called concurrently with the write in SwitchTo(). The // callsites of Close() for this balancer in Graceful Switch Balancer will // never be called until SwitchTo() returns. bw.Balancer.Close() bw.gsb.mu.Lock() for sc := range bw.subconns { sc.Shutdown() } bw.gsb.mu.Unlock() } func (bw *balancerWrapper) UpdateState(state balancer.State) { // Hold the mutex for this entire call to ensure it cannot occur // concurrently with other updateState() calls. This causes updates to // lastState and calls to cc.UpdateState to happen atomically. bw.gsb.mu.Lock() defer bw.gsb.mu.Unlock() bw.lastState = state if !bw.gsb.balancerCurrentOrPending(bw) { return } if bw == bw.gsb.balancerCurrent { // In the case that the current balancer exits READY, and there is a pending // balancer, you can forward the pending balancer's cached State up to // ClientConn and swap the pending into the current. This is because there // is no reason to gracefully switch from and keep using the old policy as // the ClientConn is not connected to any backends. if state.ConnectivityState != connectivity.Ready && bw.gsb.balancerPending != nil { bw.gsb.swap() return } // Even if there is a pending balancer waiting to be gracefully switched to, // continue to forward current balancer updates to the Client Conn. Ignoring // state + picker from the current would cause undefined behavior/cause the // system to behave incorrectly from the current LB policies perspective. // Also, the current LB is still being used by grpc to choose SubConns per // RPC, and thus should use the most updated form of the current balancer. bw.gsb.cc.UpdateState(state) return } // This method is now dealing with a state update from the pending balancer. // If the current balancer is currently in a state other than READY, the new // policy can be swapped into place immediately. This is because there is no // reason to gracefully switch from and keep using the old policy as the // ClientConn is not connected to any backends. if state.ConnectivityState != connectivity.Connecting || bw.gsb.balancerCurrent.lastState.ConnectivityState != connectivity.Ready { bw.gsb.swap() } } func (bw *balancerWrapper) NewSubConn(addrs []resolver.Address, opts balancer.NewSubConnOptions) (balancer.SubConn, error) { bw.gsb.mu.Lock() if !bw.gsb.balancerCurrentOrPending(bw) { bw.gsb.mu.Unlock() return nil, fmt.Errorf("%T at address %p that called NewSubConn is deleted", bw, bw) } bw.gsb.mu.Unlock() var sc balancer.SubConn oldListener := opts.StateListener opts.StateListener = func(state balancer.SubConnState) { bw.gsb.updateSubConnState(sc, state, oldListener) } sc, err := bw.gsb.cc.NewSubConn(addrs, opts) if err != nil { return nil, err } bw.gsb.mu.Lock() if !bw.gsb.balancerCurrentOrPending(bw) { // balancer was closed during this call sc.Shutdown() bw.gsb.mu.Unlock() return nil, fmt.Errorf("%T at address %p that called NewSubConn is deleted", bw, bw) } bw.subconns[sc] = true bw.gsb.mu.Unlock() return sc, nil } func (bw *balancerWrapper) ResolveNow(opts resolver.ResolveNowOptions) { // Ignore ResolveNow requests from anything other than the most recent // balancer, because older balancers were already removed from the config. if bw != bw.gsb.latestBalancer() { return } bw.gsb.cc.ResolveNow(opts) } func (bw *balancerWrapper) RemoveSubConn(sc balancer.SubConn) { // Note: existing third party balancers may call this, so it must remain // until RemoveSubConn is fully removed. sc.Shutdown() } func (bw *balancerWrapper) UpdateAddresses(sc balancer.SubConn, addrs []resolver.Address) { bw.gsb.mu.Lock() if !bw.gsb.balancerCurrentOrPending(bw) { bw.gsb.mu.Unlock() return } bw.gsb.mu.Unlock() bw.gsb.cc.UpdateAddresses(sc, addrs) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/balancer/gracefulswitch/config.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/balancer/gracefulswitch/config.go
/* * * Copyright 2024 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. * */ package gracefulswitch import ( "encoding/json" "fmt" "google.golang.org/grpc/balancer" "google.golang.org/grpc/serviceconfig" ) type lbConfig struct { serviceconfig.LoadBalancingConfig childBuilder balancer.Builder childConfig serviceconfig.LoadBalancingConfig } // ChildName returns the name of the child balancer of the gracefulswitch // Balancer. func ChildName(l serviceconfig.LoadBalancingConfig) string { return l.(*lbConfig).childBuilder.Name() } // ParseConfig parses a child config list and returns a LB config for the // gracefulswitch Balancer. // // cfg is expected to be a json.RawMessage containing a JSON array of LB policy // names + configs as the format of the "loadBalancingConfig" field in // ServiceConfig. It returns a type that should be passed to // UpdateClientConnState in the BalancerConfig field. func ParseConfig(cfg json.RawMessage) (serviceconfig.LoadBalancingConfig, error) { var lbCfg []map[string]json.RawMessage if err := json.Unmarshal(cfg, &lbCfg); err != nil { return nil, err } for i, e := range lbCfg { if len(e) != 1 { return nil, fmt.Errorf("expected a JSON struct with one entry; received entry %v at index %d", e, i) } var name string var jsonCfg json.RawMessage for name, jsonCfg = range e { } builder := balancer.Get(name) if builder == nil { // Skip unregistered balancer names. continue } parser, ok := builder.(balancer.ConfigParser) if !ok { // This is a valid child with no config. return &lbConfig{childBuilder: builder}, nil } cfg, err := parser.ParseConfig(jsonCfg) if err != nil { return nil, fmt.Errorf("error parsing config for policy %q: %v", name, err) } return &lbConfig{childBuilder: builder, childConfig: cfg}, nil } return nil, fmt.Errorf("no supported policies found in config: %v", string(cfg)) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/resolver/config_selector.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/resolver/config_selector.go
/* * * Copyright 2020 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. * */ // Package resolver provides internal resolver-related functionality. package resolver import ( "context" "sync" "google.golang.org/grpc/internal/serviceconfig" "google.golang.org/grpc/metadata" "google.golang.org/grpc/resolver" ) // ConfigSelector controls what configuration to use for every RPC. type ConfigSelector interface { // Selects the configuration for the RPC, or terminates it using the error. // This error will be converted by the gRPC library to a status error with // code UNKNOWN if it is not returned as a status error. SelectConfig(RPCInfo) (*RPCConfig, error) } // RPCInfo contains RPC information needed by a ConfigSelector. type RPCInfo struct { // Context is the user's context for the RPC and contains headers and // application timeout. It is passed for interception purposes and for // efficiency reasons. SelectConfig should not be blocking. Context context.Context Method string // i.e. "/Service/Method" } // RPCConfig describes the configuration to use for each RPC. type RPCConfig struct { // The context to use for the remainder of the RPC; can pass info to LB // policy or affect timeout or metadata. Context context.Context MethodConfig serviceconfig.MethodConfig // configuration to use for this RPC OnCommitted func() // Called when the RPC has been committed (retries no longer possible) Interceptor ClientInterceptor } // ClientStream is the same as grpc.ClientStream, but defined here for circular // dependency reasons. 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, if there is any. // It must only be called after stream.CloseAndRecv has returned, or // stream.Recv has returned a non-nil error (including io.EOF). Trailer() metadata.MD // CloseSend closes the send direction of the stream. It closes the stream // when non-nil error is met. It is also not safe to call CloseSend // concurrently with SendMsg. CloseSend() error // Context returns the context for this stream. // // It should not be called until after Header or RecvMsg has returned. Once // called, subsequent client-side retries are disabled. Context() context.Context // SendMsg is generally called by generated code. On error, SendMsg aborts // the stream. If the error was generated by the client, the status is // returned directly; otherwise, io.EOF is returned and the status of // the stream may be discovered using RecvMsg. // // SendMsg blocks until: // - There is sufficient flow control to schedule m with the transport, or // - The stream is done, or // - The stream breaks. // // SendMsg does not wait until the message is received by the server. An // untimely stream closure may result in lost messages. To ensure delivery, // users should ensure the RPC completed successfully using RecvMsg. // // It is safe to have a goroutine calling SendMsg and another goroutine // calling RecvMsg on the same stream at the same time, but it is not safe // to call SendMsg on the same stream in different goroutines. It is also // not safe to call CloseSend concurrently with SendMsg. SendMsg(m any) error // RecvMsg blocks until it receives a message into m or the stream is // done. It returns io.EOF when the stream completes successfully. On // any other error, the stream is aborted and the error contains the RPC // status. // // It is safe to have a goroutine calling SendMsg and another goroutine // calling RecvMsg on the same stream at the same time, but it is not // safe to call RecvMsg on the same stream in different goroutines. RecvMsg(m any) error } // ClientInterceptor is an interceptor for gRPC client streams. type ClientInterceptor interface { // NewStream produces a ClientStream for an RPC which may optionally use // the provided function to produce a stream for delegation. Note: // RPCInfo.Context should not be used (will be nil). // // done is invoked when the RPC is finished using its connection, or could // not be assigned a connection. RPC operations may still occur on // ClientStream after done is called, since the interceptor is invoked by // application-layer operations. done must never be nil when called. NewStream(ctx context.Context, ri RPCInfo, done func(), newStream func(ctx context.Context, done func()) (ClientStream, error)) (ClientStream, error) } // ServerInterceptor is an interceptor for incoming RPC's on gRPC server side. type ServerInterceptor interface { // AllowRPC checks if an incoming RPC is allowed to proceed based on // information about connection RPC was received on, and HTTP Headers. This // information will be piped into context. AllowRPC(ctx context.Context) error // TODO: Make this a real interceptor for filters such as rate limiting. } type csKeyType string const csKey = csKeyType("grpc.internal.resolver.configSelector") // SetConfigSelector sets the config selector in state and returns the new // state. func SetConfigSelector(state resolver.State, cs ConfigSelector) resolver.State { state.Attributes = state.Attributes.WithValue(csKey, cs) return state } // GetConfigSelector retrieves the config selector from state, if present, and // returns it or nil if absent. func GetConfigSelector(state resolver.State) ConfigSelector { cs, _ := state.Attributes.Value(csKey).(ConfigSelector) return cs } // SafeConfigSelector allows for safe switching of ConfigSelector // implementations such that previous values are guaranteed to not be in use // when UpdateConfigSelector returns. type SafeConfigSelector struct { mu sync.RWMutex cs ConfigSelector } // UpdateConfigSelector swaps to the provided ConfigSelector and blocks until // all uses of the previous ConfigSelector have completed. func (scs *SafeConfigSelector) UpdateConfigSelector(cs ConfigSelector) { scs.mu.Lock() defer scs.mu.Unlock() scs.cs = cs } // SelectConfig defers to the current ConfigSelector in scs. func (scs *SafeConfigSelector) SelectConfig(r RPCInfo) (*RPCConfig, error) { scs.mu.RLock() defer scs.mu.RUnlock() return scs.cs.SelectConfig(r) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/resolver/unix/unix.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/resolver/unix/unix.go
/* * * Copyright 2020 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. * */ // Package unix implements a resolver for unix targets. package unix import ( "fmt" "google.golang.org/grpc/internal/transport/networktype" "google.golang.org/grpc/resolver" ) const unixScheme = "unix" const unixAbstractScheme = "unix-abstract" type builder struct { scheme string } func (b *builder) Build(target resolver.Target, cc resolver.ClientConn, _ resolver.BuildOptions) (resolver.Resolver, error) { if target.URL.Host != "" { return nil, fmt.Errorf("invalid (non-empty) authority: %v", target.URL.Host) } // gRPC was parsing the dial target manually before PR #4817, and we // switched to using url.Parse() in that PR. To avoid breaking existing // resolver implementations we ended up stripping the leading "/" from the // endpoint. This obviously does not work for the "unix" scheme. Hence we // end up using the parsed URL instead. endpoint := target.URL.Path if endpoint == "" { endpoint = target.URL.Opaque } addr := resolver.Address{Addr: endpoint} if b.scheme == unixAbstractScheme { // We can not prepend \0 as c++ gRPC does, as in Golang '@' is used to signify we do // not want trailing \0 in address. addr.Addr = "@" + addr.Addr } cc.UpdateState(resolver.State{Addresses: []resolver.Address{networktype.Set(addr, "unix")}}) return &nopResolver{}, nil } func (b *builder) Scheme() string { return b.scheme } func (b *builder) OverrideAuthority(resolver.Target) string { return "localhost" } type nopResolver struct { } func (*nopResolver) ResolveNow(resolver.ResolveNowOptions) {} func (*nopResolver) Close() {} func init() { resolver.Register(&builder{scheme: unixScheme}) resolver.Register(&builder{scheme: unixAbstractScheme}) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/resolver/passthrough/passthrough.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/resolver/passthrough/passthrough.go
/* * * Copyright 2017 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. * */ // Package passthrough implements a pass-through resolver. It sends the target // name without scheme back to gRPC as resolved address. package passthrough import ( "errors" "google.golang.org/grpc/resolver" ) const scheme = "passthrough" type passthroughBuilder struct{} func (*passthroughBuilder) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOptions) (resolver.Resolver, error) { if target.Endpoint() == "" && opts.Dialer == nil { return nil, errors.New("passthrough: received empty target in Build()") } r := &passthroughResolver{ target: target, cc: cc, } r.start() return r, nil } func (*passthroughBuilder) Scheme() string { return scheme } type passthroughResolver struct { target resolver.Target cc resolver.ClientConn } func (r *passthroughResolver) start() { r.cc.UpdateState(resolver.State{Addresses: []resolver.Address{{Addr: r.target.Endpoint()}}}) } func (*passthroughResolver) ResolveNow(resolver.ResolveNowOptions) {} func (*passthroughResolver) Close() {} func init() { resolver.Register(&passthroughBuilder{}) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/resolver/dns/dns_resolver.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/resolver/dns/dns_resolver.go
/* * * Copyright 2018 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. * */ // Package dns implements a dns resolver to be installed as the default resolver // in grpc. package dns import ( "context" "encoding/json" "fmt" rand "math/rand/v2" "net" "net/netip" "os" "strconv" "strings" "sync" "time" grpclbstate "google.golang.org/grpc/balancer/grpclb/state" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/internal/backoff" "google.golang.org/grpc/internal/envconfig" "google.golang.org/grpc/internal/resolver/dns/internal" "google.golang.org/grpc/resolver" "google.golang.org/grpc/serviceconfig" ) var ( // EnableSRVLookups controls whether the DNS resolver attempts to fetch gRPCLB // addresses from SRV records. Must not be changed after init time. EnableSRVLookups = false // MinResolutionInterval is the minimum interval at which re-resolutions are // allowed. This helps to prevent excessive re-resolution. MinResolutionInterval = 30 * time.Second // ResolvingTimeout specifies the maximum duration for a DNS resolution request. // If the timeout expires before a response is received, the request will be canceled. // // It is recommended to set this value at application startup. Avoid modifying this variable // after initialization as it's not thread-safe for concurrent modification. ResolvingTimeout = 30 * time.Second logger = grpclog.Component("dns") ) func init() { resolver.Register(NewBuilder()) internal.TimeAfterFunc = time.After internal.TimeNowFunc = time.Now internal.TimeUntilFunc = time.Until internal.NewNetResolver = newNetResolver internal.AddressDialer = addressDialer } const ( defaultPort = "443" defaultDNSSvrPort = "53" golang = "GO" // txtPrefix is the prefix string to be prepended to the host name for txt // record lookup. txtPrefix = "_grpc_config." // In DNS, service config is encoded in a TXT record via the mechanism // described in RFC-1464 using the attribute name grpc_config. txtAttribute = "grpc_config=" ) var addressDialer = func(address string) func(context.Context, string, string) (net.Conn, error) { return func(ctx context.Context, network, _ string) (net.Conn, error) { var dialer net.Dialer return dialer.DialContext(ctx, network, address) } } var newNetResolver = func(authority string) (internal.NetResolver, error) { if authority == "" { return net.DefaultResolver, nil } host, port, err := parseTarget(authority, defaultDNSSvrPort) if err != nil { return nil, err } authorityWithPort := net.JoinHostPort(host, port) return &net.Resolver{ PreferGo: true, Dial: internal.AddressDialer(authorityWithPort), }, nil } // NewBuilder creates a dnsBuilder which is used to factory DNS resolvers. func NewBuilder() resolver.Builder { return &dnsBuilder{} } type dnsBuilder struct{} // Build creates and starts a DNS resolver that watches the name resolution of // the target. func (b *dnsBuilder) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOptions) (resolver.Resolver, error) { host, port, err := parseTarget(target.Endpoint(), defaultPort) if err != nil { return nil, err } // IP address. if ipAddr, err := formatIP(host); err == nil { addr := []resolver.Address{{Addr: ipAddr + ":" + port}} cc.UpdateState(resolver.State{Addresses: addr}) return deadResolver{}, nil } // DNS address (non-IP). ctx, cancel := context.WithCancel(context.Background()) d := &dnsResolver{ host: host, port: port, ctx: ctx, cancel: cancel, cc: cc, rn: make(chan struct{}, 1), disableServiceConfig: opts.DisableServiceConfig, } d.resolver, err = internal.NewNetResolver(target.URL.Host) if err != nil { return nil, err } d.wg.Add(1) go d.watcher() return d, nil } // Scheme returns the naming scheme of this resolver builder, which is "dns". func (b *dnsBuilder) Scheme() string { return "dns" } // deadResolver is a resolver that does nothing. type deadResolver struct{} func (deadResolver) ResolveNow(resolver.ResolveNowOptions) {} func (deadResolver) Close() {} // dnsResolver watches for the name resolution update for a non-IP target. type dnsResolver struct { host string port string resolver internal.NetResolver ctx context.Context cancel context.CancelFunc cc resolver.ClientConn // rn channel is used by ResolveNow() to force an immediate resolution of the // target. rn chan struct{} // wg is used to enforce Close() to return after the watcher() goroutine has // finished. Otherwise, data race will be possible. [Race Example] in // dns_resolver_test we replace the real lookup functions with mocked ones to // facilitate testing. If Close() doesn't wait for watcher() goroutine // finishes, race detector sometimes will warn lookup (READ the lookup // function pointers) inside watcher() goroutine has data race with // replaceNetFunc (WRITE the lookup function pointers). wg sync.WaitGroup disableServiceConfig bool } // ResolveNow invoke an immediate resolution of the target that this // dnsResolver watches. func (d *dnsResolver) ResolveNow(resolver.ResolveNowOptions) { select { case d.rn <- struct{}{}: default: } } // Close closes the dnsResolver. func (d *dnsResolver) Close() { d.cancel() d.wg.Wait() } func (d *dnsResolver) watcher() { defer d.wg.Done() backoffIndex := 1 for { state, err := d.lookup() if err != nil { // Report error to the underlying grpc.ClientConn. d.cc.ReportError(err) } else { err = d.cc.UpdateState(*state) } var nextResolutionTime time.Time if err == nil { // Success resolving, wait for the next ResolveNow. However, also wait 30 // seconds at the very least to prevent constantly re-resolving. backoffIndex = 1 nextResolutionTime = internal.TimeNowFunc().Add(MinResolutionInterval) select { case <-d.ctx.Done(): return case <-d.rn: } } else { // Poll on an error found in DNS Resolver or an error received from // ClientConn. nextResolutionTime = internal.TimeNowFunc().Add(backoff.DefaultExponential.Backoff(backoffIndex)) backoffIndex++ } select { case <-d.ctx.Done(): return case <-internal.TimeAfterFunc(internal.TimeUntilFunc(nextResolutionTime)): } } } func (d *dnsResolver) lookupSRV(ctx context.Context) ([]resolver.Address, error) { // Skip this particular host to avoid timeouts with some versions of // systemd-resolved. if !EnableSRVLookups || d.host == "metadata.google.internal." { return nil, nil } var newAddrs []resolver.Address _, srvs, err := d.resolver.LookupSRV(ctx, "grpclb", "tcp", d.host) if err != nil { err = handleDNSError(err, "SRV") // may become nil return nil, err } for _, s := range srvs { lbAddrs, err := d.resolver.LookupHost(ctx, s.Target) if err != nil { err = handleDNSError(err, "A") // may become nil if err == nil { // If there are other SRV records, look them up and ignore this // one that does not exist. continue } return nil, err } for _, a := range lbAddrs { ip, err := formatIP(a) if err != nil { return nil, fmt.Errorf("dns: error parsing A record IP address %v: %v", a, err) } addr := ip + ":" + strconv.Itoa(int(s.Port)) newAddrs = append(newAddrs, resolver.Address{Addr: addr, ServerName: s.Target}) } } return newAddrs, nil } func handleDNSError(err error, lookupType string) error { dnsErr, ok := err.(*net.DNSError) if ok && !dnsErr.IsTimeout && !dnsErr.IsTemporary { // Timeouts and temporary errors should be communicated to gRPC to // attempt another DNS query (with backoff). Other errors should be // suppressed (they may represent the absence of a TXT record). return nil } if err != nil { err = fmt.Errorf("dns: %v record lookup error: %v", lookupType, err) logger.Info(err) } return err } func (d *dnsResolver) lookupTXT(ctx context.Context) *serviceconfig.ParseResult { ss, err := d.resolver.LookupTXT(ctx, txtPrefix+d.host) if err != nil { if envconfig.TXTErrIgnore { return nil } if err = handleDNSError(err, "TXT"); err != nil { return &serviceconfig.ParseResult{Err: err} } return nil } var res string for _, s := range ss { res += s } // TXT record must have "grpc_config=" attribute in order to be used as // service config. if !strings.HasPrefix(res, txtAttribute) { logger.Warningf("dns: TXT record %v missing %v attribute", res, txtAttribute) // This is not an error; it is the equivalent of not having a service // config. return nil } sc := canaryingSC(strings.TrimPrefix(res, txtAttribute)) return d.cc.ParseServiceConfig(sc) } func (d *dnsResolver) lookupHost(ctx context.Context) ([]resolver.Address, error) { addrs, err := d.resolver.LookupHost(ctx, d.host) if err != nil { err = handleDNSError(err, "A") return nil, err } newAddrs := make([]resolver.Address, 0, len(addrs)) for _, a := range addrs { ip, err := formatIP(a) if err != nil { return nil, fmt.Errorf("dns: error parsing A record IP address %v: %v", a, err) } addr := ip + ":" + d.port newAddrs = append(newAddrs, resolver.Address{Addr: addr}) } return newAddrs, nil } func (d *dnsResolver) lookup() (*resolver.State, error) { ctx, cancel := context.WithTimeout(d.ctx, ResolvingTimeout) defer cancel() srv, srvErr := d.lookupSRV(ctx) addrs, hostErr := d.lookupHost(ctx) if hostErr != nil && (srvErr != nil || len(srv) == 0) { return nil, hostErr } state := resolver.State{Addresses: addrs} if len(srv) > 0 { state = grpclbstate.Set(state, &grpclbstate.State{BalancerAddresses: srv}) } if !d.disableServiceConfig { state.ServiceConfig = d.lookupTXT(ctx) } return &state, nil } // formatIP returns an error if addr is not a valid textual representation of // an IP address. If addr is an IPv4 address, return the addr and error = nil. // If addr is an IPv6 address, return the addr enclosed in square brackets and // error = nil. func formatIP(addr string) (string, error) { ip, err := netip.ParseAddr(addr) if err != nil { return "", err } if ip.Is4() { return addr, nil } return "[" + addr + "]", nil } // parseTarget takes the user input target string and default port, returns // formatted host and port info. If target doesn't specify a port, set the port // to be the defaultPort. If target is in IPv6 format and host-name is enclosed // in square brackets, brackets are stripped when setting the host. // examples: // target: "www.google.com" defaultPort: "443" returns host: "www.google.com", port: "443" // target: "ipv4-host:80" defaultPort: "443" returns host: "ipv4-host", port: "80" // target: "[ipv6-host]" defaultPort: "443" returns host: "ipv6-host", port: "443" // target: ":80" defaultPort: "443" returns host: "localhost", port: "80" func parseTarget(target, defaultPort string) (host, port string, err error) { if target == "" { return "", "", internal.ErrMissingAddr } if _, err := netip.ParseAddr(target); err == nil { // target is an IPv4 or IPv6(without brackets) address return target, defaultPort, nil } if host, port, err = net.SplitHostPort(target); err == nil { if port == "" { // If the port field is empty (target ends with colon), e.g. "[::1]:", // this is an error. return "", "", internal.ErrEndsWithColon } // target has port, i.e ipv4-host:port, [ipv6-host]:port, host-name:port if host == "" { // Keep consistent with net.Dial(): If the host is empty, as in ":80", // the local system is assumed. host = "localhost" } return host, port, nil } if host, port, err = net.SplitHostPort(target + ":" + defaultPort); err == nil { // target doesn't have port return host, port, nil } return "", "", fmt.Errorf("invalid target address %v, error info: %v", target, err) } type rawChoice struct { ClientLanguage *[]string `json:"clientLanguage,omitempty"` Percentage *int `json:"percentage,omitempty"` ClientHostName *[]string `json:"clientHostName,omitempty"` ServiceConfig *json.RawMessage `json:"serviceConfig,omitempty"` } func containsString(a *[]string, b string) bool { if a == nil { return true } for _, c := range *a { if c == b { return true } } return false } func chosenByPercentage(a *int) bool { if a == nil { return true } return rand.IntN(100)+1 <= *a } func canaryingSC(js string) string { if js == "" { return "" } var rcs []rawChoice err := json.Unmarshal([]byte(js), &rcs) if err != nil { logger.Warningf("dns: error parsing service config json: %v", err) return "" } cliHostname, err := os.Hostname() if err != nil { logger.Warningf("dns: error getting client hostname: %v", err) return "" } var sc string for _, c := range rcs { if !containsString(c.ClientLanguage, golang) || !chosenByPercentage(c.Percentage) || !containsString(c.ClientHostName, cliHostname) || c.ServiceConfig == nil { continue } sc = string(*c.ServiceConfig) break } return sc }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/resolver/dns/internal/internal.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/resolver/dns/internal/internal.go
/* * * Copyright 2023 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. * */ // Package internal contains functionality internal to the dns resolver package. package internal import ( "context" "errors" "net" "time" ) // NetResolver groups the methods on net.Resolver that are used by the DNS // resolver implementation. This allows the default net.Resolver instance to be // overridden from tests. type NetResolver interface { LookupHost(ctx context.Context, host string) (addrs []string, err error) LookupSRV(ctx context.Context, service, proto, name string) (cname string, addrs []*net.SRV, err error) LookupTXT(ctx context.Context, name string) (txts []string, err error) } var ( // ErrMissingAddr is the error returned when building a DNS resolver when // the provided target name is empty. ErrMissingAddr = errors.New("dns resolver: missing address") // ErrEndsWithColon is the error returned when building a DNS resolver when // the provided target name ends with a colon that is supposed to be the // separator between host and port. E.g. "::" is a valid address as it is // an IPv6 address (host only) and "[::]:" is invalid as it ends with a // colon as the host and port separator ErrEndsWithColon = errors.New("dns resolver: missing port after port-separator colon") ) // The following vars are overridden from tests. var ( // TimeAfterFunc is used by the DNS resolver to wait for the given duration // to elapse. In non-test code, this is implemented by time.After. In test // code, this can be used to control the amount of time the resolver is // blocked waiting for the duration to elapse. TimeAfterFunc func(time.Duration) <-chan time.Time // TimeNowFunc is used by the DNS resolver to get the current time. // In non-test code, this is implemented by time.Now. In test code, // this can be used to control the current time for the resolver. TimeNowFunc func() time.Time // TimeUntilFunc is used by the DNS resolver to calculate the remaining // wait time for re-resolution. In non-test code, this is implemented by // time.Until. In test code, this can be used to control the remaining // time for resolver to wait for re-resolution. TimeUntilFunc func(time.Time) time.Duration // NewNetResolver returns the net.Resolver instance for the given target. NewNetResolver func(string) (NetResolver, error) // AddressDialer is the dialer used to dial the DNS server. It accepts the // Host portion of the URL corresponding to the user's dial target and // returns a dial function. AddressDialer func(address string) func(context.Context, string, string) (net.Conn, error) )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/resolver/delegatingresolver/delegatingresolver.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/resolver/delegatingresolver/delegatingresolver.go
/* * * Copyright 2024 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. * */ // Package delegatingresolver implements a resolver capable of resolving both // target URIs and proxy addresses. package delegatingresolver import ( "fmt" "net/http" "net/url" "sync" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/internal/proxyattributes" "google.golang.org/grpc/resolver" "google.golang.org/grpc/serviceconfig" ) var ( logger = grpclog.Component("delegating-resolver") // HTTPSProxyFromEnvironment will be overwritten in the tests HTTPSProxyFromEnvironment = http.ProxyFromEnvironment ) // delegatingResolver manages both target URI and proxy address resolution by // delegating these tasks to separate child resolvers. Essentially, it acts as // a intermediary between the gRPC ClientConn and the child resolvers. // // It implements the [resolver.Resolver] interface. type delegatingResolver struct { target resolver.Target // parsed target URI to be resolved cc resolver.ClientConn // gRPC ClientConn targetResolver resolver.Resolver // resolver for the target URI, based on its scheme proxyResolver resolver.Resolver // resolver for the proxy URI; nil if no proxy is configured proxyURL *url.URL // proxy URL, derived from proxy environment and target mu sync.Mutex // protects all the fields below targetResolverState *resolver.State // state of the target resolver proxyAddrs []resolver.Address // resolved proxy addresses; empty if no proxy is configured } // nopResolver is a resolver that does nothing. type nopResolver struct{} func (nopResolver) ResolveNow(resolver.ResolveNowOptions) {} func (nopResolver) Close() {} // proxyURLForTarget determines the proxy URL for the given address based on // the environment. It can return the following: // - nil URL, nil error: No proxy is configured or the address is excluded // using the `NO_PROXY` environment variable or if req.URL.Host is // "localhost" (with or without // a port number) // - nil URL, non-nil error: An error occurred while retrieving the proxy URL. // - non-nil URL, nil error: A proxy is configured, and the proxy URL was // retrieved successfully without any errors. func proxyURLForTarget(address string) (*url.URL, error) { req := &http.Request{URL: &url.URL{ Scheme: "https", Host: address, }} return HTTPSProxyFromEnvironment(req) } // New creates a new delegating resolver that can create up to two child // resolvers: // - one to resolve the proxy address specified using the supported // environment variables. This uses the registered resolver for the "dns" // scheme. // - one to resolve the target URI using the resolver specified by the scheme // in the target URI or specified by the user using the WithResolvers dial // option. As a special case, if the target URI's scheme is "dns" and a // proxy is specified using the supported environment variables, the target // URI's path portion is used as the resolved address unless target // resolution is enabled using the dial option. func New(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOptions, targetResolverBuilder resolver.Builder, targetResolutionEnabled bool) (resolver.Resolver, error) { r := &delegatingResolver{ target: target, cc: cc, } var err error r.proxyURL, err = proxyURLForTarget(target.Endpoint()) if err != nil { return nil, fmt.Errorf("delegating_resolver: failed to determine proxy URL for target %s: %v", target, err) } // proxy is not configured or proxy address excluded using `NO_PROXY` env // var, so only target resolver is used. if r.proxyURL == nil { return targetResolverBuilder.Build(target, cc, opts) } if logger.V(2) { logger.Infof("Proxy URL detected : %s", r.proxyURL) } // When the scheme is 'dns' and target resolution on client is not enabled, // resolution should be handled by the proxy, not the client. Therefore, we // bypass the target resolver and store the unresolved target address. if target.URL.Scheme == "dns" && !targetResolutionEnabled { state := resolver.State{ Addresses: []resolver.Address{{Addr: target.Endpoint()}}, Endpoints: []resolver.Endpoint{{Addresses: []resolver.Address{{Addr: target.Endpoint()}}}}, } r.targetResolverState = &state } else { wcc := &wrappingClientConn{ stateListener: r.updateTargetResolverState, parent: r, } if r.targetResolver, err = targetResolverBuilder.Build(target, wcc, opts); err != nil { return nil, fmt.Errorf("delegating_resolver: unable to build the resolver for target %s: %v", target, err) } } if r.proxyResolver, err = r.proxyURIResolver(opts); err != nil { return nil, fmt.Errorf("delegating_resolver: failed to build resolver for proxy URL %q: %v", r.proxyURL, err) } if r.targetResolver == nil { r.targetResolver = nopResolver{} } if r.proxyResolver == nil { r.proxyResolver = nopResolver{} } return r, nil } // proxyURIResolver creates a resolver for resolving proxy URIs using the // "dns" scheme. It adjusts the proxyURL to conform to the "dns:///" format and // builds a resolver with a wrappingClientConn to capture resolved addresses. func (r *delegatingResolver) proxyURIResolver(opts resolver.BuildOptions) (resolver.Resolver, error) { proxyBuilder := resolver.Get("dns") if proxyBuilder == nil { panic("delegating_resolver: resolver for proxy not found for scheme dns") } url := *r.proxyURL url.Scheme = "dns" url.Path = "/" + r.proxyURL.Host url.Host = "" // Clear the Host field to conform to the "dns:///" format proxyTarget := resolver.Target{URL: url} wcc := &wrappingClientConn{ stateListener: r.updateProxyResolverState, parent: r, } return proxyBuilder.Build(proxyTarget, wcc, opts) } func (r *delegatingResolver) ResolveNow(o resolver.ResolveNowOptions) { r.targetResolver.ResolveNow(o) r.proxyResolver.ResolveNow(o) } func (r *delegatingResolver) Close() { r.targetResolver.Close() r.targetResolver = nil r.proxyResolver.Close() r.proxyResolver = nil } // updateClientConnStateLocked creates a list of combined addresses by // pairing each proxy address with every target address. For each pair, it // generates a new [resolver.Address] using the proxy address, and adding the // target address as the attribute along with user info. It returns nil if // either resolver has not sent update even once and returns the error from // ClientConn update once both resolvers have sent update atleast once. func (r *delegatingResolver) updateClientConnStateLocked() error { if r.targetResolverState == nil || r.proxyAddrs == nil { return nil } curState := *r.targetResolverState // If multiple resolved proxy addresses are present, we send only the // unresolved proxy host and let net.Dial handle the proxy host name // resolution when creating the transport. Sending all resolved addresses // would increase the number of addresses passed to the ClientConn and // subsequently to load balancing (LB) policies like Round Robin, leading // to additional TCP connections. However, if there's only one resolved // proxy address, we send it directly, as it doesn't affect the address // count returned by the target resolver and the address count sent to the // ClientConn. var proxyAddr resolver.Address if len(r.proxyAddrs) == 1 { proxyAddr = r.proxyAddrs[0] } else { proxyAddr = resolver.Address{Addr: r.proxyURL.Host} } var addresses []resolver.Address for _, targetAddr := range (*r.targetResolverState).Addresses { addresses = append(addresses, proxyattributes.Set(proxyAddr, proxyattributes.Options{ User: r.proxyURL.User, ConnectAddr: targetAddr.Addr, })) } // Create a list of combined endpoints by pairing all proxy endpoints // with every target endpoint. Each time, it constructs a new // [resolver.Endpoint] using the all addresses from all the proxy endpoint // and the target addresses from one endpoint. The target address and user // information from the proxy URL are added as attributes to the proxy // address.The resulting list of addresses is then grouped into endpoints, // covering all combinations of proxy and target endpoints. var endpoints []resolver.Endpoint for _, endpt := range (*r.targetResolverState).Endpoints { var addrs []resolver.Address for _, proxyAddr := range r.proxyAddrs { for _, targetAddr := range endpt.Addresses { addrs = append(addrs, proxyattributes.Set(proxyAddr, proxyattributes.Options{ User: r.proxyURL.User, ConnectAddr: targetAddr.Addr, })) } } endpoints = append(endpoints, resolver.Endpoint{Addresses: addrs}) } // Use the targetResolverState for its service config and attributes // contents. The state update is only sent after both the target and proxy // resolvers have sent their updates, and curState has been updated with // the combined addresses. curState.Addresses = addresses curState.Endpoints = endpoints return r.cc.UpdateState(curState) } // updateProxyResolverState updates the proxy resolver state by storing proxy // addresses and endpoints, marking the resolver as ready, and triggering a // state update if both proxy and target resolvers are ready. If the ClientConn // returns a non-nil error, it calls `ResolveNow()` on the target resolver. It // is a StateListener function of wrappingClientConn passed to the proxy resolver. func (r *delegatingResolver) updateProxyResolverState(state resolver.State) error { r.mu.Lock() defer r.mu.Unlock() if logger.V(2) { logger.Infof("Addresses received from proxy resolver: %s", state.Addresses) } if len(state.Endpoints) > 0 { // We expect exactly one address per endpoint because the proxy // resolver uses "dns" resolution. r.proxyAddrs = make([]resolver.Address, 0, len(state.Endpoints)) for _, endpoint := range state.Endpoints { r.proxyAddrs = append(r.proxyAddrs, endpoint.Addresses...) } } else if state.Addresses != nil { r.proxyAddrs = state.Addresses } else { r.proxyAddrs = []resolver.Address{} // ensure proxyAddrs is non-nil to indicate an update has been received } err := r.updateClientConnStateLocked() // Another possible approach was to block until updates are received from // both resolvers. But this is not used because calling `New()` triggers // `Build()` for the first resolver, which calls `UpdateState()`. And the // second resolver hasn't sent an update yet, so it would cause `New()` to // block indefinitely. if err != nil { r.targetResolver.ResolveNow(resolver.ResolveNowOptions{}) } return err } // updateTargetResolverState updates the target resolver state by storing target // addresses, endpoints, and service config, marking the resolver as ready, and // triggering a state update if both resolvers are ready. If the ClientConn // returns a non-nil error, it calls `ResolveNow()` on the proxy resolver. It // is a StateListener function of wrappingClientConn passed to the target resolver. func (r *delegatingResolver) updateTargetResolverState(state resolver.State) error { r.mu.Lock() defer r.mu.Unlock() if logger.V(2) { logger.Infof("Addresses received from target resolver: %v", state.Addresses) } r.targetResolverState = &state err := r.updateClientConnStateLocked() if err != nil { r.proxyResolver.ResolveNow(resolver.ResolveNowOptions{}) } return nil } // wrappingClientConn serves as an intermediary between the parent ClientConn // and the child resolvers created here. It implements the resolver.ClientConn // interface and is passed in that capacity to the child resolvers. type wrappingClientConn struct { // Callback to deliver resolver state updates stateListener func(state resolver.State) error parent *delegatingResolver } // UpdateState receives resolver state updates and forwards them to the // appropriate listener function (either for the proxy or target resolver). func (wcc *wrappingClientConn) UpdateState(state resolver.State) error { return wcc.stateListener(state) } // ReportError intercepts errors from the child resolvers and passes them to ClientConn. func (wcc *wrappingClientConn) ReportError(err error) { wcc.parent.cc.ReportError(err) } // NewAddress intercepts the new resolved address from the child resolvers and // passes them to ClientConn. func (wcc *wrappingClientConn) NewAddress(addrs []resolver.Address) { wcc.UpdateState(resolver.State{Addresses: addrs}) } // ParseServiceConfig parses the provided service config and returns an // object that provides the parsed config. func (wcc *wrappingClientConn) ParseServiceConfig(serviceConfigJSON string) *serviceconfig.ParseResult { return wcc.parent.cc.ParseServiceConfig(serviceConfigJSON) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/credentials/spiffe.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/credentials/spiffe.go
/* * * Copyright 2020 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. * */ // Package credentials defines APIs for parsing SPIFFE ID. // // All APIs in this package are experimental. package credentials import ( "crypto/tls" "crypto/x509" "net/url" "google.golang.org/grpc/grpclog" ) var logger = grpclog.Component("credentials") // SPIFFEIDFromState parses the SPIFFE ID from State. If the SPIFFE ID format // is invalid, return nil with warning. func SPIFFEIDFromState(state tls.ConnectionState) *url.URL { if len(state.PeerCertificates) == 0 || len(state.PeerCertificates[0].URIs) == 0 { return nil } return SPIFFEIDFromCert(state.PeerCertificates[0]) } // SPIFFEIDFromCert parses the SPIFFE ID from x509.Certificate. If the SPIFFE // ID format is invalid, return nil with warning. func SPIFFEIDFromCert(cert *x509.Certificate) *url.URL { if cert == nil || cert.URIs == nil { return nil } var spiffeID *url.URL for _, uri := range cert.URIs { if uri == nil || uri.Scheme != "spiffe" || uri.Opaque != "" || (uri.User != nil && uri.User.Username() != "") { continue } // From this point, we assume the uri is intended for a SPIFFE ID. if len(uri.String()) > 2048 { logger.Warning("invalid SPIFFE ID: total ID length larger than 2048 bytes") return nil } if len(uri.Host) == 0 || len(uri.Path) == 0 { logger.Warning("invalid SPIFFE ID: domain or workload ID is empty") return nil } if len(uri.Host) > 255 { logger.Warning("invalid SPIFFE ID: domain length larger than 255 characters") return nil } // A valid SPIFFE certificate can only have exactly one URI SAN field. if len(cert.URIs) > 1 { logger.Warning("invalid SPIFFE ID: multiple URI SANs") return nil } spiffeID = uri } return spiffeID }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/credentials/syscallconn.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/credentials/syscallconn.go
/* * * Copyright 2018 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. * */ package credentials import ( "net" "syscall" ) type sysConn = syscall.Conn // syscallConn keeps reference of rawConn to support syscall.Conn for channelz. // SyscallConn() (the method in interface syscall.Conn) is explicitly // implemented on this type, // // Interface syscall.Conn is implemented by most net.Conn implementations (e.g. // TCPConn, UnixConn), but is not part of net.Conn interface. So wrapper conns // that embed net.Conn don't implement syscall.Conn. (Side note: tls.Conn // doesn't embed net.Conn, so even if syscall.Conn is part of net.Conn, it won't // help here). type syscallConn struct { net.Conn // sysConn is a type alias of syscall.Conn. It's necessary because the name // `Conn` collides with `net.Conn`. sysConn } // WrapSyscallConn tries to wrap rawConn and newConn into a net.Conn that // implements syscall.Conn. rawConn will be used to support syscall, and newConn // will be used for read/write. // // This function returns newConn if rawConn doesn't implement syscall.Conn. func WrapSyscallConn(rawConn, newConn net.Conn) net.Conn { sysConn, ok := rawConn.(syscall.Conn) if !ok { return newConn } return &syscallConn{ Conn: newConn, sysConn: sysConn, } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/credentials/credentials.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/credentials/credentials.go
/* * Copyright 2021 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. */ package credentials import ( "context" ) // requestInfoKey is a struct to be used as the key to store RequestInfo in a // context. type requestInfoKey struct{} // NewRequestInfoContext creates a context with ri. func NewRequestInfoContext(ctx context.Context, ri any) context.Context { return context.WithValue(ctx, requestInfoKey{}, ri) } // RequestInfoFromContext extracts the RequestInfo from ctx. func RequestInfoFromContext(ctx context.Context) any { return ctx.Value(requestInfoKey{}) } // clientHandshakeInfoKey is a struct used as the key to store // ClientHandshakeInfo in a context. type clientHandshakeInfoKey struct{} // ClientHandshakeInfoFromContext extracts the ClientHandshakeInfo from ctx. func ClientHandshakeInfoFromContext(ctx context.Context) any { return ctx.Value(clientHandshakeInfoKey{}) } // NewClientHandshakeInfoContext creates a context with chi. func NewClientHandshakeInfoContext(ctx context.Context, chi any) context.Context { return context.WithValue(ctx, clientHandshakeInfoKey{}, chi) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/credentials/util.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/credentials/util.go
/* * * Copyright 2020 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. * */ package credentials import ( "crypto/tls" ) const alpnProtoStrH2 = "h2" // AppendH2ToNextProtos appends h2 to next protos. func AppendH2ToNextProtos(ps []string) []string { for _, p := range ps { if p == alpnProtoStrH2 { return ps } } ret := make([]string, 0, len(ps)+1) ret = append(ret, ps...) return append(ret, alpnProtoStrH2) } // CloneTLSConfig returns a shallow clone of the exported // fields of cfg, ignoring the unexported sync.Once, which // contains a mutex and must not be copied. // // If cfg is nil, a new zero tls.Config is returned. // // TODO: inline this function if possible. func CloneTLSConfig(cfg *tls.Config) *tls.Config { if cfg == nil { return &tls.Config{} } return cfg.Clone() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/transport/flowcontrol.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/transport/flowcontrol.go
/* * * Copyright 2014 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. * */ package transport import ( "fmt" "math" "sync" "sync/atomic" ) // writeQuota is a soft limit on the amount of data a stream can // schedule before some of it is written out. type writeQuota struct { quota int32 // get waits on read from when quota goes less than or equal to zero. // replenish writes on it when quota goes positive again. ch chan struct{} // done is triggered in error case. done <-chan struct{} // replenish is called by loopyWriter to give quota back to. // It is implemented as a field so that it can be updated // by tests. replenish func(n int) } func newWriteQuota(sz int32, done <-chan struct{}) *writeQuota { w := &writeQuota{ quota: sz, ch: make(chan struct{}, 1), done: done, } w.replenish = w.realReplenish return w } func (w *writeQuota) get(sz int32) error { for { if atomic.LoadInt32(&w.quota) > 0 { atomic.AddInt32(&w.quota, -sz) return nil } select { case <-w.ch: continue case <-w.done: return errStreamDone } } } func (w *writeQuota) realReplenish(n int) { sz := int32(n) a := atomic.AddInt32(&w.quota, sz) b := a - sz if b <= 0 && a > 0 { select { case w.ch <- struct{}{}: default: } } } type trInFlow struct { limit uint32 unacked uint32 effectiveWindowSize uint32 } func (f *trInFlow) newLimit(n uint32) uint32 { d := n - f.limit f.limit = n f.updateEffectiveWindowSize() return d } func (f *trInFlow) onData(n uint32) uint32 { f.unacked += n if f.unacked < f.limit/4 { f.updateEffectiveWindowSize() return 0 } return f.reset() } func (f *trInFlow) reset() uint32 { w := f.unacked f.unacked = 0 f.updateEffectiveWindowSize() return w } func (f *trInFlow) updateEffectiveWindowSize() { atomic.StoreUint32(&f.effectiveWindowSize, f.limit-f.unacked) } func (f *trInFlow) getSize() uint32 { return atomic.LoadUint32(&f.effectiveWindowSize) } // TODO(mmukhi): Simplify this code. // inFlow deals with inbound flow control type inFlow struct { mu sync.Mutex // The inbound flow control limit for pending data. limit uint32 // pendingData is the overall data which have been received but not been // consumed by applications. pendingData uint32 // The amount of data the application has consumed but grpc has not sent // window update for them. Used to reduce window update frequency. pendingUpdate uint32 // delta is the extra window update given by receiver when an application // is reading data bigger in size than the inFlow limit. delta uint32 } // newLimit updates the inflow window to a new value n. // It assumes that n is always greater than the old limit. func (f *inFlow) newLimit(n uint32) { f.mu.Lock() f.limit = n f.mu.Unlock() } func (f *inFlow) maybeAdjust(n uint32) uint32 { if n > uint32(math.MaxInt32) { n = uint32(math.MaxInt32) } f.mu.Lock() defer f.mu.Unlock() // estSenderQuota is the receiver's view of the maximum number of bytes the sender // can send without a window update. estSenderQuota := int32(f.limit - (f.pendingData + f.pendingUpdate)) // estUntransmittedData is the maximum number of bytes the sends might not have put // on the wire yet. A value of 0 or less means that we have already received all or // more bytes than the application is requesting to read. estUntransmittedData := int32(n - f.pendingData) // Casting into int32 since it could be negative. // This implies that unless we send a window update, the sender won't be able to send all the bytes // for this message. Therefore we must send an update over the limit since there's an active read // request from the application. if estUntransmittedData > estSenderQuota { // Sender's window shouldn't go more than 2^31 - 1 as specified in the HTTP spec. if f.limit+n > maxWindowSize { f.delta = maxWindowSize - f.limit } else { // Send a window update for the whole message and not just the difference between // estUntransmittedData and estSenderQuota. This will be helpful in case the message // is padded; We will fallback on the current available window(at least a 1/4th of the limit). f.delta = n } return f.delta } return 0 } // onData is invoked when some data frame is received. It updates pendingData. func (f *inFlow) onData(n uint32) error { f.mu.Lock() f.pendingData += n if f.pendingData+f.pendingUpdate > f.limit+f.delta { limit := f.limit rcvd := f.pendingData + f.pendingUpdate f.mu.Unlock() return fmt.Errorf("received %d-bytes data exceeding the limit %d bytes", rcvd, limit) } f.mu.Unlock() return nil } // onRead is invoked when the application reads the data. It returns the window size // to be sent to the peer. func (f *inFlow) onRead(n uint32) uint32 { f.mu.Lock() if f.pendingData == 0 { f.mu.Unlock() return 0 } f.pendingData -= n if n > f.delta { n -= f.delta f.delta = 0 } else { f.delta -= n n = 0 } f.pendingUpdate += n if f.pendingUpdate >= f.limit/4 { wu := f.pendingUpdate f.pendingUpdate = 0 f.mu.Unlock() return wu } f.mu.Unlock() return 0 }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/transport/logging.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/transport/logging.go
/* * * Copyright 2023 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. * */ package transport import ( "fmt" "google.golang.org/grpc/grpclog" internalgrpclog "google.golang.org/grpc/internal/grpclog" ) var logger = grpclog.Component("transport") func prefixLoggerForServerTransport(p *http2Server) *internalgrpclog.PrefixLogger { return internalgrpclog.NewPrefixLogger(logger, fmt.Sprintf("[server-transport %p] ", p)) } func prefixLoggerForServerHandlerTransport(p *serverHandlerTransport) *internalgrpclog.PrefixLogger { return internalgrpclog.NewPrefixLogger(logger, fmt.Sprintf("[server-handler-transport %p] ", p)) } func prefixLoggerForClientTransport(p *http2Client) *internalgrpclog.PrefixLogger { return internalgrpclog.NewPrefixLogger(logger, fmt.Sprintf("[client-transport %p] ", p)) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/transport/proxy.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/transport/proxy.go
/* * * Copyright 2017 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. * */ package transport import ( "bufio" "context" "encoding/base64" "fmt" "io" "net" "net/http" "net/http/httputil" "net/url" "google.golang.org/grpc/internal" "google.golang.org/grpc/internal/proxyattributes" "google.golang.org/grpc/resolver" ) const proxyAuthHeaderKey = "Proxy-Authorization" // To read a response from a net.Conn, http.ReadResponse() takes a bufio.Reader. // It's possible that this reader reads more than what's need for the response // and stores those bytes in the buffer. bufConn wraps the original net.Conn // and the bufio.Reader to make sure we don't lose the bytes in the buffer. type bufConn struct { net.Conn r io.Reader } func (c *bufConn) Read(b []byte) (int, error) { return c.r.Read(b) } func basicAuth(username, password string) string { auth := username + ":" + password return base64.StdEncoding.EncodeToString([]byte(auth)) } func doHTTPConnectHandshake(ctx context.Context, conn net.Conn, grpcUA string, opts proxyattributes.Options) (_ net.Conn, err error) { defer func() { if err != nil { conn.Close() } }() req := &http.Request{ Method: http.MethodConnect, URL: &url.URL{Host: opts.ConnectAddr}, Header: map[string][]string{"User-Agent": {grpcUA}}, } if user := opts.User; user != nil { u := user.Username() p, _ := user.Password() req.Header.Add(proxyAuthHeaderKey, "Basic "+basicAuth(u, p)) } if err := sendHTTPRequest(ctx, req, conn); err != nil { return nil, fmt.Errorf("failed to write the HTTP request: %v", err) } r := bufio.NewReader(conn) resp, err := http.ReadResponse(r, req) if err != nil { return nil, fmt.Errorf("reading server HTTP response: %v", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { dump, err := httputil.DumpResponse(resp, true) if err != nil { return nil, fmt.Errorf("failed to do connect handshake, status code: %s", resp.Status) } return nil, fmt.Errorf("failed to do connect handshake, response: %q", dump) } // The buffer could contain extra bytes from the target server, so we can't // discard it. However, in many cases where the server waits for the client // to send the first message (e.g. when TLS is being used), the buffer will // be empty, so we can avoid the overhead of reading through this buffer. if r.Buffered() != 0 { return &bufConn{Conn: conn, r: r}, nil } return conn, nil } // proxyDial establishes a TCP connection to the specified address and performs an HTTP CONNECT handshake. func proxyDial(ctx context.Context, addr resolver.Address, grpcUA string, opts proxyattributes.Options) (net.Conn, error) { conn, err := internal.NetDialerWithTCPKeepalive().DialContext(ctx, "tcp", addr.Addr) if err != nil { return nil, err } return doHTTPConnectHandshake(ctx, conn, grpcUA, opts) } func sendHTTPRequest(ctx context.Context, req *http.Request, conn net.Conn) error { req = req.WithContext(ctx) if err := req.Write(conn); err != nil { return fmt.Errorf("failed to write the HTTP request: %v", err) } return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/transport/http_util.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/transport/http_util.go
/* * * Copyright 2014 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. * */ package transport import ( "bufio" "encoding/base64" "errors" "fmt" "io" "math" "net" "net/http" "net/url" "strconv" "strings" "sync" "time" "unicode/utf8" "golang.org/x/net/http2" "golang.org/x/net/http2/hpack" "google.golang.org/grpc/codes" ) const ( // http2MaxFrameLen specifies the max length of a HTTP2 frame. http2MaxFrameLen = 16384 // 16KB frame // https://httpwg.org/specs/rfc7540.html#SettingValues http2InitHeaderTableSize = 4096 ) var ( clientPreface = []byte(http2.ClientPreface) http2ErrConvTab = map[http2.ErrCode]codes.Code{ http2.ErrCodeNo: codes.Internal, http2.ErrCodeProtocol: codes.Internal, http2.ErrCodeInternal: codes.Internal, http2.ErrCodeFlowControl: codes.ResourceExhausted, http2.ErrCodeSettingsTimeout: codes.Internal, http2.ErrCodeStreamClosed: codes.Internal, http2.ErrCodeFrameSize: codes.Internal, http2.ErrCodeRefusedStream: codes.Unavailable, http2.ErrCodeCancel: codes.Canceled, http2.ErrCodeCompression: codes.Internal, http2.ErrCodeConnect: codes.Internal, http2.ErrCodeEnhanceYourCalm: codes.ResourceExhausted, http2.ErrCodeInadequateSecurity: codes.PermissionDenied, http2.ErrCodeHTTP11Required: codes.Internal, } // HTTPStatusConvTab is the HTTP status code to gRPC error code conversion table. HTTPStatusConvTab = map[int]codes.Code{ // 400 Bad Request - INTERNAL. http.StatusBadRequest: codes.Internal, // 401 Unauthorized - UNAUTHENTICATED. http.StatusUnauthorized: codes.Unauthenticated, // 403 Forbidden - PERMISSION_DENIED. http.StatusForbidden: codes.PermissionDenied, // 404 Not Found - UNIMPLEMENTED. http.StatusNotFound: codes.Unimplemented, // 429 Too Many Requests - UNAVAILABLE. http.StatusTooManyRequests: codes.Unavailable, // 502 Bad Gateway - UNAVAILABLE. http.StatusBadGateway: codes.Unavailable, // 503 Service Unavailable - UNAVAILABLE. http.StatusServiceUnavailable: codes.Unavailable, // 504 Gateway timeout - UNAVAILABLE. http.StatusGatewayTimeout: codes.Unavailable, } ) var grpcStatusDetailsBinHeader = "grpc-status-details-bin" // isReservedHeader checks whether hdr belongs to HTTP2 headers // reserved by gRPC protocol. Any other headers are classified as the // user-specified metadata. func isReservedHeader(hdr string) bool { if hdr != "" && hdr[0] == ':' { return true } switch hdr { case "content-type", "user-agent", "grpc-message-type", "grpc-encoding", "grpc-message", "grpc-status", "grpc-timeout", // Intentionally exclude grpc-previous-rpc-attempts and // grpc-retry-pushback-ms, which are "reserved", but their API // intentionally works via metadata. "te": return true default: return false } } // isWhitelistedHeader checks whether hdr should be propagated into metadata // visible to users, even though it is classified as "reserved", above. func isWhitelistedHeader(hdr string) bool { switch hdr { case ":authority", "user-agent": return true default: return false } } const binHdrSuffix = "-bin" func encodeBinHeader(v []byte) string { return base64.RawStdEncoding.EncodeToString(v) } func decodeBinHeader(v string) ([]byte, error) { if len(v)%4 == 0 { // Input was padded, or padding was not necessary. return base64.StdEncoding.DecodeString(v) } return base64.RawStdEncoding.DecodeString(v) } func encodeMetadataHeader(k, v string) string { if strings.HasSuffix(k, binHdrSuffix) { return encodeBinHeader(([]byte)(v)) } return v } func decodeMetadataHeader(k, v string) (string, error) { if strings.HasSuffix(k, binHdrSuffix) { b, err := decodeBinHeader(v) return string(b), err } return v, nil } type timeoutUnit uint8 const ( hour timeoutUnit = 'H' minute timeoutUnit = 'M' second timeoutUnit = 'S' millisecond timeoutUnit = 'm' microsecond timeoutUnit = 'u' nanosecond timeoutUnit = 'n' ) func timeoutUnitToDuration(u timeoutUnit) (d time.Duration, ok bool) { switch u { case hour: return time.Hour, true case minute: return time.Minute, true case second: return time.Second, true case millisecond: return time.Millisecond, true case microsecond: return time.Microsecond, true case nanosecond: return time.Nanosecond, true default: } return } func decodeTimeout(s string) (time.Duration, error) { size := len(s) if size < 2 { return 0, fmt.Errorf("transport: timeout string is too short: %q", s) } if size > 9 { // Spec allows for 8 digits plus the unit. return 0, fmt.Errorf("transport: timeout string is too long: %q", s) } unit := timeoutUnit(s[size-1]) d, ok := timeoutUnitToDuration(unit) if !ok { return 0, fmt.Errorf("transport: timeout unit is not recognized: %q", s) } t, err := strconv.ParseInt(s[:size-1], 10, 64) if err != nil { return 0, err } const maxHours = math.MaxInt64 / int64(time.Hour) if d == time.Hour && t > maxHours { // This timeout would overflow math.MaxInt64; clamp it. return time.Duration(math.MaxInt64), nil } return d * time.Duration(t), nil } const ( spaceByte = ' ' tildeByte = '~' percentByte = '%' ) // encodeGrpcMessage is used to encode status code in header field // "grpc-message". It does percent encoding and also replaces invalid utf-8 // characters with Unicode replacement character. // // It checks to see if each individual byte in msg is an allowable byte, and // then either percent encoding or passing it through. When percent encoding, // the byte is converted into hexadecimal notation with a '%' prepended. func encodeGrpcMessage(msg string) string { if msg == "" { return "" } lenMsg := len(msg) for i := 0; i < lenMsg; i++ { c := msg[i] if !(c >= spaceByte && c <= tildeByte && c != percentByte) { return encodeGrpcMessageUnchecked(msg) } } return msg } func encodeGrpcMessageUnchecked(msg string) string { var sb strings.Builder for len(msg) > 0 { r, size := utf8.DecodeRuneInString(msg) for _, b := range []byte(string(r)) { if size > 1 { // If size > 1, r is not ascii. Always do percent encoding. fmt.Fprintf(&sb, "%%%02X", b) continue } // The for loop is necessary even if size == 1. r could be // utf8.RuneError. // // fmt.Sprintf("%%%02X", utf8.RuneError) gives "%FFFD". if b >= spaceByte && b <= tildeByte && b != percentByte { sb.WriteByte(b) } else { fmt.Fprintf(&sb, "%%%02X", b) } } msg = msg[size:] } return sb.String() } // decodeGrpcMessage decodes the msg encoded by encodeGrpcMessage. func decodeGrpcMessage(msg string) string { if msg == "" { return "" } lenMsg := len(msg) for i := 0; i < lenMsg; i++ { if msg[i] == percentByte && i+2 < lenMsg { return decodeGrpcMessageUnchecked(msg) } } return msg } func decodeGrpcMessageUnchecked(msg string) string { var sb strings.Builder lenMsg := len(msg) for i := 0; i < lenMsg; i++ { c := msg[i] if c == percentByte && i+2 < lenMsg { parsed, err := strconv.ParseUint(msg[i+1:i+3], 16, 8) if err != nil { sb.WriteByte(c) } else { sb.WriteByte(byte(parsed)) i += 2 } } else { sb.WriteByte(c) } } return sb.String() } type bufWriter struct { pool *sync.Pool buf []byte offset int batchSize int conn net.Conn err error } func newBufWriter(conn net.Conn, batchSize int, pool *sync.Pool) *bufWriter { w := &bufWriter{ batchSize: batchSize, conn: conn, pool: pool, } // this indicates that we should use non shared buf if pool == nil { w.buf = make([]byte, batchSize) } return w } func (w *bufWriter) Write(b []byte) (int, error) { if w.err != nil { return 0, w.err } if w.batchSize == 0 { // Buffer has been disabled. n, err := w.conn.Write(b) return n, toIOError(err) } if w.buf == nil { b := w.pool.Get().(*[]byte) w.buf = *b } written := 0 for len(b) > 0 { copied := copy(w.buf[w.offset:], b) b = b[copied:] written += copied w.offset += copied if w.offset < w.batchSize { continue } if err := w.flushKeepBuffer(); err != nil { return written, err } } return written, nil } func (w *bufWriter) Flush() error { err := w.flushKeepBuffer() // Only release the buffer if we are in a "shared" mode if w.buf != nil && w.pool != nil { b := w.buf w.pool.Put(&b) w.buf = nil } return err } func (w *bufWriter) flushKeepBuffer() error { if w.err != nil { return w.err } if w.offset == 0 { return nil } _, w.err = w.conn.Write(w.buf[:w.offset]) w.err = toIOError(w.err) w.offset = 0 return w.err } type ioError struct { error } func (i ioError) Unwrap() error { return i.error } func isIOError(err error) bool { return errors.As(err, &ioError{}) } func toIOError(err error) error { if err == nil { return nil } return ioError{error: err} } type framer struct { writer *bufWriter fr *http2.Framer } var writeBufferPoolMap = make(map[int]*sync.Pool) var writeBufferMutex sync.Mutex func newFramer(conn net.Conn, writeBufferSize, readBufferSize int, sharedWriteBuffer bool, maxHeaderListSize uint32) *framer { if writeBufferSize < 0 { writeBufferSize = 0 } var r io.Reader = conn if readBufferSize > 0 { r = bufio.NewReaderSize(r, readBufferSize) } var pool *sync.Pool if sharedWriteBuffer { pool = getWriteBufferPool(writeBufferSize) } w := newBufWriter(conn, writeBufferSize, pool) f := &framer{ writer: w, fr: http2.NewFramer(w, r), } f.fr.SetMaxReadFrameSize(http2MaxFrameLen) // Opt-in to Frame reuse API on framer to reduce garbage. // Frames aren't safe to read from after a subsequent call to ReadFrame. f.fr.SetReuseFrames() f.fr.MaxHeaderListSize = maxHeaderListSize f.fr.ReadMetaHeaders = hpack.NewDecoder(http2InitHeaderTableSize, nil) return f } func getWriteBufferPool(size int) *sync.Pool { writeBufferMutex.Lock() defer writeBufferMutex.Unlock() pool, ok := writeBufferPoolMap[size] if ok { return pool } pool = &sync.Pool{ New: func() any { b := make([]byte, size) return &b }, } writeBufferPoolMap[size] = pool return pool } // parseDialTarget returns the network and address to pass to dialer. func parseDialTarget(target string) (string, string) { net := "tcp" m1 := strings.Index(target, ":") m2 := strings.Index(target, ":/") // handle unix:addr which will fail with url.Parse if m1 >= 0 && m2 < 0 { if n := target[0:m1]; n == "unix" { return n, target[m1+1:] } } if m2 >= 0 { t, err := url.Parse(target) if err != nil { return net, target } scheme := t.Scheme addr := t.Path if scheme == "unix" { if addr == "" { addr = t.Host } return scheme, addr } } return net, target }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/transport/http2_server.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/transport/http2_server.go
/* * * Copyright 2014 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. * */ package transport import ( "bytes" "context" "errors" "fmt" "io" "math" rand "math/rand/v2" "net" "net/http" "strconv" "sync" "sync/atomic" "time" "golang.org/x/net/http2" "golang.org/x/net/http2/hpack" "google.golang.org/grpc/internal/grpclog" "google.golang.org/grpc/internal/grpcutil" "google.golang.org/grpc/internal/pretty" "google.golang.org/grpc/internal/syscall" "google.golang.org/grpc/mem" "google.golang.org/protobuf/proto" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" "google.golang.org/grpc/internal/channelz" "google.golang.org/grpc/internal/grpcsync" "google.golang.org/grpc/keepalive" "google.golang.org/grpc/metadata" "google.golang.org/grpc/peer" "google.golang.org/grpc/stats" "google.golang.org/grpc/status" "google.golang.org/grpc/tap" ) var ( // ErrIllegalHeaderWrite indicates that setting header is illegal because of // the stream's state. ErrIllegalHeaderWrite = status.Error(codes.Internal, "transport: SendHeader called multiple times") // ErrHeaderListSizeLimitViolation indicates that the header list size is larger // than the limit set by peer. ErrHeaderListSizeLimitViolation = status.Error(codes.Internal, "transport: trying to send header list size larger than the limit set by peer") ) // serverConnectionCounter counts the number of connections a server has seen // (equal to the number of http2Servers created). Must be accessed atomically. var serverConnectionCounter uint64 // http2Server implements the ServerTransport interface with HTTP2. type http2Server struct { lastRead int64 // Keep this field 64-bit aligned. Accessed atomically. done chan struct{} conn net.Conn loopy *loopyWriter readerDone chan struct{} // sync point to enable testing. loopyWriterDone chan struct{} peer peer.Peer inTapHandle tap.ServerInHandle framer *framer // The max number of concurrent streams. maxStreams uint32 // controlBuf delivers all the control related tasks (e.g., window // updates, reset streams, and various settings) to the controller. controlBuf *controlBuffer fc *trInFlow stats []stats.Handler // Keepalive and max-age parameters for the server. kp keepalive.ServerParameters // Keepalive enforcement policy. kep keepalive.EnforcementPolicy // The time instance last ping was received. lastPingAt time.Time // Number of times the client has violated keepalive ping policy so far. pingStrikes uint8 // Flag to signify that number of ping strikes should be reset to 0. // This is set whenever data or header frames are sent. // 1 means yes. resetPingStrikes uint32 // Accessed atomically. initialWindowSize int32 bdpEst *bdpEstimator maxSendHeaderListSize *uint32 mu sync.Mutex // guard the following // drainEvent is initialized when Drain() is called the first time. After // which the server writes out the first GoAway(with ID 2^31-1) frame. Then // an independent goroutine will be launched to later send the second // GoAway. During this time we don't want to write another first GoAway(with // ID 2^31 -1) frame. Thus call to Drain() will be a no-op if drainEvent is // already initialized since draining is already underway. drainEvent *grpcsync.Event state transportState activeStreams map[uint32]*ServerStream // idle is the time instant when the connection went idle. // This is either the beginning of the connection or when the number of // RPCs go down to 0. // When the connection is busy, this value is set to 0. idle time.Time // Fields below are for channelz metric collection. channelz *channelz.Socket bufferPool mem.BufferPool connectionID uint64 // maxStreamMu guards the maximum stream ID // This lock may not be taken if mu is already held. maxStreamMu sync.Mutex maxStreamID uint32 // max stream ID ever seen logger *grpclog.PrefixLogger } // NewServerTransport creates a http2 transport with conn and configuration // options from config. // // It returns a non-nil transport and a nil error on success. On failure, it // returns a nil transport and a non-nil error. For a special case where the // underlying conn gets closed before the client preface could be read, it // returns a nil transport and a nil error. func NewServerTransport(conn net.Conn, config *ServerConfig) (_ ServerTransport, err error) { var authInfo credentials.AuthInfo rawConn := conn if config.Credentials != nil { var err error conn, authInfo, err = config.Credentials.ServerHandshake(rawConn) if err != nil { // ErrConnDispatched means that the connection was dispatched away // from gRPC; those connections should be left open. io.EOF means // the connection was closed before handshaking completed, which can // happen naturally from probers. Return these errors directly. if err == credentials.ErrConnDispatched || err == io.EOF { return nil, err } return nil, connectionErrorf(false, err, "ServerHandshake(%q) failed: %v", rawConn.RemoteAddr(), err) } } writeBufSize := config.WriteBufferSize readBufSize := config.ReadBufferSize maxHeaderListSize := defaultServerMaxHeaderListSize if config.MaxHeaderListSize != nil { maxHeaderListSize = *config.MaxHeaderListSize } framer := newFramer(conn, writeBufSize, readBufSize, config.SharedWriteBuffer, maxHeaderListSize) // Send initial settings as connection preface to client. isettings := []http2.Setting{{ ID: http2.SettingMaxFrameSize, Val: http2MaxFrameLen, }} if config.MaxStreams != math.MaxUint32 { isettings = append(isettings, http2.Setting{ ID: http2.SettingMaxConcurrentStreams, Val: config.MaxStreams, }) } dynamicWindow := true iwz := int32(initialWindowSize) if config.InitialWindowSize >= defaultWindowSize { iwz = config.InitialWindowSize dynamicWindow = false } icwz := int32(initialWindowSize) if config.InitialConnWindowSize >= defaultWindowSize { icwz = config.InitialConnWindowSize dynamicWindow = false } if iwz != defaultWindowSize { isettings = append(isettings, http2.Setting{ ID: http2.SettingInitialWindowSize, Val: uint32(iwz)}) } if config.MaxHeaderListSize != nil { isettings = append(isettings, http2.Setting{ ID: http2.SettingMaxHeaderListSize, Val: *config.MaxHeaderListSize, }) } if config.HeaderTableSize != nil { isettings = append(isettings, http2.Setting{ ID: http2.SettingHeaderTableSize, Val: *config.HeaderTableSize, }) } if err := framer.fr.WriteSettings(isettings...); err != nil { return nil, connectionErrorf(false, err, "transport: %v", err) } // Adjust the connection flow control window if needed. if delta := uint32(icwz - defaultWindowSize); delta > 0 { if err := framer.fr.WriteWindowUpdate(0, delta); err != nil { return nil, connectionErrorf(false, err, "transport: %v", err) } } kp := config.KeepaliveParams if kp.MaxConnectionIdle == 0 { kp.MaxConnectionIdle = defaultMaxConnectionIdle } if kp.MaxConnectionAge == 0 { kp.MaxConnectionAge = defaultMaxConnectionAge } // Add a jitter to MaxConnectionAge. kp.MaxConnectionAge += getJitter(kp.MaxConnectionAge) if kp.MaxConnectionAgeGrace == 0 { kp.MaxConnectionAgeGrace = defaultMaxConnectionAgeGrace } if kp.Time == 0 { kp.Time = defaultServerKeepaliveTime } if kp.Timeout == 0 { kp.Timeout = defaultServerKeepaliveTimeout } if kp.Time != infinity { if err = syscall.SetTCPUserTimeout(rawConn, kp.Timeout); err != nil { return nil, connectionErrorf(false, err, "transport: failed to set TCP_USER_TIMEOUT: %v", err) } } kep := config.KeepalivePolicy if kep.MinTime == 0 { kep.MinTime = defaultKeepalivePolicyMinTime } done := make(chan struct{}) peer := peer.Peer{ Addr: conn.RemoteAddr(), LocalAddr: conn.LocalAddr(), AuthInfo: authInfo, } t := &http2Server{ done: done, conn: conn, peer: peer, framer: framer, readerDone: make(chan struct{}), loopyWriterDone: make(chan struct{}), maxStreams: config.MaxStreams, inTapHandle: config.InTapHandle, fc: &trInFlow{limit: uint32(icwz)}, state: reachable, activeStreams: make(map[uint32]*ServerStream), stats: config.StatsHandlers, kp: kp, idle: time.Now(), kep: kep, initialWindowSize: iwz, bufferPool: config.BufferPool, } var czSecurity credentials.ChannelzSecurityValue if au, ok := authInfo.(credentials.ChannelzSecurityInfo); ok { czSecurity = au.GetSecurityValue() } t.channelz = channelz.RegisterSocket( &channelz.Socket{ SocketType: channelz.SocketTypeNormal, Parent: config.ChannelzParent, SocketMetrics: channelz.SocketMetrics{}, EphemeralMetrics: t.socketMetrics, LocalAddr: t.peer.LocalAddr, RemoteAddr: t.peer.Addr, SocketOptions: channelz.GetSocketOption(t.conn), Security: czSecurity, }, ) t.logger = prefixLoggerForServerTransport(t) t.controlBuf = newControlBuffer(t.done) if dynamicWindow { t.bdpEst = &bdpEstimator{ bdp: initialWindowSize, updateFlowControl: t.updateFlowControl, } } t.connectionID = atomic.AddUint64(&serverConnectionCounter, 1) t.framer.writer.Flush() defer func() { if err != nil { t.Close(err) } }() // Check the validity of client preface. preface := make([]byte, len(clientPreface)) if _, err := io.ReadFull(t.conn, preface); err != nil { // In deployments where a gRPC server runs behind a cloud load balancer // which performs regular TCP level health checks, the connection is // closed immediately by the latter. Returning io.EOF here allows the // grpc server implementation to recognize this scenario and suppress // logging to reduce spam. if err == io.EOF { return nil, io.EOF } return nil, connectionErrorf(false, err, "transport: http2Server.HandleStreams failed to receive the preface from client: %v", err) } if !bytes.Equal(preface, clientPreface) { return nil, connectionErrorf(false, nil, "transport: http2Server.HandleStreams received bogus greeting from client: %q", preface) } frame, err := t.framer.fr.ReadFrame() if err == io.EOF || err == io.ErrUnexpectedEOF { return nil, err } if err != nil { return nil, connectionErrorf(false, err, "transport: http2Server.HandleStreams failed to read initial settings frame: %v", err) } atomic.StoreInt64(&t.lastRead, time.Now().UnixNano()) sf, ok := frame.(*http2.SettingsFrame) if !ok { return nil, connectionErrorf(false, nil, "transport: http2Server.HandleStreams saw invalid preface type %T from client", frame) } t.handleSettings(sf) go func() { t.loopy = newLoopyWriter(serverSide, t.framer, t.controlBuf, t.bdpEst, t.conn, t.logger, t.outgoingGoAwayHandler, t.bufferPool) err := t.loopy.run() close(t.loopyWriterDone) if !isIOError(err) { // Close the connection if a non-I/O error occurs (for I/O errors // the reader will also encounter the error and close). Wait 1 // second before closing the connection, or when the reader is done // (i.e. the client already closed the connection or a connection // error occurred). This avoids the potential problem where there // is unread data on the receive side of the connection, which, if // closed, would lead to a TCP RST instead of FIN, and the client // encountering errors. For more info: // https://github.com/grpc/grpc-go/issues/5358 timer := time.NewTimer(time.Second) defer timer.Stop() select { case <-t.readerDone: case <-timer.C: } t.conn.Close() } }() go t.keepalive() return t, nil } // operateHeaders takes action on the decoded headers. Returns an error if fatal // error encountered and transport needs to close, otherwise returns nil. func (t *http2Server) operateHeaders(ctx context.Context, frame *http2.MetaHeadersFrame, handle func(*ServerStream)) error { // Acquire max stream ID lock for entire duration t.maxStreamMu.Lock() defer t.maxStreamMu.Unlock() streamID := frame.Header().StreamID // frame.Truncated is set to true when framer detects that the current header // list size hits MaxHeaderListSize limit. if frame.Truncated { t.controlBuf.put(&cleanupStream{ streamID: streamID, rst: true, rstCode: http2.ErrCodeFrameSize, onWrite: func() {}, }) return nil } if streamID%2 != 1 || streamID <= t.maxStreamID { // illegal gRPC stream id. return fmt.Errorf("received an illegal stream id: %v. headers frame: %+v", streamID, frame) } t.maxStreamID = streamID buf := newRecvBuffer() s := &ServerStream{ Stream: &Stream{ id: streamID, buf: buf, fc: &inFlow{limit: uint32(t.initialWindowSize)}, }, st: t, headerWireLength: int(frame.Header().Length), } var ( // if false, content-type was missing or invalid isGRPC = false contentType = "" mdata = make(metadata.MD, len(frame.Fields)) httpMethod string // these are set if an error is encountered while parsing the headers protocolError bool headerError *status.Status timeoutSet bool timeout time.Duration ) for _, hf := range frame.Fields { switch hf.Name { case "content-type": contentSubtype, validContentType := grpcutil.ContentSubtype(hf.Value) if !validContentType { contentType = hf.Value break } mdata[hf.Name] = append(mdata[hf.Name], hf.Value) s.contentSubtype = contentSubtype isGRPC = true case "grpc-accept-encoding": mdata[hf.Name] = append(mdata[hf.Name], hf.Value) if hf.Value == "" { continue } compressors := hf.Value if s.clientAdvertisedCompressors != "" { compressors = s.clientAdvertisedCompressors + "," + compressors } s.clientAdvertisedCompressors = compressors case "grpc-encoding": s.recvCompress = hf.Value case ":method": httpMethod = hf.Value case ":path": s.method = hf.Value case "grpc-timeout": timeoutSet = true var err error if timeout, err = decodeTimeout(hf.Value); err != nil { headerError = status.Newf(codes.Internal, "malformed grpc-timeout: %v", err) } // "Transports must consider requests containing the Connection header // as malformed." - A41 case "connection": if t.logger.V(logLevel) { t.logger.Infof("Received a HEADERS frame with a :connection header which makes the request malformed, as per the HTTP/2 spec") } protocolError = true default: if isReservedHeader(hf.Name) && !isWhitelistedHeader(hf.Name) { break } v, err := decodeMetadataHeader(hf.Name, hf.Value) if err != nil { headerError = status.Newf(codes.Internal, "malformed binary metadata %q in header %q: %v", hf.Value, hf.Name, err) t.logger.Warningf("Failed to decode metadata header (%q, %q): %v", hf.Name, hf.Value, err) break } mdata[hf.Name] = append(mdata[hf.Name], v) } } // "If multiple Host headers or multiple :authority headers are present, the // request must be rejected with an HTTP status code 400 as required by Host // validation in RFC 7230 §5.4, gRPC status code INTERNAL, or RST_STREAM // with HTTP/2 error code PROTOCOL_ERROR." - A41. Since this is a HTTP/2 // error, this takes precedence over a client not speaking gRPC. if len(mdata[":authority"]) > 1 || len(mdata["host"]) > 1 { errMsg := fmt.Sprintf("num values of :authority: %v, num values of host: %v, both must only have 1 value as per HTTP/2 spec", len(mdata[":authority"]), len(mdata["host"])) if t.logger.V(logLevel) { t.logger.Infof("Aborting the stream early: %v", errMsg) } t.controlBuf.put(&earlyAbortStream{ httpStatus: http.StatusBadRequest, streamID: streamID, contentSubtype: s.contentSubtype, status: status.New(codes.Internal, errMsg), rst: !frame.StreamEnded(), }) return nil } if protocolError { t.controlBuf.put(&cleanupStream{ streamID: streamID, rst: true, rstCode: http2.ErrCodeProtocol, onWrite: func() {}, }) return nil } if !isGRPC { t.controlBuf.put(&earlyAbortStream{ httpStatus: http.StatusUnsupportedMediaType, streamID: streamID, contentSubtype: s.contentSubtype, status: status.Newf(codes.InvalidArgument, "invalid gRPC request content-type %q", contentType), rst: !frame.StreamEnded(), }) return nil } if headerError != nil { t.controlBuf.put(&earlyAbortStream{ httpStatus: http.StatusBadRequest, streamID: streamID, contentSubtype: s.contentSubtype, status: headerError, rst: !frame.StreamEnded(), }) return nil } // "If :authority is missing, Host must be renamed to :authority." - A41 if len(mdata[":authority"]) == 0 { // No-op if host isn't present, no eventual :authority header is a valid // RPC. if host, ok := mdata["host"]; ok { mdata[":authority"] = host delete(mdata, "host") } } else { // "If :authority is present, Host must be discarded" - A41 delete(mdata, "host") } if frame.StreamEnded() { // s is just created by the caller. No lock needed. s.state = streamReadDone } if timeoutSet { s.ctx, s.cancel = context.WithTimeout(ctx, timeout) } else { s.ctx, s.cancel = context.WithCancel(ctx) } // Attach the received metadata to the context. if len(mdata) > 0 { s.ctx = metadata.NewIncomingContext(s.ctx, mdata) } t.mu.Lock() if t.state != reachable { t.mu.Unlock() s.cancel() return nil } if uint32(len(t.activeStreams)) >= t.maxStreams { t.mu.Unlock() t.controlBuf.put(&cleanupStream{ streamID: streamID, rst: true, rstCode: http2.ErrCodeRefusedStream, onWrite: func() {}, }) s.cancel() return nil } if httpMethod != http.MethodPost { t.mu.Unlock() errMsg := fmt.Sprintf("Received a HEADERS frame with :method %q which should be POST", httpMethod) if t.logger.V(logLevel) { t.logger.Infof("Aborting the stream early: %v", errMsg) } t.controlBuf.put(&earlyAbortStream{ httpStatus: http.StatusMethodNotAllowed, streamID: streamID, contentSubtype: s.contentSubtype, status: status.New(codes.Internal, errMsg), rst: !frame.StreamEnded(), }) s.cancel() return nil } if t.inTapHandle != nil { var err error if s.ctx, err = t.inTapHandle(s.ctx, &tap.Info{FullMethodName: s.method, Header: mdata}); err != nil { t.mu.Unlock() if t.logger.V(logLevel) { t.logger.Infof("Aborting the stream early due to InTapHandle failure: %v", err) } stat, ok := status.FromError(err) if !ok { stat = status.New(codes.PermissionDenied, err.Error()) } t.controlBuf.put(&earlyAbortStream{ httpStatus: http.StatusOK, streamID: s.id, contentSubtype: s.contentSubtype, status: stat, rst: !frame.StreamEnded(), }) return nil } } t.activeStreams[streamID] = s if len(t.activeStreams) == 1 { t.idle = time.Time{} } t.mu.Unlock() if channelz.IsOn() { t.channelz.SocketMetrics.StreamsStarted.Add(1) t.channelz.SocketMetrics.LastRemoteStreamCreatedTimestamp.Store(time.Now().UnixNano()) } s.requestRead = func(n int) { t.adjustWindow(s, uint32(n)) } s.ctxDone = s.ctx.Done() s.wq = newWriteQuota(defaultWriteQuota, s.ctxDone) s.trReader = &transportReader{ reader: &recvBufferReader{ ctx: s.ctx, ctxDone: s.ctxDone, recv: s.buf, }, windowHandler: func(n int) { t.updateWindow(s, uint32(n)) }, } // Register the stream with loopy. t.controlBuf.put(&registerStream{ streamID: s.id, wq: s.wq, }) handle(s) return nil } // HandleStreams receives incoming streams using the given handler. This is // typically run in a separate goroutine. // traceCtx attaches trace to ctx and returns the new context. func (t *http2Server) HandleStreams(ctx context.Context, handle func(*ServerStream)) { defer func() { close(t.readerDone) <-t.loopyWriterDone }() for { t.controlBuf.throttle() frame, err := t.framer.fr.ReadFrame() atomic.StoreInt64(&t.lastRead, time.Now().UnixNano()) if err != nil { if se, ok := err.(http2.StreamError); ok { if t.logger.V(logLevel) { t.logger.Warningf("Encountered http2.StreamError: %v", se) } t.mu.Lock() s := t.activeStreams[se.StreamID] t.mu.Unlock() if s != nil { t.closeStream(s, true, se.Code, false) } else { t.controlBuf.put(&cleanupStream{ streamID: se.StreamID, rst: true, rstCode: se.Code, onWrite: func() {}, }) } continue } t.Close(err) return } switch frame := frame.(type) { case *http2.MetaHeadersFrame: if err := t.operateHeaders(ctx, frame, handle); err != nil { // Any error processing client headers, e.g. invalid stream ID, // is considered a protocol violation. t.controlBuf.put(&goAway{ code: http2.ErrCodeProtocol, debugData: []byte(err.Error()), closeConn: err, }) continue } case *http2.DataFrame: t.handleData(frame) case *http2.RSTStreamFrame: t.handleRSTStream(frame) case *http2.SettingsFrame: t.handleSettings(frame) case *http2.PingFrame: t.handlePing(frame) case *http2.WindowUpdateFrame: t.handleWindowUpdate(frame) case *http2.GoAwayFrame: // TODO: Handle GoAway from the client appropriately. default: if t.logger.V(logLevel) { t.logger.Infof("Received unsupported frame type %T", frame) } } } } func (t *http2Server) getStream(f http2.Frame) (*ServerStream, bool) { t.mu.Lock() defer t.mu.Unlock() if t.activeStreams == nil { // The transport is closing. return nil, false } s, ok := t.activeStreams[f.Header().StreamID] if !ok { // The stream is already done. return nil, false } return s, true } // adjustWindow sends out extra window update over the initial window size // of stream if the application is requesting data larger in size than // the window. func (t *http2Server) adjustWindow(s *ServerStream, n uint32) { if w := s.fc.maybeAdjust(n); w > 0 { t.controlBuf.put(&outgoingWindowUpdate{streamID: s.id, increment: w}) } } // updateWindow adjusts the inbound quota for the stream and the transport. // Window updates will deliver to the controller for sending when // the cumulative quota exceeds the corresponding threshold. func (t *http2Server) updateWindow(s *ServerStream, n uint32) { if w := s.fc.onRead(n); w > 0 { t.controlBuf.put(&outgoingWindowUpdate{streamID: s.id, increment: w, }) } } // updateFlowControl updates the incoming flow control windows // for the transport and the stream based on the current bdp // estimation. func (t *http2Server) updateFlowControl(n uint32) { t.mu.Lock() for _, s := range t.activeStreams { s.fc.newLimit(n) } t.initialWindowSize = int32(n) t.mu.Unlock() t.controlBuf.put(&outgoingWindowUpdate{ streamID: 0, increment: t.fc.newLimit(n), }) t.controlBuf.put(&outgoingSettings{ ss: []http2.Setting{ { ID: http2.SettingInitialWindowSize, Val: n, }, }, }) } func (t *http2Server) handleData(f *http2.DataFrame) { size := f.Header().Length var sendBDPPing bool if t.bdpEst != nil { sendBDPPing = t.bdpEst.add(size) } // Decouple connection's flow control from application's read. // An update on connection's flow control should not depend on // whether user application has read the data or not. Such a // restriction is already imposed on the stream's flow control, // and therefore the sender will be blocked anyways. // Decoupling the connection flow control will prevent other // active(fast) streams from starving in presence of slow or // inactive streams. if w := t.fc.onData(size); w > 0 { t.controlBuf.put(&outgoingWindowUpdate{ streamID: 0, increment: w, }) } if sendBDPPing { // Avoid excessive ping detection (e.g. in an L7 proxy) // by sending a window update prior to the BDP ping. if w := t.fc.reset(); w > 0 { t.controlBuf.put(&outgoingWindowUpdate{ streamID: 0, increment: w, }) } t.controlBuf.put(bdpPing) } // Select the right stream to dispatch. s, ok := t.getStream(f) if !ok { return } if s.getState() == streamReadDone { t.closeStream(s, true, http2.ErrCodeStreamClosed, false) return } if size > 0 { if err := s.fc.onData(size); err != nil { t.closeStream(s, true, http2.ErrCodeFlowControl, false) return } if f.Header().Flags.Has(http2.FlagDataPadded) { if w := s.fc.onRead(size - uint32(len(f.Data()))); w > 0 { t.controlBuf.put(&outgoingWindowUpdate{s.id, w}) } } // TODO(bradfitz, zhaoq): A copy is required here because there is no // guarantee f.Data() is consumed before the arrival of next frame. // Can this copy be eliminated? if len(f.Data()) > 0 { pool := t.bufferPool if pool == nil { // Note that this is only supposed to be nil in tests. Otherwise, stream is // always initialized with a BufferPool. pool = mem.DefaultBufferPool() } s.write(recvMsg{buffer: mem.Copy(f.Data(), pool)}) } } if f.StreamEnded() { // Received the end of stream from the client. s.compareAndSwapState(streamActive, streamReadDone) s.write(recvMsg{err: io.EOF}) } } func (t *http2Server) handleRSTStream(f *http2.RSTStreamFrame) { // If the stream is not deleted from the transport's active streams map, then do a regular close stream. if s, ok := t.getStream(f); ok { t.closeStream(s, false, 0, false) return } // If the stream is already deleted from the active streams map, then put a cleanupStream item into controlbuf to delete the stream from loopy writer's established streams map. t.controlBuf.put(&cleanupStream{ streamID: f.Header().StreamID, rst: false, rstCode: 0, onWrite: func() {}, }) } func (t *http2Server) handleSettings(f *http2.SettingsFrame) { if f.IsAck() { return } var ss []http2.Setting var updateFuncs []func() f.ForeachSetting(func(s http2.Setting) error { switch s.ID { case http2.SettingMaxHeaderListSize: updateFuncs = append(updateFuncs, func() { t.maxSendHeaderListSize = new(uint32) *t.maxSendHeaderListSize = s.Val }) default: ss = append(ss, s) } return nil }) t.controlBuf.executeAndPut(func() bool { for _, f := range updateFuncs { f() } return true }, &incomingSettings{ ss: ss, }) } const ( maxPingStrikes = 2 defaultPingTimeout = 2 * time.Hour ) func (t *http2Server) handlePing(f *http2.PingFrame) { if f.IsAck() { if f.Data == goAwayPing.data && t.drainEvent != nil { t.drainEvent.Fire() return } // Maybe it's a BDP ping. if t.bdpEst != nil { t.bdpEst.calculate(f.Data) } return } pingAck := &ping{ack: true} copy(pingAck.data[:], f.Data[:]) t.controlBuf.put(pingAck) now := time.Now() defer func() { t.lastPingAt = now }() // A reset ping strikes means that we don't need to check for policy // violation for this ping and the pingStrikes counter should be set // to 0. if atomic.CompareAndSwapUint32(&t.resetPingStrikes, 1, 0) { t.pingStrikes = 0 return } t.mu.Lock() ns := len(t.activeStreams) t.mu.Unlock() if ns < 1 && !t.kep.PermitWithoutStream { // Keepalive shouldn't be active thus, this new ping should // have come after at least defaultPingTimeout. if t.lastPingAt.Add(defaultPingTimeout).After(now) { t.pingStrikes++ } } else { // Check if keepalive policy is respected. if t.lastPingAt.Add(t.kep.MinTime).After(now) { t.pingStrikes++ } } if t.pingStrikes > maxPingStrikes { // Send goaway and close the connection. t.controlBuf.put(&goAway{code: http2.ErrCodeEnhanceYourCalm, debugData: []byte("too_many_pings"), closeConn: errors.New("got too many pings from the client")}) } } func (t *http2Server) handleWindowUpdate(f *http2.WindowUpdateFrame) { t.controlBuf.put(&incomingWindowUpdate{ streamID: f.Header().StreamID, increment: f.Increment, }) } func appendHeaderFieldsFromMD(headerFields []hpack.HeaderField, md metadata.MD) []hpack.HeaderField { for k, vv := range md { if isReservedHeader(k) { // Clients don't tolerate reading restricted headers after some non restricted ones were sent. continue } for _, v := range vv { headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)}) } } return headerFields } func (t *http2Server) checkForHeaderListSize(it any) bool { if t.maxSendHeaderListSize == nil { return true } hdrFrame := it.(*headerFrame) var sz int64 for _, f := range hdrFrame.hf { if sz += int64(f.Size()); sz > int64(*t.maxSendHeaderListSize) { if t.logger.V(logLevel) { t.logger.Infof("Header list size to send violates the maximum size (%d bytes) set by client", *t.maxSendHeaderListSize) } return false } } return true } func (t *http2Server) streamContextErr(s *ServerStream) error { select { case <-t.done: return ErrConnClosing default: } return ContextErr(s.ctx.Err()) } // WriteHeader sends the header metadata md back to the client. func (t *http2Server) writeHeader(s *ServerStream, md metadata.MD) error { s.hdrMu.Lock() defer s.hdrMu.Unlock() if s.getState() == streamDone { return t.streamContextErr(s) } if s.updateHeaderSent() { return ErrIllegalHeaderWrite } if md.Len() > 0 { if s.header.Len() > 0 { s.header = metadata.Join(s.header, md) } else { s.header = md } } if err := t.writeHeaderLocked(s); err != nil { switch e := err.(type) { case ConnectionError: return status.Error(codes.Unavailable, e.Desc) default: return status.Convert(err).Err() } } return nil } func (t *http2Server) setResetPingStrikes() { atomic.StoreUint32(&t.resetPingStrikes, 1) } func (t *http2Server) writeHeaderLocked(s *ServerStream) error { // TODO(mmukhi): Benchmark if the performance gets better if count the metadata and other header fields // first and create a slice of that exact size. headerFields := make([]hpack.HeaderField, 0, 2) // at least :status, content-type will be there if none else. headerFields = append(headerFields, hpack.HeaderField{Name: ":status", Value: "200"}) headerFields = append(headerFields, hpack.HeaderField{Name: "content-type", Value: grpcutil.ContentType(s.contentSubtype)}) if s.sendCompress != "" { headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-encoding", Value: s.sendCompress}) } headerFields = appendHeaderFieldsFromMD(headerFields, s.header) hf := &headerFrame{ streamID: s.id, hf: headerFields, endStream: false, onWrite: t.setResetPingStrikes, } success, err := t.controlBuf.executeAndPut(func() bool { return t.checkForHeaderListSize(hf) }, hf) if !success { if err != nil { return err } t.closeStream(s, true, http2.ErrCodeInternal, false) return ErrHeaderListSizeLimitViolation } for _, sh := range t.stats { // Note: Headers are compressed with hpack after this call returns. // No WireLength field is set here. outHeader := &stats.OutHeader{ Header: s.header.Copy(), Compression: s.sendCompress, } sh.HandleRPC(s.Context(), outHeader) } return nil } // WriteStatus sends stream status to the client and terminates the stream. // There is no further I/O operations being able to perform on this stream. // TODO(zhaoq): Now it indicates the end of entire stream. Revisit if early // OK is adopted. func (t *http2Server) writeStatus(s *ServerStream, st *status.Status) error { s.hdrMu.Lock() defer s.hdrMu.Unlock() if s.getState() == streamDone { return nil } // TODO(mmukhi): Benchmark if the performance gets better if count the metadata and other header fields // first and create a slice of that exact size. headerFields := make([]hpack.HeaderField, 0, 2) // grpc-status and grpc-message will be there if none else. if !s.updateHeaderSent() { // No headers have been sent. if len(s.header) > 0 { // Send a separate header frame. if err := t.writeHeaderLocked(s); err != nil { return err } } else { // Send a trailer only response.
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
true
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/transport/controlbuf.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/transport/controlbuf.go
/* * * Copyright 2014 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. * */ package transport import ( "bytes" "errors" "fmt" "net" "runtime" "strconv" "sync" "sync/atomic" "golang.org/x/net/http2" "golang.org/x/net/http2/hpack" "google.golang.org/grpc/internal/grpclog" "google.golang.org/grpc/internal/grpcutil" "google.golang.org/grpc/mem" "google.golang.org/grpc/status" ) var updateHeaderTblSize = func(e *hpack.Encoder, v uint32) { e.SetMaxDynamicTableSizeLimit(v) } type itemNode struct { it any next *itemNode } type itemList struct { head *itemNode tail *itemNode } func (il *itemList) enqueue(i any) { n := &itemNode{it: i} if il.tail == nil { il.head, il.tail = n, n return } il.tail.next = n il.tail = n } // peek returns the first item in the list without removing it from the // list. func (il *itemList) peek() any { return il.head.it } func (il *itemList) dequeue() any { if il.head == nil { return nil } i := il.head.it il.head = il.head.next if il.head == nil { il.tail = nil } return i } func (il *itemList) dequeueAll() *itemNode { h := il.head il.head, il.tail = nil, nil return h } func (il *itemList) isEmpty() bool { return il.head == nil } // The following defines various control items which could flow through // the control buffer of transport. They represent different aspects of // control tasks, e.g., flow control, settings, streaming resetting, etc. // maxQueuedTransportResponseFrames is the most queued "transport response" // frames we will buffer before preventing new reads from occurring on the // transport. These are control frames sent in response to client requests, // such as RST_STREAM due to bad headers or settings acks. const maxQueuedTransportResponseFrames = 50 type cbItem interface { isTransportResponseFrame() bool } // registerStream is used to register an incoming stream with loopy writer. type registerStream struct { streamID uint32 wq *writeQuota } func (*registerStream) isTransportResponseFrame() bool { return false } // headerFrame is also used to register stream on the client-side. type headerFrame struct { streamID uint32 hf []hpack.HeaderField endStream bool // Valid on server side. initStream func(uint32) error // Used only on the client side. onWrite func() wq *writeQuota // write quota for the stream created. cleanup *cleanupStream // Valid on the server side. onOrphaned func(error) // Valid on client-side } func (h *headerFrame) isTransportResponseFrame() bool { return h.cleanup != nil && h.cleanup.rst // Results in a RST_STREAM } type cleanupStream struct { streamID uint32 rst bool rstCode http2.ErrCode onWrite func() } func (c *cleanupStream) isTransportResponseFrame() bool { return c.rst } // Results in a RST_STREAM type earlyAbortStream struct { httpStatus uint32 streamID uint32 contentSubtype string status *status.Status rst bool } func (*earlyAbortStream) isTransportResponseFrame() bool { return false } type dataFrame struct { streamID uint32 endStream bool h []byte reader mem.Reader // onEachWrite is called every time // a part of data is written out. onEachWrite func() } func (*dataFrame) isTransportResponseFrame() bool { return false } type incomingWindowUpdate struct { streamID uint32 increment uint32 } func (*incomingWindowUpdate) isTransportResponseFrame() bool { return false } type outgoingWindowUpdate struct { streamID uint32 increment uint32 } func (*outgoingWindowUpdate) isTransportResponseFrame() bool { return false // window updates are throttled by thresholds } type incomingSettings struct { ss []http2.Setting } func (*incomingSettings) isTransportResponseFrame() bool { return true } // Results in a settings ACK type outgoingSettings struct { ss []http2.Setting } func (*outgoingSettings) isTransportResponseFrame() bool { return false } type incomingGoAway struct { } func (*incomingGoAway) isTransportResponseFrame() bool { return false } type goAway struct { code http2.ErrCode debugData []byte headsUp bool closeConn error // if set, loopyWriter will exit with this error } func (*goAway) isTransportResponseFrame() bool { return false } type ping struct { ack bool data [8]byte } func (*ping) isTransportResponseFrame() bool { return true } type outFlowControlSizeRequest struct { resp chan uint32 } func (*outFlowControlSizeRequest) isTransportResponseFrame() bool { return false } // closeConnection is an instruction to tell the loopy writer to flush the // framer and exit, which will cause the transport's connection to be closed // (by the client or server). The transport itself will close after the reader // encounters the EOF caused by the connection closure. type closeConnection struct{} func (closeConnection) isTransportResponseFrame() bool { return false } type outStreamState int const ( active outStreamState = iota empty waitingOnStreamQuota ) type outStream struct { id uint32 state outStreamState itl *itemList bytesOutStanding int wq *writeQuota next *outStream prev *outStream } func (s *outStream) deleteSelf() { if s.prev != nil { s.prev.next = s.next } if s.next != nil { s.next.prev = s.prev } s.next, s.prev = nil, nil } type outStreamList struct { // Following are sentinel objects that mark the // beginning and end of the list. They do not // contain any item lists. All valid objects are // inserted in between them. // This is needed so that an outStream object can // deleteSelf() in O(1) time without knowing which // list it belongs to. head *outStream tail *outStream } func newOutStreamList() *outStreamList { head, tail := new(outStream), new(outStream) head.next = tail tail.prev = head return &outStreamList{ head: head, tail: tail, } } func (l *outStreamList) enqueue(s *outStream) { e := l.tail.prev e.next = s s.prev = e s.next = l.tail l.tail.prev = s } // remove from the beginning of the list. func (l *outStreamList) dequeue() *outStream { b := l.head.next if b == l.tail { return nil } b.deleteSelf() return b } // controlBuffer is a way to pass information to loopy. // // Information is passed as specific struct types called control frames. A // control frame not only represents data, messages or headers to be sent out // but can also be used to instruct loopy to update its internal state. It // shouldn't be confused with an HTTP2 frame, although some of the control // frames like dataFrame and headerFrame do go out on wire as HTTP2 frames. type controlBuffer struct { wakeupCh chan struct{} // Unblocks readers waiting for something to read. done <-chan struct{} // Closed when the transport is done. // Mutex guards all the fields below, except trfChan which can be read // atomically without holding mu. mu sync.Mutex consumerWaiting bool // True when readers are blocked waiting for new data. closed bool // True when the controlbuf is finished. list *itemList // List of queued control frames. // transportResponseFrames counts the number of queued items that represent // the response of an action initiated by the peer. trfChan is created // when transportResponseFrames >= maxQueuedTransportResponseFrames and is // closed and nilled when transportResponseFrames drops below the // threshold. Both fields are protected by mu. transportResponseFrames int trfChan atomic.Pointer[chan struct{}] } func newControlBuffer(done <-chan struct{}) *controlBuffer { return &controlBuffer{ wakeupCh: make(chan struct{}, 1), list: &itemList{}, done: done, } } // throttle blocks if there are too many frames in the control buf that // represent the response of an action initiated by the peer, like // incomingSettings cleanupStreams etc. func (c *controlBuffer) throttle() { if ch := c.trfChan.Load(); ch != nil { select { case <-(*ch): case <-c.done: } } } // put adds an item to the controlbuf. func (c *controlBuffer) put(it cbItem) error { _, err := c.executeAndPut(nil, it) return err } // executeAndPut runs f, and if the return value is true, adds the given item to // the controlbuf. The item could be nil, in which case, this method simply // executes f and does not add the item to the controlbuf. // // The first return value indicates whether the item was successfully added to // the control buffer. A non-nil error, specifically ErrConnClosing, is returned // if the control buffer is already closed. func (c *controlBuffer) executeAndPut(f func() bool, it cbItem) (bool, error) { c.mu.Lock() defer c.mu.Unlock() if c.closed { return false, ErrConnClosing } if f != nil { if !f() { // f wasn't successful return false, nil } } if it == nil { return true, nil } var wakeUp bool if c.consumerWaiting { wakeUp = true c.consumerWaiting = false } c.list.enqueue(it) if it.isTransportResponseFrame() { c.transportResponseFrames++ if c.transportResponseFrames == maxQueuedTransportResponseFrames { // We are adding the frame that puts us over the threshold; create // a throttling channel. ch := make(chan struct{}) c.trfChan.Store(&ch) } } if wakeUp { select { case c.wakeupCh <- struct{}{}: default: } } return true, nil } // get returns the next control frame from the control buffer. If block is true // **and** there are no control frames in the control buffer, the call blocks // until one of the conditions is met: there is a frame to return or the // transport is closed. func (c *controlBuffer) get(block bool) (any, error) { for { c.mu.Lock() frame, err := c.getOnceLocked() if frame != nil || err != nil || !block { // If we read a frame or an error, we can return to the caller. The // call to getOnceLocked() returns a nil frame and a nil error if // there is nothing to read, and in that case, if the caller asked // us not to block, we can return now as well. c.mu.Unlock() return frame, err } c.consumerWaiting = true c.mu.Unlock() // Release the lock above and wait to be woken up. select { case <-c.wakeupCh: case <-c.done: return nil, errors.New("transport closed by client") } } } // Callers must not use this method, but should instead use get(). // // Caller must hold c.mu. func (c *controlBuffer) getOnceLocked() (any, error) { if c.closed { return false, ErrConnClosing } if c.list.isEmpty() { return nil, nil } h := c.list.dequeue().(cbItem) if h.isTransportResponseFrame() { if c.transportResponseFrames == maxQueuedTransportResponseFrames { // We are removing the frame that put us over the // threshold; close and clear the throttling channel. ch := c.trfChan.Swap(nil) close(*ch) } c.transportResponseFrames-- } return h, nil } // finish closes the control buffer, cleaning up any streams that have queued // header frames. Once this method returns, no more frames can be added to the // control buffer, and attempts to do so will return ErrConnClosing. func (c *controlBuffer) finish() { c.mu.Lock() defer c.mu.Unlock() if c.closed { return } c.closed = true // There may be headers for streams in the control buffer. // These streams need to be cleaned out since the transport // is still not aware of these yet. for head := c.list.dequeueAll(); head != nil; head = head.next { switch v := head.it.(type) { case *headerFrame: if v.onOrphaned != nil { // It will be nil on the server-side. v.onOrphaned(ErrConnClosing) } case *dataFrame: _ = v.reader.Close() } } // In case throttle() is currently in flight, it needs to be unblocked. // Otherwise, the transport may not close, since the transport is closed by // the reader encountering the connection error. ch := c.trfChan.Swap(nil) if ch != nil { close(*ch) } } type side int const ( clientSide side = iota serverSide ) // Loopy receives frames from the control buffer. // Each frame is handled individually; most of the work done by loopy goes // into handling data frames. Loopy maintains a queue of active streams, and each // stream maintains a queue of data frames; as loopy receives data frames // it gets added to the queue of the relevant stream. // Loopy goes over this list of active streams by processing one node every iteration, // thereby closely resembling a round-robin scheduling over all streams. While // processing a stream, loopy writes out data bytes from this stream capped by the min // of http2MaxFrameLen, connection-level flow control and stream-level flow control. type loopyWriter struct { side side cbuf *controlBuffer sendQuota uint32 oiws uint32 // outbound initial window size. // estdStreams is map of all established streams that are not cleaned-up yet. // On client-side, this is all streams whose headers were sent out. // On server-side, this is all streams whose headers were received. estdStreams map[uint32]*outStream // Established streams. // activeStreams is a linked-list of all streams that have data to send and some // stream-level flow control quota. // Each of these streams internally have a list of data items(and perhaps trailers // on the server-side) to be sent out. activeStreams *outStreamList framer *framer hBuf *bytes.Buffer // The buffer for HPACK encoding. hEnc *hpack.Encoder // HPACK encoder. bdpEst *bdpEstimator draining bool conn net.Conn logger *grpclog.PrefixLogger bufferPool mem.BufferPool // Side-specific handlers ssGoAwayHandler func(*goAway) (bool, error) } func newLoopyWriter(s side, fr *framer, cbuf *controlBuffer, bdpEst *bdpEstimator, conn net.Conn, logger *grpclog.PrefixLogger, goAwayHandler func(*goAway) (bool, error), bufferPool mem.BufferPool) *loopyWriter { var buf bytes.Buffer l := &loopyWriter{ side: s, cbuf: cbuf, sendQuota: defaultWindowSize, oiws: defaultWindowSize, estdStreams: make(map[uint32]*outStream), activeStreams: newOutStreamList(), framer: fr, hBuf: &buf, hEnc: hpack.NewEncoder(&buf), bdpEst: bdpEst, conn: conn, logger: logger, ssGoAwayHandler: goAwayHandler, bufferPool: bufferPool, } return l } const minBatchSize = 1000 // run should be run in a separate goroutine. // It reads control frames from controlBuf and processes them by: // 1. Updating loopy's internal state, or/and // 2. Writing out HTTP2 frames on the wire. // // Loopy keeps all active streams with data to send in a linked-list. // All streams in the activeStreams linked-list must have both: // 1. Data to send, and // 2. Stream level flow control quota available. // // In each iteration of run loop, other than processing the incoming control // frame, loopy calls processData, which processes one node from the // activeStreams linked-list. This results in writing of HTTP2 frames into an // underlying write buffer. When there's no more control frames to read from // controlBuf, loopy flushes the write buffer. As an optimization, to increase // the batch size for each flush, loopy yields the processor, once if the batch // size is too low to give stream goroutines a chance to fill it up. // // Upon exiting, if the error causing the exit is not an I/O error, run() // flushes the underlying connection. The connection is always left open to // allow different closing behavior on the client and server. func (l *loopyWriter) run() (err error) { defer func() { if l.logger.V(logLevel) { l.logger.Infof("loopyWriter exiting with error: %v", err) } if !isIOError(err) { l.framer.writer.Flush() } l.cbuf.finish() }() for { it, err := l.cbuf.get(true) if err != nil { return err } if err = l.handle(it); err != nil { return err } if _, err = l.processData(); err != nil { return err } gosched := true hasdata: for { it, err := l.cbuf.get(false) if err != nil { return err } if it != nil { if err = l.handle(it); err != nil { return err } if _, err = l.processData(); err != nil { return err } continue hasdata } isEmpty, err := l.processData() if err != nil { return err } if !isEmpty { continue hasdata } if gosched { gosched = false if l.framer.writer.offset < minBatchSize { runtime.Gosched() continue hasdata } } l.framer.writer.Flush() break hasdata } } } func (l *loopyWriter) outgoingWindowUpdateHandler(w *outgoingWindowUpdate) error { return l.framer.fr.WriteWindowUpdate(w.streamID, w.increment) } func (l *loopyWriter) incomingWindowUpdateHandler(w *incomingWindowUpdate) { // Otherwise update the quota. if w.streamID == 0 { l.sendQuota += w.increment return } // Find the stream and update it. if str, ok := l.estdStreams[w.streamID]; ok { str.bytesOutStanding -= int(w.increment) if strQuota := int(l.oiws) - str.bytesOutStanding; strQuota > 0 && str.state == waitingOnStreamQuota { str.state = active l.activeStreams.enqueue(str) return } } } func (l *loopyWriter) outgoingSettingsHandler(s *outgoingSettings) error { return l.framer.fr.WriteSettings(s.ss...) } func (l *loopyWriter) incomingSettingsHandler(s *incomingSettings) error { l.applySettings(s.ss) return l.framer.fr.WriteSettingsAck() } func (l *loopyWriter) registerStreamHandler(h *registerStream) { str := &outStream{ id: h.streamID, state: empty, itl: &itemList{}, wq: h.wq, } l.estdStreams[h.streamID] = str } func (l *loopyWriter) headerHandler(h *headerFrame) error { if l.side == serverSide { str, ok := l.estdStreams[h.streamID] if !ok { if l.logger.V(logLevel) { l.logger.Infof("Unrecognized streamID %d in loopyWriter", h.streamID) } return nil } // Case 1.A: Server is responding back with headers. if !h.endStream { return l.writeHeader(h.streamID, h.endStream, h.hf, h.onWrite) } // else: Case 1.B: Server wants to close stream. if str.state != empty { // either active or waiting on stream quota. // add it str's list of items. str.itl.enqueue(h) return nil } if err := l.writeHeader(h.streamID, h.endStream, h.hf, h.onWrite); err != nil { return err } return l.cleanupStreamHandler(h.cleanup) } // Case 2: Client wants to originate stream. str := &outStream{ id: h.streamID, state: empty, itl: &itemList{}, wq: h.wq, } return l.originateStream(str, h) } func (l *loopyWriter) originateStream(str *outStream, hdr *headerFrame) error { // l.draining is set when handling GoAway. In which case, we want to avoid // creating new streams. if l.draining { // TODO: provide a better error with the reason we are in draining. hdr.onOrphaned(errStreamDrain) return nil } if err := hdr.initStream(str.id); err != nil { return err } if err := l.writeHeader(str.id, hdr.endStream, hdr.hf, hdr.onWrite); err != nil { return err } l.estdStreams[str.id] = str return nil } func (l *loopyWriter) writeHeader(streamID uint32, endStream bool, hf []hpack.HeaderField, onWrite func()) error { if onWrite != nil { onWrite() } l.hBuf.Reset() for _, f := range hf { if err := l.hEnc.WriteField(f); err != nil { if l.logger.V(logLevel) { l.logger.Warningf("Encountered error while encoding headers: %v", err) } } } var ( err error endHeaders, first bool ) first = true for !endHeaders { size := l.hBuf.Len() if size > http2MaxFrameLen { size = http2MaxFrameLen } else { endHeaders = true } if first { first = false err = l.framer.fr.WriteHeaders(http2.HeadersFrameParam{ StreamID: streamID, BlockFragment: l.hBuf.Next(size), EndStream: endStream, EndHeaders: endHeaders, }) } else { err = l.framer.fr.WriteContinuation( streamID, endHeaders, l.hBuf.Next(size), ) } if err != nil { return err } } return nil } func (l *loopyWriter) preprocessData(df *dataFrame) { str, ok := l.estdStreams[df.streamID] if !ok { return } // If we got data for a stream it means that // stream was originated and the headers were sent out. str.itl.enqueue(df) if str.state == empty { str.state = active l.activeStreams.enqueue(str) } } func (l *loopyWriter) pingHandler(p *ping) error { if !p.ack { l.bdpEst.timesnap(p.data) } return l.framer.fr.WritePing(p.ack, p.data) } func (l *loopyWriter) outFlowControlSizeRequestHandler(o *outFlowControlSizeRequest) { o.resp <- l.sendQuota } func (l *loopyWriter) cleanupStreamHandler(c *cleanupStream) error { c.onWrite() if str, ok := l.estdStreams[c.streamID]; ok { // On the server side it could be a trailers-only response or // a RST_STREAM before stream initialization thus the stream might // not be established yet. delete(l.estdStreams, c.streamID) str.deleteSelf() for head := str.itl.dequeueAll(); head != nil; head = head.next { if df, ok := head.it.(*dataFrame); ok { _ = df.reader.Close() } } } if c.rst { // If RST_STREAM needs to be sent. if err := l.framer.fr.WriteRSTStream(c.streamID, c.rstCode); err != nil { return err } } if l.draining && len(l.estdStreams) == 0 { // Flush and close the connection; we are done with it. return errors.New("finished processing active streams while in draining mode") } return nil } func (l *loopyWriter) earlyAbortStreamHandler(eas *earlyAbortStream) error { if l.side == clientSide { return errors.New("earlyAbortStream not handled on client") } // In case the caller forgets to set the http status, default to 200. if eas.httpStatus == 0 { eas.httpStatus = 200 } headerFields := []hpack.HeaderField{ {Name: ":status", Value: strconv.Itoa(int(eas.httpStatus))}, {Name: "content-type", Value: grpcutil.ContentType(eas.contentSubtype)}, {Name: "grpc-status", Value: strconv.Itoa(int(eas.status.Code()))}, {Name: "grpc-message", Value: encodeGrpcMessage(eas.status.Message())}, } if err := l.writeHeader(eas.streamID, true, headerFields, nil); err != nil { return err } if eas.rst { if err := l.framer.fr.WriteRSTStream(eas.streamID, http2.ErrCodeNo); err != nil { return err } } return nil } func (l *loopyWriter) incomingGoAwayHandler(*incomingGoAway) error { if l.side == clientSide { l.draining = true if len(l.estdStreams) == 0 { // Flush and close the connection; we are done with it. return errors.New("received GOAWAY with no active streams") } } return nil } func (l *loopyWriter) goAwayHandler(g *goAway) error { // Handling of outgoing GoAway is very specific to side. if l.ssGoAwayHandler != nil { draining, err := l.ssGoAwayHandler(g) if err != nil { return err } l.draining = draining } return nil } func (l *loopyWriter) handle(i any) error { switch i := i.(type) { case *incomingWindowUpdate: l.incomingWindowUpdateHandler(i) case *outgoingWindowUpdate: return l.outgoingWindowUpdateHandler(i) case *incomingSettings: return l.incomingSettingsHandler(i) case *outgoingSettings: return l.outgoingSettingsHandler(i) case *headerFrame: return l.headerHandler(i) case *registerStream: l.registerStreamHandler(i) case *cleanupStream: return l.cleanupStreamHandler(i) case *earlyAbortStream: return l.earlyAbortStreamHandler(i) case *incomingGoAway: return l.incomingGoAwayHandler(i) case *dataFrame: l.preprocessData(i) case *ping: return l.pingHandler(i) case *goAway: return l.goAwayHandler(i) case *outFlowControlSizeRequest: l.outFlowControlSizeRequestHandler(i) case closeConnection: // Just return a non-I/O error and run() will flush and close the // connection. return ErrConnClosing default: return fmt.Errorf("transport: unknown control message type %T", i) } return nil } func (l *loopyWriter) applySettings(ss []http2.Setting) { for _, s := range ss { switch s.ID { case http2.SettingInitialWindowSize: o := l.oiws l.oiws = s.Val if o < l.oiws { // If the new limit is greater make all depleted streams active. for _, stream := range l.estdStreams { if stream.state == waitingOnStreamQuota { stream.state = active l.activeStreams.enqueue(stream) } } } case http2.SettingHeaderTableSize: updateHeaderTblSize(l.hEnc, s.Val) } } } // processData removes the first stream from active streams, writes out at most 16KB // of its data and then puts it at the end of activeStreams if there's still more data // to be sent and stream has some stream-level flow control. func (l *loopyWriter) processData() (bool, error) { if l.sendQuota == 0 { return true, nil } str := l.activeStreams.dequeue() // Remove the first stream. if str == nil { return true, nil } dataItem := str.itl.peek().(*dataFrame) // Peek at the first data item this stream. // A data item is represented by a dataFrame, since it later translates into // multiple HTTP2 data frames. // Every dataFrame has two buffers; h that keeps grpc-message header and data // that is the actual message. As an optimization to keep wire traffic low, data // from data is copied to h to make as big as the maximum possible HTTP2 frame // size. if len(dataItem.h) == 0 && dataItem.reader.Remaining() == 0 { // Empty data frame // Client sends out empty data frame with endStream = true if err := l.framer.fr.WriteData(dataItem.streamID, dataItem.endStream, nil); err != nil { return false, err } str.itl.dequeue() // remove the empty data item from stream _ = dataItem.reader.Close() if str.itl.isEmpty() { str.state = empty } else if trailer, ok := str.itl.peek().(*headerFrame); ok { // the next item is trailers. if err := l.writeHeader(trailer.streamID, trailer.endStream, trailer.hf, trailer.onWrite); err != nil { return false, err } if err := l.cleanupStreamHandler(trailer.cleanup); err != nil { return false, err } } else { l.activeStreams.enqueue(str) } return false, nil } // Figure out the maximum size we can send maxSize := http2MaxFrameLen if strQuota := int(l.oiws) - str.bytesOutStanding; strQuota <= 0 { // stream-level flow control. str.state = waitingOnStreamQuota return false, nil } else if maxSize > strQuota { maxSize = strQuota } if maxSize > int(l.sendQuota) { // connection-level flow control. maxSize = int(l.sendQuota) } // Compute how much of the header and data we can send within quota and max frame length hSize := min(maxSize, len(dataItem.h)) dSize := min(maxSize-hSize, dataItem.reader.Remaining()) remainingBytes := len(dataItem.h) + dataItem.reader.Remaining() - hSize - dSize size := hSize + dSize var buf *[]byte if hSize != 0 && dSize == 0 { buf = &dataItem.h } else { // Note: this is only necessary because the http2.Framer does not support // partially writing a frame, so the sequence must be materialized into a buffer. // TODO: Revisit once https://github.com/golang/go/issues/66655 is addressed. pool := l.bufferPool if pool == nil { // Note that this is only supposed to be nil in tests. Otherwise, stream is // always initialized with a BufferPool. pool = mem.DefaultBufferPool() } buf = pool.Get(size) defer pool.Put(buf) copy((*buf)[:hSize], dataItem.h) _, _ = dataItem.reader.Read((*buf)[hSize:]) } // Now that outgoing flow controls are checked we can replenish str's write quota str.wq.replenish(size) var endStream bool // If this is the last data message on this stream and all of it can be written in this iteration. if dataItem.endStream && remainingBytes == 0 { endStream = true } if dataItem.onEachWrite != nil { dataItem.onEachWrite() } if err := l.framer.fr.WriteData(dataItem.streamID, endStream, (*buf)[:size]); err != nil { return false, err } str.bytesOutStanding += size l.sendQuota -= uint32(size) dataItem.h = dataItem.h[hSize:] if remainingBytes == 0 { // All the data from that message was written out. _ = dataItem.reader.Close() str.itl.dequeue() } if str.itl.isEmpty() { str.state = empty } else if trailer, ok := str.itl.peek().(*headerFrame); ok { // The next item is trailers. if err := l.writeHeader(trailer.streamID, trailer.endStream, trailer.hf, trailer.onWrite); err != nil { return false, err } if err := l.cleanupStreamHandler(trailer.cleanup); err != nil { return false, err } } else if int(l.oiws)-str.bytesOutStanding <= 0 { // Ran out of stream quota. str.state = waitingOnStreamQuota } else { // Otherwise add it back to the list of active streams. l.activeStreams.enqueue(str) } return false, nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/transport/handler_server.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/transport/handler_server.go
/* * * Copyright 2016 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. * */ // This file is the implementation of a gRPC server using HTTP/2 which // uses the standard Go http2 Server implementation (via the // http.Handler interface), rather than speaking low-level HTTP/2 // frames itself. It is the implementation of *grpc.Server.ServeHTTP. package transport import ( "context" "errors" "fmt" "io" "net" "net/http" "strings" "sync" "time" "golang.org/x/net/http2" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" "google.golang.org/grpc/internal/grpclog" "google.golang.org/grpc/internal/grpcutil" "google.golang.org/grpc/mem" "google.golang.org/grpc/metadata" "google.golang.org/grpc/peer" "google.golang.org/grpc/stats" "google.golang.org/grpc/status" "google.golang.org/protobuf/proto" ) // NewServerHandlerTransport returns a ServerTransport handling gRPC from // inside an http.Handler, or writes an HTTP error to w and returns an error. // It requires that the http Server supports HTTP/2. func NewServerHandlerTransport(w http.ResponseWriter, r *http.Request, stats []stats.Handler, bufferPool mem.BufferPool) (ServerTransport, error) { if r.Method != http.MethodPost { w.Header().Set("Allow", http.MethodPost) msg := fmt.Sprintf("invalid gRPC request method %q", r.Method) http.Error(w, msg, http.StatusMethodNotAllowed) return nil, errors.New(msg) } contentType := r.Header.Get("Content-Type") // TODO: do we assume contentType is lowercase? we did before contentSubtype, validContentType := grpcutil.ContentSubtype(contentType) if !validContentType { msg := fmt.Sprintf("invalid gRPC request content-type %q", contentType) http.Error(w, msg, http.StatusUnsupportedMediaType) return nil, errors.New(msg) } if r.ProtoMajor != 2 { msg := "gRPC requires HTTP/2" http.Error(w, msg, http.StatusHTTPVersionNotSupported) return nil, errors.New(msg) } if _, ok := w.(http.Flusher); !ok { msg := "gRPC requires a ResponseWriter supporting http.Flusher" http.Error(w, msg, http.StatusInternalServerError) return nil, errors.New(msg) } var localAddr net.Addr if la := r.Context().Value(http.LocalAddrContextKey); la != nil { localAddr, _ = la.(net.Addr) } var authInfo credentials.AuthInfo if r.TLS != nil { authInfo = credentials.TLSInfo{State: *r.TLS, CommonAuthInfo: credentials.CommonAuthInfo{SecurityLevel: credentials.PrivacyAndIntegrity}} } p := peer.Peer{ Addr: strAddr(r.RemoteAddr), LocalAddr: localAddr, AuthInfo: authInfo, } st := &serverHandlerTransport{ rw: w, req: r, closedCh: make(chan struct{}), writes: make(chan func()), peer: p, contentType: contentType, contentSubtype: contentSubtype, stats: stats, bufferPool: bufferPool, } st.logger = prefixLoggerForServerHandlerTransport(st) if v := r.Header.Get("grpc-timeout"); v != "" { to, err := decodeTimeout(v) if err != nil { msg := fmt.Sprintf("malformed grpc-timeout: %v", err) http.Error(w, msg, http.StatusBadRequest) return nil, status.Error(codes.Internal, msg) } st.timeoutSet = true st.timeout = to } metakv := []string{"content-type", contentType} if r.Host != "" { metakv = append(metakv, ":authority", r.Host) } for k, vv := range r.Header { k = strings.ToLower(k) if isReservedHeader(k) && !isWhitelistedHeader(k) { continue } for _, v := range vv { v, err := decodeMetadataHeader(k, v) if err != nil { msg := fmt.Sprintf("malformed binary metadata %q in header %q: %v", v, k, err) http.Error(w, msg, http.StatusBadRequest) return nil, status.Error(codes.Internal, msg) } metakv = append(metakv, k, v) } } st.headerMD = metadata.Pairs(metakv...) return st, nil } // serverHandlerTransport is an implementation of ServerTransport // which replies to exactly one gRPC request (exactly one HTTP request), // using the net/http.Handler interface. This http.Handler is guaranteed // at this point to be speaking over HTTP/2, so it's able to speak valid // gRPC. type serverHandlerTransport struct { rw http.ResponseWriter req *http.Request timeoutSet bool timeout time.Duration headerMD metadata.MD peer peer.Peer closeOnce sync.Once closedCh chan struct{} // closed on Close // writes is a channel of code to run serialized in the // ServeHTTP (HandleStreams) goroutine. The channel is closed // when WriteStatus is called. writes chan func() // block concurrent WriteStatus calls // e.g. grpc/(*serverStream).SendMsg/RecvMsg writeStatusMu sync.Mutex // we just mirror the request content-type contentType string // we store both contentType and contentSubtype so we don't keep recreating them // TODO make sure this is consistent across handler_server and http2_server contentSubtype string stats []stats.Handler logger *grpclog.PrefixLogger bufferPool mem.BufferPool } func (ht *serverHandlerTransport) Close(err error) { ht.closeOnce.Do(func() { if ht.logger.V(logLevel) { ht.logger.Infof("Closing: %v", err) } close(ht.closedCh) }) } func (ht *serverHandlerTransport) Peer() *peer.Peer { return &peer.Peer{ Addr: ht.peer.Addr, LocalAddr: ht.peer.LocalAddr, AuthInfo: ht.peer.AuthInfo, } } // strAddr is a net.Addr backed by either a TCP "ip:port" string, or // the empty string if unknown. type strAddr string func (a strAddr) Network() string { if a != "" { // Per the documentation on net/http.Request.RemoteAddr, if this is // set, it's set to the IP:port of the peer (hence, TCP): // https://golang.org/pkg/net/http/#Request // // If we want to support Unix sockets later, we can // add our own grpc-specific convention within the // grpc codebase to set RemoteAddr to a different // format, or probably better: we can attach it to the // context and use that from serverHandlerTransport.RemoteAddr. return "tcp" } return "" } func (a strAddr) String() string { return string(a) } // do runs fn in the ServeHTTP goroutine. func (ht *serverHandlerTransport) do(fn func()) error { select { case <-ht.closedCh: return ErrConnClosing case ht.writes <- fn: return nil } } func (ht *serverHandlerTransport) writeStatus(s *ServerStream, st *status.Status) error { ht.writeStatusMu.Lock() defer ht.writeStatusMu.Unlock() headersWritten := s.updateHeaderSent() err := ht.do(func() { if !headersWritten { ht.writePendingHeaders(s) } // And flush, in case no header or body has been sent yet. // This forces a separation of headers and trailers if this is the // first call (for example, in end2end tests's TestNoService). ht.rw.(http.Flusher).Flush() h := ht.rw.Header() h.Set("Grpc-Status", fmt.Sprintf("%d", st.Code())) if m := st.Message(); m != "" { h.Set("Grpc-Message", encodeGrpcMessage(m)) } s.hdrMu.Lock() defer s.hdrMu.Unlock() if p := st.Proto(); p != nil && len(p.Details) > 0 { delete(s.trailer, grpcStatusDetailsBinHeader) stBytes, err := proto.Marshal(p) if err != nil { // TODO: return error instead, when callers are able to handle it. panic(err) } h.Set(grpcStatusDetailsBinHeader, encodeBinHeader(stBytes)) } if len(s.trailer) > 0 { for k, vv := range s.trailer { // Clients don't tolerate reading restricted headers after some non restricted ones were sent. if isReservedHeader(k) { continue } for _, v := range vv { // http2 ResponseWriter mechanism to send undeclared Trailers after // the headers have possibly been written. h.Add(http2.TrailerPrefix+k, encodeMetadataHeader(k, v)) } } } }) if err == nil { // transport has not been closed // Note: The trailer fields are compressed with hpack after this call returns. // No WireLength field is set here. for _, sh := range ht.stats { sh.HandleRPC(s.Context(), &stats.OutTrailer{ Trailer: s.trailer.Copy(), }) } } ht.Close(errors.New("finished writing status")) return err } // writePendingHeaders sets common and custom headers on the first // write call (Write, WriteHeader, or WriteStatus) func (ht *serverHandlerTransport) writePendingHeaders(s *ServerStream) { ht.writeCommonHeaders(s) ht.writeCustomHeaders(s) } // writeCommonHeaders sets common headers on the first write // call (Write, WriteHeader, or WriteStatus). func (ht *serverHandlerTransport) writeCommonHeaders(s *ServerStream) { h := ht.rw.Header() h["Date"] = nil // suppress Date to make tests happy; TODO: restore h.Set("Content-Type", ht.contentType) // Predeclare trailers we'll set later in WriteStatus (after the body). // This is a SHOULD in the HTTP RFC, and the way you add (known) // Trailers per the net/http.ResponseWriter contract. // See https://golang.org/pkg/net/http/#ResponseWriter // and https://golang.org/pkg/net/http/#example_ResponseWriter_trailers h.Add("Trailer", "Grpc-Status") h.Add("Trailer", "Grpc-Message") h.Add("Trailer", "Grpc-Status-Details-Bin") if s.sendCompress != "" { h.Set("Grpc-Encoding", s.sendCompress) } } // writeCustomHeaders sets custom headers set on the stream via SetHeader // on the first write call (Write, WriteHeader, or WriteStatus) func (ht *serverHandlerTransport) writeCustomHeaders(s *ServerStream) { h := ht.rw.Header() s.hdrMu.Lock() for k, vv := range s.header { if isReservedHeader(k) { continue } for _, v := range vv { h.Add(k, encodeMetadataHeader(k, v)) } } s.hdrMu.Unlock() } func (ht *serverHandlerTransport) write(s *ServerStream, hdr []byte, data mem.BufferSlice, _ *WriteOptions) error { // Always take a reference because otherwise there is no guarantee the data will // be available after this function returns. This is what callers to Write // expect. data.Ref() headersWritten := s.updateHeaderSent() err := ht.do(func() { defer data.Free() if !headersWritten { ht.writePendingHeaders(s) } ht.rw.Write(hdr) for _, b := range data { _, _ = ht.rw.Write(b.ReadOnlyData()) } ht.rw.(http.Flusher).Flush() }) if err != nil { data.Free() return err } return nil } func (ht *serverHandlerTransport) writeHeader(s *ServerStream, md metadata.MD) error { if err := s.SetHeader(md); err != nil { return err } headersWritten := s.updateHeaderSent() err := ht.do(func() { if !headersWritten { ht.writePendingHeaders(s) } ht.rw.WriteHeader(200) ht.rw.(http.Flusher).Flush() }) if err == nil { for _, sh := range ht.stats { // Note: The header fields are compressed with hpack after this call returns. // No WireLength field is set here. sh.HandleRPC(s.Context(), &stats.OutHeader{ Header: md.Copy(), Compression: s.sendCompress, }) } } return err } func (ht *serverHandlerTransport) HandleStreams(ctx context.Context, startStream func(*ServerStream)) { // With this transport type there will be exactly 1 stream: this HTTP request. var cancel context.CancelFunc if ht.timeoutSet { ctx, cancel = context.WithTimeout(ctx, ht.timeout) } else { ctx, cancel = context.WithCancel(ctx) } // requestOver is closed when the status has been written via WriteStatus. requestOver := make(chan struct{}) go func() { select { case <-requestOver: case <-ht.closedCh: case <-ht.req.Context().Done(): } cancel() ht.Close(errors.New("request is done processing")) }() ctx = metadata.NewIncomingContext(ctx, ht.headerMD) req := ht.req s := &ServerStream{ Stream: &Stream{ id: 0, // irrelevant ctx: ctx, requestRead: func(int) {}, buf: newRecvBuffer(), method: req.URL.Path, recvCompress: req.Header.Get("grpc-encoding"), contentSubtype: ht.contentSubtype, }, cancel: cancel, st: ht, headerWireLength: 0, // won't have access to header wire length until golang/go#18997. } s.trReader = &transportReader{ reader: &recvBufferReader{ctx: s.ctx, ctxDone: s.ctx.Done(), recv: s.buf}, windowHandler: func(int) {}, } // readerDone is closed when the Body.Read-ing goroutine exits. readerDone := make(chan struct{}) go func() { defer close(readerDone) for { buf := ht.bufferPool.Get(http2MaxFrameLen) n, err := req.Body.Read(*buf) if n > 0 { *buf = (*buf)[:n] s.buf.put(recvMsg{buffer: mem.NewBuffer(buf, ht.bufferPool)}) } else { ht.bufferPool.Put(buf) } if err != nil { s.buf.put(recvMsg{err: mapRecvMsgError(err)}) return } } }() // startStream is provided by the *grpc.Server's serveStreams. // It starts a goroutine serving s and exits immediately. // The goroutine that is started is the one that then calls // into ht, calling WriteHeader, Write, WriteStatus, Close, etc. startStream(s) ht.runStream() close(requestOver) // Wait for reading goroutine to finish. req.Body.Close() <-readerDone } func (ht *serverHandlerTransport) runStream() { for { select { case fn := <-ht.writes: fn() case <-ht.closedCh: return } } } func (ht *serverHandlerTransport) incrMsgRecv() {} func (ht *serverHandlerTransport) Drain(string) { panic("Drain() is not implemented") } // mapRecvMsgError returns the non-nil err into the appropriate // error value as expected by callers of *grpc.parser.recvMsg. // In particular, in can only be: // - io.EOF // - io.ErrUnexpectedEOF // - of type transport.ConnectionError // - an error from the status package func mapRecvMsgError(err error) error { if err == io.EOF || err == io.ErrUnexpectedEOF { return err } if se, ok := err.(http2.StreamError); ok { if code, ok := http2ErrConvTab[se.Code]; ok { return status.Error(code, se.Error()) } } if strings.Contains(err.Error(), "body closed by handler") { return status.Error(codes.Canceled, err.Error()) } return connectionErrorf(true, err, "%s", err.Error()) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/transport/defaults.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/transport/defaults.go
/* * * Copyright 2018 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. * */ package transport import ( "math" "time" ) const ( // The default value of flow control window size in HTTP2 spec. defaultWindowSize = 65535 // The initial window size for flow control. initialWindowSize = defaultWindowSize // for an RPC infinity = time.Duration(math.MaxInt64) defaultClientKeepaliveTime = infinity defaultClientKeepaliveTimeout = 20 * time.Second defaultMaxStreamsClient = 100 defaultMaxConnectionIdle = infinity defaultMaxConnectionAge = infinity defaultMaxConnectionAgeGrace = infinity defaultServerKeepaliveTime = 2 * time.Hour defaultServerKeepaliveTimeout = 20 * time.Second defaultKeepalivePolicyMinTime = 5 * time.Minute // max window limit set by HTTP2 Specs. maxWindowSize = math.MaxInt32 // defaultWriteQuota is the default value for number of data // bytes that each stream can schedule before some of it being // flushed out. defaultWriteQuota = 64 * 1024 defaultClientMaxHeaderListSize = uint32(16 << 20) defaultServerMaxHeaderListSize = uint32(16 << 20) ) // MaxStreamID is the upper bound for the stream ID before the current // transport gracefully closes and new transport is created for subsequent RPCs. // This is set to 75% of 2^31-1. Streams are identified with an unsigned 31-bit // integer. It's exported so that tests can override it. var MaxStreamID = uint32(math.MaxInt32 * 3 / 4)
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/transport/server_stream.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/transport/server_stream.go
/* * * Copyright 2024 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. * */ package transport import ( "context" "errors" "strings" "sync" "sync/atomic" "google.golang.org/grpc/mem" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" ) // ServerStream implements streaming functionality for a gRPC server. type ServerStream struct { *Stream // Embed for common stream functionality. st internalServerTransport ctxDone <-chan struct{} // closed at the end of stream. Cache of ctx.Done() (for performance) cancel context.CancelFunc // invoked at the end of stream to cancel ctx. // Holds compressor names passed in grpc-accept-encoding metadata from the // client. clientAdvertisedCompressors string headerWireLength int // hdrMu protects outgoing header and trailer metadata. hdrMu sync.Mutex header metadata.MD // the outgoing header metadata. Updated by WriteHeader. headerSent atomic.Bool // atomically set when the headers are sent out. } // Read reads an n byte message from the input stream. func (s *ServerStream) Read(n int) (mem.BufferSlice, error) { b, err := s.Stream.read(n) if err == nil { s.st.incrMsgRecv() } return b, err } // SendHeader sends the header metadata for the given stream. func (s *ServerStream) SendHeader(md metadata.MD) error { return s.st.writeHeader(s, md) } // Write writes the hdr and data bytes to the output stream. func (s *ServerStream) Write(hdr []byte, data mem.BufferSlice, opts *WriteOptions) error { return s.st.write(s, hdr, data, opts) } // WriteStatus sends the status of a stream to the client. WriteStatus is // the final call made on a stream and always occurs. func (s *ServerStream) WriteStatus(st *status.Status) error { return s.st.writeStatus(s, st) } // isHeaderSent indicates whether headers have been sent. func (s *ServerStream) isHeaderSent() bool { return s.headerSent.Load() } // updateHeaderSent updates headerSent and returns true // if it was already set. func (s *ServerStream) updateHeaderSent() bool { return s.headerSent.Swap(true) } // RecvCompress returns the compression algorithm applied to the inbound // message. It is empty string if there is no compression applied. func (s *ServerStream) RecvCompress() string { return s.recvCompress } // SendCompress returns the send compressor name. func (s *ServerStream) SendCompress() string { return s.sendCompress } // ContentSubtype returns the content-subtype for a request. For example, a // content-subtype of "proto" will result in a content-type of // "application/grpc+proto". This will always be lowercase. See // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for // more details. func (s *ServerStream) ContentSubtype() string { return s.contentSubtype } // SetSendCompress sets the compression algorithm to the stream. func (s *ServerStream) SetSendCompress(name string) error { if s.isHeaderSent() || s.getState() == streamDone { return errors.New("transport: set send compressor called after headers sent or stream done") } s.sendCompress = name return nil } // SetContext sets the context of the stream. This will be deleted once the // stats handler callouts all move to gRPC layer. func (s *ServerStream) SetContext(ctx context.Context) { s.ctx = ctx } // ClientAdvertisedCompressors returns the compressor names advertised by the // client via grpc-accept-encoding header. func (s *ServerStream) ClientAdvertisedCompressors() []string { values := strings.Split(s.clientAdvertisedCompressors, ",") for i, v := range values { values[i] = strings.TrimSpace(v) } return values } // Header returns the header metadata of the stream. It returns the out header // after t.WriteHeader is called. It does not block and must not be called // until after WriteHeader. func (s *ServerStream) Header() (metadata.MD, error) { // Return the header in stream. It will be the out // header after t.WriteHeader is called. return s.header.Copy(), nil } // HeaderWireLength returns the size of the headers of the stream as received // from the wire. func (s *ServerStream) HeaderWireLength() int { return s.headerWireLength } // SetHeader sets the header metadata. This can be called multiple times. // This should not be called in parallel to other data writes. func (s *ServerStream) SetHeader(md metadata.MD) error { if md.Len() == 0 { return nil } if s.isHeaderSent() || s.getState() == streamDone { return ErrIllegalHeaderWrite } s.hdrMu.Lock() s.header = metadata.Join(s.header, md) s.hdrMu.Unlock() return nil } // SetTrailer sets the trailer metadata which will be sent with the RPC status // by the server. This can be called multiple times. // This should not be called parallel to other data writes. func (s *ServerStream) SetTrailer(md metadata.MD) error { if md.Len() == 0 { return nil } if s.getState() == streamDone { return ErrIllegalHeaderWrite } s.hdrMu.Lock() s.trailer = metadata.Join(s.trailer, md) s.hdrMu.Unlock() return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/transport/client_stream.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/transport/client_stream.go
/* * * Copyright 2024 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. * */ package transport import ( "sync/atomic" "golang.org/x/net/http2" "google.golang.org/grpc/mem" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" ) // ClientStream implements streaming functionality for a gRPC client. type ClientStream struct { *Stream // Embed for common stream functionality. ct *http2Client done chan struct{} // closed at the end of stream to unblock writers. doneFunc func() // invoked at the end of stream. headerChan chan struct{} // closed to indicate the end of header metadata. headerChanClosed uint32 // set when headerChan is closed. Used to avoid closing headerChan multiple times. // headerValid indicates whether a valid header was received. Only // meaningful after headerChan is closed (always call waitOnHeader() before // reading its value). headerValid bool header metadata.MD // the received header metadata noHeaders bool // set if the client never received headers (set only after the stream is done). bytesReceived atomic.Bool // indicates whether any bytes have been received on this stream unprocessed atomic.Bool // set if the server sends a refused stream or GOAWAY including this stream status *status.Status // the status error received from the server } // Read reads an n byte message from the input stream. func (s *ClientStream) Read(n int) (mem.BufferSlice, error) { b, err := s.Stream.read(n) if err == nil { s.ct.incrMsgRecv() } return b, err } // Close closes the stream and popagates err to any readers. func (s *ClientStream) Close(err error) { var ( rst bool rstCode http2.ErrCode ) if err != nil { rst = true rstCode = http2.ErrCodeCancel } s.ct.closeStream(s, err, rst, rstCode, status.Convert(err), nil, false) } // Write writes the hdr and data bytes to the output stream. func (s *ClientStream) Write(hdr []byte, data mem.BufferSlice, opts *WriteOptions) error { return s.ct.write(s, hdr, data, opts) } // BytesReceived indicates whether any bytes have been received on this stream. func (s *ClientStream) BytesReceived() bool { return s.bytesReceived.Load() } // Unprocessed indicates whether the server did not process this stream -- // i.e. it sent a refused stream or GOAWAY including this stream ID. func (s *ClientStream) Unprocessed() bool { return s.unprocessed.Load() } func (s *ClientStream) waitOnHeader() { select { case <-s.ctx.Done(): // Close the stream to prevent headers/trailers from changing after // this function returns. s.Close(ContextErr(s.ctx.Err())) // headerChan could possibly not be closed yet if closeStream raced // with operateHeaders; wait until it is closed explicitly here. <-s.headerChan case <-s.headerChan: } } // RecvCompress returns the compression algorithm applied to the inbound // message. It is empty string if there is no compression applied. func (s *ClientStream) RecvCompress() string { s.waitOnHeader() return s.recvCompress } // Done returns a channel which is closed when it receives the final status // from the server. func (s *ClientStream) Done() <-chan struct{} { return s.done } // Header returns the header metadata of the stream. Acquires the key-value // pairs of header metadata once it is available. It blocks until i) the // metadata is ready or ii) there is no header metadata or iii) the stream is // canceled/expired. func (s *ClientStream) Header() (metadata.MD, error) { s.waitOnHeader() if !s.headerValid || s.noHeaders { return nil, s.status.Err() } return s.header.Copy(), nil } // TrailersOnly blocks until a header or trailers-only frame is received and // then returns true if the stream was trailers-only. If the stream ends // before headers are received, returns true, nil. func (s *ClientStream) TrailersOnly() bool { s.waitOnHeader() return s.noHeaders } // Status returns the status received from the server. // Status can be read safely only after the stream has ended, // that is, after Done() is closed. func (s *ClientStream) Status() *status.Status { return s.status }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/transport/http2_client.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/transport/http2_client.go
/* * * Copyright 2014 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. * */ package transport import ( "context" "fmt" "io" "math" "net" "net/http" "path/filepath" "strconv" "strings" "sync" "sync/atomic" "time" "golang.org/x/net/http2" "golang.org/x/net/http2/hpack" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" "google.golang.org/grpc/internal" "google.golang.org/grpc/internal/channelz" icredentials "google.golang.org/grpc/internal/credentials" "google.golang.org/grpc/internal/grpclog" "google.golang.org/grpc/internal/grpcsync" "google.golang.org/grpc/internal/grpcutil" imetadata "google.golang.org/grpc/internal/metadata" "google.golang.org/grpc/internal/proxyattributes" istatus "google.golang.org/grpc/internal/status" isyscall "google.golang.org/grpc/internal/syscall" "google.golang.org/grpc/internal/transport/networktype" "google.golang.org/grpc/keepalive" "google.golang.org/grpc/mem" "google.golang.org/grpc/metadata" "google.golang.org/grpc/peer" "google.golang.org/grpc/resolver" "google.golang.org/grpc/stats" "google.golang.org/grpc/status" ) // clientConnectionCounter counts the number of connections a client has // initiated (equal to the number of http2Clients created). Must be accessed // atomically. var clientConnectionCounter uint64 var goAwayLoopyWriterTimeout = 5 * time.Second var metadataFromOutgoingContextRaw = internal.FromOutgoingContextRaw.(func(context.Context) (metadata.MD, [][]string, bool)) // http2Client implements the ClientTransport interface with HTTP2. type http2Client struct { lastRead int64 // Keep this field 64-bit aligned. Accessed atomically. ctx context.Context cancel context.CancelFunc ctxDone <-chan struct{} // Cache the ctx.Done() chan. userAgent string // address contains the resolver returned address for this transport. // If the `ServerName` field is set, it takes precedence over `CallHdr.Host` // passed to `NewStream`, when determining the :authority header. address resolver.Address md metadata.MD conn net.Conn // underlying communication channel loopy *loopyWriter remoteAddr net.Addr localAddr net.Addr authInfo credentials.AuthInfo // auth info about the connection readerDone chan struct{} // sync point to enable testing. writerDone chan struct{} // sync point to enable testing. // goAway is closed to notify the upper layer (i.e., addrConn.transportMonitor) // that the server sent GoAway on this transport. goAway chan struct{} keepaliveDone chan struct{} // Closed when the keepalive goroutine exits. framer *framer // controlBuf delivers all the control related tasks (e.g., window // updates, reset streams, and various settings) to the controller. // Do not access controlBuf with mu held. controlBuf *controlBuffer fc *trInFlow // The scheme used: https if TLS is on, http otherwise. scheme string isSecure bool perRPCCreds []credentials.PerRPCCredentials kp keepalive.ClientParameters keepaliveEnabled bool statsHandlers []stats.Handler initialWindowSize int32 // configured by peer through SETTINGS_MAX_HEADER_LIST_SIZE maxSendHeaderListSize *uint32 bdpEst *bdpEstimator maxConcurrentStreams uint32 streamQuota int64 streamsQuotaAvailable chan struct{} waitingStreams uint32 registeredCompressors string // Do not access controlBuf with mu held. mu sync.Mutex // guard the following variables nextID uint32 state transportState activeStreams map[uint32]*ClientStream // prevGoAway ID records the Last-Stream-ID in the previous GOAway frame. prevGoAwayID uint32 // goAwayReason records the http2.ErrCode and debug data received with the // GoAway frame. goAwayReason GoAwayReason // goAwayDebugMessage contains a detailed human readable string about a // GoAway frame, useful for error messages. goAwayDebugMessage string // A condition variable used to signal when the keepalive goroutine should // go dormant. The condition for dormancy is based on the number of active // streams and the `PermitWithoutStream` keepalive client parameter. And // since the number of active streams is guarded by the above mutex, we use // the same for this condition variable as well. kpDormancyCond *sync.Cond // A boolean to track whether the keepalive goroutine is dormant or not. // This is checked before attempting to signal the above condition // variable. kpDormant bool channelz *channelz.Socket onClose func(GoAwayReason) bufferPool mem.BufferPool connectionID uint64 logger *grpclog.PrefixLogger } func dial(ctx context.Context, fn func(context.Context, string) (net.Conn, error), addr resolver.Address, grpcUA string) (net.Conn, error) { address := addr.Addr networkType, ok := networktype.Get(addr) if fn != nil { // Special handling for unix scheme with custom dialer. Back in the day, // we did not have a unix resolver and therefore targets with a unix // scheme would end up using the passthrough resolver. So, user's used a // custom dialer in this case and expected the original dial target to // be passed to the custom dialer. Now, we have a unix resolver. But if // a custom dialer is specified, we want to retain the old behavior in // terms of the address being passed to the custom dialer. if networkType == "unix" && !strings.HasPrefix(address, "\x00") { // Supported unix targets are either "unix://absolute-path" or // "unix:relative-path". if filepath.IsAbs(address) { return fn(ctx, "unix://"+address) } return fn(ctx, "unix:"+address) } return fn(ctx, address) } if !ok { networkType, address = parseDialTarget(address) } if opts, present := proxyattributes.Get(addr); present { return proxyDial(ctx, addr, grpcUA, opts) } return internal.NetDialerWithTCPKeepalive().DialContext(ctx, networkType, address) } func isTemporary(err error) bool { switch err := err.(type) { case interface { Temporary() bool }: return err.Temporary() case interface { Timeout() bool }: // Timeouts may be resolved upon retry, and are thus treated as // temporary. return err.Timeout() } return true } // NewHTTP2Client constructs a connected ClientTransport to addr based on HTTP2 // and starts to receive messages on it. Non-nil error returns if construction // fails. func NewHTTP2Client(connectCtx, ctx context.Context, addr resolver.Address, opts ConnectOptions, onClose func(GoAwayReason)) (_ ClientTransport, err error) { scheme := "http" ctx, cancel := context.WithCancel(ctx) defer func() { if err != nil { cancel() } }() // gRPC, resolver, balancer etc. can specify arbitrary data in the // Attributes field of resolver.Address, which is shoved into connectCtx // and passed to the dialer and credential handshaker. This makes it possible for // address specific arbitrary data to reach custom dialers and credential handshakers. connectCtx = icredentials.NewClientHandshakeInfoContext(connectCtx, credentials.ClientHandshakeInfo{Attributes: addr.Attributes}) conn, err := dial(connectCtx, opts.Dialer, addr, opts.UserAgent) if err != nil { if opts.FailOnNonTempDialError { return nil, connectionErrorf(isTemporary(err), err, "transport: error while dialing: %v", err) } return nil, connectionErrorf(true, err, "transport: Error while dialing: %v", err) } // Any further errors will close the underlying connection defer func(conn net.Conn) { if err != nil { conn.Close() } }(conn) // The following defer and goroutine monitor the connectCtx for cancellation // and deadline. On context expiration, the connection is hard closed and // this function will naturally fail as a result. Otherwise, the defer // waits for the goroutine to exit to prevent the context from being // monitored (and to prevent the connection from ever being closed) after // returning from this function. ctxMonitorDone := grpcsync.NewEvent() newClientCtx, newClientDone := context.WithCancel(connectCtx) defer func() { newClientDone() // Awaken the goroutine below if connectCtx hasn't expired. <-ctxMonitorDone.Done() // Wait for the goroutine below to exit. }() go func(conn net.Conn) { defer ctxMonitorDone.Fire() // Signal this goroutine has exited. <-newClientCtx.Done() // Block until connectCtx expires or the defer above executes. if err := connectCtx.Err(); err != nil { // connectCtx expired before exiting the function. Hard close the connection. if logger.V(logLevel) { logger.Infof("Aborting due to connect deadline expiring: %v", err) } conn.Close() } }(conn) kp := opts.KeepaliveParams // Validate keepalive parameters. if kp.Time == 0 { kp.Time = defaultClientKeepaliveTime } if kp.Timeout == 0 { kp.Timeout = defaultClientKeepaliveTimeout } keepaliveEnabled := false if kp.Time != infinity { if err = isyscall.SetTCPUserTimeout(conn, kp.Timeout); err != nil { return nil, connectionErrorf(false, err, "transport: failed to set TCP_USER_TIMEOUT: %v", err) } keepaliveEnabled = true } var ( isSecure bool authInfo credentials.AuthInfo ) transportCreds := opts.TransportCredentials perRPCCreds := opts.PerRPCCredentials if b := opts.CredsBundle; b != nil { if t := b.TransportCredentials(); t != nil { transportCreds = t } if t := b.PerRPCCredentials(); t != nil { perRPCCreds = append(perRPCCreds, t) } } if transportCreds != nil { conn, authInfo, err = transportCreds.ClientHandshake(connectCtx, addr.ServerName, conn) if err != nil { return nil, connectionErrorf(isTemporary(err), err, "transport: authentication handshake failed: %v", err) } for _, cd := range perRPCCreds { if cd.RequireTransportSecurity() { if ci, ok := authInfo.(interface { GetCommonAuthInfo() credentials.CommonAuthInfo }); ok { secLevel := ci.GetCommonAuthInfo().SecurityLevel if secLevel != credentials.InvalidSecurityLevel && secLevel < credentials.PrivacyAndIntegrity { return nil, connectionErrorf(true, nil, "transport: cannot send secure credentials on an insecure connection") } } } } isSecure = true if transportCreds.Info().SecurityProtocol == "tls" { scheme = "https" } } dynamicWindow := true icwz := int32(initialWindowSize) if opts.InitialConnWindowSize >= defaultWindowSize { icwz = opts.InitialConnWindowSize dynamicWindow = false } writeBufSize := opts.WriteBufferSize readBufSize := opts.ReadBufferSize maxHeaderListSize := defaultClientMaxHeaderListSize if opts.MaxHeaderListSize != nil { maxHeaderListSize = *opts.MaxHeaderListSize } t := &http2Client{ ctx: ctx, ctxDone: ctx.Done(), // Cache Done chan. cancel: cancel, userAgent: opts.UserAgent, registeredCompressors: grpcutil.RegisteredCompressors(), address: addr, conn: conn, remoteAddr: conn.RemoteAddr(), localAddr: conn.LocalAddr(), authInfo: authInfo, readerDone: make(chan struct{}), writerDone: make(chan struct{}), goAway: make(chan struct{}), keepaliveDone: make(chan struct{}), framer: newFramer(conn, writeBufSize, readBufSize, opts.SharedWriteBuffer, maxHeaderListSize), fc: &trInFlow{limit: uint32(icwz)}, scheme: scheme, activeStreams: make(map[uint32]*ClientStream), isSecure: isSecure, perRPCCreds: perRPCCreds, kp: kp, statsHandlers: opts.StatsHandlers, initialWindowSize: initialWindowSize, nextID: 1, maxConcurrentStreams: defaultMaxStreamsClient, streamQuota: defaultMaxStreamsClient, streamsQuotaAvailable: make(chan struct{}, 1), keepaliveEnabled: keepaliveEnabled, bufferPool: opts.BufferPool, onClose: onClose, } var czSecurity credentials.ChannelzSecurityValue if au, ok := authInfo.(credentials.ChannelzSecurityInfo); ok { czSecurity = au.GetSecurityValue() } t.channelz = channelz.RegisterSocket( &channelz.Socket{ SocketType: channelz.SocketTypeNormal, Parent: opts.ChannelzParent, SocketMetrics: channelz.SocketMetrics{}, EphemeralMetrics: t.socketMetrics, LocalAddr: t.localAddr, RemoteAddr: t.remoteAddr, SocketOptions: channelz.GetSocketOption(t.conn), Security: czSecurity, }) t.logger = prefixLoggerForClientTransport(t) // Add peer information to the http2client context. t.ctx = peer.NewContext(t.ctx, t.getPeer()) if md, ok := addr.Metadata.(*metadata.MD); ok { t.md = *md } else if md := imetadata.Get(addr); md != nil { t.md = md } t.controlBuf = newControlBuffer(t.ctxDone) if opts.InitialWindowSize >= defaultWindowSize { t.initialWindowSize = opts.InitialWindowSize dynamicWindow = false } if dynamicWindow { t.bdpEst = &bdpEstimator{ bdp: initialWindowSize, updateFlowControl: t.updateFlowControl, } } for _, sh := range t.statsHandlers { t.ctx = sh.TagConn(t.ctx, &stats.ConnTagInfo{ RemoteAddr: t.remoteAddr, LocalAddr: t.localAddr, }) connBegin := &stats.ConnBegin{ Client: true, } sh.HandleConn(t.ctx, connBegin) } if t.keepaliveEnabled { t.kpDormancyCond = sync.NewCond(&t.mu) go t.keepalive() } // Start the reader goroutine for incoming messages. Each transport has a // dedicated goroutine which reads HTTP2 frames from the network. Then it // dispatches the frame to the corresponding stream entity. When the // server preface is received, readerErrCh is closed. If an error occurs // first, an error is pushed to the channel. This must be checked before // returning from this function. readerErrCh := make(chan error, 1) go t.reader(readerErrCh) defer func() { if err != nil { // writerDone should be closed since the loopy goroutine // wouldn't have started in the case this function returns an error. close(t.writerDone) t.Close(err) } }() // Send connection preface to server. n, err := t.conn.Write(clientPreface) if err != nil { err = connectionErrorf(true, err, "transport: failed to write client preface: %v", err) return nil, err } if n != len(clientPreface) { err = connectionErrorf(true, nil, "transport: preface mismatch, wrote %d bytes; want %d", n, len(clientPreface)) return nil, err } var ss []http2.Setting if t.initialWindowSize != defaultWindowSize { ss = append(ss, http2.Setting{ ID: http2.SettingInitialWindowSize, Val: uint32(t.initialWindowSize), }) } if opts.MaxHeaderListSize != nil { ss = append(ss, http2.Setting{ ID: http2.SettingMaxHeaderListSize, Val: *opts.MaxHeaderListSize, }) } err = t.framer.fr.WriteSettings(ss...) if err != nil { err = connectionErrorf(true, err, "transport: failed to write initial settings frame: %v", err) return nil, err } // Adjust the connection flow control window if needed. if delta := uint32(icwz - defaultWindowSize); delta > 0 { if err := t.framer.fr.WriteWindowUpdate(0, delta); err != nil { err = connectionErrorf(true, err, "transport: failed to write window update: %v", err) return nil, err } } t.connectionID = atomic.AddUint64(&clientConnectionCounter, 1) if err := t.framer.writer.Flush(); err != nil { return nil, err } // Block until the server preface is received successfully or an error occurs. if err = <-readerErrCh; err != nil { return nil, err } go func() { t.loopy = newLoopyWriter(clientSide, t.framer, t.controlBuf, t.bdpEst, t.conn, t.logger, t.outgoingGoAwayHandler, t.bufferPool) if err := t.loopy.run(); !isIOError(err) { // Immediately close the connection, as the loopy writer returns // when there are no more active streams and we were draining (the // server sent a GOAWAY). For I/O errors, the reader will hit it // after draining any remaining incoming data. t.conn.Close() } close(t.writerDone) }() return t, nil } func (t *http2Client) newStream(ctx context.Context, callHdr *CallHdr) *ClientStream { // TODO(zhaoq): Handle uint32 overflow of Stream.id. s := &ClientStream{ Stream: &Stream{ method: callHdr.Method, sendCompress: callHdr.SendCompress, buf: newRecvBuffer(), contentSubtype: callHdr.ContentSubtype, }, ct: t, done: make(chan struct{}), headerChan: make(chan struct{}), doneFunc: callHdr.DoneFunc, } s.wq = newWriteQuota(defaultWriteQuota, s.done) s.requestRead = func(n int) { t.adjustWindow(s, uint32(n)) } // The client side stream context should have exactly the same life cycle with the user provided context. // That means, s.ctx should be read-only. And s.ctx is done iff ctx is done. // So we use the original context here instead of creating a copy. s.ctx = ctx s.trReader = &transportReader{ reader: &recvBufferReader{ ctx: s.ctx, ctxDone: s.ctx.Done(), recv: s.buf, closeStream: func(err error) { s.Close(err) }, }, windowHandler: func(n int) { t.updateWindow(s, uint32(n)) }, } return s } func (t *http2Client) getPeer() *peer.Peer { return &peer.Peer{ Addr: t.remoteAddr, AuthInfo: t.authInfo, // Can be nil LocalAddr: t.localAddr, } } // OutgoingGoAwayHandler writes a GOAWAY to the connection. Always returns (false, err) as we want the GoAway // to be the last frame loopy writes to the transport. func (t *http2Client) outgoingGoAwayHandler(g *goAway) (bool, error) { t.mu.Lock() maxStreamID := t.nextID - 2 t.mu.Unlock() if err := t.framer.fr.WriteGoAway(maxStreamID, http2.ErrCodeNo, g.debugData); err != nil { return false, err } return false, g.closeConn } func (t *http2Client) createHeaderFields(ctx context.Context, callHdr *CallHdr) ([]hpack.HeaderField, error) { aud := t.createAudience(callHdr) ri := credentials.RequestInfo{ Method: callHdr.Method, AuthInfo: t.authInfo, } ctxWithRequestInfo := icredentials.NewRequestInfoContext(ctx, ri) authData, err := t.getTrAuthData(ctxWithRequestInfo, aud) if err != nil { return nil, err } callAuthData, err := t.getCallAuthData(ctxWithRequestInfo, aud, callHdr) if err != nil { return nil, err } // TODO(mmukhi): Benchmark if the performance gets better if count the metadata and other header fields // first and create a slice of that exact size. // Make the slice of certain predictable size to reduce allocations made by append. hfLen := 7 // :method, :scheme, :path, :authority, content-type, user-agent, te hfLen += len(authData) + len(callAuthData) headerFields := make([]hpack.HeaderField, 0, hfLen) headerFields = append(headerFields, hpack.HeaderField{Name: ":method", Value: "POST"}) headerFields = append(headerFields, hpack.HeaderField{Name: ":scheme", Value: t.scheme}) headerFields = append(headerFields, hpack.HeaderField{Name: ":path", Value: callHdr.Method}) headerFields = append(headerFields, hpack.HeaderField{Name: ":authority", Value: callHdr.Host}) headerFields = append(headerFields, hpack.HeaderField{Name: "content-type", Value: grpcutil.ContentType(callHdr.ContentSubtype)}) headerFields = append(headerFields, hpack.HeaderField{Name: "user-agent", Value: t.userAgent}) headerFields = append(headerFields, hpack.HeaderField{Name: "te", Value: "trailers"}) if callHdr.PreviousAttempts > 0 { headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-previous-rpc-attempts", Value: strconv.Itoa(callHdr.PreviousAttempts)}) } registeredCompressors := t.registeredCompressors if callHdr.SendCompress != "" { headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-encoding", Value: callHdr.SendCompress}) // Include the outgoing compressor name when compressor is not registered // via encoding.RegisterCompressor. This is possible when client uses // WithCompressor dial option. if !grpcutil.IsCompressorNameRegistered(callHdr.SendCompress) { if registeredCompressors != "" { registeredCompressors += "," } registeredCompressors += callHdr.SendCompress } } if registeredCompressors != "" { headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-accept-encoding", Value: registeredCompressors}) } if dl, ok := ctx.Deadline(); ok { // Send out timeout regardless its value. The server can detect timeout context by itself. // TODO(mmukhi): Perhaps this field should be updated when actually writing out to the wire. timeout := time.Until(dl) headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-timeout", Value: grpcutil.EncodeDuration(timeout)}) } for k, v := range authData { headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)}) } for k, v := range callAuthData { headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)}) } if md, added, ok := metadataFromOutgoingContextRaw(ctx); ok { var k string for k, vv := range md { // HTTP doesn't allow you to set pseudoheaders after non pseudoheaders were set. if isReservedHeader(k) { continue } for _, v := range vv { headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)}) } } for _, vv := range added { for i, v := range vv { if i%2 == 0 { k = strings.ToLower(v) continue } // HTTP doesn't allow you to set pseudoheaders after non pseudoheaders were set. if isReservedHeader(k) { continue } headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)}) } } } for k, vv := range t.md { if isReservedHeader(k) { continue } for _, v := range vv { headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)}) } } return headerFields, nil } func (t *http2Client) createAudience(callHdr *CallHdr) string { // Create an audience string only if needed. if len(t.perRPCCreds) == 0 && callHdr.Creds == nil { return "" } // Construct URI required to get auth request metadata. // Omit port if it is the default one. host := strings.TrimSuffix(callHdr.Host, ":443") pos := strings.LastIndex(callHdr.Method, "/") if pos == -1 { pos = len(callHdr.Method) } return "https://" + host + callHdr.Method[:pos] } func (t *http2Client) getTrAuthData(ctx context.Context, audience string) (map[string]string, error) { if len(t.perRPCCreds) == 0 { return nil, nil } authData := map[string]string{} for _, c := range t.perRPCCreds { data, err := c.GetRequestMetadata(ctx, audience) if err != nil { if st, ok := status.FromError(err); ok { // Restrict the code to the list allowed by gRFC A54. if istatus.IsRestrictedControlPlaneCode(st) { err = status.Errorf(codes.Internal, "transport: received per-RPC creds error with illegal status: %v", err) } return nil, err } return nil, status.Errorf(codes.Unauthenticated, "transport: per-RPC creds failed due to error: %v", err) } for k, v := range data { // Capital header names are illegal in HTTP/2. k = strings.ToLower(k) authData[k] = v } } return authData, nil } func (t *http2Client) getCallAuthData(ctx context.Context, audience string, callHdr *CallHdr) (map[string]string, error) { var callAuthData map[string]string // Check if credentials.PerRPCCredentials were provided via call options. // Note: if these credentials are provided both via dial options and call // options, then both sets of credentials will be applied. if callCreds := callHdr.Creds; callCreds != nil { if callCreds.RequireTransportSecurity() { ri, _ := credentials.RequestInfoFromContext(ctx) if !t.isSecure || credentials.CheckSecurityLevel(ri.AuthInfo, credentials.PrivacyAndIntegrity) != nil { return nil, status.Error(codes.Unauthenticated, "transport: cannot send secure credentials on an insecure connection") } } data, err := callCreds.GetRequestMetadata(ctx, audience) if err != nil { if st, ok := status.FromError(err); ok { // Restrict the code to the list allowed by gRFC A54. if istatus.IsRestrictedControlPlaneCode(st) { err = status.Errorf(codes.Internal, "transport: received per-RPC creds error with illegal status: %v", err) } return nil, err } return nil, status.Errorf(codes.Internal, "transport: per-RPC creds failed due to error: %v", err) } callAuthData = make(map[string]string, len(data)) for k, v := range data { // Capital header names are illegal in HTTP/2 k = strings.ToLower(k) callAuthData[k] = v } } return callAuthData, nil } // NewStreamError wraps an error and reports additional information. Typically // NewStream errors result in transparent retry, as they mean nothing went onto // the wire. However, there are two notable exceptions: // // 1. If the stream headers violate the max header list size allowed by the // server. It's possible this could succeed on another transport, even if // it's unlikely, but do not transparently retry. // 2. If the credentials errored when requesting their headers. In this case, // it's possible a retry can fix the problem, but indefinitely transparently // retrying is not appropriate as it is likely the credentials, if they can // eventually succeed, would need I/O to do so. type NewStreamError struct { Err error AllowTransparentRetry bool } func (e NewStreamError) Error() string { return e.Err.Error() } // NewStream creates a stream and registers it into the transport as "active" // streams. All non-nil errors returned will be *NewStreamError. func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr) (*ClientStream, error) { ctx = peer.NewContext(ctx, t.getPeer()) // ServerName field of the resolver returned address takes precedence over // Host field of CallHdr to determine the :authority header. This is because, // the ServerName field takes precedence for server authentication during // TLS handshake, and the :authority header should match the value used // for server authentication. if t.address.ServerName != "" { newCallHdr := *callHdr newCallHdr.Host = t.address.ServerName callHdr = &newCallHdr } headerFields, err := t.createHeaderFields(ctx, callHdr) if err != nil { return nil, &NewStreamError{Err: err, AllowTransparentRetry: false} } s := t.newStream(ctx, callHdr) cleanup := func(err error) { if s.swapState(streamDone) == streamDone { // If it was already done, return. return } // The stream was unprocessed by the server. s.unprocessed.Store(true) s.write(recvMsg{err: err}) close(s.done) // If headerChan isn't closed, then close it. if atomic.CompareAndSwapUint32(&s.headerChanClosed, 0, 1) { close(s.headerChan) } } hdr := &headerFrame{ hf: headerFields, endStream: false, initStream: func(uint32) error { t.mu.Lock() // TODO: handle transport closure in loopy instead and remove this // initStream is never called when transport is draining. if t.state == closing { t.mu.Unlock() cleanup(ErrConnClosing) return ErrConnClosing } if channelz.IsOn() { t.channelz.SocketMetrics.StreamsStarted.Add(1) t.channelz.SocketMetrics.LastLocalStreamCreatedTimestamp.Store(time.Now().UnixNano()) } // If the keepalive goroutine has gone dormant, wake it up. if t.kpDormant { t.kpDormancyCond.Signal() } t.mu.Unlock() return nil }, onOrphaned: cleanup, wq: s.wq, } firstTry := true var ch chan struct{} transportDrainRequired := false checkForStreamQuota := func() bool { if t.streamQuota <= 0 { // Can go negative if server decreases it. if firstTry { t.waitingStreams++ } ch = t.streamsQuotaAvailable return false } if !firstTry { t.waitingStreams-- } t.streamQuota-- t.mu.Lock() if t.state == draining || t.activeStreams == nil { // Can be niled from Close(). t.mu.Unlock() return false // Don't create a stream if the transport is already closed. } hdr.streamID = t.nextID t.nextID += 2 // Drain client transport if nextID > MaxStreamID which signals gRPC that // the connection is closed and a new one must be created for subsequent RPCs. transportDrainRequired = t.nextID > MaxStreamID s.id = hdr.streamID s.fc = &inFlow{limit: uint32(t.initialWindowSize)} t.activeStreams[s.id] = s t.mu.Unlock() if t.streamQuota > 0 && t.waitingStreams > 0 { select { case t.streamsQuotaAvailable <- struct{}{}: default: } } return true } var hdrListSizeErr error checkForHeaderListSize := func() bool { if t.maxSendHeaderListSize == nil { return true } var sz int64 for _, f := range hdr.hf { if sz += int64(f.Size()); sz > int64(*t.maxSendHeaderListSize) { hdrListSizeErr = status.Errorf(codes.Internal, "header list size to send violates the maximum size (%d bytes) set by server", *t.maxSendHeaderListSize) return false } } return true } for { success, err := t.controlBuf.executeAndPut(func() bool { return checkForHeaderListSize() && checkForStreamQuota() }, hdr) if err != nil { // Connection closed. return nil, &NewStreamError{Err: err, AllowTransparentRetry: true} } if success { break } if hdrListSizeErr != nil { return nil, &NewStreamError{Err: hdrListSizeErr} } firstTry = false select { case <-ch: case <-ctx.Done(): return nil, &NewStreamError{Err: ContextErr(ctx.Err())} case <-t.goAway: return nil, &NewStreamError{Err: errStreamDrain, AllowTransparentRetry: true} case <-t.ctx.Done(): return nil, &NewStreamError{Err: ErrConnClosing, AllowTransparentRetry: true} } } if len(t.statsHandlers) != 0 { header, ok := metadata.FromOutgoingContext(ctx) if ok { header.Set("user-agent", t.userAgent) } else { header = metadata.Pairs("user-agent", t.userAgent) } for _, sh := range t.statsHandlers { // Note: The header fields are compressed with hpack after this call returns. // No WireLength field is set here. // Note: Creating a new stats object to prevent pollution. outHeader := &stats.OutHeader{ Client: true, FullMethod: callHdr.Method, RemoteAddr: t.remoteAddr, LocalAddr: t.localAddr, Compression: callHdr.SendCompress, Header: header, } sh.HandleRPC(s.ctx, outHeader) } } if transportDrainRequired { if t.logger.V(logLevel) { t.logger.Infof("Draining transport: t.nextID > MaxStreamID") } t.GracefulClose() } return s, nil } func (t *http2Client) closeStream(s *ClientStream, err error, rst bool, rstCode http2.ErrCode, st *status.Status, mdata map[string][]string, eosReceived bool) { // Set stream status to done. if s.swapState(streamDone) == streamDone { // If it was already done, return. If multiple closeStream calls // happen simultaneously, wait for the first to finish. <-s.done return } // status and trailers can be updated here without any synchronization because the stream goroutine will // only read it after it sees an io.EOF error from read or write and we'll write those errors // only after updating this. s.status = st if len(mdata) > 0 { s.trailer = mdata } if err != nil { // This will unblock reads eventually. s.write(recvMsg{err: err}) } // If headerChan isn't closed, then close it. if atomic.CompareAndSwapUint32(&s.headerChanClosed, 0, 1) { s.noHeaders = true close(s.headerChan) } cleanup := &cleanupStream{ streamID: s.id, onWrite: func() { t.mu.Lock() if t.activeStreams != nil { delete(t.activeStreams, s.id) } t.mu.Unlock() if channelz.IsOn() { if eosReceived { t.channelz.SocketMetrics.StreamsSucceeded.Add(1) } else { t.channelz.SocketMetrics.StreamsFailed.Add(1) } } }, rst: rst, rstCode: rstCode, } addBackStreamQuota := func() bool { t.streamQuota++ if t.streamQuota > 0 && t.waitingStreams > 0 { select { case t.streamsQuotaAvailable <- struct{}{}: default: } } return true }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
true
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/transport/transport.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/transport/transport.go
/* * * Copyright 2014 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. * */ // Package transport defines and implements message oriented communication // channel to complete various transactions (e.g., an RPC). It is meant for // grpc-internal usage and is not intended to be imported directly by users. package transport import ( "context" "errors" "fmt" "io" "net" "sync" "sync/atomic" "time" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" "google.golang.org/grpc/internal/channelz" "google.golang.org/grpc/keepalive" "google.golang.org/grpc/mem" "google.golang.org/grpc/metadata" "google.golang.org/grpc/peer" "google.golang.org/grpc/stats" "google.golang.org/grpc/status" "google.golang.org/grpc/tap" ) const logLevel = 2 // recvMsg represents the received msg from the transport. All transport // protocol specific info has been removed. type recvMsg struct { buffer mem.Buffer // nil: received some data // io.EOF: stream is completed. data is nil. // other non-nil error: transport failure. data is nil. err error } // recvBuffer is an unbounded channel of recvMsg structs. // // Note: recvBuffer differs from buffer.Unbounded only in the fact that it // holds a channel of recvMsg structs instead of objects implementing "item" // interface. recvBuffer is written to much more often and using strict recvMsg // structs helps avoid allocation in "recvBuffer.put" type recvBuffer struct { c chan recvMsg mu sync.Mutex backlog []recvMsg err error } func newRecvBuffer() *recvBuffer { b := &recvBuffer{ c: make(chan recvMsg, 1), } return b } func (b *recvBuffer) put(r recvMsg) { b.mu.Lock() if b.err != nil { // drop the buffer on the floor. Since b.err is not nil, any subsequent reads // will always return an error, making this buffer inaccessible. r.buffer.Free() b.mu.Unlock() // An error had occurred earlier, don't accept more // data or errors. return } b.err = r.err if len(b.backlog) == 0 { select { case b.c <- r: b.mu.Unlock() return default: } } b.backlog = append(b.backlog, r) b.mu.Unlock() } func (b *recvBuffer) load() { b.mu.Lock() if len(b.backlog) > 0 { select { case b.c <- b.backlog[0]: b.backlog[0] = recvMsg{} b.backlog = b.backlog[1:] default: } } b.mu.Unlock() } // get returns the channel that receives a recvMsg in the buffer. // // Upon receipt of a recvMsg, the caller should call load to send another // recvMsg onto the channel if there is any. func (b *recvBuffer) get() <-chan recvMsg { return b.c } // recvBufferReader implements io.Reader interface to read the data from // recvBuffer. type recvBufferReader struct { closeStream func(error) // Closes the client transport stream with the given error and nil trailer metadata. ctx context.Context ctxDone <-chan struct{} // cache of ctx.Done() (for performance). recv *recvBuffer last mem.Buffer // Stores the remaining data in the previous calls. err error } func (r *recvBufferReader) ReadMessageHeader(header []byte) (n int, err error) { if r.err != nil { return 0, r.err } if r.last != nil { n, r.last = mem.ReadUnsafe(header, r.last) return n, nil } if r.closeStream != nil { n, r.err = r.readMessageHeaderClient(header) } else { n, r.err = r.readMessageHeader(header) } return n, r.err } // Read reads the next n bytes from last. If last is drained, it tries to read // additional data from recv. It blocks if there no additional data available in // recv. If Read returns any non-nil error, it will continue to return that // error. func (r *recvBufferReader) Read(n int) (buf mem.Buffer, err error) { if r.err != nil { return nil, r.err } if r.last != nil { buf = r.last if r.last.Len() > n { buf, r.last = mem.SplitUnsafe(buf, n) } else { r.last = nil } return buf, nil } if r.closeStream != nil { buf, r.err = r.readClient(n) } else { buf, r.err = r.read(n) } return buf, r.err } func (r *recvBufferReader) readMessageHeader(header []byte) (n int, err error) { select { case <-r.ctxDone: return 0, ContextErr(r.ctx.Err()) case m := <-r.recv.get(): return r.readMessageHeaderAdditional(m, header) } } func (r *recvBufferReader) read(n int) (buf mem.Buffer, err error) { select { case <-r.ctxDone: return nil, ContextErr(r.ctx.Err()) case m := <-r.recv.get(): return r.readAdditional(m, n) } } func (r *recvBufferReader) readMessageHeaderClient(header []byte) (n int, err error) { // If the context is canceled, then closes the stream with nil metadata. // closeStream writes its error parameter to r.recv as a recvMsg. // r.readAdditional acts on that message and returns the necessary error. select { case <-r.ctxDone: // Note that this adds the ctx error to the end of recv buffer, and // reads from the head. This will delay the error until recv buffer is // empty, thus will delay ctx cancellation in Recv(). // // It's done this way to fix a race between ctx cancel and trailer. The // race was, stream.Recv() may return ctx error if ctxDone wins the // race, but stream.Trailer() may return a non-nil md because the stream // was not marked as done when trailer is received. This closeStream // call will mark stream as done, thus fix the race. // // TODO: delaying ctx error seems like a unnecessary side effect. What // we really want is to mark the stream as done, and return ctx error // faster. r.closeStream(ContextErr(r.ctx.Err())) m := <-r.recv.get() return r.readMessageHeaderAdditional(m, header) case m := <-r.recv.get(): return r.readMessageHeaderAdditional(m, header) } } func (r *recvBufferReader) readClient(n int) (buf mem.Buffer, err error) { // If the context is canceled, then closes the stream with nil metadata. // closeStream writes its error parameter to r.recv as a recvMsg. // r.readAdditional acts on that message and returns the necessary error. select { case <-r.ctxDone: // Note that this adds the ctx error to the end of recv buffer, and // reads from the head. This will delay the error until recv buffer is // empty, thus will delay ctx cancellation in Recv(). // // It's done this way to fix a race between ctx cancel and trailer. The // race was, stream.Recv() may return ctx error if ctxDone wins the // race, but stream.Trailer() may return a non-nil md because the stream // was not marked as done when trailer is received. This closeStream // call will mark stream as done, thus fix the race. // // TODO: delaying ctx error seems like a unnecessary side effect. What // we really want is to mark the stream as done, and return ctx error // faster. r.closeStream(ContextErr(r.ctx.Err())) m := <-r.recv.get() return r.readAdditional(m, n) case m := <-r.recv.get(): return r.readAdditional(m, n) } } func (r *recvBufferReader) readMessageHeaderAdditional(m recvMsg, header []byte) (n int, err error) { r.recv.load() if m.err != nil { if m.buffer != nil { m.buffer.Free() } return 0, m.err } n, r.last = mem.ReadUnsafe(header, m.buffer) return n, nil } func (r *recvBufferReader) readAdditional(m recvMsg, n int) (b mem.Buffer, err error) { r.recv.load() if m.err != nil { if m.buffer != nil { m.buffer.Free() } return nil, m.err } if m.buffer.Len() > n { m.buffer, r.last = mem.SplitUnsafe(m.buffer, n) } return m.buffer, nil } type streamState uint32 const ( streamActive streamState = iota streamWriteDone // EndStream sent streamReadDone // EndStream received streamDone // the entire stream is finished. ) // Stream represents an RPC in the transport layer. type Stream struct { id uint32 ctx context.Context // the associated context of the stream method string // the associated RPC method of the stream recvCompress string sendCompress string buf *recvBuffer trReader *transportReader fc *inFlow wq *writeQuota // Callback to state application's intentions to read data. This // is used to adjust flow control, if needed. requestRead func(int) state streamState // contentSubtype is the content-subtype for requests. // this must be lowercase or the behavior is undefined. contentSubtype string trailer metadata.MD // the key-value map of trailer metadata. } func (s *Stream) swapState(st streamState) streamState { return streamState(atomic.SwapUint32((*uint32)(&s.state), uint32(st))) } func (s *Stream) compareAndSwapState(oldState, newState streamState) bool { return atomic.CompareAndSwapUint32((*uint32)(&s.state), uint32(oldState), uint32(newState)) } func (s *Stream) getState() streamState { return streamState(atomic.LoadUint32((*uint32)(&s.state))) } // Trailer returns the cached trailer metadata. Note that if it is not called // after the entire stream is done, it could return an empty MD. // It can be safely read only after stream has ended that is either read // or write have returned io.EOF. func (s *Stream) Trailer() metadata.MD { return s.trailer.Copy() } // Context returns the context of the stream. func (s *Stream) Context() context.Context { return s.ctx } // Method returns the method for the stream. func (s *Stream) Method() string { return s.method } func (s *Stream) write(m recvMsg) { s.buf.put(m) } // ReadMessageHeader reads data into the provided header slice from the stream. // It first checks if there was an error during a previous read operation and // returns it if present. It then requests a read operation for the length of // the header. It continues to read from the stream until the entire header // slice is filled or an error occurs. If an `io.EOF` error is encountered with // partially read data, it is converted to `io.ErrUnexpectedEOF` to indicate an // unexpected end of the stream. The method returns any error encountered during // the read process or nil if the header was successfully read. func (s *Stream) ReadMessageHeader(header []byte) (err error) { // Don't request a read if there was an error earlier if er := s.trReader.er; er != nil { return er } s.requestRead(len(header)) for len(header) != 0 { n, err := s.trReader.ReadMessageHeader(header) header = header[n:] if len(header) == 0 { err = nil } if err != nil { if n > 0 && err == io.EOF { err = io.ErrUnexpectedEOF } return err } } return nil } // Read reads n bytes from the wire for this stream. func (s *Stream) read(n int) (data mem.BufferSlice, err error) { // Don't request a read if there was an error earlier if er := s.trReader.er; er != nil { return nil, er } s.requestRead(n) for n != 0 { buf, err := s.trReader.Read(n) var bufLen int if buf != nil { bufLen = buf.Len() } n -= bufLen if n == 0 { err = nil } if err != nil { if bufLen > 0 && err == io.EOF { err = io.ErrUnexpectedEOF } data.Free() return nil, err } data = append(data, buf) } return data, nil } // transportReader reads all the data available for this Stream from the transport and // passes them into the decoder, which converts them into a gRPC message stream. // The error is io.EOF when the stream is done or another non-nil error if // the stream broke. type transportReader struct { reader *recvBufferReader // The handler to control the window update procedure for both this // particular stream and the associated transport. windowHandler func(int) er error } func (t *transportReader) ReadMessageHeader(header []byte) (int, error) { n, err := t.reader.ReadMessageHeader(header) if err != nil { t.er = err return 0, err } t.windowHandler(n) return n, nil } func (t *transportReader) Read(n int) (mem.Buffer, error) { buf, err := t.reader.Read(n) if err != nil { t.er = err return buf, err } t.windowHandler(buf.Len()) return buf, nil } // GoString is implemented by Stream so context.String() won't // race when printing %#v. func (s *Stream) GoString() string { return fmt.Sprintf("<stream: %p, %v>", s, s.method) } // state of transport type transportState int const ( reachable transportState = iota closing draining ) // ServerConfig consists of all the configurations to establish a server transport. type ServerConfig struct { MaxStreams uint32 ConnectionTimeout time.Duration Credentials credentials.TransportCredentials InTapHandle tap.ServerInHandle StatsHandlers []stats.Handler KeepaliveParams keepalive.ServerParameters KeepalivePolicy keepalive.EnforcementPolicy InitialWindowSize int32 InitialConnWindowSize int32 WriteBufferSize int ReadBufferSize int SharedWriteBuffer bool ChannelzParent *channelz.Server MaxHeaderListSize *uint32 HeaderTableSize *uint32 BufferPool mem.BufferPool } // ConnectOptions covers all relevant options for communicating with the server. type ConnectOptions struct { // UserAgent is the application user agent. UserAgent string // Dialer specifies how to dial a network address. Dialer func(context.Context, string) (net.Conn, error) // FailOnNonTempDialError specifies if gRPC fails on non-temporary dial errors. FailOnNonTempDialError bool // PerRPCCredentials stores the PerRPCCredentials required to issue RPCs. PerRPCCredentials []credentials.PerRPCCredentials // TransportCredentials stores the Authenticator required to setup a client // connection. Only one of TransportCredentials and CredsBundle is non-nil. TransportCredentials credentials.TransportCredentials // CredsBundle is the credentials bundle to be used. Only one of // TransportCredentials and CredsBundle is non-nil. CredsBundle credentials.Bundle // KeepaliveParams stores the keepalive parameters. KeepaliveParams keepalive.ClientParameters // StatsHandlers stores the handler for stats. StatsHandlers []stats.Handler // InitialWindowSize sets the initial window size for a stream. InitialWindowSize int32 // InitialConnWindowSize sets the initial window size for a connection. InitialConnWindowSize int32 // WriteBufferSize sets the size of write buffer which in turn determines how much data can be batched before it's written on the wire. WriteBufferSize int // ReadBufferSize sets the size of read buffer, which in turn determines how much data can be read at most for one read syscall. ReadBufferSize int // SharedWriteBuffer indicates whether connections should reuse write buffer SharedWriteBuffer bool // ChannelzParent sets the addrConn id which initiated the creation of this client transport. ChannelzParent *channelz.SubChannel // MaxHeaderListSize sets the max (uncompressed) size of header list that is prepared to be received. MaxHeaderListSize *uint32 // The mem.BufferPool to use when reading/writing to the wire. BufferPool mem.BufferPool } // WriteOptions provides additional hints and information for message // transmission. type WriteOptions struct { // Last indicates whether this write is the last piece for // this stream. Last bool } // CallHdr carries the information of a particular RPC. type CallHdr struct { // Host specifies the peer's host. Host string // Method specifies the operation to perform. Method string // SendCompress specifies the compression algorithm applied on // outbound message. SendCompress string // Creds specifies credentials.PerRPCCredentials for a call. Creds credentials.PerRPCCredentials // ContentSubtype specifies the content-subtype for a request. For example, a // content-subtype of "proto" will result in a content-type of // "application/grpc+proto". The value of ContentSubtype must be all // lowercase, otherwise the behavior is undefined. See // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests // for more details. ContentSubtype string PreviousAttempts int // value of grpc-previous-rpc-attempts header to set DoneFunc func() // called when the stream is finished } // ClientTransport is the common interface for all gRPC client-side transport // implementations. type ClientTransport interface { // Close tears down this transport. Once it returns, the transport // should not be accessed any more. The caller must make sure this // is called only once. Close(err error) // GracefulClose starts to tear down the transport: the transport will stop // accepting new RPCs and NewStream will return error. Once all streams are // finished, the transport will close. // // It does not block. GracefulClose() // NewStream creates a Stream for an RPC. NewStream(ctx context.Context, callHdr *CallHdr) (*ClientStream, error) // Error returns a channel that is closed when some I/O error // happens. Typically the caller should have a goroutine to monitor // this in order to take action (e.g., close the current transport // and create a new one) in error case. It should not return nil // once the transport is initiated. Error() <-chan struct{} // GoAway returns a channel that is closed when ClientTransport // receives the draining signal from the server (e.g., GOAWAY frame in // HTTP/2). GoAway() <-chan struct{} // GetGoAwayReason returns the reason why GoAway frame was received, along // with a human readable string with debug info. GetGoAwayReason() (GoAwayReason, string) // RemoteAddr returns the remote network address. RemoteAddr() net.Addr } // ServerTransport is the common interface for all gRPC server-side transport // implementations. // // Methods may be called concurrently from multiple goroutines, but // Write methods for a given Stream will be called serially. type ServerTransport interface { // HandleStreams receives incoming streams using the given handler. HandleStreams(context.Context, func(*ServerStream)) // Close tears down the transport. Once it is called, the transport // should not be accessed any more. All the pending streams and their // handlers will be terminated asynchronously. Close(err error) // Peer returns the peer of the server transport. Peer() *peer.Peer // Drain notifies the client this ServerTransport stops accepting new RPCs. Drain(debugData string) } type internalServerTransport interface { ServerTransport writeHeader(s *ServerStream, md metadata.MD) error write(s *ServerStream, hdr []byte, data mem.BufferSlice, opts *WriteOptions) error writeStatus(s *ServerStream, st *status.Status) error incrMsgRecv() } // connectionErrorf creates an ConnectionError with the specified error description. func connectionErrorf(temp bool, e error, format string, a ...any) ConnectionError { return ConnectionError{ Desc: fmt.Sprintf(format, a...), temp: temp, err: e, } } // ConnectionError is an error that results in the termination of the // entire connection and the retry of all the active streams. type ConnectionError struct { Desc string temp bool err error } func (e ConnectionError) Error() string { return fmt.Sprintf("connection error: desc = %q", e.Desc) } // Temporary indicates if this connection error is temporary or fatal. func (e ConnectionError) Temporary() bool { return e.temp } // Origin returns the original error of this connection error. func (e ConnectionError) Origin() error { // Never return nil error here. // If the original error is nil, return itself. if e.err == nil { return e } return e.err } // Unwrap returns the original error of this connection error or nil when the // origin is nil. func (e ConnectionError) Unwrap() error { return e.err } var ( // ErrConnClosing indicates that the transport is closing. ErrConnClosing = connectionErrorf(true, nil, "transport is closing") // errStreamDrain indicates that the stream is rejected because the // connection is draining. This could be caused by goaway or balancer // removing the address. errStreamDrain = status.Error(codes.Unavailable, "the connection is draining") // errStreamDone is returned from write at the client side to indicate application // layer of an error. errStreamDone = errors.New("the stream is done") // StatusGoAway indicates that the server sent a GOAWAY that included this // stream's ID in unprocessed RPCs. statusGoAway = status.New(codes.Unavailable, "the stream is rejected because server is draining the connection") ) // GoAwayReason contains the reason for the GoAway frame received. type GoAwayReason uint8 const ( // GoAwayInvalid indicates that no GoAway frame is received. GoAwayInvalid GoAwayReason = 0 // GoAwayNoReason is the default value when GoAway frame is received. GoAwayNoReason GoAwayReason = 1 // GoAwayTooManyPings indicates that a GoAway frame with // ErrCodeEnhanceYourCalm was received and that the debug data said // "too_many_pings". GoAwayTooManyPings GoAwayReason = 2 ) // ContextErr converts the error from context package into a status error. func ContextErr(err error) error { switch err { case context.DeadlineExceeded: return status.Error(codes.DeadlineExceeded, err.Error()) case context.Canceled: return status.Error(codes.Canceled, err.Error()) } return status.Errorf(codes.Internal, "Unexpected error from context packet: %v", err) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/transport/bdp_estimator.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/transport/bdp_estimator.go
/* * * Copyright 2017 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. * */ package transport import ( "sync" "time" ) const ( // bdpLimit is the maximum value the flow control windows will be increased // to. TCP typically limits this to 4MB, but some systems go up to 16MB. // Since this is only a limit, it is safe to make it optimistic. bdpLimit = (1 << 20) * 16 // alpha is a constant factor used to keep a moving average // of RTTs. alpha = 0.9 // If the current bdp sample is greater than or equal to // our beta * our estimated bdp and the current bandwidth // sample is the maximum bandwidth observed so far, we // increase our bbp estimate by a factor of gamma. beta = 0.66 // To put our bdp to be smaller than or equal to twice the real BDP, // we should multiply our current sample with 4/3, however to round things out // we use 2 as the multiplication factor. gamma = 2 ) // Adding arbitrary data to ping so that its ack can be identified. // Easter-egg: what does the ping message say? var bdpPing = &ping{data: [8]byte{2, 4, 16, 16, 9, 14, 7, 7}} type bdpEstimator struct { // sentAt is the time when the ping was sent. sentAt time.Time mu sync.Mutex // bdp is the current bdp estimate. bdp uint32 // sample is the number of bytes received in one measurement cycle. sample uint32 // bwMax is the maximum bandwidth noted so far (bytes/sec). bwMax float64 // bool to keep track of the beginning of a new measurement cycle. isSent bool // Callback to update the window sizes. updateFlowControl func(n uint32) // sampleCount is the number of samples taken so far. sampleCount uint64 // round trip time (seconds) rtt float64 } // timesnap registers the time bdp ping was sent out so that // network rtt can be calculated when its ack is received. // It is called (by controller) when the bdpPing is // being written on the wire. func (b *bdpEstimator) timesnap(d [8]byte) { if bdpPing.data != d { return } b.sentAt = time.Now() } // add adds bytes to the current sample for calculating bdp. // It returns true only if a ping must be sent. This can be used // by the caller (handleData) to make decision about batching // a window update with it. func (b *bdpEstimator) add(n uint32) bool { b.mu.Lock() defer b.mu.Unlock() if b.bdp == bdpLimit { return false } if !b.isSent { b.isSent = true b.sample = n b.sentAt = time.Time{} b.sampleCount++ return true } b.sample += n return false } // calculate is called when an ack for a bdp ping is received. // Here we calculate the current bdp and bandwidth sample and // decide if the flow control windows should go up. func (b *bdpEstimator) calculate(d [8]byte) { // Check if the ping acked for was the bdp ping. if bdpPing.data != d { return } b.mu.Lock() rttSample := time.Since(b.sentAt).Seconds() if b.sampleCount < 10 { // Bootstrap rtt with an average of first 10 rtt samples. b.rtt += (rttSample - b.rtt) / float64(b.sampleCount) } else { // Heed to the recent past more. b.rtt += (rttSample - b.rtt) * float64(alpha) } b.isSent = false // The number of bytes accumulated so far in the sample is smaller // than or equal to 1.5 times the real BDP on a saturated connection. bwCurrent := float64(b.sample) / (b.rtt * float64(1.5)) if bwCurrent > b.bwMax { b.bwMax = bwCurrent } // If the current sample (which is smaller than or equal to the 1.5 times the real BDP) is // greater than or equal to 2/3rd our perceived bdp AND this is the maximum bandwidth seen so far, we // should update our perception of the network BDP. if float64(b.sample) >= beta*float64(b.bdp) && bwCurrent == b.bwMax && b.bdp != bdpLimit { sampleFloat := float64(b.sample) b.bdp = uint32(gamma * sampleFloat) if b.bdp > bdpLimit { b.bdp = bdpLimit } bdp := b.bdp b.mu.Unlock() b.updateFlowControl(bdp) return } b.mu.Unlock() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/transport/networktype/networktype.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/transport/networktype/networktype.go
/* * * Copyright 2020 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. * */ // Package networktype declares the network type to be used in the default // dialer. Attribute of a resolver.Address. package networktype import ( "google.golang.org/grpc/resolver" ) // keyType is the key to use for storing State in Attributes. type keyType string const key = keyType("grpc.internal.transport.networktype") // Set returns a copy of the provided address with attributes containing networkType. func Set(address resolver.Address, networkType string) resolver.Address { address.Attributes = address.Attributes.WithValue(key, networkType) return address } // Get returns the network type in the resolver.Address and true, or "", false // if not present. func Get(address resolver.Address) (string, bool) { v := address.Attributes.Value(key) if v == nil { return "", false } return v.(string), true }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/status/status.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/status/status.go
/* * * Copyright 2020 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. * */ // Package status implements errors returned by gRPC. These errors are // serialized and transmitted on the wire between server and client, and allow // for additional data to be transmitted via the Details field in the status // proto. gRPC service handlers should return an error created by this // package, and gRPC clients should expect a corresponding error to be // returned from the RPC call. // // This package upholds the invariants that a non-nil error may not // contain an OK code, and an OK code must result in a nil error. package status import ( "errors" "fmt" spb "google.golang.org/genproto/googleapis/rpc/status" "google.golang.org/grpc/codes" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/protoadapt" "google.golang.org/protobuf/types/known/anypb" ) // Status represents an RPC status code, message, and details. It is immutable // and should be created with New, Newf, or FromProto. type Status struct { s *spb.Status } // NewWithProto returns a new status including details from statusProto. This // is meant to be used by the gRPC library only. func NewWithProto(code codes.Code, message string, statusProto []string) *Status { if len(statusProto) != 1 { // No grpc-status-details bin header, or multiple; just ignore. return &Status{s: &spb.Status{Code: int32(code), Message: message}} } st := &spb.Status{} if err := proto.Unmarshal([]byte(statusProto[0]), st); err != nil { // Probably not a google.rpc.Status proto; do not provide details. return &Status{s: &spb.Status{Code: int32(code), Message: message}} } if st.Code == int32(code) { // The codes match between the grpc-status header and the // grpc-status-details-bin header; use the full details proto. return &Status{s: st} } return &Status{ s: &spb.Status{ Code: int32(codes.Internal), Message: fmt.Sprintf( "grpc-status-details-bin mismatch: grpc-status=%v, grpc-message=%q, grpc-status-details-bin=%+v", code, message, st, ), }, } } // New returns a Status representing c and msg. func New(c codes.Code, msg string) *Status { return &Status{s: &spb.Status{Code: int32(c), Message: msg}} } // Newf returns New(c, fmt.Sprintf(format, a...)). func Newf(c codes.Code, format string, a ...any) *Status { return New(c, fmt.Sprintf(format, a...)) } // FromProto returns a Status representing s. func FromProto(s *spb.Status) *Status { return &Status{s: proto.Clone(s).(*spb.Status)} } // Err returns an error representing c and msg. If c is OK, returns nil. func Err(c codes.Code, msg string) error { return New(c, msg).Err() } // Errorf returns Error(c, fmt.Sprintf(format, a...)). func Errorf(c codes.Code, format string, a ...any) error { return Err(c, fmt.Sprintf(format, a...)) } // Code returns the status code contained in s. func (s *Status) Code() codes.Code { if s == nil || s.s == nil { return codes.OK } return codes.Code(s.s.Code) } // Message returns the message contained in s. func (s *Status) Message() string { if s == nil || s.s == nil { return "" } return s.s.Message } // Proto returns s's status as an spb.Status proto message. func (s *Status) Proto() *spb.Status { if s == nil { return nil } return proto.Clone(s.s).(*spb.Status) } // Err returns an immutable error representing s; returns nil if s.Code() is OK. func (s *Status) Err() error { if s.Code() == codes.OK { return nil } return &Error{s: s} } // WithDetails returns a new status with the provided details messages appended to the status. // If any errors are encountered, it returns nil and the first error encountered. func (s *Status) WithDetails(details ...protoadapt.MessageV1) (*Status, error) { if s.Code() == codes.OK { return nil, errors.New("no error details for status with code OK") } // s.Code() != OK implies that s.Proto() != nil. p := s.Proto() for _, detail := range details { m, err := anypb.New(protoadapt.MessageV2Of(detail)) if err != nil { return nil, err } p.Details = append(p.Details, m) } return &Status{s: p}, nil } // Details returns a slice of details messages attached to the status. // If a detail cannot be decoded, the error is returned in place of the detail. // If the detail can be decoded, the proto message returned is of the same // type that was given to WithDetails(). func (s *Status) Details() []any { if s == nil || s.s == nil { return nil } details := make([]any, 0, len(s.s.Details)) for _, any := range s.s.Details { detail, err := any.UnmarshalNew() if err != nil { details = append(details, err) continue } // The call to MessageV1Of is required to unwrap the proto message if // it implemented only the MessageV1 API. The proto message would have // been wrapped in a V2 wrapper in Status.WithDetails. V2 messages are // added to a global registry used by any.UnmarshalNew(). // MessageV1Of has the following behaviour: // 1. If the given message is a wrapped MessageV1, it returns the // unwrapped value. // 2. If the given message already implements MessageV1, it returns it // as is. // 3. Else, it wraps the MessageV2 in a MessageV1 wrapper. // // Since the Status.WithDetails() API only accepts MessageV1, calling // MessageV1Of ensures we return the same type that was given to // WithDetails: // * If the give type implemented only MessageV1, the unwrapping from // point 1 above will restore the type. // * If the given type implemented both MessageV1 and MessageV2, point 2 // above will ensure no wrapping is performed. // * If the given type implemented only MessageV2 and was wrapped using // MessageV1Of before passing to WithDetails(), it would be unwrapped // in WithDetails by calling MessageV2Of(). Point 3 above will ensure // that the type is wrapped in a MessageV1 wrapper again before // returning. Note that protoc-gen-go doesn't generate code which // implements ONLY MessageV2 at the time of writing. // // NOTE: Status details can also be added using the FromProto method. // This could theoretically allow passing a Detail message that only // implements the V2 API. In such a case the message will be wrapped in // a MessageV1 wrapper when fetched using Details(). // Since protoc-gen-go generates only code that implements both V1 and // V2 APIs for backward compatibility, this is not a concern. details = append(details, protoadapt.MessageV1Of(detail)) } return details } func (s *Status) String() string { return fmt.Sprintf("rpc error: code = %s desc = %s", s.Code(), s.Message()) } // Error wraps a pointer of a status proto. It implements error and Status, // and a nil *Error should never be returned by this package. type Error struct { s *Status } func (e *Error) Error() string { return e.s.String() } // GRPCStatus returns the Status represented by se. func (e *Error) GRPCStatus() *Status { return e.s } // Is implements future error.Is functionality. // A Error is equivalent if the code and message are identical. func (e *Error) Is(target error) bool { tse, ok := target.(*Error) if !ok { return false } return proto.Equal(e.s.s, tse.s.s) } // IsRestrictedControlPlaneCode returns whether the status includes a code // restricted for control plane usage as defined by gRFC A54. func IsRestrictedControlPlaneCode(s *Status) bool { switch s.Code() { case codes.InvalidArgument, codes.NotFound, codes.AlreadyExists, codes.FailedPrecondition, codes.Aborted, codes.OutOfRange, codes.DataLoss: return true } return false }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/binarylog/binarylog.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/binarylog/binarylog.go
/* * * Copyright 2018 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. * */ // Package binarylog implementation binary logging as defined in // https://github.com/grpc/proposal/blob/master/A16-binary-logging.md. package binarylog import ( "fmt" "os" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/internal/grpcutil" ) var grpclogLogger = grpclog.Component("binarylog") // Logger specifies MethodLoggers for method names with a Log call that // takes a context. // // This is used in the 1.0 release of gcp/observability, and thus must not be // deleted or changed. type Logger interface { GetMethodLogger(methodName string) MethodLogger } // binLogger is the global binary logger for the binary. One of this should be // built at init time from the configuration (environment variable or flags). // // It is used to get a MethodLogger for each individual method. var binLogger Logger // SetLogger sets the binary logger. // // Only call this at init time. func SetLogger(l Logger) { binLogger = l } // GetLogger gets the binary logger. // // Only call this at init time. func GetLogger() Logger { return binLogger } // GetMethodLogger returns the MethodLogger for the given methodName. // // methodName should be in the format of "/service/method". // // Each MethodLogger returned by this method is a new instance. This is to // generate sequence id within the call. func GetMethodLogger(methodName string) MethodLogger { if binLogger == nil { return nil } return binLogger.GetMethodLogger(methodName) } func init() { const envStr = "GRPC_BINARY_LOG_FILTER" configStr := os.Getenv(envStr) binLogger = NewLoggerFromConfigString(configStr) } // MethodLoggerConfig contains the setting for logging behavior of a method // logger. Currently, it contains the max length of header and message. type MethodLoggerConfig struct { // Max length of header and message. Header, Message uint64 } // LoggerConfig contains the config for loggers to create method loggers. type LoggerConfig struct { All *MethodLoggerConfig Services map[string]*MethodLoggerConfig Methods map[string]*MethodLoggerConfig Blacklist map[string]struct{} } type logger struct { config LoggerConfig } // NewLoggerFromConfig builds a logger with the given LoggerConfig. func NewLoggerFromConfig(config LoggerConfig) Logger { return &logger{config: config} } // newEmptyLogger creates an empty logger. The map fields need to be filled in // using the set* functions. func newEmptyLogger() *logger { return &logger{} } // Set method logger for "*". func (l *logger) setDefaultMethodLogger(ml *MethodLoggerConfig) error { if l.config.All != nil { return fmt.Errorf("conflicting global rules found") } l.config.All = ml return nil } // Set method logger for "service/*". // // New MethodLogger with same service overrides the old one. func (l *logger) setServiceMethodLogger(service string, ml *MethodLoggerConfig) error { if _, ok := l.config.Services[service]; ok { return fmt.Errorf("conflicting service rules for service %v found", service) } if l.config.Services == nil { l.config.Services = make(map[string]*MethodLoggerConfig) } l.config.Services[service] = ml return nil } // Set method logger for "service/method". // // New MethodLogger with same method overrides the old one. func (l *logger) setMethodMethodLogger(method string, ml *MethodLoggerConfig) error { if _, ok := l.config.Blacklist[method]; ok { return fmt.Errorf("conflicting blacklist rules for method %v found", method) } if _, ok := l.config.Methods[method]; ok { return fmt.Errorf("conflicting method rules for method %v found", method) } if l.config.Methods == nil { l.config.Methods = make(map[string]*MethodLoggerConfig) } l.config.Methods[method] = ml return nil } // Set blacklist method for "-service/method". func (l *logger) setBlacklist(method string) error { if _, ok := l.config.Blacklist[method]; ok { return fmt.Errorf("conflicting blacklist rules for method %v found", method) } if _, ok := l.config.Methods[method]; ok { return fmt.Errorf("conflicting method rules for method %v found", method) } if l.config.Blacklist == nil { l.config.Blacklist = make(map[string]struct{}) } l.config.Blacklist[method] = struct{}{} return nil } // getMethodLogger returns the MethodLogger for the given methodName. // // methodName should be in the format of "/service/method". // // Each MethodLogger returned by this method is a new instance. This is to // generate sequence id within the call. func (l *logger) GetMethodLogger(methodName string) MethodLogger { s, m, err := grpcutil.ParseMethod(methodName) if err != nil { grpclogLogger.Infof("binarylogging: failed to parse %q: %v", methodName, err) return nil } if ml, ok := l.config.Methods[s+"/"+m]; ok { return NewTruncatingMethodLogger(ml.Header, ml.Message) } if _, ok := l.config.Blacklist[s+"/"+m]; ok { return nil } if ml, ok := l.config.Services[s]; ok { return NewTruncatingMethodLogger(ml.Header, ml.Message) } if l.config.All == nil { return nil } return NewTruncatingMethodLogger(l.config.All.Header, l.config.All.Message) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/binarylog/sink.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/binarylog/sink.go
/* * * Copyright 2018 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. * */ package binarylog import ( "bufio" "encoding/binary" "io" "sync" "time" binlogpb "google.golang.org/grpc/binarylog/grpc_binarylog_v1" "google.golang.org/protobuf/proto" ) var ( // DefaultSink is the sink where the logs will be written to. It's exported // for the binarylog package to update. DefaultSink Sink = &noopSink{} // TODO(blog): change this default (file in /tmp). ) // Sink writes log entry into the binary log sink. // // sink is a copy of the exported binarylog.Sink, to avoid circular dependency. type Sink interface { // Write will be called to write the log entry into the sink. // // It should be thread-safe so it can be called in parallel. Write(*binlogpb.GrpcLogEntry) error // Close will be called when the Sink is replaced by a new Sink. Close() error } type noopSink struct{} func (ns *noopSink) Write(*binlogpb.GrpcLogEntry) error { return nil } func (ns *noopSink) Close() error { return nil } // newWriterSink creates a binary log sink with the given writer. // // Write() marshals the proto message and writes it to the given writer. Each // message is prefixed with a 4 byte big endian unsigned integer as the length. // // No buffer is done, Close() doesn't try to close the writer. func newWriterSink(w io.Writer) Sink { return &writerSink{out: w} } type writerSink struct { out io.Writer } func (ws *writerSink) Write(e *binlogpb.GrpcLogEntry) error { b, err := proto.Marshal(e) if err != nil { grpclogLogger.Errorf("binary logging: failed to marshal proto message: %v", err) return err } hdr := make([]byte, 4) binary.BigEndian.PutUint32(hdr, uint32(len(b))) if _, err := ws.out.Write(hdr); err != nil { return err } if _, err := ws.out.Write(b); err != nil { return err } return nil } func (ws *writerSink) Close() error { return nil } type bufferedSink struct { mu sync.Mutex closer io.Closer out Sink // out is built on buf. buf *bufio.Writer // buf is kept for flush. flusherStarted bool writeTicker *time.Ticker done chan struct{} } func (fs *bufferedSink) Write(e *binlogpb.GrpcLogEntry) error { fs.mu.Lock() defer fs.mu.Unlock() if !fs.flusherStarted { // Start the write loop when Write is called. fs.startFlushGoroutine() fs.flusherStarted = true } if err := fs.out.Write(e); err != nil { return err } return nil } const ( bufFlushDuration = 60 * time.Second ) func (fs *bufferedSink) startFlushGoroutine() { fs.writeTicker = time.NewTicker(bufFlushDuration) go func() { for { select { case <-fs.done: return case <-fs.writeTicker.C: } fs.mu.Lock() if err := fs.buf.Flush(); err != nil { grpclogLogger.Warningf("failed to flush to Sink: %v", err) } fs.mu.Unlock() } }() } func (fs *bufferedSink) Close() error { fs.mu.Lock() defer fs.mu.Unlock() if fs.writeTicker != nil { fs.writeTicker.Stop() } close(fs.done) if err := fs.buf.Flush(); err != nil { grpclogLogger.Warningf("failed to flush to Sink: %v", err) } if err := fs.closer.Close(); err != nil { grpclogLogger.Warningf("failed to close the underlying WriterCloser: %v", err) } if err := fs.out.Close(); err != nil { grpclogLogger.Warningf("failed to close the Sink: %v", err) } return nil } // NewBufferedSink creates a binary log sink with the given WriteCloser. // // Write() marshals the proto message and writes it to the given writer. Each // message is prefixed with a 4 byte big endian unsigned integer as the length. // // Content is kept in a buffer, and is flushed every 60 seconds. // // Close closes the WriteCloser. func NewBufferedSink(o io.WriteCloser) Sink { bufW := bufio.NewWriter(o) return &bufferedSink{ closer: o, out: newWriterSink(bufW), buf: bufW, done: make(chan struct{}), } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/binarylog/method_logger.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/binarylog/method_logger.go
/* * * Copyright 2018 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. * */ package binarylog import ( "context" "net" "strings" "sync/atomic" "time" binlogpb "google.golang.org/grpc/binarylog/grpc_binarylog_v1" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/durationpb" "google.golang.org/protobuf/types/known/timestamppb" ) type callIDGenerator struct { id uint64 } func (g *callIDGenerator) next() uint64 { id := atomic.AddUint64(&g.id, 1) return id } // reset is for testing only, and doesn't need to be thread safe. func (g *callIDGenerator) reset() { g.id = 0 } var idGen callIDGenerator // MethodLogger is the sub-logger for each method. // // This is used in the 1.0 release of gcp/observability, and thus must not be // deleted or changed. type MethodLogger interface { Log(context.Context, LogEntryConfig) } // TruncatingMethodLogger is a method logger that truncates headers and messages // based on configured fields. type TruncatingMethodLogger struct { headerMaxLen, messageMaxLen uint64 callID uint64 idWithinCallGen *callIDGenerator sink Sink // TODO(blog): make this pluggable. } // NewTruncatingMethodLogger returns a new truncating method logger. // // This is used in the 1.0 release of gcp/observability, and thus must not be // deleted or changed. func NewTruncatingMethodLogger(h, m uint64) *TruncatingMethodLogger { return &TruncatingMethodLogger{ headerMaxLen: h, messageMaxLen: m, callID: idGen.next(), idWithinCallGen: &callIDGenerator{}, sink: DefaultSink, // TODO(blog): make it pluggable. } } // Build is an internal only method for building the proto message out of the // input event. It's made public to enable other library to reuse as much logic // in TruncatingMethodLogger as possible. func (ml *TruncatingMethodLogger) Build(c LogEntryConfig) *binlogpb.GrpcLogEntry { m := c.toProto() timestamp := timestamppb.Now() m.Timestamp = timestamp m.CallId = ml.callID m.SequenceIdWithinCall = ml.idWithinCallGen.next() switch pay := m.Payload.(type) { case *binlogpb.GrpcLogEntry_ClientHeader: m.PayloadTruncated = ml.truncateMetadata(pay.ClientHeader.GetMetadata()) case *binlogpb.GrpcLogEntry_ServerHeader: m.PayloadTruncated = ml.truncateMetadata(pay.ServerHeader.GetMetadata()) case *binlogpb.GrpcLogEntry_Message: m.PayloadTruncated = ml.truncateMessage(pay.Message) } return m } // Log creates a proto binary log entry, and logs it to the sink. func (ml *TruncatingMethodLogger) Log(_ context.Context, c LogEntryConfig) { ml.sink.Write(ml.Build(c)) } func (ml *TruncatingMethodLogger) truncateMetadata(mdPb *binlogpb.Metadata) (truncated bool) { if ml.headerMaxLen == maxUInt { return false } var ( bytesLimit = ml.headerMaxLen index int ) // At the end of the loop, index will be the first entry where the total // size is greater than the limit: // // len(entry[:index]) <= ml.hdr && len(entry[:index+1]) > ml.hdr. for ; index < len(mdPb.Entry); index++ { entry := mdPb.Entry[index] if entry.Key == "grpc-trace-bin" { // "grpc-trace-bin" is a special key. It's kept in the log entry, // but not counted towards the size limit. continue } currentEntryLen := uint64(len(entry.GetKey())) + uint64(len(entry.GetValue())) if currentEntryLen > bytesLimit { break } bytesLimit -= currentEntryLen } truncated = index < len(mdPb.Entry) mdPb.Entry = mdPb.Entry[:index] return truncated } func (ml *TruncatingMethodLogger) truncateMessage(msgPb *binlogpb.Message) (truncated bool) { if ml.messageMaxLen == maxUInt { return false } if ml.messageMaxLen >= uint64(len(msgPb.Data)) { return false } msgPb.Data = msgPb.Data[:ml.messageMaxLen] return true } // LogEntryConfig represents the configuration for binary log entry. // // This is used in the 1.0 release of gcp/observability, and thus must not be // deleted or changed. type LogEntryConfig interface { toProto() *binlogpb.GrpcLogEntry } // ClientHeader configs the binary log entry to be a ClientHeader entry. type ClientHeader struct { OnClientSide bool Header metadata.MD MethodName string Authority string Timeout time.Duration // PeerAddr is required only when it's on server side. PeerAddr net.Addr } func (c *ClientHeader) toProto() *binlogpb.GrpcLogEntry { // This function doesn't need to set all the fields (e.g. seq ID). The Log // function will set the fields when necessary. clientHeader := &binlogpb.ClientHeader{ Metadata: mdToMetadataProto(c.Header), MethodName: c.MethodName, Authority: c.Authority, } if c.Timeout > 0 { clientHeader.Timeout = durationpb.New(c.Timeout) } ret := &binlogpb.GrpcLogEntry{ Type: binlogpb.GrpcLogEntry_EVENT_TYPE_CLIENT_HEADER, Payload: &binlogpb.GrpcLogEntry_ClientHeader{ ClientHeader: clientHeader, }, } if c.OnClientSide { ret.Logger = binlogpb.GrpcLogEntry_LOGGER_CLIENT } else { ret.Logger = binlogpb.GrpcLogEntry_LOGGER_SERVER } if c.PeerAddr != nil { ret.Peer = addrToProto(c.PeerAddr) } return ret } // ServerHeader configs the binary log entry to be a ServerHeader entry. type ServerHeader struct { OnClientSide bool Header metadata.MD // PeerAddr is required only when it's on client side. PeerAddr net.Addr } func (c *ServerHeader) toProto() *binlogpb.GrpcLogEntry { ret := &binlogpb.GrpcLogEntry{ Type: binlogpb.GrpcLogEntry_EVENT_TYPE_SERVER_HEADER, Payload: &binlogpb.GrpcLogEntry_ServerHeader{ ServerHeader: &binlogpb.ServerHeader{ Metadata: mdToMetadataProto(c.Header), }, }, } if c.OnClientSide { ret.Logger = binlogpb.GrpcLogEntry_LOGGER_CLIENT } else { ret.Logger = binlogpb.GrpcLogEntry_LOGGER_SERVER } if c.PeerAddr != nil { ret.Peer = addrToProto(c.PeerAddr) } return ret } // ClientMessage configs the binary log entry to be a ClientMessage entry. type ClientMessage struct { OnClientSide bool // Message can be a proto.Message or []byte. Other messages formats are not // supported. Message any } func (c *ClientMessage) toProto() *binlogpb.GrpcLogEntry { var ( data []byte err error ) if m, ok := c.Message.(proto.Message); ok { data, err = proto.Marshal(m) if err != nil { grpclogLogger.Infof("binarylogging: failed to marshal proto message: %v", err) } } else if b, ok := c.Message.([]byte); ok { data = b } else { grpclogLogger.Infof("binarylogging: message to log is neither proto.message nor []byte") } ret := &binlogpb.GrpcLogEntry{ Type: binlogpb.GrpcLogEntry_EVENT_TYPE_CLIENT_MESSAGE, Payload: &binlogpb.GrpcLogEntry_Message{ Message: &binlogpb.Message{ Length: uint32(len(data)), Data: data, }, }, } if c.OnClientSide { ret.Logger = binlogpb.GrpcLogEntry_LOGGER_CLIENT } else { ret.Logger = binlogpb.GrpcLogEntry_LOGGER_SERVER } return ret } // ServerMessage configs the binary log entry to be a ServerMessage entry. type ServerMessage struct { OnClientSide bool // Message can be a proto.Message or []byte. Other messages formats are not // supported. Message any } func (c *ServerMessage) toProto() *binlogpb.GrpcLogEntry { var ( data []byte err error ) if m, ok := c.Message.(proto.Message); ok { data, err = proto.Marshal(m) if err != nil { grpclogLogger.Infof("binarylogging: failed to marshal proto message: %v", err) } } else if b, ok := c.Message.([]byte); ok { data = b } else { grpclogLogger.Infof("binarylogging: message to log is neither proto.message nor []byte") } ret := &binlogpb.GrpcLogEntry{ Type: binlogpb.GrpcLogEntry_EVENT_TYPE_SERVER_MESSAGE, Payload: &binlogpb.GrpcLogEntry_Message{ Message: &binlogpb.Message{ Length: uint32(len(data)), Data: data, }, }, } if c.OnClientSide { ret.Logger = binlogpb.GrpcLogEntry_LOGGER_CLIENT } else { ret.Logger = binlogpb.GrpcLogEntry_LOGGER_SERVER } return ret } // ClientHalfClose configs the binary log entry to be a ClientHalfClose entry. type ClientHalfClose struct { OnClientSide bool } func (c *ClientHalfClose) toProto() *binlogpb.GrpcLogEntry { ret := &binlogpb.GrpcLogEntry{ Type: binlogpb.GrpcLogEntry_EVENT_TYPE_CLIENT_HALF_CLOSE, Payload: nil, // No payload here. } if c.OnClientSide { ret.Logger = binlogpb.GrpcLogEntry_LOGGER_CLIENT } else { ret.Logger = binlogpb.GrpcLogEntry_LOGGER_SERVER } return ret } // ServerTrailer configs the binary log entry to be a ServerTrailer entry. type ServerTrailer struct { OnClientSide bool Trailer metadata.MD // Err is the status error. Err error // PeerAddr is required only when it's on client side and the RPC is trailer // only. PeerAddr net.Addr } func (c *ServerTrailer) toProto() *binlogpb.GrpcLogEntry { st, ok := status.FromError(c.Err) if !ok { grpclogLogger.Info("binarylogging: error in trailer is not a status error") } var ( detailsBytes []byte err error ) stProto := st.Proto() if stProto != nil && len(stProto.Details) != 0 { detailsBytes, err = proto.Marshal(stProto) if err != nil { grpclogLogger.Infof("binarylogging: failed to marshal status proto: %v", err) } } ret := &binlogpb.GrpcLogEntry{ Type: binlogpb.GrpcLogEntry_EVENT_TYPE_SERVER_TRAILER, Payload: &binlogpb.GrpcLogEntry_Trailer{ Trailer: &binlogpb.Trailer{ Metadata: mdToMetadataProto(c.Trailer), StatusCode: uint32(st.Code()), StatusMessage: st.Message(), StatusDetails: detailsBytes, }, }, } if c.OnClientSide { ret.Logger = binlogpb.GrpcLogEntry_LOGGER_CLIENT } else { ret.Logger = binlogpb.GrpcLogEntry_LOGGER_SERVER } if c.PeerAddr != nil { ret.Peer = addrToProto(c.PeerAddr) } return ret } // Cancel configs the binary log entry to be a Cancel entry. type Cancel struct { OnClientSide bool } func (c *Cancel) toProto() *binlogpb.GrpcLogEntry { ret := &binlogpb.GrpcLogEntry{ Type: binlogpb.GrpcLogEntry_EVENT_TYPE_CANCEL, Payload: nil, } if c.OnClientSide { ret.Logger = binlogpb.GrpcLogEntry_LOGGER_CLIENT } else { ret.Logger = binlogpb.GrpcLogEntry_LOGGER_SERVER } return ret } // metadataKeyOmit returns whether the metadata entry with this key should be // omitted. func metadataKeyOmit(key string) bool { switch key { case "lb-token", ":path", ":authority", "content-encoding", "content-type", "user-agent", "te": return true case "grpc-trace-bin": // grpc-trace-bin is special because it's visible to users. return false } return strings.HasPrefix(key, "grpc-") } func mdToMetadataProto(md metadata.MD) *binlogpb.Metadata { ret := &binlogpb.Metadata{} for k, vv := range md { if metadataKeyOmit(k) { continue } for _, v := range vv { ret.Entry = append(ret.Entry, &binlogpb.MetadataEntry{ Key: k, Value: []byte(v), }, ) } } return ret } func addrToProto(addr net.Addr) *binlogpb.Address { ret := &binlogpb.Address{} switch a := addr.(type) { case *net.TCPAddr: if a.IP.To4() != nil { ret.Type = binlogpb.Address_TYPE_IPV4 } else if a.IP.To16() != nil { ret.Type = binlogpb.Address_TYPE_IPV6 } else { ret.Type = binlogpb.Address_TYPE_UNKNOWN // Do not set address and port fields. break } ret.Address = a.IP.String() ret.IpPort = uint32(a.Port) case *net.UnixAddr: ret.Type = binlogpb.Address_TYPE_UNIX ret.Address = a.String() default: ret.Type = binlogpb.Address_TYPE_UNKNOWN } return ret }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/binarylog/env_config.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/binarylog/env_config.go
/* * * Copyright 2018 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. * */ package binarylog import ( "errors" "fmt" "regexp" "strconv" "strings" ) // NewLoggerFromConfigString reads the string and build a logger. It can be used // to build a new logger and assign it to binarylog.Logger. // // Example filter config strings: // - "" Nothing will be logged // - "*" All headers and messages will be fully logged. // - "*{h}" Only headers will be logged. // - "*{m:256}" Only the first 256 bytes of each message will be logged. // - "Foo/*" Logs every method in service Foo // - "Foo/*,-Foo/Bar" Logs every method in service Foo except method /Foo/Bar // - "Foo/*,Foo/Bar{m:256}" Logs the first 256 bytes of each message in method // /Foo/Bar, logs all headers and messages in every other method in service // Foo. // // If two configs exist for one certain method or service, the one specified // later overrides the previous config. func NewLoggerFromConfigString(s string) Logger { if s == "" { return nil } l := newEmptyLogger() methods := strings.Split(s, ",") for _, method := range methods { if err := l.fillMethodLoggerWithConfigString(method); err != nil { grpclogLogger.Warningf("failed to parse binary log config: %v", err) return nil } } return l } // fillMethodLoggerWithConfigString parses config, creates TruncatingMethodLogger and adds // it to the right map in the logger. func (l *logger) fillMethodLoggerWithConfigString(config string) error { // "" is invalid. if config == "" { return errors.New("empty string is not a valid method binary logging config") } // "-service/method", blacklist, no * or {} allowed. if config[0] == '-' { s, m, suffix, err := parseMethodConfigAndSuffix(config[1:]) if err != nil { return fmt.Errorf("invalid config: %q, %v", config, err) } if m == "*" { return fmt.Errorf("invalid config: %q, %v", config, "* not allowed in blacklist config") } if suffix != "" { return fmt.Errorf("invalid config: %q, %v", config, "header/message limit not allowed in blacklist config") } if err := l.setBlacklist(s + "/" + m); err != nil { return fmt.Errorf("invalid config: %v", err) } return nil } // "*{h:256;m:256}" if config[0] == '*' { hdr, msg, err := parseHeaderMessageLengthConfig(config[1:]) if err != nil { return fmt.Errorf("invalid config: %q, %v", config, err) } if err := l.setDefaultMethodLogger(&MethodLoggerConfig{Header: hdr, Message: msg}); err != nil { return fmt.Errorf("invalid config: %v", err) } return nil } s, m, suffix, err := parseMethodConfigAndSuffix(config) if err != nil { return fmt.Errorf("invalid config: %q, %v", config, err) } hdr, msg, err := parseHeaderMessageLengthConfig(suffix) if err != nil { return fmt.Errorf("invalid header/message length config: %q, %v", suffix, err) } if m == "*" { if err := l.setServiceMethodLogger(s, &MethodLoggerConfig{Header: hdr, Message: msg}); err != nil { return fmt.Errorf("invalid config: %v", err) } } else { if err := l.setMethodMethodLogger(s+"/"+m, &MethodLoggerConfig{Header: hdr, Message: msg}); err != nil { return fmt.Errorf("invalid config: %v", err) } } return nil } const ( // TODO: this const is only used by env_config now. But could be useful for // other config. Move to binarylog.go if necessary. maxUInt = ^uint64(0) // For "p.s/m" plus any suffix. Suffix will be parsed again. See test for // expected output. longMethodConfigRegexpStr = `^([\w./]+)/((?:\w+)|[*])(.+)?$` // For suffix from above, "{h:123,m:123}". See test for expected output. optionalLengthRegexpStr = `(?::(\d+))?` // Optional ":123". headerConfigRegexpStr = `^{h` + optionalLengthRegexpStr + `}$` messageConfigRegexpStr = `^{m` + optionalLengthRegexpStr + `}$` headerMessageConfigRegexpStr = `^{h` + optionalLengthRegexpStr + `;m` + optionalLengthRegexpStr + `}$` ) var ( longMethodConfigRegexp = regexp.MustCompile(longMethodConfigRegexpStr) headerConfigRegexp = regexp.MustCompile(headerConfigRegexpStr) messageConfigRegexp = regexp.MustCompile(messageConfigRegexpStr) headerMessageConfigRegexp = regexp.MustCompile(headerMessageConfigRegexpStr) ) // Turn "service/method{h;m}" into "service", "method", "{h;m}". func parseMethodConfigAndSuffix(c string) (service, method, suffix string, _ error) { // Regexp result: // // in: "p.s/m{h:123,m:123}", // out: []string{"p.s/m{h:123,m:123}", "p.s", "m", "{h:123,m:123}"}, match := longMethodConfigRegexp.FindStringSubmatch(c) if match == nil { return "", "", "", fmt.Errorf("%q contains invalid substring", c) } service = match[1] method = match[2] suffix = match[3] return } // Turn "{h:123;m:345}" into 123, 345. // // Return maxUInt if length is unspecified. func parseHeaderMessageLengthConfig(c string) (hdrLenStr, msgLenStr uint64, err error) { if c == "" { return maxUInt, maxUInt, nil } // Header config only. if match := headerConfigRegexp.FindStringSubmatch(c); match != nil { if s := match[1]; s != "" { hdrLenStr, err = strconv.ParseUint(s, 10, 64) if err != nil { return 0, 0, fmt.Errorf("failed to convert %q to uint", s) } return hdrLenStr, 0, nil } return maxUInt, 0, nil } // Message config only. if match := messageConfigRegexp.FindStringSubmatch(c); match != nil { if s := match[1]; s != "" { msgLenStr, err = strconv.ParseUint(s, 10, 64) if err != nil { return 0, 0, fmt.Errorf("failed to convert %q to uint", s) } return 0, msgLenStr, nil } return 0, maxUInt, nil } // Header and message config both. if match := headerMessageConfigRegexp.FindStringSubmatch(c); match != nil { // Both hdr and msg are specified, but one or two of them might be empty. hdrLenStr = maxUInt msgLenStr = maxUInt if s := match[1]; s != "" { hdrLenStr, err = strconv.ParseUint(s, 10, 64) if err != nil { return 0, 0, fmt.Errorf("failed to convert %q to uint", s) } } if s := match[2]; s != "" { msgLenStr, err = strconv.ParseUint(s, 10, 64) if err != nil { return 0, 0, fmt.Errorf("failed to convert %q to uint", s) } } return hdrLenStr, msgLenStr, nil } return 0, 0, fmt.Errorf("%q contains invalid substring", c) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/binarylog/binarylog_testutil.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/binarylog/binarylog_testutil.go
/* * * Copyright 2018 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. * */ // This file contains exported variables/functions that are exported for testing // only. // // An ideal way for this would be to put those in a *_test.go but in binarylog // package. But this doesn't work with staticcheck with go module. Error was: // "MdToMetadataProto not declared by package binarylog". This could be caused // by the way staticcheck looks for files for a certain package, which doesn't // support *_test.go files. // // Move those to binary_test.go when staticcheck is fixed. package binarylog var ( // AllLogger is a logger that logs all headers/messages for all RPCs. It's // for testing only. AllLogger = NewLoggerFromConfigString("*") // MdToMetadataProto converts metadata to a binary logging proto message. // It's for testing only. MdToMetadataProto = mdToMetadataProto // AddrToProto converts an address to a binary logging proto message. It's // for testing only. AddrToProto = addrToProto )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/grpcsync/pubsub.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/grpcsync/pubsub.go
/* * * Copyright 2023 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. * */ package grpcsync import ( "context" "sync" ) // Subscriber represents an entity that is subscribed to messages published on // a PubSub. It wraps the callback to be invoked by the PubSub when a new // message is published. type Subscriber interface { // OnMessage is invoked when a new message is published. Implementations // must not block in this method. OnMessage(msg any) } // PubSub is a simple one-to-many publish-subscribe system that supports // messages of arbitrary type. It guarantees that messages are delivered in // the same order in which they were published. // // Publisher invokes the Publish() method to publish new messages, while // subscribers interested in receiving these messages register a callback // via the Subscribe() method. // // Once a PubSub is stopped, no more messages can be published, but any pending // published messages will be delivered to the subscribers. Done may be used // to determine when all published messages have been delivered. type PubSub struct { cs *CallbackSerializer // Access to the below fields are guarded by this mutex. mu sync.Mutex msg any subscribers map[Subscriber]bool } // NewPubSub returns a new PubSub instance. Users should cancel the // provided context to shutdown the PubSub. func NewPubSub(ctx context.Context) *PubSub { return &PubSub{ cs: NewCallbackSerializer(ctx), subscribers: map[Subscriber]bool{}, } } // Subscribe registers the provided Subscriber to the PubSub. // // If the PubSub contains a previously published message, the Subscriber's // OnMessage() callback will be invoked asynchronously with the existing // message to begin with, and subsequently for every newly published message. // // The caller is responsible for invoking the returned cancel function to // unsubscribe itself from the PubSub. func (ps *PubSub) Subscribe(sub Subscriber) (cancel func()) { ps.mu.Lock() defer ps.mu.Unlock() ps.subscribers[sub] = true if ps.msg != nil { msg := ps.msg ps.cs.TrySchedule(func(context.Context) { ps.mu.Lock() defer ps.mu.Unlock() if !ps.subscribers[sub] { return } sub.OnMessage(msg) }) } return func() { ps.mu.Lock() defer ps.mu.Unlock() delete(ps.subscribers, sub) } } // Publish publishes the provided message to the PubSub, and invokes // callbacks registered by subscribers asynchronously. func (ps *PubSub) Publish(msg any) { ps.mu.Lock() defer ps.mu.Unlock() ps.msg = msg for sub := range ps.subscribers { s := sub ps.cs.TrySchedule(func(context.Context) { ps.mu.Lock() defer ps.mu.Unlock() if !ps.subscribers[s] { return } s.OnMessage(msg) }) } } // Done returns a channel that is closed after the context passed to NewPubSub // is canceled and all updates have been sent to subscribers. func (ps *PubSub) Done() <-chan struct{} { return ps.cs.Done() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/grpcsync/callback_serializer.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/grpcsync/callback_serializer.go
/* * * Copyright 2022 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. * */ package grpcsync import ( "context" "google.golang.org/grpc/internal/buffer" ) // CallbackSerializer provides a mechanism to schedule callbacks in a // synchronized manner. It provides a FIFO guarantee on the order of execution // of scheduled callbacks. New callbacks can be scheduled by invoking the // Schedule() method. // // This type is safe for concurrent access. type CallbackSerializer struct { // done is closed once the serializer is shut down completely, i.e all // scheduled callbacks are executed and the serializer has deallocated all // its resources. done chan struct{} callbacks *buffer.Unbounded } // NewCallbackSerializer returns a new CallbackSerializer instance. The provided // context will be passed to the scheduled callbacks. Users should cancel the // provided context to shutdown the CallbackSerializer. It is guaranteed that no // callbacks will be added once this context is canceled, and any pending un-run // callbacks will be executed before the serializer is shut down. func NewCallbackSerializer(ctx context.Context) *CallbackSerializer { cs := &CallbackSerializer{ done: make(chan struct{}), callbacks: buffer.NewUnbounded(), } go cs.run(ctx) return cs } // TrySchedule tries to schedule the provided callback function f to be // executed in the order it was added. This is a best-effort operation. If the // context passed to NewCallbackSerializer was canceled before this method is // called, the callback will not be scheduled. // // Callbacks are expected to honor the context when performing any blocking // operations, and should return early when the context is canceled. func (cs *CallbackSerializer) TrySchedule(f func(ctx context.Context)) { cs.callbacks.Put(f) } // ScheduleOr schedules the provided callback function f to be executed in the // order it was added. If the context passed to NewCallbackSerializer has been // canceled before this method is called, the onFailure callback will be // executed inline instead. // // Callbacks are expected to honor the context when performing any blocking // operations, and should return early when the context is canceled. func (cs *CallbackSerializer) ScheduleOr(f func(ctx context.Context), onFailure func()) { if cs.callbacks.Put(f) != nil { onFailure() } } func (cs *CallbackSerializer) run(ctx context.Context) { defer close(cs.done) // TODO: when Go 1.21 is the oldest supported version, this loop and Close // can be replaced with: // // context.AfterFunc(ctx, cs.callbacks.Close) for ctx.Err() == nil { select { case <-ctx.Done(): // Do nothing here. Next iteration of the for loop will not happen, // since ctx.Err() would be non-nil. case cb := <-cs.callbacks.Get(): cs.callbacks.Load() cb.(func(context.Context))(ctx) } } // Close the buffer to prevent new callbacks from being added. cs.callbacks.Close() // Run all pending callbacks. for cb := range cs.callbacks.Get() { cs.callbacks.Load() cb.(func(context.Context))(ctx) } } // Done returns a channel that is closed after the context passed to // NewCallbackSerializer is canceled and all callbacks have been executed. func (cs *CallbackSerializer) Done() <-chan struct{} { return cs.done }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/grpcsync/event.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/grpcsync/event.go
/* * * Copyright 2018 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. * */ // Package grpcsync implements additional synchronization primitives built upon // the sync package. package grpcsync import ( "sync" "sync/atomic" ) // Event represents a one-time event that may occur in the future. type Event struct { fired int32 c chan struct{} o sync.Once } // Fire causes e to complete. It is safe to call multiple times, and // concurrently. It returns true iff this call to Fire caused the signaling // channel returned by Done to close. func (e *Event) Fire() bool { ret := false e.o.Do(func() { atomic.StoreInt32(&e.fired, 1) close(e.c) ret = true }) return ret } // Done returns a channel that will be closed when Fire is called. func (e *Event) Done() <-chan struct{} { return e.c } // HasFired returns true if Fire has been called. func (e *Event) HasFired() bool { return atomic.LoadInt32(&e.fired) == 1 } // NewEvent returns a new, ready-to-use Event. func NewEvent() *Event { return &Event{c: make(chan struct{})} }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/grpclog/prefix_logger.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/grpclog/prefix_logger.go
/* * * Copyright 2020 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. * */ // Package grpclog provides logging functionality for internal gRPC packages, // outside of the functionality provided by the external `grpclog` package. package grpclog import ( "fmt" "google.golang.org/grpc/grpclog" ) // PrefixLogger does logging with a prefix. // // Logging method on a nil logs without any prefix. type PrefixLogger struct { logger grpclog.DepthLoggerV2 prefix string } // Infof does info logging. func (pl *PrefixLogger) Infof(format string, args ...any) { if pl != nil { // Handle nil, so the tests can pass in a nil logger. format = pl.prefix + format pl.logger.InfoDepth(1, fmt.Sprintf(format, args...)) return } grpclog.InfoDepth(1, fmt.Sprintf(format, args...)) } // Warningf does warning logging. func (pl *PrefixLogger) Warningf(format string, args ...any) { if pl != nil { format = pl.prefix + format pl.logger.WarningDepth(1, fmt.Sprintf(format, args...)) return } grpclog.WarningDepth(1, fmt.Sprintf(format, args...)) } // Errorf does error logging. func (pl *PrefixLogger) Errorf(format string, args ...any) { if pl != nil { format = pl.prefix + format pl.logger.ErrorDepth(1, fmt.Sprintf(format, args...)) return } grpclog.ErrorDepth(1, fmt.Sprintf(format, args...)) } // V reports whether verbosity level l is at least the requested verbose level. func (pl *PrefixLogger) V(l int) bool { if pl != nil { return pl.logger.V(l) } return true } // NewPrefixLogger creates a prefix logger with the given prefix. func NewPrefixLogger(logger grpclog.DepthLoggerV2, prefix string) *PrefixLogger { return &PrefixLogger{logger: logger, prefix: prefix} }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/channelz/logging.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/channelz/logging.go
/* * * Copyright 2020 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. * */ package channelz import ( "fmt" "google.golang.org/grpc/grpclog" ) var logger = grpclog.Component("channelz") // Info logs and adds a trace event if channelz is on. func Info(l grpclog.DepthLoggerV2, e Entity, args ...any) { AddTraceEvent(l, e, 1, &TraceEvent{ Desc: fmt.Sprint(args...), Severity: CtInfo, }) } // Infof logs and adds a trace event if channelz is on. func Infof(l grpclog.DepthLoggerV2, e Entity, format string, args ...any) { AddTraceEvent(l, e, 1, &TraceEvent{ Desc: fmt.Sprintf(format, args...), Severity: CtInfo, }) } // Warning logs and adds a trace event if channelz is on. func Warning(l grpclog.DepthLoggerV2, e Entity, args ...any) { AddTraceEvent(l, e, 1, &TraceEvent{ Desc: fmt.Sprint(args...), Severity: CtWarning, }) } // Warningf logs and adds a trace event if channelz is on. func Warningf(l grpclog.DepthLoggerV2, e Entity, format string, args ...any) { AddTraceEvent(l, e, 1, &TraceEvent{ Desc: fmt.Sprintf(format, args...), Severity: CtWarning, }) } // Error logs and adds a trace event if channelz is on. func Error(l grpclog.DepthLoggerV2, e Entity, args ...any) { AddTraceEvent(l, e, 1, &TraceEvent{ Desc: fmt.Sprint(args...), Severity: CtError, }) } // Errorf logs and adds a trace event if channelz is on. func Errorf(l grpclog.DepthLoggerV2, e Entity, format string, args ...any) { AddTraceEvent(l, e, 1, &TraceEvent{ Desc: fmt.Sprintf(format, args...), Severity: CtError, }) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/channelz/subchannel.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/channelz/subchannel.go
/* * * Copyright 2024 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. * */ package channelz import ( "fmt" "sync/atomic" ) // SubChannel is the channelz representation of a subchannel. type SubChannel struct { Entity // ID is the channelz id of this subchannel. ID int64 // RefName is the human readable reference string of this subchannel. RefName string closeCalled bool sockets map[int64]string parent *Channel trace *ChannelTrace traceRefCount int32 ChannelMetrics ChannelMetrics } func (sc *SubChannel) String() string { return fmt.Sprintf("%s SubChannel #%d", sc.parent, sc.ID) } func (sc *SubChannel) id() int64 { return sc.ID } // Sockets returns a copy of the sockets map associated with the SubChannel. func (sc *SubChannel) Sockets() map[int64]string { db.mu.RLock() defer db.mu.RUnlock() return copyMap(sc.sockets) } // Trace returns a copy of the ChannelTrace associated with the SubChannel. func (sc *SubChannel) Trace() *ChannelTrace { db.mu.RLock() defer db.mu.RUnlock() return sc.trace.copy() } func (sc *SubChannel) addChild(id int64, e entry) { if v, ok := e.(*Socket); ok && v.SocketType == SocketTypeNormal { sc.sockets[id] = v.RefName } else { logger.Errorf("cannot add a child (id = %d) of type %T to a subChannel", id, e) } } func (sc *SubChannel) deleteChild(id int64) { delete(sc.sockets, id) sc.deleteSelfIfReady() } func (sc *SubChannel) triggerDelete() { sc.closeCalled = true sc.deleteSelfIfReady() } func (sc *SubChannel) getParentID() int64 { return sc.parent.ID } // deleteSelfFromTree tries to delete the subchannel from the channelz entry relation tree, which // means deleting the subchannel reference from its parent's child list. // // In order for a subchannel to be deleted from the tree, it must meet the criteria that, removal of // the corresponding grpc object has been invoked, and the subchannel does not have any children left. // // The returned boolean value indicates whether the channel has been successfully deleted from tree. func (sc *SubChannel) deleteSelfFromTree() (deleted bool) { if !sc.closeCalled || len(sc.sockets) != 0 { return false } sc.parent.deleteChild(sc.ID) return true } // deleteSelfFromMap checks whether it is valid to delete the subchannel from the map, which means // deleting the subchannel from channelz's tracking entirely. Users can no longer use id to query // the subchannel, and its memory will be garbage collected. // // The trace reference count of the subchannel must be 0 in order to be deleted from the map. This is // specified in the channel tracing gRFC that as long as some other trace has reference to an entity, // the trace of the referenced entity must not be deleted. In order to release the resource allocated // by grpc, the reference to the grpc object is reset to a dummy object. // // deleteSelfFromMap must be called after deleteSelfFromTree returns true. // // It returns a bool to indicate whether the channel can be safely deleted from map. func (sc *SubChannel) deleteSelfFromMap() (delete bool) { return sc.getTraceRefCount() == 0 } // deleteSelfIfReady tries to delete the subchannel itself from the channelz database. // The delete process includes two steps: // 1. delete the subchannel from the entry relation tree, i.e. delete the subchannel reference from // its parent's child list. // 2. delete the subchannel from the map, i.e. delete the subchannel entirely from channelz. Lookup // by id will return entry not found error. func (sc *SubChannel) deleteSelfIfReady() { if !sc.deleteSelfFromTree() { return } if !sc.deleteSelfFromMap() { return } db.deleteEntry(sc.ID) sc.trace.clear() } func (sc *SubChannel) getChannelTrace() *ChannelTrace { return sc.trace } func (sc *SubChannel) incrTraceRefCount() { atomic.AddInt32(&sc.traceRefCount, 1) } func (sc *SubChannel) decrTraceRefCount() { atomic.AddInt32(&sc.traceRefCount, -1) } func (sc *SubChannel) getTraceRefCount() int { i := atomic.LoadInt32(&sc.traceRefCount) return int(i) } func (sc *SubChannel) getRefName() string { return sc.RefName }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/channelz/trace.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/channelz/trace.go
/* * * Copyright 2018 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. * */ package channelz import ( "fmt" "sync" "sync/atomic" "time" "google.golang.org/grpc/grpclog" ) const ( defaultMaxTraceEntry int32 = 30 ) var maxTraceEntry = defaultMaxTraceEntry // SetMaxTraceEntry sets maximum number of trace entries per entity (i.e. // channel/subchannel). Setting it to 0 will disable channel tracing. func SetMaxTraceEntry(i int32) { atomic.StoreInt32(&maxTraceEntry, i) } // ResetMaxTraceEntryToDefault resets the maximum number of trace entries per // entity to default. func ResetMaxTraceEntryToDefault() { atomic.StoreInt32(&maxTraceEntry, defaultMaxTraceEntry) } func getMaxTraceEntry() int { i := atomic.LoadInt32(&maxTraceEntry) return int(i) } // traceEvent is an internal representation of a single trace event type traceEvent struct { // Desc is a simple description of the trace event. Desc string // Severity states the severity of this trace event. Severity Severity // Timestamp is the event time. Timestamp time.Time // RefID is the id of the entity that gets referenced in the event. RefID is 0 if no other entity is // involved in this event. // e.g. SubChannel (id: 4[]) Created. --> RefID = 4, RefName = "" (inside []) RefID int64 // RefName is the reference name for the entity that gets referenced in the event. RefName string // RefType indicates the referenced entity type, i.e Channel or SubChannel. RefType RefChannelType } // TraceEvent is what the caller of AddTraceEvent should provide to describe the // event to be added to the channel trace. // // The Parent field is optional. It is used for an event that will be recorded // in the entity's parent trace. type TraceEvent struct { Desc string Severity Severity Parent *TraceEvent } // ChannelTrace provides tracing information for a channel. // It tracks various events and metadata related to the channel's lifecycle // and operations. type ChannelTrace struct { cm *channelMap clearCalled bool // The time when the trace was created. CreationTime time.Time // A counter for the number of events recorded in the // trace. EventNum int64 mu sync.Mutex // A slice of traceEvent pointers representing the events recorded for // this channel. Events []*traceEvent } func (c *ChannelTrace) copy() *ChannelTrace { return &ChannelTrace{ CreationTime: c.CreationTime, EventNum: c.EventNum, Events: append(([]*traceEvent)(nil), c.Events...), } } func (c *ChannelTrace) append(e *traceEvent) { c.mu.Lock() if len(c.Events) == getMaxTraceEntry() { del := c.Events[0] c.Events = c.Events[1:] if del.RefID != 0 { // start recursive cleanup in a goroutine to not block the call originated from grpc. go func() { // need to acquire c.cm.mu lock to call the unlocked attemptCleanup func. c.cm.mu.Lock() c.cm.decrTraceRefCount(del.RefID) c.cm.mu.Unlock() }() } } e.Timestamp = time.Now() c.Events = append(c.Events, e) c.EventNum++ c.mu.Unlock() } func (c *ChannelTrace) clear() { if c.clearCalled { return } c.clearCalled = true c.mu.Lock() for _, e := range c.Events { if e.RefID != 0 { // caller should have already held the c.cm.mu lock. c.cm.decrTraceRefCount(e.RefID) } } c.mu.Unlock() } // Severity is the severity level of a trace event. // The canonical enumeration of all valid values is here: // https://github.com/grpc/grpc-proto/blob/9b13d199cc0d4703c7ea26c9c330ba695866eb23/grpc/channelz/v1/channelz.proto#L126. type Severity int const ( // CtUnknown indicates unknown severity of a trace event. CtUnknown Severity = iota // CtInfo indicates info level severity of a trace event. CtInfo // CtWarning indicates warning level severity of a trace event. CtWarning // CtError indicates error level severity of a trace event. CtError ) // RefChannelType is the type of the entity being referenced in a trace event. type RefChannelType int const ( // RefUnknown indicates an unknown entity type, the zero value for this type. RefUnknown RefChannelType = iota // RefChannel indicates the referenced entity is a Channel. RefChannel // RefSubChannel indicates the referenced entity is a SubChannel. RefSubChannel // RefServer indicates the referenced entity is a Server. RefServer // RefListenSocket indicates the referenced entity is a ListenSocket. RefListenSocket // RefNormalSocket indicates the referenced entity is a NormalSocket. RefNormalSocket ) var refChannelTypeToString = map[RefChannelType]string{ RefUnknown: "Unknown", RefChannel: "Channel", RefSubChannel: "SubChannel", RefServer: "Server", RefListenSocket: "ListenSocket", RefNormalSocket: "NormalSocket", } // String returns a string representation of the RefChannelType func (r RefChannelType) String() string { return refChannelTypeToString[r] } // AddTraceEvent adds trace related to the entity with specified id, using the // provided TraceEventDesc. // // If channelz is not turned ON, this will simply log the event descriptions. func AddTraceEvent(l grpclog.DepthLoggerV2, e Entity, depth int, desc *TraceEvent) { // Log only the trace description associated with the bottom most entity. d := fmt.Sprintf("[%s]%s", e, desc.Desc) switch desc.Severity { case CtUnknown, CtInfo: l.InfoDepth(depth+1, d) case CtWarning: l.WarningDepth(depth+1, d) case CtError: l.ErrorDepth(depth+1, d) } if getMaxTraceEntry() == 0 { return } if IsOn() { db.traceEvent(e.id(), desc) } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/channelz/channelmap.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/channelz/channelmap.go
/* * * Copyright 2018 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. * */ package channelz import ( "fmt" "sort" "sync" "time" ) // entry represents a node in the channelz database. type entry interface { // addChild adds a child e, whose channelz id is id to child list addChild(id int64, e entry) // deleteChild deletes a child with channelz id to be id from child list deleteChild(id int64) // triggerDelete tries to delete self from channelz database. However, if // child list is not empty, then deletion from the database is on hold until // the last child is deleted from database. triggerDelete() // deleteSelfIfReady check whether triggerDelete() has been called before, // and whether child list is now empty. If both conditions are met, then // delete self from database. deleteSelfIfReady() // getParentID returns parent ID of the entry. 0 value parent ID means no parent. getParentID() int64 Entity } // channelMap is the storage data structure for channelz. // // Methods of channelMap can be divided into two categories with respect to // locking. // // 1. Methods acquire the global lock. // 2. Methods that can only be called when global lock is held. // // A second type of method need always to be called inside a first type of method. type channelMap struct { mu sync.RWMutex topLevelChannels map[int64]struct{} channels map[int64]*Channel subChannels map[int64]*SubChannel sockets map[int64]*Socket servers map[int64]*Server } func newChannelMap() *channelMap { return &channelMap{ topLevelChannels: make(map[int64]struct{}), channels: make(map[int64]*Channel), subChannels: make(map[int64]*SubChannel), sockets: make(map[int64]*Socket), servers: make(map[int64]*Server), } } func (c *channelMap) addServer(id int64, s *Server) { c.mu.Lock() defer c.mu.Unlock() s.cm = c c.servers[id] = s } func (c *channelMap) addChannel(id int64, cn *Channel, isTopChannel bool, pid int64) { c.mu.Lock() defer c.mu.Unlock() cn.trace.cm = c c.channels[id] = cn if isTopChannel { c.topLevelChannels[id] = struct{}{} } else if p := c.channels[pid]; p != nil { p.addChild(id, cn) } else { logger.Infof("channel %d references invalid parent ID %d", id, pid) } } func (c *channelMap) addSubChannel(id int64, sc *SubChannel, pid int64) { c.mu.Lock() defer c.mu.Unlock() sc.trace.cm = c c.subChannels[id] = sc if p := c.channels[pid]; p != nil { p.addChild(id, sc) } else { logger.Infof("subchannel %d references invalid parent ID %d", id, pid) } } func (c *channelMap) addSocket(s *Socket) { c.mu.Lock() defer c.mu.Unlock() s.cm = c c.sockets[s.ID] = s if s.Parent == nil { logger.Infof("normal socket %d has no parent", s.ID) } s.Parent.(entry).addChild(s.ID, s) } // removeEntry triggers the removal of an entry, which may not indeed delete the // entry, if it has to wait on the deletion of its children and until no other // entity's channel trace references it. It may lead to a chain of entry // deletion. For example, deleting the last socket of a gracefully shutting down // server will lead to the server being also deleted. func (c *channelMap) removeEntry(id int64) { c.mu.Lock() defer c.mu.Unlock() c.findEntry(id).triggerDelete() } // tracedChannel represents tracing operations which are present on both // channels and subChannels. type tracedChannel interface { getChannelTrace() *ChannelTrace incrTraceRefCount() decrTraceRefCount() getRefName() string } // c.mu must be held by the caller func (c *channelMap) decrTraceRefCount(id int64) { e := c.findEntry(id) if v, ok := e.(tracedChannel); ok { v.decrTraceRefCount() e.deleteSelfIfReady() } } // c.mu must be held by the caller. func (c *channelMap) findEntry(id int64) entry { if v, ok := c.channels[id]; ok { return v } if v, ok := c.subChannels[id]; ok { return v } if v, ok := c.servers[id]; ok { return v } if v, ok := c.sockets[id]; ok { return v } return &dummyEntry{idNotFound: id} } // c.mu must be held by the caller // // deleteEntry deletes an entry from the channelMap. Before calling this method, // caller must check this entry is ready to be deleted, i.e removeEntry() has // been called on it, and no children still exist. func (c *channelMap) deleteEntry(id int64) entry { if v, ok := c.sockets[id]; ok { delete(c.sockets, id) return v } if v, ok := c.subChannels[id]; ok { delete(c.subChannels, id) return v } if v, ok := c.channels[id]; ok { delete(c.channels, id) delete(c.topLevelChannels, id) return v } if v, ok := c.servers[id]; ok { delete(c.servers, id) return v } return &dummyEntry{idNotFound: id} } func (c *channelMap) traceEvent(id int64, desc *TraceEvent) { c.mu.Lock() defer c.mu.Unlock() child := c.findEntry(id) childTC, ok := child.(tracedChannel) if !ok { return } childTC.getChannelTrace().append(&traceEvent{Desc: desc.Desc, Severity: desc.Severity, Timestamp: time.Now()}) if desc.Parent != nil { parent := c.findEntry(child.getParentID()) var chanType RefChannelType switch child.(type) { case *Channel: chanType = RefChannel case *SubChannel: chanType = RefSubChannel } if parentTC, ok := parent.(tracedChannel); ok { parentTC.getChannelTrace().append(&traceEvent{ Desc: desc.Parent.Desc, Severity: desc.Parent.Severity, Timestamp: time.Now(), RefID: id, RefName: childTC.getRefName(), RefType: chanType, }) childTC.incrTraceRefCount() } } } type int64Slice []int64 func (s int64Slice) Len() int { return len(s) } func (s int64Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s int64Slice) Less(i, j int) bool { return s[i] < s[j] } func copyMap(m map[int64]string) map[int64]string { n := make(map[int64]string) for k, v := range m { n[k] = v } return n } func (c *channelMap) getTopChannels(id int64, maxResults int) ([]*Channel, bool) { if maxResults <= 0 { maxResults = EntriesPerPage } c.mu.RLock() defer c.mu.RUnlock() l := int64(len(c.topLevelChannels)) ids := make([]int64, 0, l) for k := range c.topLevelChannels { ids = append(ids, k) } sort.Sort(int64Slice(ids)) idx := sort.Search(len(ids), func(i int) bool { return ids[i] >= id }) end := true var t []*Channel for _, v := range ids[idx:] { if len(t) == maxResults { end = false break } if cn, ok := c.channels[v]; ok { t = append(t, cn) } } return t, end } func (c *channelMap) getServers(id int64, maxResults int) ([]*Server, bool) { if maxResults <= 0 { maxResults = EntriesPerPage } c.mu.RLock() defer c.mu.RUnlock() ids := make([]int64, 0, len(c.servers)) for k := range c.servers { ids = append(ids, k) } sort.Sort(int64Slice(ids)) idx := sort.Search(len(ids), func(i int) bool { return ids[i] >= id }) end := true var s []*Server for _, v := range ids[idx:] { if len(s) == maxResults { end = false break } if svr, ok := c.servers[v]; ok { s = append(s, svr) } } return s, end } func (c *channelMap) getServerSockets(id int64, startID int64, maxResults int) ([]*Socket, bool) { if maxResults <= 0 { maxResults = EntriesPerPage } c.mu.RLock() defer c.mu.RUnlock() svr, ok := c.servers[id] if !ok { // server with id doesn't exist. return nil, true } svrskts := svr.sockets ids := make([]int64, 0, len(svrskts)) sks := make([]*Socket, 0, min(len(svrskts), maxResults)) for k := range svrskts { ids = append(ids, k) } sort.Sort(int64Slice(ids)) idx := sort.Search(len(ids), func(i int) bool { return ids[i] >= startID }) end := true for _, v := range ids[idx:] { if len(sks) == maxResults { end = false break } if ns, ok := c.sockets[v]; ok { sks = append(sks, ns) } } return sks, end } func (c *channelMap) getChannel(id int64) *Channel { c.mu.RLock() defer c.mu.RUnlock() return c.channels[id] } func (c *channelMap) getSubChannel(id int64) *SubChannel { c.mu.RLock() defer c.mu.RUnlock() return c.subChannels[id] } func (c *channelMap) getSocket(id int64) *Socket { c.mu.RLock() defer c.mu.RUnlock() return c.sockets[id] } func (c *channelMap) getServer(id int64) *Server { c.mu.RLock() defer c.mu.RUnlock() return c.servers[id] } type dummyEntry struct { // dummyEntry is a fake entry to handle entry not found case. idNotFound int64 Entity } func (d *dummyEntry) String() string { return fmt.Sprintf("non-existent entity #%d", d.idNotFound) } func (d *dummyEntry) ID() int64 { return d.idNotFound } func (d *dummyEntry) addChild(id int64, e entry) { // Note: It is possible for a normal program to reach here under race // condition. For example, there could be a race between ClientConn.Close() // info being propagated to addrConn and http2Client. ClientConn.Close() // cancel the context and result in http2Client to error. The error info is // then caught by transport monitor and before addrConn.tearDown() is called // in side ClientConn.Close(). Therefore, the addrConn will create a new // transport. And when registering the new transport in channelz, its parent // addrConn could have already been torn down and deleted from channelz // tracking, and thus reach the code here. logger.Infof("attempt to add child of type %T with id %d to a parent (id=%d) that doesn't currently exist", e, id, d.idNotFound) } func (d *dummyEntry) deleteChild(id int64) { // It is possible for a normal program to reach here under race condition. // Refer to the example described in addChild(). logger.Infof("attempt to delete child with id %d from a parent (id=%d) that doesn't currently exist", id, d.idNotFound) } func (d *dummyEntry) triggerDelete() { logger.Warningf("attempt to delete an entry (id=%d) that doesn't currently exist", d.idNotFound) } func (*dummyEntry) deleteSelfIfReady() { // code should not reach here. deleteSelfIfReady is always called on an existing entry. } func (*dummyEntry) getParentID() int64 { return 0 } // Entity is implemented by all channelz types. type Entity interface { isEntity() fmt.Stringer id() int64 }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/channelz/syscall_linux.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/channelz/syscall_linux.go
/* * * Copyright 2018 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. * */ package channelz import ( "syscall" "golang.org/x/sys/unix" ) // SocketOptionData defines the struct to hold socket option data, and related // getter function to obtain info from fd. type SocketOptionData struct { Linger *unix.Linger RecvTimeout *unix.Timeval SendTimeout *unix.Timeval TCPInfo *unix.TCPInfo } // Getsockopt defines the function to get socket options requested by channelz. // It is to be passed to syscall.RawConn.Control(). func (s *SocketOptionData) Getsockopt(fd uintptr) { if v, err := unix.GetsockoptLinger(int(fd), syscall.SOL_SOCKET, syscall.SO_LINGER); err == nil { s.Linger = v } if v, err := unix.GetsockoptTimeval(int(fd), syscall.SOL_SOCKET, syscall.SO_RCVTIMEO); err == nil { s.RecvTimeout = v } if v, err := unix.GetsockoptTimeval(int(fd), syscall.SOL_SOCKET, syscall.SO_SNDTIMEO); err == nil { s.SendTimeout = v } if v, err := unix.GetsockoptTCPInfo(int(fd), syscall.SOL_TCP, syscall.TCP_INFO); err == nil { s.TCPInfo = v } } // GetSocketOption gets the socket option info of the conn. func GetSocketOption(socket any) *SocketOptionData { c, ok := socket.(syscall.Conn) if !ok { return nil } data := &SocketOptionData{} if rawConn, err := c.SyscallConn(); err == nil { rawConn.Control(data.Getsockopt) return data } return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/channelz/syscall_nonlinux.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/channelz/syscall_nonlinux.go
//go:build !linux /* * * Copyright 2018 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. * */ package channelz import ( "sync" ) var once sync.Once // SocketOptionData defines the struct to hold socket option data, and related // getter function to obtain info from fd. // Windows OS doesn't support Socket Option type SocketOptionData struct { } // Getsockopt defines the function to get socket options requested by channelz. // It is to be passed to syscall.RawConn.Control(). // Windows OS doesn't support Socket Option func (s *SocketOptionData) Getsockopt(uintptr) { once.Do(func() { logger.Warning("Channelz: socket options are not supported on non-linux environments") }) } // GetSocketOption gets the socket option info of the conn. func GetSocketOption(any) *SocketOptionData { return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/channelz/server.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/channelz/server.go
/* * * Copyright 2024 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. * */ package channelz import ( "fmt" "sync/atomic" ) // Server is the channelz representation of a server. type Server struct { Entity ID int64 RefName string ServerMetrics ServerMetrics closeCalled bool sockets map[int64]string listenSockets map[int64]string cm *channelMap } // ServerMetrics defines a struct containing metrics for servers. type ServerMetrics struct { // The number of incoming calls started on the server. CallsStarted atomic.Int64 // The number of incoming calls that have completed with an OK status. CallsSucceeded atomic.Int64 // The number of incoming calls that have a completed with a non-OK status. CallsFailed atomic.Int64 // The last time a call was started on the server. LastCallStartedTimestamp atomic.Int64 } // NewServerMetricsForTesting returns an initialized ServerMetrics. func NewServerMetricsForTesting(started, succeeded, failed, timestamp int64) *ServerMetrics { sm := &ServerMetrics{} sm.CallsStarted.Store(started) sm.CallsSucceeded.Store(succeeded) sm.CallsFailed.Store(failed) sm.LastCallStartedTimestamp.Store(timestamp) return sm } // CopyFrom copies the metrics data from the provided ServerMetrics // instance into the current instance. func (sm *ServerMetrics) CopyFrom(o *ServerMetrics) { sm.CallsStarted.Store(o.CallsStarted.Load()) sm.CallsSucceeded.Store(o.CallsSucceeded.Load()) sm.CallsFailed.Store(o.CallsFailed.Load()) sm.LastCallStartedTimestamp.Store(o.LastCallStartedTimestamp.Load()) } // ListenSockets returns the listening sockets for s. func (s *Server) ListenSockets() map[int64]string { db.mu.RLock() defer db.mu.RUnlock() return copyMap(s.listenSockets) } // String returns a printable description of s. func (s *Server) String() string { return fmt.Sprintf("Server #%d", s.ID) } func (s *Server) id() int64 { return s.ID } func (s *Server) addChild(id int64, e entry) { switch v := e.(type) { case *Socket: switch v.SocketType { case SocketTypeNormal: s.sockets[id] = v.RefName case SocketTypeListen: s.listenSockets[id] = v.RefName } default: logger.Errorf("cannot add a child (id = %d) of type %T to a server", id, e) } } func (s *Server) deleteChild(id int64) { delete(s.sockets, id) delete(s.listenSockets, id) s.deleteSelfIfReady() } func (s *Server) triggerDelete() { s.closeCalled = true s.deleteSelfIfReady() } func (s *Server) deleteSelfIfReady() { if !s.closeCalled || len(s.sockets)+len(s.listenSockets) != 0 { return } s.cm.deleteEntry(s.ID) } func (s *Server) getParentID() int64 { return 0 }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/channelz/funcs.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/channelz/funcs.go
/* * * Copyright 2018 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. * */ // Package channelz defines internal APIs for enabling channelz service, entry // registration/deletion, and accessing channelz data. It also defines channelz // metric struct formats. package channelz import ( "sync/atomic" "time" "google.golang.org/grpc/internal" ) var ( // IDGen is the global channelz entity ID generator. It should not be used // outside this package except by tests. IDGen IDGenerator db = newChannelMap() // EntriesPerPage defines the number of channelz entries to be shown on a web page. EntriesPerPage = 50 curState int32 ) // TurnOn turns on channelz data collection. func TurnOn() { atomic.StoreInt32(&curState, 1) } func init() { internal.ChannelzTurnOffForTesting = func() { atomic.StoreInt32(&curState, 0) } } // IsOn returns whether channelz data collection is on. func IsOn() bool { return atomic.LoadInt32(&curState) == 1 } // GetTopChannels returns a slice of top channel's ChannelMetric, along with a // boolean indicating whether there's more top channels to be queried for. // // The arg id specifies that only top channel with id at or above it will be // included in the result. The returned slice is up to a length of the arg // maxResults or EntriesPerPage if maxResults is zero, and is sorted in ascending // id order. func GetTopChannels(id int64, maxResults int) ([]*Channel, bool) { return db.getTopChannels(id, maxResults) } // GetServers returns a slice of server's ServerMetric, along with a // boolean indicating whether there's more servers to be queried for. // // The arg id specifies that only server with id at or above it will be included // in the result. The returned slice is up to a length of the arg maxResults or // EntriesPerPage if maxResults is zero, and is sorted in ascending id order. func GetServers(id int64, maxResults int) ([]*Server, bool) { return db.getServers(id, maxResults) } // GetServerSockets returns a slice of server's (identified by id) normal socket's // SocketMetrics, along with a boolean indicating whether there's more sockets to // be queried for. // // The arg startID specifies that only sockets with id at or above it will be // included in the result. The returned slice is up to a length of the arg maxResults // or EntriesPerPage if maxResults is zero, and is sorted in ascending id order. func GetServerSockets(id int64, startID int64, maxResults int) ([]*Socket, bool) { return db.getServerSockets(id, startID, maxResults) } // GetChannel returns the Channel for the channel (identified by id). func GetChannel(id int64) *Channel { return db.getChannel(id) } // GetSubChannel returns the SubChannel for the subchannel (identified by id). func GetSubChannel(id int64) *SubChannel { return db.getSubChannel(id) } // GetSocket returns the Socket for the socket (identified by id). func GetSocket(id int64) *Socket { return db.getSocket(id) } // GetServer returns the ServerMetric for the server (identified by id). func GetServer(id int64) *Server { return db.getServer(id) } // RegisterChannel registers the given channel c in the channelz database with // target as its target and reference name, and adds it to the child list of its // parent. parent == nil means no parent. // // Returns a unique channelz identifier assigned to this channel. // // If channelz is not turned ON, the channelz database is not mutated. func RegisterChannel(parent *Channel, target string) *Channel { id := IDGen.genID() if !IsOn() { return &Channel{ID: id} } isTopChannel := parent == nil cn := &Channel{ ID: id, RefName: target, nestedChans: make(map[int64]string), subChans: make(map[int64]string), Parent: parent, trace: &ChannelTrace{CreationTime: time.Now(), Events: make([]*traceEvent, 0, getMaxTraceEntry())}, } cn.ChannelMetrics.Target.Store(&target) db.addChannel(id, cn, isTopChannel, cn.getParentID()) return cn } // RegisterSubChannel registers the given subChannel c in the channelz database // with ref as its reference name, and adds it to the child list of its parent // (identified by pid). // // Returns a unique channelz identifier assigned to this subChannel. // // If channelz is not turned ON, the channelz database is not mutated. func RegisterSubChannel(parent *Channel, ref string) *SubChannel { id := IDGen.genID() sc := &SubChannel{ ID: id, RefName: ref, parent: parent, } if !IsOn() { return sc } sc.sockets = make(map[int64]string) sc.trace = &ChannelTrace{CreationTime: time.Now(), Events: make([]*traceEvent, 0, getMaxTraceEntry())} db.addSubChannel(id, sc, parent.ID) return sc } // RegisterServer registers the given server s in channelz database. It returns // the unique channelz tracking id assigned to this server. // // If channelz is not turned ON, the channelz database is not mutated. func RegisterServer(ref string) *Server { id := IDGen.genID() if !IsOn() { return &Server{ID: id} } svr := &Server{ RefName: ref, sockets: make(map[int64]string), listenSockets: make(map[int64]string), ID: id, } db.addServer(id, svr) return svr } // RegisterSocket registers the given normal socket s in channelz database // with ref as its reference name, and adds it to the child list of its parent // (identified by skt.Parent, which must be set). It returns the unique channelz // tracking id assigned to this normal socket. // // If channelz is not turned ON, the channelz database is not mutated. func RegisterSocket(skt *Socket) *Socket { skt.ID = IDGen.genID() if IsOn() { db.addSocket(skt) } return skt } // RemoveEntry removes an entry with unique channelz tracking id to be id from // channelz database. // // If channelz is not turned ON, this function is a no-op. func RemoveEntry(id int64) { if !IsOn() { return } db.removeEntry(id) } // IDGenerator is an incrementing atomic that tracks IDs for channelz entities. type IDGenerator struct { id int64 } // Reset resets the generated ID back to zero. Should only be used at // initialization or by tests sensitive to the ID number. func (i *IDGenerator) Reset() { atomic.StoreInt64(&i.id, 0) } func (i *IDGenerator) genID() int64 { return atomic.AddInt64(&i.id, 1) } // Identifier is an opaque channelz identifier used to expose channelz symbols // outside of grpc. Currently only implemented by Channel since no other // types require exposure outside grpc. type Identifier interface { Entity channelzIdentifier() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/channelz/channel.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/channelz/channel.go
/* * * Copyright 2024 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. * */ package channelz import ( "fmt" "sync/atomic" "google.golang.org/grpc/connectivity" ) // Channel represents a channel within channelz, which includes metrics and // internal channelz data, such as channelz id, child list, etc. type Channel struct { Entity // ID is the channelz id of this channel. ID int64 // RefName is the human readable reference string of this channel. RefName string closeCalled bool nestedChans map[int64]string subChans map[int64]string Parent *Channel trace *ChannelTrace // traceRefCount is the number of trace events that reference this channel. // Non-zero traceRefCount means the trace of this channel cannot be deleted. traceRefCount int32 // ChannelMetrics holds connectivity state, target and call metrics for the // channel within channelz. ChannelMetrics ChannelMetrics } // Implemented to make Channel implement the Identifier interface used for // nesting. func (c *Channel) channelzIdentifier() {} // String returns a string representation of the Channel, including its parent // entity and ID. func (c *Channel) String() string { if c.Parent == nil { return fmt.Sprintf("Channel #%d", c.ID) } return fmt.Sprintf("%s Channel #%d", c.Parent, c.ID) } func (c *Channel) id() int64 { return c.ID } // SubChans returns a copy of the map of sub-channels associated with the // Channel. func (c *Channel) SubChans() map[int64]string { db.mu.RLock() defer db.mu.RUnlock() return copyMap(c.subChans) } // NestedChans returns a copy of the map of nested channels associated with the // Channel. func (c *Channel) NestedChans() map[int64]string { db.mu.RLock() defer db.mu.RUnlock() return copyMap(c.nestedChans) } // Trace returns a copy of the Channel's trace data. func (c *Channel) Trace() *ChannelTrace { db.mu.RLock() defer db.mu.RUnlock() return c.trace.copy() } // ChannelMetrics holds connectivity state, target and call metrics for the // channel within channelz. type ChannelMetrics struct { // The current connectivity state of the channel. State atomic.Pointer[connectivity.State] // The target this channel originally tried to connect to. May be absent Target atomic.Pointer[string] // The number of calls started on the channel. CallsStarted atomic.Int64 // The number of calls that have completed with an OK status. CallsSucceeded atomic.Int64 // The number of calls that have a completed with a non-OK status. CallsFailed atomic.Int64 // The last time a call was started on the channel. LastCallStartedTimestamp atomic.Int64 } // CopyFrom copies the metrics in o to c. For testing only. func (c *ChannelMetrics) CopyFrom(o *ChannelMetrics) { c.State.Store(o.State.Load()) c.Target.Store(o.Target.Load()) c.CallsStarted.Store(o.CallsStarted.Load()) c.CallsSucceeded.Store(o.CallsSucceeded.Load()) c.CallsFailed.Store(o.CallsFailed.Load()) c.LastCallStartedTimestamp.Store(o.LastCallStartedTimestamp.Load()) } // Equal returns true iff the metrics of c are the same as the metrics of o. // For testing only. func (c *ChannelMetrics) Equal(o any) bool { oc, ok := o.(*ChannelMetrics) if !ok { return false } if (c.State.Load() == nil) != (oc.State.Load() == nil) { return false } if c.State.Load() != nil && *c.State.Load() != *oc.State.Load() { return false } if (c.Target.Load() == nil) != (oc.Target.Load() == nil) { return false } if c.Target.Load() != nil && *c.Target.Load() != *oc.Target.Load() { return false } return c.CallsStarted.Load() == oc.CallsStarted.Load() && c.CallsFailed.Load() == oc.CallsFailed.Load() && c.CallsSucceeded.Load() == oc.CallsSucceeded.Load() && c.LastCallStartedTimestamp.Load() == oc.LastCallStartedTimestamp.Load() } func strFromPointer(s *string) string { if s == nil { return "" } return *s } // String returns a string representation of the ChannelMetrics, including its // state, target, and call metrics. func (c *ChannelMetrics) String() string { return fmt.Sprintf("State: %v, Target: %s, CallsStarted: %v, CallsSucceeded: %v, CallsFailed: %v, LastCallStartedTimestamp: %v", c.State.Load(), strFromPointer(c.Target.Load()), c.CallsStarted.Load(), c.CallsSucceeded.Load(), c.CallsFailed.Load(), c.LastCallStartedTimestamp.Load(), ) } // NewChannelMetricForTesting creates a new instance of ChannelMetrics with // specified initial values for testing purposes. func NewChannelMetricForTesting(state connectivity.State, target string, started, succeeded, failed, timestamp int64) *ChannelMetrics { c := &ChannelMetrics{} c.State.Store(&state) c.Target.Store(&target) c.CallsStarted.Store(started) c.CallsSucceeded.Store(succeeded) c.CallsFailed.Store(failed) c.LastCallStartedTimestamp.Store(timestamp) return c } func (c *Channel) addChild(id int64, e entry) { switch v := e.(type) { case *SubChannel: c.subChans[id] = v.RefName case *Channel: c.nestedChans[id] = v.RefName default: logger.Errorf("cannot add a child (id = %d) of type %T to a channel", id, e) } } func (c *Channel) deleteChild(id int64) { delete(c.subChans, id) delete(c.nestedChans, id) c.deleteSelfIfReady() } func (c *Channel) triggerDelete() { c.closeCalled = true c.deleteSelfIfReady() } func (c *Channel) getParentID() int64 { if c.Parent == nil { return -1 } return c.Parent.ID } // deleteSelfFromTree tries to delete the channel from the channelz entry relation tree, which means // deleting the channel reference from its parent's child list. // // In order for a channel to be deleted from the tree, it must meet the criteria that, removal of the // corresponding grpc object has been invoked, and the channel does not have any children left. // // The returned boolean value indicates whether the channel has been successfully deleted from tree. func (c *Channel) deleteSelfFromTree() (deleted bool) { if !c.closeCalled || len(c.subChans)+len(c.nestedChans) != 0 { return false } // not top channel if c.Parent != nil { c.Parent.deleteChild(c.ID) } return true } // deleteSelfFromMap checks whether it is valid to delete the channel from the map, which means // deleting the channel from channelz's tracking entirely. Users can no longer use id to query the // channel, and its memory will be garbage collected. // // The trace reference count of the channel must be 0 in order to be deleted from the map. This is // specified in the channel tracing gRFC that as long as some other trace has reference to an entity, // the trace of the referenced entity must not be deleted. In order to release the resource allocated // by grpc, the reference to the grpc object is reset to a dummy object. // // deleteSelfFromMap must be called after deleteSelfFromTree returns true. // // It returns a bool to indicate whether the channel can be safely deleted from map. func (c *Channel) deleteSelfFromMap() (delete bool) { return c.getTraceRefCount() == 0 } // deleteSelfIfReady tries to delete the channel itself from the channelz database. // The delete process includes two steps: // 1. delete the channel from the entry relation tree, i.e. delete the channel reference from its // parent's child list. // 2. delete the channel from the map, i.e. delete the channel entirely from channelz. Lookup by id // will return entry not found error. func (c *Channel) deleteSelfIfReady() { if !c.deleteSelfFromTree() { return } if !c.deleteSelfFromMap() { return } db.deleteEntry(c.ID) c.trace.clear() } func (c *Channel) getChannelTrace() *ChannelTrace { return c.trace } func (c *Channel) incrTraceRefCount() { atomic.AddInt32(&c.traceRefCount, 1) } func (c *Channel) decrTraceRefCount() { atomic.AddInt32(&c.traceRefCount, -1) } func (c *Channel) getTraceRefCount() int { i := atomic.LoadInt32(&c.traceRefCount) return int(i) } func (c *Channel) getRefName() string { return c.RefName }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/channelz/socket.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/channelz/socket.go
/* * * Copyright 2024 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. * */ package channelz import ( "fmt" "net" "sync/atomic" "google.golang.org/grpc/credentials" ) // SocketMetrics defines the struct that the implementor of Socket interface // should return from ChannelzMetric(). type SocketMetrics struct { // The number of streams that have been started. StreamsStarted atomic.Int64 // The number of streams that have ended successfully: // On client side, receiving frame with eos bit set. // On server side, sending frame with eos bit set. StreamsSucceeded atomic.Int64 // The number of streams that have ended unsuccessfully: // On client side, termination without receiving frame with eos bit set. // On server side, termination without sending frame with eos bit set. StreamsFailed atomic.Int64 // The number of messages successfully sent on this socket. MessagesSent atomic.Int64 MessagesReceived atomic.Int64 // The number of keep alives sent. This is typically implemented with HTTP/2 // ping messages. KeepAlivesSent atomic.Int64 // The last time a stream was created by this endpoint. Usually unset for // servers. LastLocalStreamCreatedTimestamp atomic.Int64 // The last time a stream was created by the remote endpoint. Usually unset // for clients. LastRemoteStreamCreatedTimestamp atomic.Int64 // The last time a message was sent by this endpoint. LastMessageSentTimestamp atomic.Int64 // The last time a message was received by this endpoint. LastMessageReceivedTimestamp atomic.Int64 } // EphemeralSocketMetrics are metrics that change rapidly and are tracked // outside of channelz. type EphemeralSocketMetrics struct { // The amount of window, granted to the local endpoint by the remote endpoint. // This may be slightly out of date due to network latency. This does NOT // include stream level or TCP level flow control info. LocalFlowControlWindow int64 // The amount of window, granted to the remote endpoint by the local endpoint. // This may be slightly out of date due to network latency. This does NOT // include stream level or TCP level flow control info. RemoteFlowControlWindow int64 } // SocketType represents the type of socket. type SocketType string // SocketType can be one of these. const ( SocketTypeNormal = "NormalSocket" SocketTypeListen = "ListenSocket" ) // Socket represents a socket within channelz which includes socket // metrics and data related to socket activity and provides methods // for managing and interacting with sockets. type Socket struct { Entity SocketType SocketType ID int64 Parent Entity cm *channelMap SocketMetrics SocketMetrics EphemeralMetrics func() *EphemeralSocketMetrics RefName string // The locally bound address. Immutable. LocalAddr net.Addr // The remote bound address. May be absent. Immutable. RemoteAddr net.Addr // Optional, represents the name of the remote endpoint, if different than // the original target name. Immutable. RemoteName string // Immutable. SocketOptions *SocketOptionData // Immutable. Security credentials.ChannelzSecurityValue } // String returns a string representation of the Socket, including its parent // entity, socket type, and ID. func (ls *Socket) String() string { return fmt.Sprintf("%s %s #%d", ls.Parent, ls.SocketType, ls.ID) } func (ls *Socket) id() int64 { return ls.ID } func (ls *Socket) addChild(id int64, e entry) { logger.Errorf("cannot add a child (id = %d) of type %T to a listen socket", id, e) } func (ls *Socket) deleteChild(id int64) { logger.Errorf("cannot delete a child (id = %d) from a listen socket", id) } func (ls *Socket) triggerDelete() { ls.cm.deleteEntry(ls.ID) ls.Parent.(entry).deleteChild(ls.ID) } func (ls *Socket) deleteSelfIfReady() { logger.Errorf("cannot call deleteSelfIfReady on a listen socket") } func (ls *Socket) getParentID() int64 { return ls.Parent.id() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/idle/idle.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/idle/idle.go
/* * * Copyright 2023 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. * */ // Package idle contains a component for managing idleness (entering and exiting) // based on RPC activity. package idle import ( "fmt" "math" "sync" "sync/atomic" "time" ) // For overriding in unit tests. var timeAfterFunc = func(d time.Duration, f func()) *time.Timer { return time.AfterFunc(d, f) } // Enforcer is the functionality provided by grpc.ClientConn to enter // and exit from idle mode. type Enforcer interface { ExitIdleMode() error EnterIdleMode() } // Manager implements idleness detection and calls the configured Enforcer to // enter/exit idle mode when appropriate. Must be created by NewManager. type Manager struct { // State accessed atomically. lastCallEndTime int64 // Unix timestamp in nanos; time when the most recent RPC completed. activeCallsCount int32 // Count of active RPCs; -math.MaxInt32 means channel is idle or is trying to get there. activeSinceLastTimerCheck int32 // Boolean; True if there was an RPC since the last timer callback. closed int32 // Boolean; True when the manager is closed. // Can be accessed without atomics or mutex since these are set at creation // time and read-only after that. enforcer Enforcer // Functionality provided by grpc.ClientConn. timeout time.Duration // idleMu is used to guarantee mutual exclusion in two scenarios: // - Opposing intentions: // - a: Idle timeout has fired and handleIdleTimeout() is trying to put // the channel in idle mode because the channel has been inactive. // - b: At the same time an RPC is made on the channel, and OnCallBegin() // is trying to prevent the channel from going idle. // - Competing intentions: // - The channel is in idle mode and there are multiple RPCs starting at // the same time, all trying to move the channel out of idle. Only one // of them should succeed in doing so, while the other RPCs should // piggyback on the first one and be successfully handled. idleMu sync.RWMutex actuallyIdle bool timer *time.Timer } // NewManager creates a new idleness manager implementation for the // given idle timeout. It begins in idle mode. func NewManager(enforcer Enforcer, timeout time.Duration) *Manager { return &Manager{ enforcer: enforcer, timeout: timeout, actuallyIdle: true, activeCallsCount: -math.MaxInt32, } } // resetIdleTimerLocked resets the idle timer to the given duration. Called // when exiting idle mode or when the timer fires and we need to reset it. func (m *Manager) resetIdleTimerLocked(d time.Duration) { if m.isClosed() || m.timeout == 0 || m.actuallyIdle { return } // It is safe to ignore the return value from Reset() because this method is // only ever called from the timer callback or when exiting idle mode. if m.timer != nil { m.timer.Stop() } m.timer = timeAfterFunc(d, m.handleIdleTimeout) } func (m *Manager) resetIdleTimer(d time.Duration) { m.idleMu.Lock() defer m.idleMu.Unlock() m.resetIdleTimerLocked(d) } // handleIdleTimeout is the timer callback that is invoked upon expiry of the // configured idle timeout. The channel is considered inactive if there are no // ongoing calls and no RPC activity since the last time the timer fired. func (m *Manager) handleIdleTimeout() { if m.isClosed() { return } if atomic.LoadInt32(&m.activeCallsCount) > 0 { m.resetIdleTimer(m.timeout) return } // There has been activity on the channel since we last got here. Reset the // timer and return. if atomic.LoadInt32(&m.activeSinceLastTimerCheck) == 1 { // Set the timer to fire after a duration of idle timeout, calculated // from the time the most recent RPC completed. atomic.StoreInt32(&m.activeSinceLastTimerCheck, 0) m.resetIdleTimer(time.Duration(atomic.LoadInt64(&m.lastCallEndTime)-time.Now().UnixNano()) + m.timeout) return } // Now that we've checked that there has been no activity, attempt to enter // idle mode, which is very likely to succeed. if m.tryEnterIdleMode() { // Successfully entered idle mode. No timer needed until we exit idle. return } // Failed to enter idle mode due to a concurrent RPC that kept the channel // active, or because of an error from the channel. Undo the attempt to // enter idle, and reset the timer to try again later. m.resetIdleTimer(m.timeout) } // tryEnterIdleMode instructs the channel to enter idle mode. But before // that, it performs a last minute check to ensure that no new RPC has come in, // making the channel active. // // Return value indicates whether or not the channel moved to idle mode. // // Holds idleMu which ensures mutual exclusion with exitIdleMode. func (m *Manager) tryEnterIdleMode() bool { // Setting the activeCallsCount to -math.MaxInt32 indicates to OnCallBegin() // that the channel is either in idle mode or is trying to get there. if !atomic.CompareAndSwapInt32(&m.activeCallsCount, 0, -math.MaxInt32) { // This CAS operation can fail if an RPC started after we checked for // activity in the timer handler, or one was ongoing from before the // last time the timer fired, or if a test is attempting to enter idle // mode without checking. In all cases, abort going into idle mode. return false } // N.B. if we fail to enter idle mode after this, we must re-add // math.MaxInt32 to m.activeCallsCount. m.idleMu.Lock() defer m.idleMu.Unlock() if atomic.LoadInt32(&m.activeCallsCount) != -math.MaxInt32 { // We raced and lost to a new RPC. Very rare, but stop entering idle. atomic.AddInt32(&m.activeCallsCount, math.MaxInt32) return false } if atomic.LoadInt32(&m.activeSinceLastTimerCheck) == 1 { // A very short RPC could have come in (and also finished) after we // checked for calls count and activity in handleIdleTimeout(), but // before the CAS operation. So, we need to check for activity again. atomic.AddInt32(&m.activeCallsCount, math.MaxInt32) return false } // No new RPCs have come in since we set the active calls count value to // -math.MaxInt32. And since we have the lock, it is safe to enter idle mode // unconditionally now. m.enforcer.EnterIdleMode() m.actuallyIdle = true return true } // EnterIdleModeForTesting instructs the channel to enter idle mode. func (m *Manager) EnterIdleModeForTesting() { m.tryEnterIdleMode() } // OnCallBegin is invoked at the start of every RPC. func (m *Manager) OnCallBegin() error { if m.isClosed() { return nil } if atomic.AddInt32(&m.activeCallsCount, 1) > 0 { // Channel is not idle now. Set the activity bit and allow the call. atomic.StoreInt32(&m.activeSinceLastTimerCheck, 1) return nil } // Channel is either in idle mode or is in the process of moving to idle // mode. Attempt to exit idle mode to allow this RPC. if err := m.ExitIdleMode(); err != nil { // Undo the increment to calls count, and return an error causing the // RPC to fail. atomic.AddInt32(&m.activeCallsCount, -1) return err } atomic.StoreInt32(&m.activeSinceLastTimerCheck, 1) return nil } // ExitIdleMode instructs m to call the enforcer's ExitIdleMode and update m's // internal state. func (m *Manager) ExitIdleMode() error { // Holds idleMu which ensures mutual exclusion with tryEnterIdleMode. m.idleMu.Lock() defer m.idleMu.Unlock() if m.isClosed() || !m.actuallyIdle { // This can happen in three scenarios: // - handleIdleTimeout() set the calls count to -math.MaxInt32 and called // tryEnterIdleMode(). But before the latter could grab the lock, an RPC // came in and OnCallBegin() noticed that the calls count is negative. // - Channel is in idle mode, and multiple new RPCs come in at the same // time, all of them notice a negative calls count in OnCallBegin and get // here. The first one to get the lock would get the channel to exit idle. // - Channel is not in idle mode, and the user calls Connect which calls // m.ExitIdleMode. // // In any case, there is nothing to do here. return nil } if err := m.enforcer.ExitIdleMode(); err != nil { return fmt.Errorf("failed to exit idle mode: %w", err) } // Undo the idle entry process. This also respects any new RPC attempts. atomic.AddInt32(&m.activeCallsCount, math.MaxInt32) m.actuallyIdle = false // Start a new timer to fire after the configured idle timeout. m.resetIdleTimerLocked(m.timeout) return nil } // OnCallEnd is invoked at the end of every RPC. func (m *Manager) OnCallEnd() { if m.isClosed() { return } // Record the time at which the most recent call finished. atomic.StoreInt64(&m.lastCallEndTime, time.Now().UnixNano()) // Decrement the active calls count. This count can temporarily go negative // when the timer callback is in the process of moving the channel to idle // mode, but one or more RPCs come in and complete before the timer callback // can get done with the process of moving to idle mode. atomic.AddInt32(&m.activeCallsCount, -1) } func (m *Manager) isClosed() bool { return atomic.LoadInt32(&m.closed) == 1 } // Close stops the timer associated with the Manager, if it exists. func (m *Manager) Close() { atomic.StoreInt32(&m.closed, 1) m.idleMu.Lock() if m.timer != nil { m.timer.Stop() m.timer = nil } m.idleMu.Unlock() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/envconfig/xds.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/envconfig/xds.go
/* * * Copyright 2020 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. * */ package envconfig import ( "os" ) const ( // XDSBootstrapFileNameEnv is the env variable to set bootstrap file name. // Do not use this and read from env directly. Its value is read and kept in // variable XDSBootstrapFileName. // // When both bootstrap FileName and FileContent are set, FileName is used. XDSBootstrapFileNameEnv = "GRPC_XDS_BOOTSTRAP" // XDSBootstrapFileContentEnv is the env variable to set bootstrap file // content. Do not use this and read from env directly. Its value is read // and kept in variable XDSBootstrapFileContent. // // When both bootstrap FileName and FileContent are set, FileName is used. XDSBootstrapFileContentEnv = "GRPC_XDS_BOOTSTRAP_CONFIG" ) var ( // XDSBootstrapFileName holds the name of the file which contains xDS // bootstrap configuration. Users can specify the location of the bootstrap // file by setting the environment variable "GRPC_XDS_BOOTSTRAP". // // When both bootstrap FileName and FileContent are set, FileName is used. XDSBootstrapFileName = os.Getenv(XDSBootstrapFileNameEnv) // XDSBootstrapFileContent holds the content of the xDS bootstrap // configuration. Users can specify the bootstrap config by setting the // environment variable "GRPC_XDS_BOOTSTRAP_CONFIG". // // When both bootstrap FileName and FileContent are set, FileName is used. XDSBootstrapFileContent = os.Getenv(XDSBootstrapFileContentEnv) // C2PResolverTestOnlyTrafficDirectorURI is the TD URI for testing. C2PResolverTestOnlyTrafficDirectorURI = os.Getenv("GRPC_TEST_ONLY_GOOGLE_C2P_RESOLVER_TRAFFIC_DIRECTOR_URI") // XDSDualstackEndpointsEnabled is true if gRPC should read the // "additional addresses" in the xDS endpoint resource. XDSDualstackEndpointsEnabled = boolFromEnv("GRPC_EXPERIMENTAL_XDS_DUALSTACK_ENDPOINTS", true) // XDSSystemRootCertsEnabled is true when xDS enabled gRPC clients can use // the system's default root certificates for TLS certificate validation. // For more details, see: // https://github.com/grpc/proposal/blob/master/A82-xds-system-root-certs.md. XDSSystemRootCertsEnabled = boolFromEnv("GRPC_EXPERIMENTAL_XDS_SYSTEM_ROOT_CERTS", false) )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/envconfig/envconfig.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/internal/envconfig/envconfig.go
/* * * Copyright 2018 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. * */ // Package envconfig contains grpc settings configured by environment variables. package envconfig import ( "os" "strconv" "strings" ) var ( // TXTErrIgnore is set if TXT errors should be ignored ("GRPC_GO_IGNORE_TXT_ERRORS" is not "false"). TXTErrIgnore = boolFromEnv("GRPC_GO_IGNORE_TXT_ERRORS", true) // RingHashCap indicates the maximum ring size which defaults to 4096 // entries but may be overridden by setting the environment variable // "GRPC_RING_HASH_CAP". This does not override the default bounds // checking which NACKs configs specifying ring sizes > 8*1024*1024 (~8M). RingHashCap = uint64FromEnv("GRPC_RING_HASH_CAP", 4096, 1, 8*1024*1024) // LeastRequestLB is set if we should support the least_request_experimental // LB policy, which can be enabled by setting the environment variable // "GRPC_EXPERIMENTAL_ENABLE_LEAST_REQUEST" to "true". LeastRequestLB = boolFromEnv("GRPC_EXPERIMENTAL_ENABLE_LEAST_REQUEST", false) // ALTSMaxConcurrentHandshakes is the maximum number of concurrent ALTS // handshakes that can be performed. ALTSMaxConcurrentHandshakes = uint64FromEnv("GRPC_ALTS_MAX_CONCURRENT_HANDSHAKES", 100, 1, 100) // EnforceALPNEnabled is set if TLS connections to servers with ALPN disabled // should be rejected. The HTTP/2 protocol requires ALPN to be enabled, this // option is present for backward compatibility. This option may be overridden // by setting the environment variable "GRPC_ENFORCE_ALPN_ENABLED" to "true" // or "false". EnforceALPNEnabled = boolFromEnv("GRPC_ENFORCE_ALPN_ENABLED", true) // XDSFallbackSupport is the env variable that controls whether support for // xDS fallback is turned on. If this is unset or is false, only the first // xDS server in the list of server configs will be used. XDSFallbackSupport = boolFromEnv("GRPC_EXPERIMENTAL_XDS_FALLBACK", true) // NewPickFirstEnabled is set if the new pickfirst leaf policy is to be used // instead of the exiting pickfirst implementation. This can be enabled by // setting the environment variable "GRPC_EXPERIMENTAL_ENABLE_NEW_PICK_FIRST" // to "true". NewPickFirstEnabled = boolFromEnv("GRPC_EXPERIMENTAL_ENABLE_NEW_PICK_FIRST", false) ) func boolFromEnv(envVar string, def bool) bool { if def { // The default is true; return true unless the variable is "false". return !strings.EqualFold(os.Getenv(envVar), "false") } // The default is false; return false unless the variable is "true". return strings.EqualFold(os.Getenv(envVar), "true") } func uint64FromEnv(envVar string, def, min, max uint64) uint64 { v, err := strconv.ParseUint(os.Getenv(envVar), 10, 64) if err != nil { return def } if v < min { return min } if v > max { return max } return v }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false