func testAccCheckVSphereVirtualMachineExists(n string, vm *virtualMachine) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		rs, ok := s.RootModule().Resources[n]
		if !ok {
			return fmt.Errorf("Not found: %s", n)
		}

		if rs.Primary.ID == "" {
			return fmt.Errorf("No ID is set")
		}

		client := testAccProvider.Meta().(*govmomi.Client)
		finder := find.NewFinder(client.Client, true)

		dc, err := finder.Datacenter(context.TODO(), rs.Primary.Attributes["datacenter"])
		if err != nil {
			return fmt.Errorf("error %s", err)
		}

		dcFolders, err := dc.Folders(context.TODO())
		if err != nil {
			return fmt.Errorf("error %s", err)
		}

		_, err = object.NewSearchIndex(client.Client).FindChild(context.TODO(), dcFolders.VmFolder, rs.Primary.Attributes["name"])

		*vm = virtualMachine{
			name: rs.Primary.ID,
		}

		return nil
	}
}
示例#2
0
func (flag *DatacenterFlag) Finder() (*find.Finder, error) {
	if flag.finder != nil {
		return flag.finder, nil
	}

	c, err := flag.Client()
	if err != nil {
		return nil, err
	}

	finder := find.NewFinder(c, flag.JSON || flag.Dump)

	// Datacenter is not required (ls command for example).
	// Set for relative func if dc flag is given or
	// if there is a single (default) Datacenter
	if flag.path == "" {
		flag.dc, flag.err = finder.DefaultDatacenter(context.TODO())
	} else {
		if flag.dc, err = finder.Datacenter(context.TODO(), flag.path); err != nil {
			return nil, err
		}
	}

	finder.SetDatacenter(flag.dc)

	flag.finder = finder

	return flag.finder, nil
}
func testAccVSphereVirtualDiskExists(name string) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		rs, ok := s.RootModule().Resources[name]
		if !ok {
			return fmt.Errorf("Not found: %s", name)
		}
		if rs.Primary.ID == "" {
			return fmt.Errorf("No ID is set")
		}

		client := testAccProvider.Meta().(*govmomi.Client)
		finder := find.NewFinder(client.Client, true)

		dc, err := finder.Datacenter(context.TODO(), rs.Primary.Attributes["datacenter"])
		if err != nil {
			return fmt.Errorf("error %s", err)
		}
		finder = finder.SetDatacenter(dc)

		ds, err := finder.Datastore(context.TODO(), rs.Primary.Attributes["datastore"])
		if err != nil {
			return fmt.Errorf("error %s", err)
		}

		_, err = ds.Stat(context.TODO(), rs.Primary.Attributes["vmdk_path"])
		if err != nil {
			return fmt.Errorf("error %s", err)
		}

		return nil
	}
}
func testAccCheckVSphereVirtualDiskDestroy(s *terraform.State) error {
	log.Printf("[FINDME] test Destroy")
	client := testAccProvider.Meta().(*govmomi.Client)
	finder := find.NewFinder(client.Client, true)

	for _, rs := range s.RootModule().Resources {
		if rs.Type != "vsphere_virtual_disk" {
			continue
		}

		dc, err := finder.Datacenter(context.TODO(), rs.Primary.Attributes["datacenter"])
		if err != nil {
			return fmt.Errorf("error %s", err)
		}

		finder = finder.SetDatacenter(dc)

		ds, err := finder.Datastore(context.TODO(), rs.Primary.Attributes["datastore"])
		if err != nil {
			return fmt.Errorf("error %s", err)
		}

		_, err = ds.Stat(context.TODO(), rs.Primary.Attributes["vmdk_path"])
		if err == nil {
			return fmt.Errorf("error %s", err)
		}
	}

	return nil
}
func testAccCheckVSphereVirtualMachineDestroy(s *terraform.State) error {
	client := testAccProvider.Meta().(*govmomi.Client)
	finder := find.NewFinder(client.Client, true)

	for _, rs := range s.RootModule().Resources {
		if rs.Type != "vsphere_virtual_machine" {
			continue
		}

		dc, err := finder.Datacenter(context.TODO(), rs.Primary.Attributes["datacenter"])
		if err != nil {
			return fmt.Errorf("error %s", err)
		}

		dcFolders, err := dc.Folders(context.TODO())
		if err != nil {
			return fmt.Errorf("error %s", err)
		}

		_, err = object.NewSearchIndex(client.Client).FindChild(context.TODO(), dcFolders.VmFolder, rs.Primary.Attributes["name"])
		if err == nil {
			return fmt.Errorf("Record still exists")
		}
	}

	return nil
}
func createFile(client *govmomi.Client, f *file) error {

	finder := find.NewFinder(client.Client, true)

	dc, err := finder.Datacenter(context.TODO(), f.datacenter)
	if err != nil {
		return fmt.Errorf("error %s", err)
	}
	finder = finder.SetDatacenter(dc)

	ds, err := getDatastore(finder, f.datastore)
	if err != nil {
		return fmt.Errorf("error %s", err)
	}

	dsurl, err := ds.URL(context.TODO(), dc, f.destinationFile)
	if err != nil {
		return err
	}

	p := soap.DefaultUpload
	err = client.Client.UploadFile(f.sourceFile, dsurl, &p)
	if err != nil {
		return fmt.Errorf("error %s", err)
	}
	return nil
}
func testAccCheckVSphereFolderExistingPathExists(n string, f *folder) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		rs, ok := s.RootModule().Resources[n]
		if !ok {
			return fmt.Errorf("Resource %s not found in %#v", n, s.RootModule().Resources)
		}

		if rs.Primary.ID == "" {
			return fmt.Errorf("No ID is set")
		}

		client := testAccProvider.Meta().(*govmomi.Client)
		finder := find.NewFinder(client.Client, true)

		dc, err := finder.Datacenter(context.TODO(), rs.Primary.Attributes["datacenter"])
		if err != nil {
			return fmt.Errorf("error %s", err)
		}

		dcFolders, err := dc.Folders(context.TODO())
		if err != nil {
			return fmt.Errorf("error %s", err)
		}

		_, err = object.NewSearchIndex(client.Client).FindChild(context.TODO(), dcFolders.VmFolder, rs.Primary.Attributes["existing_path"])

		*f = folder{
			path: rs.Primary.Attributes["path"],
		}

		return nil
	}
}
示例#8
0
// Returns vSphere objects virtual machine, virtual device list, datastore and datacenter.
func getVirtualMachineDevices(cfg *VSphereConfig, ctx context.Context, c *govmomi.Client, name string) (*object.VirtualMachine, object.VirtualDeviceList, *object.Datastore, *object.Datacenter, error) {
	// Create a new finder
	f := find.NewFinder(c.Client, true)

	// Fetch and set data center
	dc, err := f.Datacenter(ctx, cfg.Global.Datacenter)
	if err != nil {
		return nil, nil, nil, nil, err
	}
	f.SetDatacenter(dc)

	// Find datastores
	ds, err := f.Datastore(ctx, cfg.Global.Datastore)
	if err != nil {
		return nil, nil, nil, nil, err
	}

	vmRegex := cfg.Global.WorkingDir + name

	vm, err := f.VirtualMachine(ctx, vmRegex)
	if err != nil {
		return nil, nil, nil, nil, err
	}

	// Get devices from VM
	vmDevices, err := vm.Device(ctx)
	if err != nil {
		return nil, nil, nil, nil, err
	}
	return vm, vmDevices, ds, dc, nil
}
func deleteFile(client *govmomi.Client, f *file) error {

	dc, err := getDatacenter(client, f.datacenter)
	if err != nil {
		return err
	}

	finder := find.NewFinder(client.Client, true)
	finder = finder.SetDatacenter(dc)

	ds, err := getDatastore(finder, f.datastore)
	if err != nil {
		return fmt.Errorf("error %s", err)
	}

	fm := object.NewFileManager(client.Client)
	task, err := fm.DeleteDatastoreFile(context.TODO(), ds.Path(f.destinationFile), dc)
	if err != nil {
		return err
	}

	_, err = task.WaitForResult(context.TODO(), nil)
	if err != nil {
		return err
	}
	return nil
}
func waitForNetworkingActive(client *govmomi.Client, datacenter, name string) resource.StateRefreshFunc {
	return func() (interface{}, string, error) {
		dc, err := getDatacenter(client, datacenter)
		if err != nil {
			log.Printf("[ERROR] %#v", err)
			return nil, "", err
		}
		finder := find.NewFinder(client.Client, true)
		finder = finder.SetDatacenter(dc)

		vm, err := finder.VirtualMachine(context.TODO(), name)
		if err != nil {
			log.Printf("[ERROR] %#v", err)
			return nil, "", err
		}

		var mvm mo.VirtualMachine
		collector := property.DefaultCollector(client.Client)
		if err := collector.RetrieveOne(context.TODO(), vm.Reference(), []string{"summary"}, &mvm); err != nil {
			log.Printf("[ERROR] %#v", err)
			return nil, "", err
		}

		if mvm.Summary.Guest.IpAddress != "" {
			log.Printf("[DEBUG] IP address with DHCP: %v", mvm.Summary.Guest.IpAddress)
			return mvm.Summary, "active", err
		} else {
			log.Printf("[DEBUG] Waiting for IP address")
			return nil, "pending", err
		}
	}
}
示例#11
0
// DeleteVolume deletes a volume given volume name.
func (vs *VSphere) DeleteVolume(vmDiskPath string) error {
	// Create context
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	// Create vSphere client
	c, err := vsphereLogin(vs.cfg, ctx)
	if err != nil {
		return err
	}
	defer c.Logout(ctx)

	// Create a new finder
	f := find.NewFinder(c.Client, true)

	// Fetch and set data center
	dc, err := f.Datacenter(ctx, vs.cfg.Global.Datacenter)
	f.SetDatacenter(dc)

	// Create a virtual disk manager
	virtualDiskManager := object.NewVirtualDiskManager(c.Client)

	// Delete virtual disk
	task, err := virtualDiskManager.DeleteVirtualDisk(ctx, vmDiskPath, dc)
	if err != nil {
		return err
	}

	return task.Wait(ctx)
}
示例#12
0
文件: vmomi.go 项目: zhaog918/govmax
func (vmh *VMHost) findVM(targetMACAddress string) (vm *object.VirtualMachine, err error) {

	targetMACAddress = strings.ToUpper(targetMACAddress)
	f := find.NewFinder(vmh.client.Client, true)
	allDatacenters, err := f.DatacenterList(vmh.Ctx, "*")
	if err != nil {
		return nil, errors.New("Could not get List of Datacenters")
	}

	for _, datacenter := range allDatacenters {
		f.SetDatacenter(datacenter)
		allVMs, err := f.VirtualMachineList(vmh.Ctx, "*")
		if err != nil {
			return nil, errors.New("Could not get List of VMs")
		}
		for _, vm := range allVMs {
			VM_MAC, err := vmh.getMACAddressOfVM(vm)
			VM_MAC = strings.ToUpper(VM_MAC)
			if err != nil {
				return nil, errors.New("Could not get MAC Address of VM")
			}
			if VM_MAC == targetMACAddress {
				return vm, nil
			}
		}
	}
	return nil, errors.New("Could not find VM with specified MAC Address of " + targetMACAddress)
}
示例#13
0
func (cmd *destroy) Run(ctx context.Context, f *flag.FlagSet) error {
	if f.NArg() == 0 {
		return flag.ErrHelp
	}

	client, err := cmd.ClientFlag.Client()
	if err != nil {
		return err
	}

	finder := find.NewFinder(client, false)

	for _, path := range f.Args() {
		dcs, err := finder.DatacenterList(ctx, path)
		if err != nil {
			return err
		}

		for _, dc := range dcs {
			task, err := dc.Destroy(ctx)
			if err != nil {
				return err
			}

			if err := task.Wait(ctx); err != nil {
				return err
			}
		}
	}

	return nil
}
示例#14
0
// DeleteVolume deletes a volume given volume name.
func (vs *VSphere) DeleteVolume(vmDiskPath string) error {
	// Create context
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	// Ensure client is logged in and session is valid
	err := vSphereLogin(vs, ctx)
	if err != nil {
		glog.Errorf("Failed to login into vCenter - %v", err)
		return err
	}

	// Create a new finder
	f := find.NewFinder(vs.client.Client, true)

	// Fetch and set data center
	dc, err := f.Datacenter(ctx, vs.cfg.Global.Datacenter)
	f.SetDatacenter(dc)

	// Create a virtual disk manager
	virtualDiskManager := object.NewVirtualDiskManager(vs.client.Client)

	// Delete virtual disk
	task, err := virtualDiskManager.DeleteVirtualDisk(ctx, vmDiskPath, dc)
	if err != nil {
		return err
	}

	return task.Wait(ctx)
}
示例#15
0
func (cmd *ovf) Folder() (*object.Folder, error) {
	if len(cmd.folder) == 0 {
		folders, err := cmd.Datacenter.Folders(context.TODO())
		if err != nil {
			return nil, err
		}
		return folders.VmFolder, nil
	} else {
		finder := find.NewFinder(cmd.Client, false)

		mo, err := finder.ManagedObjectList(context.TODO(), cmd.folder)
		if err != nil {
			return nil, err
		}
		if len(mo) == 0 {
			return nil, errors.New("folder does not resolve to object")
		}
		if len(mo) > 1 {
			return nil, errors.New("folder resolves to more than one object")
		}

		ref := mo[0].Object.Reference()
		if ref.Type != "Folder" {
			return nil, errors.New("folder does not resolve to folder")
		}

		return object.NewFolder(cmd.Client, ref), nil
	}
}
示例#16
0
func (cmd *destroy) Run(ctx context.Context, f *flag.FlagSet) error {
	if len(f.Args()) < 1 {
		return flag.ErrHelp
	}
	datacentersToDestroy := f.Args()

	client, err := cmd.ClientFlag.Client()
	if err != nil {
		return err
	}

	finder := find.NewFinder(client, false)
	for _, datacenterToDestroy := range datacentersToDestroy {
		foundDatacenters, err := finder.DatacenterList(context.TODO(), datacenterToDestroy)
		if err != nil {
			return err
		}
		for _, foundDatacenter := range foundDatacenters {
			task, err := foundDatacenter.Destroy(context.TODO())
			if err != nil {
				return err
			}

			if err := task.Wait(context.TODO()); err != nil {
				return err
			}
		}
	}
	return nil
}
func createAndAttachDisk(t *testing.T, vmName string, size int, datastore string, diskPath string, diskType string, adapterType string, datacenter string) {
	client := testAccProvider.Meta().(*govmomi.Client)
	finder := find.NewFinder(client.Client, true)

	dc, err := finder.Datacenter(context.TODO(), datacenter)
	if err != nil {
		log.Printf("[ERROR] finding Datacenter %s: %v", datacenter, err)
		t.Fail()
		return
	}
	finder = finder.SetDatacenter(dc)
	ds, err := getDatastore(finder, datastore)
	if err != nil {
		log.Printf("[ERROR] getDatastore %s: %v", datastore, err)
		t.Fail()
		return
	}
	vm, err := finder.VirtualMachine(context.TODO(), vmName)
	if err != nil {
		log.Printf("[ERROR] finding VM %s: %v", vmName, err)
		t.Fail()
		return
	}
	err = addHardDisk(vm, int64(size), int64(0), diskType, ds, diskPath, adapterType)
	if err != nil {
		log.Printf("[ERROR] addHardDisk: %v", err)
		t.Fail()
		return
	}
}
示例#18
0
func (cmd *create) Run(f *flag.FlagSet) error {
	datacenters := f.Args()
	if len(datacenters) < 1 {
		return flag.ErrHelp
	}

	client, err := cmd.ClientFlag.Client()
	if err != nil {
		return err
	}

	finder := find.NewFinder(client, false)
	rootFolder := object.NewRootFolder(client)
	for _, datacenterToCreate := range datacenters {
		_, err := finder.Datacenter(context.TODO(), datacenterToCreate)
		if err == nil {
			// The datacenter was found, no need to create it
			continue
		}

		switch err.(type) {
		case *find.NotFoundError:
			_, err = rootFolder.CreateDatacenter(context.TODO(), datacenterToCreate)
			if err != nil {
				return err
			}
		default:
			return err
		}
	}

	return nil
}
func resourceVSphereFolderRead(d *schema.ResourceData, meta interface{}) error {

	log.Printf("[DEBUG] reading folder: %#v", d)
	client := meta.(*govmomi.Client)

	dc, err := getDatacenter(client, d.Get("datacenter").(string))
	if err != nil {
		return err
	}

	finder := find.NewFinder(client.Client, true)
	finder = finder.SetDatacenter(dc)

	folder, err := object.NewSearchIndex(client.Client).FindByInventoryPath(
		context.TODO(), fmt.Sprintf("%v/vm/%v", d.Get("datacenter").(string),
			d.Get("path").(string)))

	if err != nil {
		return err
	}

	if folder == nil {
		d.SetId("")
	}

	return nil
}
示例#20
0
文件: network.go 项目: vmware/vic
func Init(ctx context.Context, sess *session.Session, source extraconfig.DataSource, sink extraconfig.DataSink) error {
	trace.End(trace.Begin(""))

	initializer.once.Do(func() {
		var err error
		defer func() {
			initializer.err = err
		}()

		f := find.NewFinder(sess.Vim25(), false)

		var config Configuration
		config.sink = sink
		config.source = source
		config.Decode()
		config.PortGroups = make(map[string]object.NetworkReference)

		log.Debugf("Decoded VCH config for network: %#v", config)
		for nn, n := range config.ContainerNetworks {
			pgref := new(types.ManagedObjectReference)
			if !pgref.FromString(n.ID) {
				log.Warnf("Could not reacquire object reference from id for network %s: %s", nn, n.ID)
			}

			var r object.Reference
			if r, err = f.ObjectReference(ctx, *pgref); err != nil {
				log.Warnf("could not get network reference for %s network: %s", nn, err)
				err = nil
				continue
			}

			config.PortGroups[nn] = r.(object.NetworkReference)
		}

		// make sure a NIC attached to the bridge network exists
		config.BridgeLink, err = getBridgeLink(&config)
		if err != nil {
			return
		}

		var kv kvstore.KeyValueStore
		kv, err = store.NewDatastoreKeyValue(ctx, sess, "network.contexts.default")
		if err != nil {
			return
		}

		var netctx *Context
		if netctx, err = NewContext(&config, kv); err != nil {
			return
		}

		if err = engageContext(ctx, netctx, exec.Config.EventManager); err == nil {
			DefaultContext = netctx
			log.Infof("Default network context allocated")
		}
	})

	return initializer.err
}
func resourceVSphereFileUpdate(d *schema.ResourceData, meta interface{}) error {

	log.Printf("[DEBUG] updating file: %#v", d)
	if d.HasChange("destination_file") {
		oldDestinationFile, newDestinationFile := d.GetChange("destination_file")
		f := file{}

		if v, ok := d.GetOk("datacenter"); ok {
			f.datacenter = v.(string)
		}

		if v, ok := d.GetOk("datastore"); ok {
			f.datastore = v.(string)
		} else {
			return fmt.Errorf("datastore argument is required")
		}

		if v, ok := d.GetOk("source_file"); ok {
			f.sourceFile = v.(string)
		} else {
			return fmt.Errorf("source_file argument is required")
		}

		if v, ok := d.GetOk("destination_file"); ok {
			f.destinationFile = v.(string)
		} else {
			return fmt.Errorf("destination_file argument is required")
		}

		client := meta.(*govmomi.Client)
		dc, err := getDatacenter(client, f.datacenter)
		if err != nil {
			return err
		}

		finder := find.NewFinder(client.Client, true)
		finder = finder.SetDatacenter(dc)

		ds, err := getDatastore(finder, f.datastore)
		if err != nil {
			return fmt.Errorf("error %s", err)
		}

		fm := object.NewFileManager(client.Client)
		task, err := fm.MoveDatastoreFile(context.TODO(), ds.Path(oldDestinationFile.(string)), dc, ds.Path(newDestinationFile.(string)), dc, true)
		if err != nil {
			return err
		}

		_, err = task.WaitForResult(context.TODO(), nil)
		if err != nil {
			return err
		}

	}

	return nil
}
func deleteFolder(client *govmomi.Client, f *folder) error {
	dc, err := getDatacenter(client, f.datacenter)
	if err != nil {
		return err
	}
	var folder *object.Folder
	currentPath := f.path

	finder := find.NewFinder(client.Client, true)
	finder = finder.SetDatacenter(dc)
	si := object.NewSearchIndex(client.Client)

	folderRef, err := si.FindByInventoryPath(
		context.TODO(), fmt.Sprintf("%v/vm/%v", f.datacenter, f.path))

	if err != nil {
		return fmt.Errorf("[ERROR] Could not locate folder %s: %v", f.path, err)
	} else {
		folder = folderRef.(*object.Folder)
	}

	log.Printf("[INFO] Deleting empty sub-folders of existing path: %s", f.existingPath)
	for currentPath != f.existingPath {
		log.Printf("[INFO] Deleting folder: %s", currentPath)
		children, err := folder.Children(context.TODO())
		if err != nil {
			return err
		}

		if len(children) > 0 {
			return fmt.Errorf("Folder %s is non-empty and will not be deleted", currentPath)
		} else {
			log.Printf("[DEBUG] current folder: %#v", folder)
			currentPath = path.Dir(currentPath)
			if currentPath == "." {
				currentPath = ""
			}
			log.Printf("[INFO] parent path of %s is calculated as %s", f.path, currentPath)
			task, err := folder.Destroy(context.TODO())
			if err != nil {
				return err
			}
			err = task.Wait(context.TODO())
			if err != nil {
				return err
			}
			folderRef, err = si.FindByInventoryPath(
				context.TODO(), fmt.Sprintf("%v/vm/%v", f.datacenter, currentPath))

			if err != nil {
				return err
			} else if folderRef != nil {
				folder = folderRef.(*object.Folder)
			}
		}
	}
	return nil
}
示例#23
0
// Returns the name of the VM on which this code is running.
// This is done by searching for the name of virtual machine by current IP.
// Prerequisite: this code assumes VMWare vmtools or open-vm-tools to be installed in the VM.
func readInstanceID(cfg *VSphereConfig) (string, error) {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return "", err
	}

	if len(addrs) == 0 {
		return "", fmt.Errorf("unable to retrieve Instance ID")
	}

	// Create context
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	// Create vSphere client
	c, err := vsphereLogin(cfg, ctx)
	if err != nil {
		return "", err
	}
	defer c.Logout(ctx)

	// Create a new finder
	f := find.NewFinder(c.Client, true)

	// Fetch and set data center
	dc, err := f.Datacenter(ctx, cfg.Global.Datacenter)
	if err != nil {
		return "", err
	}
	f.SetDatacenter(dc)

	s := object.NewSearchIndex(c.Client)

	var svm object.Reference
	for _, v := range addrs {
		ip, _, err := net.ParseCIDR(v.String())
		if err != nil {
			return "", fmt.Errorf("unable to parse cidr from ip")
		}

		// Finds a virtual machine or host by IP address.
		svm, err = s.FindByIp(ctx, dc, ip.String(), true)
		if err == nil && svm != nil {
			break
		}
	}
	if svm == nil {
		return "", fmt.Errorf("unable to retrieve vm reference from vSphere")
	}

	var vm mo.VirtualMachine
	err = s.Properties(ctx, svm.Reference(), []string{"name"}, &vm)
	if err != nil {
		return "", err
	}
	return vm.Name, nil
}
示例#24
0
文件: validator.go 项目: kjplatz/vic
func CreateNoDCCheck(ctx context.Context, input *data.Data) (*Validator, error) {
	defer trace.End(trace.Begin(""))
	var err error

	v := &Validator{}
	v.Context = ctx
	tURL := input.URL

	// default to https scheme
	if tURL.Scheme == "" {
		tURL.Scheme = "https"
	}

	// if they specified only an IP address the parser for some reason considers that a path
	if tURL.Host == "" {
		tURL.Host = tURL.Path
		tURL.Path = ""
	}

	sessionconfig := &session.Config{
		Insecure: input.Insecure,
	}

	// if a datacenter was specified, set it
	v.DatacenterPath = tURL.Path
	if v.DatacenterPath != "" {
		sessionconfig.DatacenterPath = v.DatacenterPath
		// path needs to be stripped before we can use it as a service url
		tURL.Path = ""
	}

	sessionconfig.Service = tURL.String()

	v.Session = session.NewSession(sessionconfig)
	v.Session, err = v.Session.Connect(v.Context)
	if err != nil {
		return nil, err
	}

	// cached here to allow a modicum of testing while session is still in use.
	v.isVC = v.Session.IsVC()
	finder := find.NewFinder(v.Session.Client.Client, false)
	v.Session.Finder = finder

	v.Session.Populate(ctx)

	// only allow the datacenter to be specified in the taget url, if any
	pElems := strings.Split(v.DatacenterPath, "/")
	if len(pElems) > 2 {
		detail := "--target should only specify datacenter in the path (e.g. https://addr/datacenter) - specify cluster, resource pool, or folder with --compute-resource"
		log.Error(detail)
		v.suggestDatacenter()
		return nil, errors.New(detail)
	}

	return v, nil
}
示例#25
0
文件: session.go 项目: jak-atx/vic
// 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
}
// getDatacenter gets datacenter object
func getDatacenter(c *govmomi.Client, dc string) (*object.Datacenter, error) {
	finder := find.NewFinder(c.Client, true)
	if dc != "" {
		d, err := finder.Datacenter(context.TODO(), dc)
		return d, err
	} else {
		d, err := finder.DefaultDatacenter(context.TODO())
		return d, err
	}
}
示例#27
0
func resourceVSphereFileRead(d *schema.ResourceData, meta interface{}) error {

	log.Printf("[DEBUG] reading file: %#v", d)
	f := file{}

	if v, ok := d.GetOk("datacenter"); ok {
		f.datacenter = v.(string)
	}

	if v, ok := d.GetOk("datastore"); ok {
		f.datastore = v.(string)
	} else {
		return fmt.Errorf("datastore argument is required")
	}

	if v, ok := d.GetOk("source_file"); ok {
		f.sourceFile = v.(string)
	} else {
		return fmt.Errorf("source_file argument is required")
	}

	if v, ok := d.GetOk("destination_file"); ok {
		f.destinationFile = v.(string)
	} else {
		return fmt.Errorf("destination_file argument is required")
	}

	client := meta.(*govmomi.Client)
	finder := find.NewFinder(client.Client, true)

	dc, err := finder.Datacenter(context.TODO(), f.datacenter)
	if err != nil {
		return fmt.Errorf("error %s", err)
	}
	finder = finder.SetDatacenter(dc)

	ds, err := getDatastore(finder, f.datastore)
	if err != nil {
		return fmt.Errorf("error %s", err)
	}

	_, err = ds.Stat(context.TODO(), f.destinationFile)
	if err != nil {
		log.Printf("[DEBUG] resourceVSphereFileRead - stat failed on: %v", f.destinationFile)
		d.SetId("")

		_, ok := err.(object.DatastoreNoSuchFileError)
		if !ok {
			return err
		}
	}

	return nil
}
示例#28
0
文件: helper.go 项目: vmware/vic
func NewHelper(t *testing.T) *Helper {
	h := &Helper{
		T: t,

		c:   test.NewAuthenticatedClient(t),
		fns: make([]func(), 0),
	}

	h.f = find.NewFinder(h.c, true)

	return h
}
func testAccCheckVSphereVirtualMachineExists(n string, vm *virtualMachine) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		if n == "" {
			return fmt.Errorf("No vm name passed in")
		}
		if vm == nil {
			return fmt.Errorf("No vm obj passed in")
		}
		rs, ok := s.RootModule().Resources[n]
		if !ok {
			return fmt.Errorf("Not found: %s", n)
		}

		if rs.Primary.ID == "" {
			return fmt.Errorf("No ID is set")
		}

		client := testAccProvider.Meta().(*govmomi.Client)
		finder := find.NewFinder(client.Client, true)

		dc, err := finder.Datacenter(context.TODO(), rs.Primary.Attributes["datacenter"])
		if err != nil {
			return fmt.Errorf("error %s", err)
		}

		dcFolders, err := dc.Folders(context.TODO())
		if err != nil {
			return fmt.Errorf("error %s", err)
		}

		folder := dcFolders.VmFolder
		if len(rs.Primary.Attributes["folder"]) > 0 {
			si := object.NewSearchIndex(client.Client)
			folderRef, err := si.FindByInventoryPath(
				context.TODO(), fmt.Sprintf("%v/vm/%v", rs.Primary.Attributes["datacenter"], rs.Primary.Attributes["folder"]))
			if err != nil {
				return err
			} else if folderRef != nil {
				folder = folderRef.(*object.Folder)
			}
		}

		_, err = object.NewSearchIndex(client.Client).FindChild(context.TODO(), folder, rs.Primary.Attributes["name"])

		*vm = virtualMachine{
			name: rs.Primary.ID,
		}

		return nil
	}
}
func resourceVSphereVirtualDiskCreate(d *schema.ResourceData, meta interface{}) error {
	log.Printf("[INFO] Creating Virtual Disk")
	client := meta.(*govmomi.Client)

	vDisk := virtualDisk{
		size: d.Get("size").(int),
	}

	if v, ok := d.GetOk("vmdk_path"); ok {
		vDisk.vmdkPath = v.(string)
	}

	if v, ok := d.GetOk("type"); ok {
		vDisk.initType = v.(string)
	}

	if v, ok := d.GetOk("adapter_type"); ok {
		vDisk.adapterType = v.(string)
	}

	if v, ok := d.GetOk("datacenter"); ok {
		vDisk.datacenter = v.(string)
	}

	if v, ok := d.GetOk("datastore"); ok {
		vDisk.datastore = v.(string)
	}

	finder := find.NewFinder(client.Client, true)

	dc, err := getDatacenter(client, d.Get("datacenter").(string))
	if err != nil {
		return fmt.Errorf("Error finding Datacenter: %s: %s", vDisk.datacenter, err)
	}
	finder = finder.SetDatacenter(dc)

	ds, err := getDatastore(finder, vDisk.datastore)
	if err != nil {
		return fmt.Errorf("Error finding Datastore: %s: %s", vDisk.datastore, err)
	}

	err = createHardDisk(client, vDisk.size, ds.Path(vDisk.vmdkPath), vDisk.initType, vDisk.adapterType, vDisk.datacenter)
	if err != nil {
		return err
	}

	d.SetId(ds.Path(vDisk.vmdkPath))
	log.Printf("[DEBUG] Virtual Disk id: %v", ds.Path(vDisk.vmdkPath))

	return resourceVSphereVirtualDiskRead(d, meta)
}