github.com/GuanceCloud/cliutils@v1.1.21/dialtesting/traceroute.go (about) 1 // Unless explicitly stated otherwise all files in this repository are licensed 2 // under the MIT License. 3 // This product includes software developed at Guance Cloud (https://www.guance.com/). 4 // Copyright 2021-present Guance, Inc. 5 6 package dialtesting 7 8 import ( 9 "math" 10 "net" 11 "time" 12 ) 13 14 const ( 15 MaxTimeout = 10 * time.Second 16 MaxHops = 60 17 MaxRetry = 3 18 ) 19 20 // TracerouteOption represent traceroute option. 21 type TracerouteOption struct { 22 Hops int 23 Retry int 24 Timeout string 25 26 timeout time.Duration 27 } 28 29 // Response for sent packet, may be failed response when timeout. 30 type Response struct { 31 From net.IP 32 ResponseTime time.Duration 33 34 fail bool 35 } 36 37 // RouteItem represent each retry response. 38 type RouteItem struct { 39 IP string `json:"ip"` 40 ResponseTime float64 `json:"response_time"` 41 } 42 43 // Route is summary for each hop. 44 type Route struct { 45 Total int `json:"total"` 46 Failed int `json:"failed"` 47 Loss float64 `json:"loss"` 48 AvgCost float64 `json:"avg_cost"` 49 MinCost float64 `json:"min_cost"` 50 MaxCost float64 `json:"max_cost"` 51 StdCost float64 `json:"std_cost"` 52 Items []*RouteItem `json:"items"` 53 } 54 55 // Packet represent sent packet. 56 type Packet struct { 57 ID int 58 Dst net.IP 59 60 startTime time.Time 61 } 62 63 func mean(v []float64) float64 { 64 var res float64 = 0 65 var n int = len(v) 66 67 if n == 0 { 68 return 0 69 } 70 71 for i := 0; i < n; i++ { 72 res += v[i] 73 } 74 return res / float64(n) 75 } 76 77 func variance(v []float64) float64 { 78 var res float64 = 0 79 m := mean(v) 80 var n int = len(v) 81 for i := 0; i < n; i++ { 82 res += (v[i] - m) * (v[i] - m) 83 } 84 if n <= 1 { 85 return 0 86 } 87 return res / float64(n-1) 88 } 89 90 func std(v []float64) float64 { 91 if len(v) == 0 { 92 return 0 93 } 94 return math.Sqrt(variance(v)) 95 }