本文整理汇总了Golang中github.com/vmware/govmomi/object.VirtualMachine类的典型用法代码示例。如果您正苦于以下问题:Golang VirtualMachine类的具体用法?Golang VirtualMachine怎么用?Golang VirtualMachine使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了VirtualMachine类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: addVNIC
func addVNIC(ui packer.Ui, f *find.Finder, ctx context.Context, c *govmomi.Client, vm *object.VirtualMachine, network string, nwType string) error {
ui.Say("Adding NIC")
nets, err := f.NetworkList(ctx, network)
if err != nil {
return err
}
// TODO expose param for DVS
net := nets[1]
backing, err := net.EthernetCardBackingInfo(ctx)
if err != nil {
return err
}
device, err := object.EthernetCardTypes().CreateEthernetCard(nwType, backing)
if err != nil {
return err
}
err = vm.AddDevice(ctx, device)
if err != nil {
return err
}
ui.Say("Adding NIC Success")
return nil
} //
示例2: DetachDisk
func (cmd *vmdk) DetachDisk(vm *object.VirtualMachine) (string, error) {
ctx := context.TODO()
var mvm mo.VirtualMachine
pc := property.DefaultCollector(cmd.Client)
err := pc.RetrieveOne(ctx, vm.Reference(), []string{"config.hardware"}, &mvm)
if err != nil {
return "", err
}
spec := new(configSpec)
dsFile := spec.RemoveDisk(&mvm)
task, err := vm.Reconfigure(ctx, spec.ToSpec())
if err != nil {
return "", err
}
err = task.Wait(ctx)
if err != nil {
return "", err
}
return dsFile, nil
}
示例3: FindHosts
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!!")
}
}
示例4: IpAddress
// IpAddress attempts to find the guest IP address using esxcli.
// ESX hosts must be configured with the /Net/GuestIPHack enabled.
// For example:
// $ govc host.esxcli -- system settings advanced set -o /Net/GuestIPHack -i 1
func (g *GuestInfo) IpAddress(vm *object.VirtualMachine) (string, error) {
const any = "0.0.0.0"
var mvm mo.VirtualMachine
pc := property.DefaultCollector(g.c)
err := pc.RetrieveOne(context.TODO(), vm.Reference(), []string{"runtime.host", "config.uuid"}, &mvm)
if err != nil {
return "", err
}
h, err := g.hostInfo(mvm.Runtime.Host)
if err != nil {
return "", err
}
// Normalize uuid, esxcli and mo.VirtualMachine have different formats
uuid := strings.Replace(mvm.Config.Uuid, "-", "", -1)
if wid, ok := h.wids[uuid]; ok {
res, err := h.Run([]string{"network", "vm", "port", "list", "--world-id", wid})
if err != nil {
return "", err
}
for _, val := range res.Values {
if ip, ok := val["IPAddress"]; ok {
if ip[0] != any {
return ip[0], nil
}
}
}
}
return any, nil
}
示例5: instanceForVirtualMachine
func (i *vSphereInstanceManager) instanceForVirtualMachine(ctx context.Context, vm *object.VirtualMachine) (inst *Instance, err error) {
defer func() {
recoverErr := recover()
if recoverErr != nil {
inst = nil
err = recoverErr.(error)
}
}()
var mvm mo.VirtualMachine
err = vm.Properties(ctx, vm.Reference(), []string{"config", "guest", "runtime"}, &mvm)
if err != nil {
return nil, err
}
var ipAddresses []string
for _, nic := range mvm.Guest.Net {
for _, ip := range nic.IpConfig.IpAddress {
ipAddresses = append(ipAddresses, ip.IpAddress)
}
}
if reflect.DeepEqual(mvm.Runtime, types.VirtualMachineRuntimeInfo{}) {
return nil, fmt.Errorf("no instance for vm %v", vm)
}
return &Instance{
ID: mvm.Config.Name,
IPAddresses: ipAddresses,
State: string(mvm.Runtime.PowerState),
}, nil
}
示例6: buildVMRelocateSpec
// buildVMRelocateSpec builds VirtualMachineRelocateSpec to set a place for a new VirtualMachine.
func buildVMRelocateSpec(rp *object.ResourcePool, ds *object.Datastore, vm *object.VirtualMachine) (types.VirtualMachineRelocateSpec, error) {
var key int
devices, err := vm.Device(context.TODO())
if err != nil {
return types.VirtualMachineRelocateSpec{}, err
}
for _, d := range devices {
if devices.Type(d) == "disk" {
key = d.GetVirtualDevice().Key
}
}
rpr := rp.Reference()
dsr := ds.Reference()
return types.VirtualMachineRelocateSpec{
Datastore: &dsr,
Pool: &rpr,
Disk: []types.VirtualMachineRelocateSpecDiskLocator{
types.VirtualMachineRelocateSpecDiskLocator{
Datastore: dsr,
DiskBackingInfo: &types.VirtualDiskFlatVer2BackingInfo{
DiskMode: "persistent",
ThinProvisioned: types.NewBool(false),
EagerlyScrub: types.NewBool(true),
},
DiskId: key,
},
},
}, nil
}
示例7: getMACAddressOfVM
func (vmh *VMHost) getMACAddressOfVM(vm *object.VirtualMachine) (string, error) {
vmDeviceList, err := vm.Device(context.TODO())
if err != nil {
return "", errors.New("Cannot read VM VirtualDevices")
}
return vmDeviceList.PrimaryMacAddress(), nil
}
示例8: getVirtualMachineManagedObjectReference
func getVirtualMachineManagedObjectReference(ctx context.Context, c *govmomi.Client, vm *object.VirtualMachine, field string, dst interface{}) error {
collector := property.DefaultCollector(c.Client)
// Retrieve required field from VM object
err := collector.RetrieveOne(ctx, vm.Reference(), []string{field}, dst)
if err != nil {
return err
}
return nil
}
示例9: buildVMRelocateSpec
// buildVMRelocateSpec builds VirtualMachineRelocateSpec to set a place for a new VirtualMachine.
func buildVMRelocateSpec(finder *find.Finder, rp *object.ResourcePool, ds *object.Datastore, vm *object.VirtualMachine, linked bool) (types.VirtualMachineRelocateSpec, error) {
var key int
var parent *types.VirtualDiskFlatVer2BackingInfo
devices, err := vm.Device(context.TODO())
if err != nil {
return types.VirtualMachineRelocateSpec{}, err
}
for _, d := range devices {
if devices.Type(d) == "disk" {
vd := d.GetVirtualDevice()
parent = vd.Backing.(*types.VirtualDiskFlatVer2BackingInfo)
key = vd.Key
}
}
rpr := rp.Reference()
relocateSpec := types.VirtualMachineRelocateSpec{}
// Treat linked clones a bit differently.
if linked {
parentDs := strings.SplitN(parent.FileName[1:], "]", 2)
parentDsObj, err := finder.Datastore(context.TODO(), parentDs[0])
if err != nil {
return types.VirtualMachineRelocateSpec{}, err
}
parentDbObjRef := parentDsObj.Reference()
relocateSpec = types.VirtualMachineRelocateSpec{
Datastore: &parentDbObjRef,
Pool: &rpr,
DiskMoveType: "createNewChildDiskBacking",
}
} else {
dsr := ds.Reference()
relocateSpec = types.VirtualMachineRelocateSpec{
Datastore: &dsr,
Pool: &rpr,
Disk: []types.VirtualMachineRelocateSpecDiskLocator{
types.VirtualMachineRelocateSpecDiskLocator{
Datastore: dsr,
DiskId: key,
DiskBackingInfo: &types.VirtualDiskFlatVer2BackingInfo{
DiskMode: "persistent",
ThinProvisioned: types.NewBool(false),
EagerlyScrub: types.NewBool(true),
},
},
},
}
}
return relocateSpec, nil
}
示例10: addHardDisk
// addHardDisk adds a new Hard Disk to the VirtualMachine.
func addHardDisk(vm *object.VirtualMachine, size, iops int64, diskType string, datastore *object.Datastore, diskPath string, controller_type string) error {
devices, err := vm.Device(context.TODO())
if err != nil {
return err
}
log.Printf("[DEBUG] vm devices: %#v\n", devices)
controller, err := devices.FindDiskController(controller_type)
if err != nil {
return err
}
log.Printf("[DEBUG] disk controller: %#v\n", controller)
// TODO Check if diskPath & datastore exist
// If diskPath is not specified, pass empty string to CreateDisk()
if diskPath == "" {
return fmt.Errorf("[ERROR] addHardDisk - No path proided")
} else {
// TODO Check if diskPath & datastore exist
diskPath = fmt.Sprintf("[%v] %v", datastore.Name(), diskPath)
}
log.Printf("[DEBUG] addHardDisk - diskPath: %v", diskPath)
disk := devices.CreateDisk(controller, datastore.Reference(), diskPath)
existing := devices.SelectByBackingInfo(disk.Backing)
log.Printf("[DEBUG] disk: %#v\n", disk)
if len(existing) == 0 {
disk.CapacityInKB = int64(size * 1024 * 1024)
if iops != 0 {
disk.StorageIOAllocation = &types.StorageIOAllocationInfo{
Limit: iops,
}
}
backing := disk.Backing.(*types.VirtualDiskFlatVer2BackingInfo)
if diskType == "eager_zeroed" {
// eager zeroed thick virtual disk
backing.ThinProvisioned = types.NewBool(false)
backing.EagerlyScrub = types.NewBool(true)
} else if diskType == "thin" {
// thin provisioned virtual disk
backing.ThinProvisioned = types.NewBool(true)
}
log.Printf("[DEBUG] addHardDisk: %#v\n", disk)
log.Printf("[DEBUG] addHardDisk capacity: %#v\n", disk.CapacityInKB)
return vm.AddDevice(context.TODO(), disk)
} else {
log.Printf("[DEBUG] addHardDisk: Disk already present.\n")
return nil
}
}
示例11: cleanUpController
// Removes SCSI controller which is latest attached to VM.
func cleanUpController(newSCSIController types.BaseVirtualDevice, vmDevices object.VirtualDeviceList, vm *object.VirtualMachine, ctx context.Context) error {
ctls := vmDevices.SelectByType(newSCSIController)
if len(ctls) < 1 {
return ErrNoDevicesFound
}
newScsi := ctls[len(ctls)-1]
err := vm.RemoveDevice(ctx, true, newScsi)
if err != nil {
return err
}
return nil
}
示例12: WaitForIP
func (cmd *ovfx) WaitForIP(vm *object.VirtualMachine) error {
if !cmd.Options.PowerOn || !cmd.Options.WaitForIP {
return nil
}
cmd.Log("Waiting for IP address...\n")
ip, err := vm.WaitForIP(context.TODO())
if err != nil {
return err
}
cmd.Log(fmt.Sprintf("Received IP address: %s\n", ip))
return nil
}
示例13: InjectOvfEnv
func (cmd *ovfx) InjectOvfEnv(vm *object.VirtualMachine) error {
if !cmd.Options.InjectOvfEnv {
return nil
}
cmd.Log("Injecting OVF environment...\n")
var opts []types.BaseOptionValue
a := cmd.Client.ServiceContent.About
// build up Environment in order to marshal to xml
var props []ovf.EnvProperty
for _, p := range cmd.Options.PropertyMapping {
props = append(props, ovf.EnvProperty{
Key: p.Key,
Value: p.Value,
})
}
env := ovf.Env{
EsxID: vm.Reference().Value,
Platform: &ovf.PlatformSection{
Kind: a.Name,
Version: a.Version,
Vendor: a.Vendor,
Locale: "US",
},
Property: &ovf.PropertySection{
Properties: props,
},
}
opts = append(opts, &types.OptionValue{
Key: "guestinfo.ovfEnv",
Value: env.MarshalManual(),
})
ctx := context.Background()
task, err := vm.Reconfigure(ctx, types.VirtualMachineConfigSpec{
ExtraConfig: opts,
})
if err != nil {
return err
}
return task.Wait(ctx)
}
示例14: InjectOvfEnv
func (cmd *ovfx) InjectOvfEnv(vm *object.VirtualMachine) error {
ctx := context.TODO()
if !cmd.Options.PowerOn || !cmd.Options.InjectOvfEnv {
return nil
}
a := cmd.Client.ServiceContent.About
if strings.EqualFold(a.ProductLineId, "esx") || strings.EqualFold(a.ProductLineId, "embeddedEsx") || strings.EqualFold(a.ProductLineId, "vpx") {
cmd.Log("Injecting OVF environment...\n")
// build up Environment in order to marshal to xml
var epa []ovf.EnvProperty
for _, p := range cmd.Options.PropertyMapping {
epa = append(epa, ovf.EnvProperty{
Key: p.Key,
Value: p.Value})
}
env := ovf.Env{
EsxID: vm.Reference().Value,
Platform: &ovf.PlatformSection{
Kind: a.Name,
Version: a.Version,
Vendor: a.Vendor,
Locale: "US",
},
Property: &ovf.PropertySection{
Properties: epa},
}
xenv := env.MarshalManual()
vmConfigSpec := types.VirtualMachineConfigSpec{
ExtraConfig: []types.BaseOptionValue{&types.OptionValue{
Key: "guestinfo.ovfEnv",
Value: xenv}}}
task, err := vm.Reconfigure(ctx, vmConfigSpec)
if err != nil {
return err
}
if err := task.Wait(ctx); err != nil {
return err
}
}
return nil
}
示例15: addDevices
func (cmd *create) addDevices(vm *object.VirtualMachine) error {
devices, err := vm.Device(context.TODO())
if err != nil {
return err
}
var add []types.BaseVirtualDevice
if cmd.disk != "" {
controller, err := devices.FindDiskController(cmd.controller)
if err != nil {
return err
}
disk := devices.CreateDisk(controller, cmd.Datastore.Path(cmd.disk))
if cmd.link {
disk = devices.ChildDisk(disk)
}
add = append(add, disk)
}
if cmd.iso != "" {
ide, err := devices.FindIDEController("")
if err != nil {
return err
}
cdrom, err := devices.CreateCdrom(ide)
if err != nil {
return err
}
add = append(add, devices.InsertIso(cdrom, cmd.Datastore.Path(cmd.iso)))
}
netdev, err := cmd.NetworkFlag.Device()
if err != nil {
return err
}
add = append(add, netdev)
return vm.AddDevice(context.TODO(), add...)
}