func (f *Finder) HostSystemList(ctx context.Context, path string) ([]*object.HostSystem, error) { es, err := f.find(ctx, f.hostFolder, false, path) if err != nil { return nil, err } var hss []*object.HostSystem for _, e := range es { var hs *object.HostSystem switch o := e.Object.(type) { case mo.HostSystem: hs = object.NewHostSystem(f.client, o.Reference()) case mo.ComputeResource: cr := object.NewComputeResource(f.client, o.Reference()) hosts, err := cr.Hosts(ctx) if err != nil { return nil, err } hs = object.NewHostSystem(f.client, hosts[0]) default: continue } hs.InventoryPath = e.Path hss = append(hss, hs) } if len(hss) == 0 { return nil, &NotFoundError{"host", path} } return hss, nil }
func (g *GuestInfo) hostInfo(ref *types.ManagedObjectReference) (*hostInfo, error) { // cache exectuor and uuid -> worldid map if h, ok := g.hosts[ref.Value]; ok { return h, nil } host := object.NewHostSystem(g.c, *ref) e, err := NewExecutor(g.c, host) if err != nil { return nil, err } res, err := e.Run([]string{"vm", "process", "list"}) if err != nil { return nil, err } ids := make(map[string]string, len(res.Values)) for _, process := range res.Values { // Normalize uuid, esxcli and mo.VirtualMachine have different formats uuid := strings.Replace(process["UUID"][0], " ", "", -1) uuid = strings.Replace(uuid, "-", "", -1) ids[uuid] = process["WorldID"][0] } h := &hostInfo{e, ids} g.hosts[ref.Value] = h return h, nil }
func (vmh *VMHost) FindHosts(targetVM *object.VirtualMachine) (hosts []*object.HostSystem, err error) { targetResourcePool, err := targetVM.ResourcePool(vmh.Ctx) if err != nil { return nil, errors.New("Error with finding Resource Pool of VM") } var resourcePoolProp mo.ResourcePool err = targetResourcePool.Properties(vmh.Ctx, targetResourcePool.Reference(), []string{"owner"}, &resourcePoolProp) if err != nil { return nil, errors.New("Error with finding Owner of Resource Pool") } typeOfOwningResource := resourcePoolProp.Owner.Type //Scenario in which VM is apart of a Cluster (Not tied to 1 ESXi host) - VMware DRS if typeOfOwningResource == "ClusterComputeResource" { cluster := object.NewClusterComputeResource(vmh.client.Client, resourcePoolProp.Owner) var clusterProp mo.ClusterComputeResource err = cluster.Properties(vmh.Ctx, cluster.Reference(), []string{"host"}, &clusterProp) if err != nil { return nil, errors.New("Error with finding Hosts of Cluster") } //convert Managed Object References into actual host_sytem objects to return var hosts []*object.HostSystem for _, host := range clusterProp.Host { newHost := object.NewHostSystem(vmh.client.Client, host) hosts = append(hosts, newHost) } return hosts, nil } else { return nil, errors.New("Looks like you are on a single/Non-Clustered host and we havent gotten to this yet!!") } }
func (vm *VirtualMachine) registerVM(ctx context.Context, path, name string, vapp, pool, host *types.ManagedObjectReference, vmfolder *object.Folder) (*object.Task, error) { log.Debugf("Register VM %s", name) if vapp == nil { var hostObject *object.HostSystem if host != nil { hostObject = object.NewHostSystem(vm.Vim25(), *host) } poolObject := object.NewResourcePool(vm.Vim25(), *pool) return vmfolder.RegisterVM(ctx, path, name, false, poolObject, hostObject) } req := types.RegisterChildVM_Task{ This: vapp.Reference(), Path: path, Host: host, } if name != "" { req.Name = name } res, err := methods.RegisterChildVM_Task(ctx, vm.Vim25(), &req) if err != nil { return nil, err } return object.NewTask(vm.Vim25(), res.Returnval), nil }
func (cmd *vnc) loadVMs(args []string) ([]*vncVM, error) { c, err := cmd.Client() if err != nil { return nil, err } vms, err := cmd.VirtualMachines(args) if err != nil { return nil, err } var vncVMs []*vncVM for _, vm := range vms { v, err := newVNCVM(c, vm) if err != nil { return nil, err } vncVMs = append(vncVMs, v) } // Assign vncHosts to vncVMs hosts := make(map[string]*vncHost) for _, vm := range vncVMs { if h, ok := hosts[vm.hostReference().Value]; ok { vm.host = h continue } hs := object.NewHostSystem(c, vm.hostReference()) h, err := newVNCHost(c, hs, cmd.PortRange.low, cmd.PortRange.high) if err != nil { return nil, err } hosts[vm.hostReference().Value] = h vm.host = h } return vncVMs, nil }
// Create populates the Model with the given ModelConfig func (m *Model) Create() error { m.Service = New(NewServiceInstance(m.ServiceContent, m.RootFolder)) ctx := context.Background() client := m.Service.client root := object.NewRootFolder(client) // After all hosts are created, this var is used to mount the host datastores. var hosts []*object.HostSystem // We need to defer VM creation until after the datastores are created. var vms []func() error // addHost adds a cluster host or a stanalone host. addHost := func(name string, f func(types.HostConnectSpec) (*object.Task, error)) (*object.HostSystem, error) { spec := types.HostConnectSpec{ HostName: name, } task, err := f(spec) if err != nil { return nil, err } info, err := task.WaitForResult(context.Background(), nil) if err != nil { return nil, err } host := object.NewHostSystem(client, info.Result.(types.ManagedObjectReference)) hosts = append(hosts, host) return host, nil } // addMachine returns a func to create a VM. addMachine := func(prefix string, host *object.HostSystem, pool *object.ResourcePool, folders *object.DatacenterFolders) { f := func() error { for i := 0; i < m.Machine; i++ { name := m.fmtName(prefix+"_VM", i) config := types.VirtualMachineConfigSpec{ Name: name, GuestId: string(types.VirtualMachineGuestOsIdentifierOtherGuest), Files: &types.VirtualMachineFileInfo{ VmPathName: fmt.Sprintf("[LocalDS_0] %s", name), }, } if pool == nil { pool, _ = host.ResourcePool(ctx) } task, err := folders.VmFolder.CreateVM(ctx, config, pool, host) if err != nil { return err } err = task.Wait(ctx) if err != nil { return err } } return nil } vms = append(vms, f) } for ndc := 0; ndc < m.Datacenter; ndc++ { dcName := m.fmtName("DC", ndc) dc, err := root.CreateDatacenter(ctx, dcName) if err != nil { return err } folders, err := dc.Folders(ctx) if err != nil { return err } for nhost := 0; nhost < m.Host; nhost++ { name := m.fmtName(dcName+"_H", nhost) host, err := addHost(name, func(spec types.HostConnectSpec) (*object.Task, error) { return folders.HostFolder.AddStandaloneHost(ctx, spec, true, nil, nil) }) if err != nil { return err } addMachine(name, host, nil, folders) } for ncluster := 0; ncluster < m.Cluster; ncluster++ { clusterName := m.fmtName(dcName+"_C", ncluster) cluster, err := folders.HostFolder.CreateCluster(ctx, clusterName, types.ClusterConfigSpecEx{}) if err != nil { return err } // TODO: create DistributedVirtualPortgroup for npg := 0; npg < m.Portgroup; npg++ for nhost := 0; nhost < m.ClusterHost; nhost++ { name := m.fmtName(clusterName+"_H", nhost) _, err := addHost(name, func(spec types.HostConnectSpec) (*object.Task, error) { return cluster.AddHost(ctx, spec, true, nil, nil) }) if err != nil { return err } } pool, err := cluster.ResourcePool(ctx) if err != nil { return err } prefix := clusterName + "_RP" addMachine(prefix+"0", nil, pool, folders) for npool := 1; npool <= m.Pool; npool++ { spec := NewResourceConfigSpec() _, err = pool.Create(ctx, m.fmtName(prefix, npool), spec) if err != nil { return err } } } } if m.ServiceContent.RootFolder == esx.RootFolder.Reference() { // ESX model host := object.NewHostSystem(client, esx.HostSystem.Reference()) hosts = append(hosts, host) dc := object.NewDatacenter(client, esx.Datacenter.Reference()) folders, err := dc.Folders(ctx) if err != nil { return err } addMachine(host.Reference().Value, host, nil, folders) } for i := 0; i < m.Datastore; i++ { err := m.createLocalDatastore(m.fmtName("LocalDS_", i), hosts) if err != nil { return err } } for _, createVM := range vms { err := createVM() if err != nil { return err } } return nil }
func TestHostDatastoreSystem(t *testing.T) { s := New(NewServiceInstance(esx.ServiceContent, 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) } host := object.NewHostSystem(c.Client, esx.HostSystem.Reference()) dss, err := host.ConfigManager().DatastoreSystem(ctx) if err != nil { t.Error(err) } pwd, err := os.Getwd() if err != nil { t.Fatal(err) } spec := types.HostNasVolumeSpec{ Type: string(types.HostFileSystemVolumeFileSystemTypeNFS), RemoteHost: "localhost", } tests := []func(string) (*object.Datastore, error){ func(dir string) (*object.Datastore, error) { spec.LocalPath = dir spec.RemotePath = dir return dss.CreateNasDatastore(ctx, spec) }, func(dir string) (*object.Datastore, error) { return dss.CreateLocalDatastore(ctx, filepath.Base(dir), dir) }, } for _, create := range tests { for _, fail := range []bool{false, true} { if fail { _, err = create(pwd) if err == nil { t.Error("expected error") } // TODO: hds.Remove(ds) pwd = filepath.Join(pwd, "esx") } else { _, err = create(pwd) if err != nil { t.Error(err) } } } } for _, create := range tests { for _, dir := range []string{"./enoent", "host_datastore_system.go"} { _, err = create(dir) if err == nil { t.Error("expected error") } } } }
func (cmd *info) Run(f *flag.FlagSet) error { c, err := cmd.Client() if err != nil { return err } vms, err := cmd.VirtualMachines(f.Args()) if err != nil { if _, ok := err.(*find.NotFoundError); ok { // Continue with empty VM slice } else { return err } } var res infoResult var props []string if cmd.OutputFlag.JSON { props = nil // Load everything } else { props = []string{"summary", "guest.ipAddress"} // Load summary if cmd.ExtraConfig { props = append(props, "config.extraConfig") } } ctx := context.TODO() for _, vm := range vms { for { var mvm mo.VirtualMachine pc := property.DefaultCollector(c) err = pc.RetrieveOne(ctx, vm.Reference(), props, &mvm) if err != nil { return err } if cmd.WaitForIP && mvm.Guest.IpAddress == "" { _, err = vm.WaitForIP(ctx) if err != nil { return err } // Reload virtual machine object continue } var hostName string hostRef := mvm.Summary.Runtime.Host if hostRef == nil { hostName = "<unavailable>" } else { host := object.NewHostSystem(c, *hostRef) hostName, err = host.Name(ctx) if err != nil { return err } } res.VmInfos = append(res.VmInfos, vmInfo{mvm, hostName}) break } } return cmd.WriteResult(&res) }