From 0c5cd9c0460accc52e7bdca625d455741f1f6b3a Mon Sep 17 00:00:00 2001 From: Flavio Castelli Date: Sun, 18 Feb 2018 14:25:07 +0100 Subject: Ensure libvirt connection is released Deallocate the libvirt connect object before exit. Fixes issue #266 Signed-off-by: Flavio Castelli --- libvirt/config.go | 12 ++++++++---- libvirt/provider.go | 3 +++ main.go | 18 ++++++++++++++++++ 3 files changed, 29 insertions(+), 4 deletions(-) diff --git a/libvirt/config.go b/libvirt/config.go index 41edc021..6c16e114 100644 --- a/libvirt/config.go +++ b/libvirt/config.go @@ -18,13 +18,17 @@ type Client struct { // Client libvirt, generate libvirt client given URI func (c *Config) Client() (*Client, error) { - conn, err := libvirt.NewConnect(c.URI) - if err != nil { - return nil, err + var err error + + if LibvirtClient == nil { + LibvirtClient, err = libvirt.NewConnect(c.URI) + if err != nil { + return nil, err + } } client := &Client{ - libvirt: conn, + libvirt: LibvirtClient, } log.Println("[INFO] Created libvirt client") diff --git a/libvirt/provider.go b/libvirt/provider.go index 07b0c72e..cbe9ab95 100644 --- a/libvirt/provider.go +++ b/libvirt/provider.go @@ -4,10 +4,13 @@ import ( "github.com/hashicorp/terraform/helper/mutexkv" "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/terraform" + + libvirt "github.com/libvirt/libvirt-go" ) // Global poolMutexKV var poolMutexKV = mutexkv.NewMutexKV() +var LibvirtClient *libvirt.Connect // Provider libvirt func Provider() terraform.ResourceProvider { diff --git a/main.go b/main.go index 08194c95..d84366ac 100644 --- a/main.go +++ b/main.go @@ -3,11 +3,29 @@ package main import ( "github.com/dmacvicar/terraform-provider-libvirt/libvirt" "github.com/hashicorp/terraform/plugin" + "log" "math/rand" "time" ) func main() { + defer func() { + if libvirt.LibvirtClient != nil { + alive, err := libvirt.LibvirtClient.IsAlive() + if err != nil { + log.Printf("[ERROR] cannot determine libvirt connection status: %v", err) + } + if alive { + ret, err := libvirt.LibvirtClient.Close() + if err != nil { + log.Printf("[ERROR] cannot close libvirt connection %d - %v", ret, err) + } else { + libvirt.LibvirtClient = nil + } + } + } + }() + plugin.Serve(&plugin.ServeOpts{ ProviderFunc: libvirt.Provider, }) -- cgit v1.2.3