2015-10-06 05:53:07 +02:00
|
|
|
package vsphere
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"log"
|
|
|
|
"net/url"
|
2016-06-02 21:15:01 +02:00
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
"time"
|
2015-10-06 05:53:07 +02:00
|
|
|
|
|
|
|
"github.com/vmware/govmomi"
|
2016-06-02 21:15:01 +02:00
|
|
|
"github.com/vmware/govmomi/vim25/debug"
|
2015-10-06 05:53:07 +02:00
|
|
|
"golang.org/x/net/context"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Config struct {
|
|
|
|
User string
|
|
|
|
Password string
|
2015-11-01 15:07:23 +01:00
|
|
|
VSphereServer string
|
2015-11-15 04:24:28 +01:00
|
|
|
InsecureFlag bool
|
2016-06-02 21:15:01 +02:00
|
|
|
Debug bool
|
|
|
|
DebugPath string
|
|
|
|
DebugPathRun string
|
2015-10-06 05:53:07 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Client() returns a new client for accessing VMWare vSphere.
|
|
|
|
func (c *Config) Client() (*govmomi.Client, error) {
|
2015-11-01 15:07:23 +01:00
|
|
|
u, err := url.Parse("https://" + c.VSphereServer + "/sdk")
|
2015-10-06 05:53:07 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("Error parse url: %s", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
u.User = url.UserPassword(c.User, c.Password)
|
|
|
|
|
2016-06-02 21:15:01 +02:00
|
|
|
err = c.EnableDebug()
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("Error setting up client debug: %s", err)
|
|
|
|
}
|
|
|
|
|
2015-11-15 04:24:28 +01:00
|
|
|
client, err := govmomi.NewClient(context.TODO(), u, c.InsecureFlag)
|
2015-10-06 05:53:07 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("Error setting up client: %s", err)
|
|
|
|
}
|
|
|
|
|
2016-06-02 21:15:01 +02:00
|
|
|
log.Printf("[INFO] VMWare vSphere Client configured for URL: %s", c.VSphereServer)
|
2015-10-06 05:53:07 +02:00
|
|
|
|
|
|
|
return client, nil
|
|
|
|
}
|
2016-06-02 21:15:01 +02:00
|
|
|
|
|
|
|
func (c *Config) EnableDebug() error {
|
|
|
|
if !c.Debug {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Base path for storing debug logs.
|
|
|
|
r := c.DebugPath
|
|
|
|
if r == "" {
|
|
|
|
r = filepath.Join(os.Getenv("HOME"), ".govmomi")
|
|
|
|
}
|
|
|
|
r = filepath.Join(r, "debug")
|
|
|
|
|
|
|
|
// Path for this particular run.
|
|
|
|
run := c.DebugPathRun
|
|
|
|
if run == "" {
|
|
|
|
now := time.Now().Format("2006-01-02T15-04-05.999999999")
|
|
|
|
r = filepath.Join(r, now)
|
|
|
|
} else {
|
|
|
|
// reuse the same path
|
|
|
|
r = filepath.Join(r, run)
|
|
|
|
_ = os.RemoveAll(r)
|
|
|
|
}
|
|
|
|
|
|
|
|
err := os.MkdirAll(r, 0700)
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("[ERROR] Client debug setup failed: %v", err)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
p := debug.FileProvider{
|
|
|
|
Path: r,
|
|
|
|
}
|
|
|
|
|
|
|
|
debug.SetProvider(&p)
|
|
|
|
return nil
|
|
|
|
}
|