probe/ping/service/connection/connection.go

109 lines
2.5 KiB
Go
Raw Normal View History

2018-09-17 16:25:56 +00:00
package connection
import (
"crypto/tls"
"net"
"strings"
"time"
omd "git.loafle.net/overflow/model/discovery"
omm "git.loafle.net/overflow/model/meta"
ounp "git.loafle.net/overflow/util-go/net/ping"
)
func Ping(service *omd.Service, pingOption ounp.Option) (ounp.Result, error) {
2018-09-21 16:18:59 +00:00
responses := make(map[int]ounp.Response, 0)
summary := &ounp.PingSummary{}
2018-09-17 16:25:56 +00:00
pingResult := &ounp.PingResult{
2018-09-21 16:18:59 +00:00
Responses: responses,
Summary: summary,
2018-09-17 16:25:56 +00:00
}
2018-09-21 16:18:59 +00:00
var _sum float64
var _res *ounp.PingResponse
2018-09-20 05:57:30 +00:00
for indexR := 0; indexR < pingOption.GetCount(); indexR++ {
2018-09-21 16:18:59 +00:00
summary.SendCount = summary.SendCount + 1
_res = &ounp.PingResponse{}
if 0 < indexR {
select {
case <-time.After(time.Duration(pingOption.GetDeadline()) * time.Second):
2018-09-17 16:25:56 +00:00
}
}
2018-09-21 16:18:59 +00:00
_, elapsedTime, err := sendPing(service, pingOption)
if 0 == indexR {
summary.MinTime = elapsedTime
summary.MaxTime = elapsedTime
2018-09-17 16:25:56 +00:00
}
2018-09-21 16:18:59 +00:00
if nil == err {
_sum = _sum + elapsedTime
summary.ReceiveCount = summary.ReceiveCount + 1
if summary.MinTime > elapsedTime {
summary.MinTime = elapsedTime
}
if summary.MaxTime < elapsedTime {
summary.MaxTime = elapsedTime
}
_res.Time = elapsedTime
} else {
_res.Error = err.Error()
}
pingResult.Responses[indexR] = _res
}
2018-09-17 16:25:56 +00:00
2018-09-21 16:18:59 +00:00
if 0 == summary.ReceiveCount {
summary.AvgTime = 0
summary.LossPercent = 100
} else {
summary.AvgTime = _sum / float64(summary.ReceiveCount)
summary.LossPercent = (float32(summary.SendCount) - float32(summary.ReceiveCount)) / float32(summary.SendCount) * float32(100)
2018-09-17 16:25:56 +00:00
}
return pingResult, nil
}
2018-09-21 16:18:59 +00:00
func sendPing(service *omd.Service, pingOption ounp.Option) (ttl int, elapsedTime float64, err error) {
startTime := time.Now()
var conn net.Conn
conn, err = getConnection(service, pingOption)
if nil != err {
return
}
defer conn.Close()
elapsed := time.Since(startTime)
elapsedTime = elapsed.Seconds() * 1E3
return
}
2018-09-17 16:25:56 +00:00
func getConnection(service *omd.Service, pingOption ounp.Option) (net.Conn, error) {
addr := net.JoinHostPort(service.Port.Host.Address, service.Port.PortNumber.String())
portType := strings.ToLower(service.Port.MetaPortType.Key)
switch omm.ToMetaCryptoTypeEnum(service.MetaCryptoType) {
case omm.MetaCryptoTypeEnumTLS:
dialer := &net.Dialer{
Timeout: time.Duration(pingOption.GetDeadline()) * time.Second,
}
return tls.DialWithDialer(
dialer,
portType,
addr,
&tls.Config{
InsecureSkipVerify: true,
ServerName: service.Port.Host.Address,
},
)
default:
return net.DialTimeout(portType, addr, time.Duration(pingOption.GetDeadline())*time.Second)
}
}