Skip to content

Commit

Permalink
Reduce a number of creating connection
Browse files Browse the repository at this point in the history
  • Loading branch information
whywaita committed Sep 9, 2024
1 parent c447595 commit 9cd81df
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions server/pkg/lxdclient/connect.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,11 @@ var (
// ConnectLXDWithTimeout connect LXD API with timeout
// lxd.ConnectLXD is not support context yet. So ConnectLXDWithTimeout occurred goroutine leak if timeout.
func ConnectLXDWithTimeout(host, clientCert, clientKey string) (*lxd.InstanceServer, error) {
client, ok := loadConnectedInstance(host)
if ok {
return client, nil
}

type resultConnectLXD struct {
client lxd.InstanceServer
err error
Expand All @@ -105,9 +110,32 @@ func ConnectLXDWithTimeout(host, clientCert, clientKey string) (*lxd.InstanceSer
if result.err != nil {
return nil, fmt.Errorf("failed to connect LXD: %w", result.err)
}

storeConnectedInstance(host, result.client)

return &result.client, nil
case <-time.After(2 * time.Second):
// lxd.ConnectLXD() is not support context.Context yet. need to refactor it after support context.Context.
return nil, ErrTimeoutConnectLXD
}
}

// connectedInstances is map of connected LXD instances
// key: lxdhost value: LXDHost
var connectedInstances sync.Map

// storeConnectedInstance store connected instance
func storeConnectedInstance(host string, lh lxd.InstanceServer) {
connectedInstances.Store(host, lh)
}

// loadConnectedInstance load connected instance
func loadConnectedInstance(host string) (*lxd.InstanceServer, bool) {
v, ok := connectedInstances.Load(host)
if !ok {
return nil, false
}
i := v.(lxd.InstanceServer)

return &i, true
}

0 comments on commit 9cd81df

Please sign in to comment.