本文整理匯總了Golang中github.com/vmware/govmomi.NewClient函數的典型用法代碼示例。如果您正苦於以下問題:Golang NewClient函數的具體用法?Golang NewClient怎麽用?Golang NewClient使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了NewClient函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: NewVMHost
// NewVMHost connects to a ESXi or vCenter instance and returns a *VMHost
func NewVMHost(insecure bool, hostURL_param, user, pass string) (*VMHost, error) {
ctx, _ := context.WithCancel(context.Background())
hostURL, err := url.Parse("https://" + hostURL_param + "/sdk")
hostURL.User = url.UserPassword(user, pass)
cli, err := govmomi.NewClient(ctx, hostURL, insecure)
if err != nil {
return nil, err
}
mac, err := getLocalMAC()
if err != nil {
return nil, err
}
vmh := &VMHost{
client: cli,
Ctx: ctx,
mac: mac,
}
vm, err := vmh.findVM(vmh.mac)
if err != nil {
return nil, err
}
vmh.Vm = vm
return vmh, nil
}
示例2: TestClusterESX
func TestClusterESX(t *testing.T) {
content := esx.ServiceContent
s := New(NewServiceInstance(content, esx.RootFolder))
ts := s.NewServer()
defer ts.Close()
ctx := context.Background()
c, err := govmomi.NewClient(ctx, ts.URL, true)
if err != nil {
t.Fatal(err)
}
dc := object.NewDatacenter(c.Client, esx.Datacenter.Reference())
folders, err := dc.Folders(ctx)
if err != nil {
t.Fatal(err)
}
_, err = folders.HostFolder.CreateCluster(ctx, "cluster1", types.ClusterConfigSpecEx{})
if err == nil {
t.Fatal("expected error")
}
}
示例3: TestClusterVC
func TestClusterVC(t *testing.T) {
content := vc.ServiceContent
s := New(NewServiceInstance(content, vc.RootFolder))
ts := s.NewServer()
defer ts.Close()
ctx := context.Background()
c, err := govmomi.NewClient(ctx, ts.URL, true)
if err != nil {
t.Fatal(err)
}
f := object.NewRootFolder(c.Client)
dc, err := f.CreateDatacenter(ctx, "foo")
if err != nil {
t.Error(err)
}
folders, err := dc.Folders(ctx)
if err != nil {
t.Fatal(err)
}
cluster, err := folders.HostFolder.CreateCluster(ctx, "cluster1", types.ClusterConfigSpecEx{})
if err != nil {
t.Fatal(err)
}
_, err = folders.HostFolder.CreateCluster(ctx, "cluster1", types.ClusterConfigSpecEx{})
if err == nil {
t.Error("expected DuplicateName error")
}
spec := types.HostConnectSpec{}
for _, fail := range []bool{true, false} {
task, err := cluster.AddHost(ctx, spec, true, nil, nil)
if err != nil {
t.Fatal(err)
}
_, err = task.WaitForResult(ctx, nil)
if fail {
if err == nil {
t.Error("expected error")
}
spec.HostName = "localhost"
} else {
if err != nil {
t.Error(err)
}
}
}
}
示例4: TestWaitForUpdates
func TestWaitForUpdates(t *testing.T) {
folder := esx.RootFolder
s := New(NewServiceInstance(esx.ServiceContent, folder))
ts := s.NewServer()
defer ts.Close()
ctx := context.Background()
c, err := govmomi.NewClient(ctx, ts.URL, true)
if err != nil {
t.Fatal(err)
}
cb := func(once bool) func([]types.PropertyChange) bool {
return func(pc []types.PropertyChange) bool {
if len(pc) != 1 {
t.Fail()
}
c := pc[0]
if c.Op != types.PropertyChangeOpAssign {
t.Fail()
}
if c.Name != "name" {
t.Fail()
}
if c.Val.(string) != folder.Name {
t.Fail()
}
return once
}
}
pc := property.DefaultCollector(c.Client)
props := []string{"name"}
err = property.Wait(ctx, pc, folder.Reference(), props, cb(true))
if err != nil {
t.Error(err)
}
// incremental updates not yet suppported
err = property.Wait(ctx, pc, folder.Reference(), props, cb(false))
if err == nil {
t.Error("expected error")
}
// test object not found
Map.Remove(folder.Reference())
err = property.Wait(ctx, pc, folder.Reference(), props, cb(true))
if err == nil {
t.Error("expected error")
}
}
示例5: Connect
// Connect establishes the connection for the session but nothing more
func (s *Session) Connect(ctx context.Context) (*Session, error) {
soapURL, err := soap.ParseURL(s.Service)
if soapURL == nil || err != nil {
return nil, errors.Errorf("SDK URL (%s) could not be parsed: %s", s.Service, err)
}
// update the service URL with the resolved soapURL
s.Service = soapURL.String()
// we can't set a keep alive if we log in directly with client creation
user := soapURL.User
soapURL.User = nil
// 1st connect without any userinfo to get the API type
s.Client, err = govmomi.NewClient(ctx, soapURL, s.Insecure)
if err != nil {
return nil, errors.Errorf("Failed to connect to %s: %s", soapURL.String(), err)
}
if s.HasCertificate() && s.Client.IsVC() {
// load the certificates
cert, err2 := tls.X509KeyPair([]byte(s.ExtensionCert), []byte(s.ExtensionKey))
if err2 != nil {
return nil, errors.Errorf("Unable to load X509 key pair(%s,%s): %s",
s.ExtensionCert, s.ExtensionKey, err2)
}
// create the new client
s.Client, err = govmomi.NewClientWithCertificate(ctx, soapURL, s.Insecure, cert)
if err != nil {
return nil, errors.Errorf("Failed to connect to %s: %s", soapURL.String(), err)
}
}
if s.Keepalive != 0 {
// now that we've verified everything, enable keepalive
s.RoundTripper = session.KeepAlive(s.Client.RoundTripper, s.Keepalive)
}
// and now that the keepalive is registered we can log in to trigger it
if !s.IsVC() || !s.HasCertificate() {
log.Debugf("Trying to log in with username/password in lieu of cert")
err = s.Client.Login(ctx, user)
} else {
log.Debugf("Logging into extension %s", s.ExtensionName)
err = s.LoginExtensionByCertificate(ctx, s.ExtensionName, "")
}
if err != nil {
return nil, errors.Errorf("Failed to log in to %s: %s", soapURL.String(), err)
}
s.Finder = find.NewFinder(s.Vim25(), true)
// log high-level environement information
s.logEnvironmentInfo()
return s, nil
}
示例6: createClient
func (i *vSphereInstanceManager) createClient(ctx context.Context) (*govmomi.Client, error) {
client, err := govmomi.NewClient(ctx, i.vSphereURL, true)
if err != nil {
return nil, err
}
client.Client.RoundTripper = vim25.Retry(client.Client.RoundTripper, vim25.TemporaryNetworkError(3))
return client, nil
}
示例7: TestServeHTTP
func TestServeHTTP(t *testing.T) {
configs := []struct {
content types.ServiceContent
folder mo.Folder
}{
{esx.ServiceContent, esx.RootFolder},
{vc.ServiceContent, vc.RootFolder},
}
for _, config := range configs {
s := New(NewServiceInstance(config.content, config.folder))
ts := s.NewServer()
defer ts.Close()
ctx := context.Background()
client, err := govmomi.NewClient(ctx, ts.URL, true)
if err != nil {
t.Fatal(err)
}
err = client.Login(ctx, nil)
if err == nil {
t.Fatal("expected invalid login error")
}
err = client.Login(ctx, url.UserPassword("user", "pass"))
if err != nil {
t.Fatal(err)
}
// Testing http client + reflect client
clients := []soap.RoundTripper{client, s.client}
for _, c := range clients {
now, err := methods.GetCurrentTime(ctx, c)
if err != nil {
t.Fatal(err)
}
if now.After(time.Now()) {
t.Fail()
}
// test the fail/Fault path
_, err = methods.QueryVMotionCompatibility(ctx, c, &types.QueryVMotionCompatibility{})
if err == nil {
t.Errorf("expected error")
}
}
err = client.Logout(ctx)
if err != nil {
t.Error(err)
}
}
}
示例8: Client
func (c *Config) Client() (*vim25.Client, error) {
u, err := url.Parse(fmt.Sprintf("https://%s:%[email protected]%s/sdk", c.User, c.Password, c.vCenter))
if err != nil {
return nil, fmt.Errorf("Incorrect vCenter server address: %s", err)
}
client, err := govmomi.NewClient(context.TODO(), u, c.Insecure)
if err != nil {
return nil, fmt.Errorf("Error setting up client: %s", err)
}
log.Printf("[INFO] vSphere Client configured")
return client.Client, nil
}
示例9: main
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
flag.Parse()
// Parse URL from string
u, err := url.Parse(*urlFlag)
if err != nil {
exit(err)
}
fmt.Println("u:", u)
// Override username and/or password as required
processOverride(u)
// Connect and log in to ESX or vCenter
client, err := govmomi.NewClient(ctx, u, *insecureFlag)
if err != nil {
exit(err)
}
if client.IsVC() {
fmt.Println("connected to vCenter")
} else {
fmt.Println("connected to ESXi host")
}
var perfManager mo.PerformanceManager
err = client.RetrieveOne(ctx, *client.ServiceContent.PerfManager, nil, &perfManager)
perfCounters := perfManager.PerfCounter
counterDetails := make([][]string, 0)
for _, perfCounter := range perfCounters {
groupInfo := perfCounter.GroupInfo.GetElementDescription()
nameInfo := perfCounter.NameInfo.GetElementDescription()
fullName := groupInfo.Key + "." + nameInfo.Key + "." + fmt.Sprint(perfCounter.RollupType)
counterDetails = append(counterDetails, []string{fullName, fmt.Sprint(perfCounter.Level), nameInfo.Summary})
}
outputFile, err := os.Create("performanceCounters.csv")
csvWriter := csv.NewWriter(outputFile)
csvWriter.WriteAll(counterDetails)
if err := csvWriter.Error(); err != nil {
log.Fatalln("error writing csv:", err)
}
}
示例10: Initialize
// Initialize establishes a connection to the remote vSphere API endpoint.
func (bv *BaseVSphere) Initialize() error {
bv.ctx, bv.cancel = context.WithCancel(context.Background())
// Connect and login to the VMWare vSphere API endpoint
c, err := govmomi.NewClient(bv.ctx, bv.url, bv.Insecure)
if err != nil {
return err
}
bv.client = c
bv.finder = find.NewFinder(bv.client.Client, true)
return nil
}
示例11: Client
// Client() returns a new client for accessing VMWare vSphere.
func (c *Config) Client() (*govmomi.Client, error) {
u, err := url.Parse("https://" + c.VSphereServer + "/sdk")
if err != nil {
return nil, fmt.Errorf("Error parse url: %s", err)
}
u.User = url.UserPassword(c.User, c.Password)
client, err := govmomi.NewClient(context.TODO(), u, c.InsecureFlag)
if err != nil {
return nil, fmt.Errorf("Error setting up client: %s", err)
}
log.Printf("[INFO] VMWare vSphere Client configured for URL: %s", u)
return client, nil
}
示例12: vsphereLogin
// Returns a client which communicates with vCenter.
// This client can used to perform further vCenter operations.
func vsphereLogin(cfg *VSphereConfig, ctx context.Context) (*govmomi.Client, error) {
// Parse URL from string
u, err := url.Parse(fmt.Sprintf("https://%s:%s/sdk", cfg.Global.VCenterIP, cfg.Global.VCenterPort))
if err != nil {
return nil, err
}
// set username and password for the URL
u.User = url.UserPassword(cfg.Global.User, cfg.Global.Password)
// Connect and log in to ESX or vCenter
c, err := govmomi.NewClient(ctx, u, cfg.Global.InsecureFlag)
if err != nil {
return nil, err
}
return c, nil
}
示例13: vsphereLogin
func (d *Driver) vsphereLogin(ctx context.Context) (*govmomi.Client, error) {
// Parse URL from string
u, err := url.Parse(fmt.Sprintf("https://%s:%d/sdk", d.IP, d.Port))
if err != nil {
return nil, err
}
// set username and password for the URL
u.User = url.UserPassword(d.Username, d.Password)
// Connect and log in to ESX or vCenter
c, err := govmomi.NewClient(ctx, u, true)
if err != nil {
return nil, err
}
return c, nil
}
示例14: TestFolderESX
func TestFolderESX(t *testing.T) {
content := esx.ServiceContent
s := New(NewServiceInstance(content, esx.RootFolder))
ts := s.NewServer()
defer ts.Close()
ctx := context.Background()
c, err := govmomi.NewClient(ctx, ts.URL, true)
if err != nil {
t.Fatal(err)
}
f := object.NewRootFolder(c.Client)
_, err = f.CreateFolder(ctx, "foo")
if err == nil {
t.Error("expected error")
}
_, err = f.CreateDatacenter(ctx, "foo")
if err == nil {
t.Error("expected error")
}
finder := find.NewFinder(c.Client, false)
dc, err := finder.DatacenterOrDefault(ctx, "")
if err != nil {
t.Fatal(err)
}
folders, err := dc.Folders(ctx)
if err != nil {
t.Fatal(err)
}
spec := types.HostConnectSpec{}
_, err = addStandaloneHost(folders.HostFolder, spec)
if err == nil {
t.Fatal("expected error")
}
}
示例15: newClient
func newClient(cfg *VSphereConfig, ctx context.Context) (*govmomi.Client, error) {
// Parse URL from string
u, err := url.Parse(fmt.Sprintf("https://%s:%s/sdk", cfg.Global.VCenterIP, cfg.Global.VCenterPort))
if err != nil {
return nil, err
}
// set username and password for the URL
u.User = url.UserPassword(cfg.Global.User, cfg.Global.Password)
// Connect and log in to ESX or vCenter
c, err := govmomi.NewClient(ctx, u, cfg.Global.InsecureFlag)
if err != nil {
return nil, err
}
// Add retry functionality
c.RoundTripper = vim25.Retry(c.RoundTripper, vim25.TemporaryNetworkError(int(cfg.Global.RoundTripperCount)))
return c, nil
}