...

Source file src/cloud.google.com/go/auth/grpctransport/dial_socketopt.go

Documentation: cloud.google.com/go/auth/grpctransport

     1  // Copyright 2023 Google LLC
     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  //go:build linux
    16  // +build linux
    17  
    18  package grpctransport
    19  
    20  import (
    21  	"context"
    22  	"net"
    23  	"syscall"
    24  
    25  	"google.golang.org/grpc"
    26  )
    27  
    28  const (
    29  	// defaultTCPUserTimeout is the default TCP_USER_TIMEOUT socket option. By
    30  	// default is 20 seconds.
    31  	tcpUserTimeoutMilliseconds = 20000
    32  
    33  	// Copied from golang.org/x/sys/unix.TCP_USER_TIMEOUT.
    34  	tcpUserTimeoutOp = 0x12
    35  )
    36  
    37  func init() {
    38  	// timeoutDialerOption is a grpc.DialOption that contains dialer with
    39  	// socket option TCP_USER_TIMEOUT. This dialer requires go versions 1.11+.
    40  	timeoutDialerOption = grpc.WithContextDialer(dialTCPUserTimeout)
    41  }
    42  
    43  func dialTCPUserTimeout(ctx context.Context, addr string) (net.Conn, error) {
    44  	control := func(network, address string, c syscall.RawConn) error {
    45  		var syscallErr error
    46  		controlErr := c.Control(func(fd uintptr) {
    47  			syscallErr = syscall.SetsockoptInt(
    48  				int(fd), syscall.IPPROTO_TCP, tcpUserTimeoutOp, tcpUserTimeoutMilliseconds)
    49  		})
    50  		if syscallErr != nil {
    51  			return syscallErr
    52  		}
    53  		if controlErr != nil {
    54  			return controlErr
    55  		}
    56  		return nil
    57  	}
    58  	d := &net.Dialer{
    59  		Control: control,
    60  	}
    61  	return d.DialContext(ctx, "tcp", addr)
    62  }
    63  

View as plain text