github.com/richardbowden/terraform@v0.6.12-0.20160901200758-30ea22c25211/builtin/providers/vsphere/config.go (about)

     1  package vsphere
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"net/url"
     7  	"os"
     8  	"path/filepath"
     9  	"time"
    10  
    11  	"github.com/vmware/govmomi"
    12  	"github.com/vmware/govmomi/vim25/debug"
    13  	"golang.org/x/net/context"
    14  )
    15  
    16  type Config struct {
    17  	User          string
    18  	Password      string
    19  	VSphereServer string
    20  	InsecureFlag  bool
    21  	Debug         bool
    22  	DebugPath     string
    23  	DebugPathRun  string
    24  }
    25  
    26  // Client() returns a new client for accessing VMWare vSphere.
    27  func (c *Config) Client() (*govmomi.Client, error) {
    28  	u, err := url.Parse("https://" + c.VSphereServer + "/sdk")
    29  	if err != nil {
    30  		return nil, fmt.Errorf("Error parse url: %s", err)
    31  	}
    32  
    33  	u.User = url.UserPassword(c.User, c.Password)
    34  
    35  	err = c.EnableDebug()
    36  	if err != nil {
    37  		return nil, fmt.Errorf("Error setting up client debug: %s", err)
    38  	}
    39  
    40  	client, err := govmomi.NewClient(context.TODO(), u, c.InsecureFlag)
    41  	if err != nil {
    42  		return nil, fmt.Errorf("Error setting up client: %s", err)
    43  	}
    44  
    45  	log.Printf("[INFO] VMWare vSphere Client configured for URL: %s", c.VSphereServer)
    46  
    47  	return client, nil
    48  }
    49  
    50  func (c *Config) EnableDebug() error {
    51  	if !c.Debug {
    52  		return nil
    53  	}
    54  
    55  	// Base path for storing debug logs.
    56  	r := c.DebugPath
    57  	if r == "" {
    58  		r = filepath.Join(os.Getenv("HOME"), ".govmomi")
    59  	}
    60  	r = filepath.Join(r, "debug")
    61  
    62  	// Path for this particular run.
    63  	run := c.DebugPathRun
    64  	if run == "" {
    65  		now := time.Now().Format("2006-01-02T15-04-05.999999999")
    66  		r = filepath.Join(r, now)
    67  	} else {
    68  		// reuse the same path
    69  		r = filepath.Join(r, run)
    70  		_ = os.RemoveAll(r)
    71  	}
    72  
    73  	err := os.MkdirAll(r, 0700)
    74  	if err != nil {
    75  		log.Printf("[ERROR] Client debug setup failed: %v", err)
    76  		return err
    77  	}
    78  
    79  	p := debug.FileProvider{
    80  		Path: r,
    81  	}
    82  
    83  	debug.SetProvider(&p)
    84  	return nil
    85  }