istio.io/istio@v0.0.0-20240520182934-d79c90f27776/pkg/test/echo/common/util.go (about) 1 // Copyright Istio Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package common 16 17 import ( 18 "flag" 19 "net/http" 20 "strings" 21 "time" 22 23 "istio.io/istio/pkg/test/echo/proto" 24 ) 25 26 func init() { 27 flag.DurationVar(&DefaultRequestTimeout, "istio.test.echo.requestTimeout", DefaultRequestTimeout, 28 "Specifies the timeout for individual ForwardEcho calls.") 29 } 30 31 var DefaultRequestTimeout = 5 * time.Second 32 33 const ( 34 ConnectionTimeout = 2 * time.Second 35 DefaultCount = 1 36 ) 37 38 // FillInDefaults fills in the timeout and count if not specified in the given message. 39 func FillInDefaults(request *proto.ForwardEchoRequest) { 40 request.TimeoutMicros = DurationToMicros(GetTimeout(request)) 41 request.Count = int32(GetCount(request)) 42 } 43 44 // GetTimeout returns the timeout value as a time.Duration or DefaultRequestTimeout if not set. 45 func GetTimeout(request *proto.ForwardEchoRequest) time.Duration { 46 timeout := MicrosToDuration(request.TimeoutMicros) 47 if timeout == 0 { 48 timeout = DefaultRequestTimeout 49 } 50 return timeout 51 } 52 53 // GetCount returns the count value or DefaultCount if not set. 54 func GetCount(request *proto.ForwardEchoRequest) int { 55 if request.Count > 1 { 56 return int(request.Count) 57 } 58 return DefaultCount 59 } 60 61 func HTTPToProtoHeaders(headers http.Header) []*proto.Header { 62 out := make([]*proto.Header, 0, len(headers)) 63 for k, v := range headers { 64 out = append(out, &proto.Header{Key: k, Value: strings.Join(v, ",")}) 65 } 66 return out 67 } 68 69 func ProtoToHTTPHeaders(headers []*proto.Header) http.Header { 70 out := make(http.Header) 71 for _, h := range headers { 72 // Avoid using .Add() to allow users to pass non-canonical forms 73 out[h.Key] = append(out[h.Key], h.Value) 74 } 75 return out 76 } 77 78 // GetHeaders returns the headers for the message. 79 func GetHeaders(request *proto.ForwardEchoRequest) http.Header { 80 return ProtoToHTTPHeaders(request.Headers) 81 } 82 83 // MicrosToDuration converts the given microseconds to a time.Duration. 84 func MicrosToDuration(micros int64) time.Duration { 85 return time.Duration(micros) * time.Microsecond 86 } 87 88 // DurationToMicros converts the given duration to microseconds. 89 func DurationToMicros(d time.Duration) int64 { 90 return int64(d / time.Microsecond) 91 }