github.com/containerd/Containerd@v1.4.13/pkg/dialer/dialer.go (about)

     1  /*
     2     Copyright The containerd Authors.
     3  
     4     Licensed under the Apache License, Version 2.0 (the "License");
     5     you may not use this file except in compliance with the License.
     6     You may obtain a copy of the License at
     7  
     8         http://www.apache.org/licenses/LICENSE-2.0
     9  
    10     Unless required by applicable law or agreed to in writing, software
    11     distributed under the License is distributed on an "AS IS" BASIS,
    12     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13     See the License for the specific language governing permissions and
    14     limitations under the License.
    15  */
    16  
    17  package dialer
    18  
    19  import (
    20  	"context"
    21  	"net"
    22  	"time"
    23  
    24  	"github.com/pkg/errors"
    25  )
    26  
    27  type dialResult struct {
    28  	c   net.Conn
    29  	err error
    30  }
    31  
    32  // ContextDialer returns a GRPC net.Conn connected to the provided address
    33  func ContextDialer(ctx context.Context, address string) (net.Conn, error) {
    34  	if deadline, ok := ctx.Deadline(); ok {
    35  		return timeoutDialer(address, time.Until(deadline))
    36  	}
    37  	return timeoutDialer(address, 0)
    38  }
    39  
    40  // Dialer returns a GRPC net.Conn connected to the provided address
    41  // Deprecated: use ContextDialer and grpc.WithContextDialer.
    42  var Dialer = timeoutDialer
    43  
    44  func timeoutDialer(address string, timeout time.Duration) (net.Conn, error) {
    45  	var (
    46  		stopC = make(chan struct{})
    47  		synC  = make(chan *dialResult)
    48  	)
    49  	go func() {
    50  		defer close(synC)
    51  		for {
    52  			select {
    53  			case <-stopC:
    54  				return
    55  			default:
    56  				c, err := dialer(address, timeout)
    57  				if isNoent(err) {
    58  					<-time.After(10 * time.Millisecond)
    59  					continue
    60  				}
    61  				synC <- &dialResult{c, err}
    62  				return
    63  			}
    64  		}
    65  	}()
    66  	select {
    67  	case dr := <-synC:
    68  		return dr.c, dr.err
    69  	case <-time.After(timeout):
    70  		close(stopC)
    71  		go func() {
    72  			dr := <-synC
    73  			if dr != nil && dr.c != nil {
    74  				dr.c.Close()
    75  			}
    76  		}()
    77  		return nil, errors.Errorf("dial %s: timeout", address)
    78  	}
    79  }