VictoriaMetrics/lib/netutil/netutil.go

54 lines
1.4 KiB
Go
Raw Normal View History

package netutil
import (
"context"
"fmt"
"math/rand"
"net"
"strings"
"time"
)
// IsTrivialNetworkError returns true if the err can be ignored during logging.
func IsTrivialNetworkError(err error) bool {
// Suppress trivial network errors, which could occur at remote side.
s := err.Error()
if strings.Contains(s, "broken pipe") || strings.Contains(s, "reset by peer") {
return true
}
return false
}
// DialMaybeSRV dials the given addr.
//
// The addr may be either the usual TCP address or srv+host form, where host is SRV addr.
// If the addr has srv+host form, then the host is resolved with SRV into randomly chosen TCP address for the connection.
func DialMaybeSRV(ctx context.Context, network, addr string) (net.Conn, error) {
if strings.HasPrefix(addr, "srv+") {
addr = strings.TrimPrefix(addr, "srv+")
_, addrs, err := Resolver.LookupSRV(ctx, "", "", addr)
if err != nil {
return nil, fmt.Errorf("cannot resolve SRV addr %s: %w", addr, err)
}
if len(addrs) == 0 {
return nil, fmt.Errorf("missing SRV records for %s", addr)
}
n := rand.Intn(len(addrs))
addr = fmt.Sprintf("%s:%d", addrs[n].Target, addrs[n].Port)
}
return Dialer.DialContext(ctx, network, addr)
}
// Resolver is default DNS resolver.
var Resolver = &net.Resolver{
PreferGo: true,
StrictErrors: true,
}
// Dialer is default network dialer.
var Dialer = &net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: TCP6Enabled(),
}