dial_socketopt.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // Copyright 2019 Google LLC.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // +build go1.11,linux
  5. package grpc
  6. import (
  7. "context"
  8. "net"
  9. "syscall"
  10. "golang.org/x/sys/unix"
  11. "google.golang.org/grpc"
  12. )
  13. const (
  14. // defaultTCPUserTimeout is the default TCP_USER_TIMEOUT socket option. By
  15. // default is 20 seconds.
  16. tcpUserTimeoutMilliseconds = 20000
  17. )
  18. func init() {
  19. // timeoutDialerOption is a grpc.DialOption that contains dialer with
  20. // socket option TCP_USER_TIMEOUT. This dialer requires go versions 1.11+.
  21. timeoutDialerOption = grpc.WithContextDialer(dialTCPUserTimeout)
  22. }
  23. func dialTCPUserTimeout(ctx context.Context, addr string) (net.Conn, error) {
  24. control := func(network, address string, c syscall.RawConn) error {
  25. var syscallErr error
  26. controlErr := c.Control(func(fd uintptr) {
  27. syscallErr = syscall.SetsockoptInt(
  28. int(fd), syscall.IPPROTO_TCP, unix.TCP_USER_TIMEOUT, tcpUserTimeoutMilliseconds)
  29. })
  30. if syscallErr != nil {
  31. return syscallErr
  32. }
  33. if controlErr != nil {
  34. return controlErr
  35. }
  36. return nil
  37. }
  38. d := &net.Dialer{
  39. Control: control,
  40. }
  41. return d.DialContext(ctx, "tcp", addr)
  42. }