...

Source file src/edge-infra.dev/pkg/sds/lib/etcd/server/embed/embed.go

Documentation: edge-infra.dev/pkg/sds/lib/etcd/server/embed

     1  package embed
     2  
     3  import (
     4  	"net"
     5  	"net/url"
     6  
     7  	"go.etcd.io/etcd/server/v3/embed"
     8  )
     9  
    10  const (
    11  	DefaultHost = "localhost"
    12  	DefaultPort = "0"
    13  )
    14  
    15  // Config struct provides the configuration options for an etcd instance.
    16  type Config struct {
    17  	Name      string
    18  	PeerURL   *url.URL
    19  	ClientURL *url.URL
    20  	LogLevel  string
    21  	embed     *embed.Config
    22  }
    23  
    24  // assignedAddress provides functionality to find an open host:port combination
    25  type assignedAddress struct {
    26  	host, port string
    27  }
    28  
    29  // assign tries to claim a URL using the provided host and port. A connection
    30  // will be established to the assigned address to prevent other processes from
    31  // attempting to claim the host:port for 60s.
    32  //
    33  // If no host is provided, then localhost will be used as a default.
    34  //
    35  // If no port is provided, then an available port will be selected at random.
    36  func (a *assignedAddress) assign(url *url.URL) error {
    37  	l, err := reserve(url.Hostname(), url.Port())
    38  	if err != nil {
    39  		return err
    40  	}
    41  	defer l.Close()
    42  	a.host, a.port, err = net.SplitHostPort(l.Addr().String())
    43  	return err
    44  }
    45  
    46  // reserve will reserve the host:port combination. If no host is provided, then
    47  // localhost is used. If no port is provided, then one is selected at random
    48  // from the pool of available ports.
    49  func reserve(host, port string) (net.Listener, error) {
    50  	if host == "" {
    51  		host = DefaultHost
    52  	}
    53  	if port == "" {
    54  		port = DefaultPort
    55  	}
    56  
    57  	addr, err := net.ResolveTCPAddr("tcp", net.JoinHostPort(host, port))
    58  	if err != nil {
    59  		return nil, err
    60  	}
    61  	return net.ListenTCP("tcp", addr)
    62  }
    63  
    64  // url returns the assignedAddress as a url.URL object
    65  func (a *assignedAddress) url() url.URL {
    66  	return url.URL{
    67  		Scheme: "http",
    68  		Host:   net.JoinHostPort(a.host, a.port),
    69  	}
    70  }
    71  

View as plain text