github.com/cloud-foundations/dominator@v0.0.0-20221004181915-6e4fee580046/lib/rpcclientpool/impl.go (about)

     1  package rpcclientpool
     2  
     3  import (
     4  	gonet "net"
     5  	gorpc "net/rpc"
     6  
     7  	"github.com/Cloud-Foundations/Dominator/lib/connpool"
     8  	"github.com/Cloud-Foundations/Dominator/lib/net"
     9  	"github.com/Cloud-Foundations/Dominator/lib/net/rpc"
    10  )
    11  
    12  var (
    13  	defaultDialer = &gonet.Dialer{}
    14  )
    15  
    16  func newClientResource(network, address string, http bool,
    17  	path string, dialer net.Dialer) *ClientResource {
    18  	if path == "" {
    19  		path = gorpc.DefaultRPCPath
    20  	}
    21  	clientResource := &ClientResource{
    22  		network: network,
    23  		address: address,
    24  		http:    http,
    25  		path:    path,
    26  		dialer:  dialer,
    27  	}
    28  	clientResource.privateClientResource.clientResource = clientResource
    29  	rp := connpool.GetResourcePool()
    30  	clientResource.resource = rp.Create(&clientResource.privateClientResource)
    31  	return clientResource
    32  }
    33  
    34  func (cr *ClientResource) get(cancelChannel <-chan struct{}) (*Client, error) {
    35  	if err := cr.resource.Get(cancelChannel); err != nil {
    36  		return nil, err
    37  	}
    38  	cr.client.rpcClient = cr.rpcClient
    39  	return cr.client, nil
    40  }
    41  
    42  func (pcr *privateClientResource) Allocate() error {
    43  	cr := pcr.clientResource
    44  	var rpcClient *gorpc.Client
    45  	var err error
    46  	if cr.http {
    47  		rpcClient, err = rpc.DialHTTPPath(
    48  			cr.dialer, cr.network, cr.address, cr.path)
    49  	} else {
    50  		rpcClient, err = rpc.Dial(cr.dialer, cr.network, cr.address)
    51  	}
    52  	if err != nil {
    53  		return err
    54  	}
    55  	client := &Client{resource: cr}
    56  	cr.client = client
    57  	cr.rpcClient = rpcClient
    58  	return nil
    59  }
    60  
    61  func (pcr *privateClientResource) Release() error {
    62  	cr := pcr.clientResource
    63  	err := cr.client.rpcClient.Close()
    64  	cr.client.rpcClient = nil
    65  	cr.client = nil
    66  	return err
    67  }
    68  
    69  func (client *Client) close() error {
    70  	return client.resource.resource.Release()
    71  }
    72  
    73  func (client *Client) put() {
    74  	client.rpcClient = nil
    75  	client.resource.resource.Put()
    76  }